From a0072b36c131c30d4c100992b567a8e3bf687aec Mon Sep 17 00:00:00 2001 From: =?utf8?q?David=20=E2=80=98Bombe=E2=80=99=20Roden?= Date: Tue, 10 Mar 2009 18:39:09 +0100 Subject: [PATCH] Add parser factory. --- .../arachne/parser/ParserFactory.java | 61 ++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 src/net/pterodactylus/arachne/parser/ParserFactory.java diff --git a/src/net/pterodactylus/arachne/parser/ParserFactory.java b/src/net/pterodactylus/arachne/parser/ParserFactory.java new file mode 100644 index 0000000..8385f73 --- /dev/null +++ b/src/net/pterodactylus/arachne/parser/ParserFactory.java @@ -0,0 +1,61 @@ +/* + * © 2009 David ‘Bombe’ Roden + */ +package net.pterodactylus.arachne.parser; + +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +import de.ina.util.data.InternetMediaType; +import de.ina.util.validation.Validation; + +/** + * Factory that can create {@link Parser} objects depending on a given content + * type. + * + * @author David ‘Bombe’ Roden + */ +public class ParserFactory { + + /** The logger. */ + private static final Logger logger = Logger.getLogger(ParserFactory.class.getName()); + + /** Mapping from MIME type to parser classes. */ + private final Map> parsers = new HashMap>(); + + /** + * Creates a new parser factory using default parsers for common MIME types. + */ + public ParserFactory() { + parsers.put(new InternetMediaType("text", "html"), HtmlEditorKitParser.class); + } + + /** + * Returns a {@link Parser} for the given content type. + * + * @param contentType + * The content type + * @return A parser for the content type, or null if no parser + * for the given content type could be found + */ + public Parser getParser(String contentType) { + Validation.begin().isNotNull("contentType", (Object) contentType).check(); + InternetMediaType internetMediaType = InternetMediaType.fromString(contentType); + Class parserClass = parsers.get(internetMediaType); + if (parserClass == null) { + return null; + } + try { + Parser parser = parserClass.newInstance(); + return parser; + } catch (InstantiationException ie1) { + logger.log(Level.WARNING, "Could not instantiate parser “" + parserClass.getName() + "!", ie1); + } catch (IllegalAccessException iae1) { + logger.log(Level.WARNING, "Could not instantiate parser “" + parserClass.getName() + "!", iae1); + } + return null; + } + +} -- 2.7.4