From: David ‘Bombe’ Roden Date: Tue, 10 Mar 2009 17:39:09 +0000 (+0100) Subject: Add parser factory. X-Git-Url: https://git.pterodactylus.net/?p=arachne.git;a=commitdiff_plain;h=a0072b36c131c30d4c100992b567a8e3bf687aec Add parser factory. --- 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; + } + +}