Add parser factory.
[arachne.git] / src / net / pterodactylus / arachne / parser / ParserFactory.java
1 /*
2  * © 2009 David ‘Bombe’ Roden
3  */
4 package net.pterodactylus.arachne.parser;
5
6 import java.util.HashMap;
7 import java.util.Map;
8 import java.util.logging.Level;
9 import java.util.logging.Logger;
10
11 import de.ina.util.data.InternetMediaType;
12 import de.ina.util.validation.Validation;
13
14 /**
15  * Factory that can create {@link Parser} objects depending on a given content
16  * type.
17  *
18  * @author David ‘Bombe’ Roden <bombe@pterodactylus.net>
19  */
20 public class ParserFactory {
21
22         /** The logger. */
23         private static final Logger logger = Logger.getLogger(ParserFactory.class.getName());
24
25         /** Mapping from MIME type to parser classes. */
26         private final Map<InternetMediaType, Class<? extends Parser>> parsers = new HashMap<InternetMediaType, Class<? extends Parser>>();
27
28         /**
29          * Creates a new parser factory using default parsers for common MIME types.
30          */
31         public ParserFactory() {
32                 parsers.put(new InternetMediaType("text", "html"), HtmlEditorKitParser.class);
33         }
34
35         /**
36          * Returns a {@link Parser} for the given content type.
37          *
38          * @param contentType
39          *            The content type
40          * @return A parser for the content type, or <code>null</code> if no parser
41          *         for the given content type could be found
42          */
43         public Parser getParser(String contentType) {
44                 Validation.begin().isNotNull("contentType", (Object) contentType).check();
45                 InternetMediaType internetMediaType = InternetMediaType.fromString(contentType);
46                 Class<? extends Parser> parserClass = parsers.get(internetMediaType);
47                 if (parserClass == null) {
48                         return null;
49                 }
50                 try {
51                         Parser parser = parserClass.newInstance();
52                         return parser;
53                 } catch (InstantiationException ie1) {
54                         logger.log(Level.WARNING, "Could not instantiate parser “" + parserClass.getName() + "!", ie1);
55                 } catch (IllegalAccessException iae1) {
56                         logger.log(Level.WARNING, "Could not instantiate parser “" + parserClass.getName() + "!", iae1);
57                 }
58                 return null;
59         }
60
61 }