1 package org.naftulin.configmgr.parsers;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.net.URL;
6
7 import org.apache.log4j.Logger;
8 import org.naftulin.configmgr.ConfigurationManagementEntryImpl;
9 import org.naftulin.configmgr.ConfigurationManagerException;
10 import org.naftulin.configmgr.ConfigurationManagementEntry;
11 import org.naftulin.configmgr.ConfigurationType;
12
13 /***
14 * Log4J entry parser converts log4j configuration record into configuration management enttry.
15 * It parses a log 4j file that the record describes, (re) initializes log4j
16 * engine, and stores the configuration
17 * as a content of an {@link org.naftulin.configmgr.ConfigurationManagementEntry entry}.
18 *
19 * @author Henry Naftulin
20 * @since 1.0
21 */
22 public abstract class AbstractLog4JParser extends AbstractConfigEntryParser {
23 private static final Logger log = Logger.getLogger(AbstractLog4JParser.class);
24
25 /***
26 * Calls appropriate log4j configurator: for DOM object it is dom configurator
27 * to (re)initilize log4j engine.
28 */
29 abstract void doCallLog4JConfigurator(URL fileUrl);
30
31 /***
32 * Retrurns a configuration managment entry by parsing the log4j file passed in.
33 * @param key the key configuration entry will be assigned
34 * @param fileUrl the file URL to be parsed.
35 * @return a log4j managment entry by parsing the record passed in.
36 * @throws ConfigurationManagerException if an error occurs while parsing an entry.
37 */
38 public ConfigurationManagementEntry getConfigurationManagementEntry(final String key, final URL fileUrl) throws ConfigurationManagerException {
39 checkParameters(key, fileUrl);
40
41 final String fileName = fileUrl.getFile();
42 String content = null;
43 try {
44 final InputStream stream = fileUrl.openStream();
45 log.debug("reading log4j configuration from file " + fileName);
46 content = readStreamContentAsString(stream);
47 log.debug("log4j configuration is " + content);
48 doCallLog4JConfigurator(fileUrl);
49 log.info("reloaded log4j configuratoin from " + fileName);
50 } catch (IOException e) {
51 log.warn("Error while reading log4j file", e);
52 throw new ConfigurationManagerException("Error while reading log4j file",e);
53 }
54 final ConfigurationManagementEntry entry = new ConfigurationManagementEntryImpl(key, fileName , content, this, getConfigurationType());
55 log.info("configured entry " + entry);
56 return entry;
57 }
58
59 private void checkParameters(final String key, final URL fileUrl)
60 throws ConfigurationManagerException {
61 if (fileUrl == null) {
62 throw new ConfigurationManagerException("file URL is null");
63 }
64 if (fileUrl.getFile() == null) {
65 throw new ConfigurationManagerException("file name passed in the URL " + fileUrl + " is null");
66 }
67 if (key == null) {
68 throw new ConfigurationManagerException("key is null");
69 }
70 }
71
72 protected abstract ConfigurationType getConfigurationType();
73
74 }