1 package org.naftulin.configmgr.parsers;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.net.URL;
6 import java.util.Properties;
7
8 import org.apache.log4j.Logger;
9 import org.naftulin.configmgr.ConfigurationManagementEntryImpl;
10 import org.naftulin.configmgr.ConfigurationManagerException;
11 import org.naftulin.configmgr.ConfigurationManagementEntry;
12 import org.naftulin.configmgr.ConfigurationType;
13
14 /***
15 * Configuration entry parser converts property configuration record into property configuration management enttry.
16 * It parses the property file that the record describes, and stores the configuration
17 * as a properties in content of an {@link org.naftulin.configmgr.ConfigurationManagementEntry entry}.
18 *
19 * @author Henry Naftulin
20 * @since 1.0
21 */
22 public class PropertyFileParserImpl implements ConfigEntryParser {
23 private static final long serialVersionUID = 1L;
24 private static final Logger log = Logger.getLogger(PropertyFileParserImpl.class);
25
26 /***
27 * Retrurns a configuration managment entry by parsing the property file passed in.
28 * @param key the key configuration entry will be assigned
29 * @param fileUrl the file URL to be parsed.
30 * @return a configuration managment entry by parsing the record passed in.
31 * @throws ConfigurationManagerException if an error occurs while parsing an entry.
32 */
33 public ConfigurationManagementEntry getConfigurationManagementEntry(final String key,
34 final URL fileUrl) throws ConfigurationManagerException {
35 validateParameters(key, fileUrl);
36
37 final String fileName = fileUrl.getFile();
38
39 final Properties content = new Properties();
40 InputStream stream;
41 try {
42 stream = fileUrl.openStream();
43 content.load(stream );
44 } catch (IOException e) {
45 log.warn("Error while reading property file", e);
46 throw new ConfigurationManagerException("Error while reading property file",e);
47 }
48 final ConfigurationManagementEntry entry = new ConfigurationManagementEntryImpl(key, fileName, content, this, ConfigurationType.PROPERTIES);
49
50 return entry;
51 }
52
53 private void validateParameters(final String key, final URL fileUrl) throws ConfigurationManagerException {
54 if (fileUrl == null) {
55 throw new ConfigurationManagerException("file URL is null");
56 }
57 if (fileUrl.getFile() == null) {
58 throw new ConfigurationManagerException("file name passed in the URL " + fileUrl + " is null");
59 }
60 if (key == null) {
61 throw new ConfigurationManagerException("key is null");
62 }
63 }
64
65 /***
66 * Returns a string representation of this parser.
67 * @return a string representation of this parser.
68 */
69 public String toString() {
70 return "Property file parser";
71 }
72 }