KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > igfay > jfig > JFig


1 package org.igfay.jfig;
2
3 import org.apache.log4j.Logger;
4 import org.igfay.util.PropertyUtility;
5
6 import java.util.ArrayList JavaDoc;
7 import java.util.HashMap JavaDoc;
8 import java.util.Iterator JavaDoc;
9 import java.util.List JavaDoc;
10 import java.util.Map JavaDoc;
11 import java.util.Properties JavaDoc;
12 import java.util.TreeMap JavaDoc;
13
14 /**
15  * The JFig package provides very simple, flexible and powerful
16  * functionality for managing one or more configurations in a java environment.
17  *
18  * <P>It allows for a combination of a hierarchy of configuration files,
19  * substitution variables and property variables. Methods are provided to get
20  * values stored in a configuration dictionary with a variety of types (String,
21  * array, integer, float, boolean, etc) and default values.
22  *<P>
23  * Usage:
24  * <BR>To get an instance of the JFig singleton, use:
25  * JFig. getInstance();
26  *
27  * <P>There are a number of helper methods to retrieve configuration values. The
28  * most common is:
29  * <BR>String value = JFig. getInstance().getValue ("aSection","aKey","aDefaultValue");
30  *
31  * <P>See the javadocs for additional helper methods to retrieve values as
32  * different java types and with different exception handling.
33  *
34  *@author bconrad
35  *@created April 3, 2001
36  */

37 public class JFig implements JFigIF {
38     private static Logger log = Logger.getLogger(JFig.class);
39     private static JFigIF configSingleton;
40     private JFigDictionary configDictionary;
41     private Map JavaDoc allConfigFiles;
42     private JFigLocatorIF configLocator;
43     private JFigParser configParser;
44     private List JavaDoc configListeners;
45
46     // for creating a "null" jfig object
47
private JFig() {
48         this.configDictionary = new JFigDictionary();
49         this.allConfigFiles = new HashMap JavaDoc();
50     }
51     private JFig(JFigLocatorIF jfigLocator) throws JFigException {
52         if (jfigLocator == null) {
53             jfigLocator = new JFigLocator(null);
54         }
55         this.configLocator = jfigLocator;
56         this.configDictionary = new JFigDictionary();
57         this.allConfigFiles = new HashMap JavaDoc();
58         processConfig();
59     }
60     
61     public static void main(String JavaDoc[] args) {
62         JFig.getInstance().print();
63         PropertyUtility.listProperties();
64     }
65
66     /**
67      * Return the config singleton
68          * @return
69      */

70     public synchronized static JFigIF getInstance() {
71         return getInstance(null);
72     }
73     public static void setInstance(JFigIF jfig) {
74         configSingleton = jfig;
75     }
76     
77     /**
78      * Return the config singleton. If the configuration file is not found, throw an exception.
79      * @return
80      * @deprecated - Use initialize
81      */

82     public synchronized static JFigIF getInstance(int dummy) throws JFigException {
83         return getConfigSingleton(null);
84     }
85
86     /**
87      * Return the config singleton passing a JFigLocator. If the configuration file is not found, throw an exception.
88      * @return
89      * @deprecated - Use initialize
90      */

91     public synchronized static JFigIF getInstance(int dummy, JFigLocatorIF locator) throws JFigException {
92         return getConfigSingleton(locator);
93     }
94
95     /**
96      * Return the config singleton passing a JFigLocator
97      * @return
98      */

99     public synchronized static JFigIF getInstance(JFigLocatorIF jfigLocator) {
100         // default to a "null" jfig if there are problems
101
JFigIF myConfigSingleton = new JFig();
102         try {
103             myConfigSingleton = getConfigSingleton(jfigLocator);
104         } catch (JFigException e) {
105             log.error("*** Unable to create configuration dictionary. " + e.getMessage()+ " ***");
106         } catch (NoClassDefFoundError JavaDoc e) {
107             log.error("*** Unable to create configuration dictionary. NoClassDefFoundError "+ e.getMessage() +"\nThis may be the result of incompatible XML jars. See JFIG documentation.");
108         } catch (Throwable JavaDoc e) {
109             log.error("*** Unhandled exception initializing JFig "+e.getMessage(),e);
110         }
111         setInstance(myConfigSingleton);
112         return myConfigSingleton;
113     }
114
115     private static JFigIF getConfigSingleton(JFigLocatorIF jfigLocator) throws JFigException {
116         if (configSingleton == null) {
117             log.debug("Create singleton object.");
118             configSingleton = new JFig(jfigLocator);
119             log.debug("Created singleton object");
120         }
121         return configSingleton;
122     }
123
124     /**
125      * Add JFig listeners to list so they can be notified when there
126      * is a significant change in the configuration.
127      *
128      *@param listener The feature to be added to the ConfigEventListener
129      * attribute
130      */

131     public void addConfigEventListener(JFigListener listener) {
132         log.debug("Add listener: " + listener);
133         getConfigListeners().add(listener);
134         log.debug("Number listeners: " + configListeners.size());
135     }
136
137     /**
138      * Lazily initialize and return listeners
139      *
140      */

141     protected List JavaDoc getConfigListeners() {
142         if (configListeners == null) {
143             configListeners = new ArrayList JavaDoc();
144         }
145
146         return configListeners;
147     }
148
149     /**
150      * Notify registered listeners when configuration is updated.
151      */

152     protected void fireConfigUpdateEvent() {
153         log.debug("Number listeners: " + getConfigListeners().size());
154
155         JFigEvent event = new JFigEvent("Configuration Updated");
156
157         // loop through eventListener list and call configurationUpdate() method
158
for (int i = 0; i < getConfigListeners().size(); i++) {
159             log.debug("Notify listener");
160             ((JFigListener) getConfigListeners().get(i)).configurationUpdate(
161                 event);
162         }
163     }
164
165     /**
166      * Print the values in the JFig dictionary.
167      */

168     public void print() {
169         getConfigDictionary().print();
170     }
171
172     /**
173      * Print the values in the JFig dictionary.
174      * @deprecated
175      */

176     public void printConfigurationDictionary() {
177         print();
178     }
179
180     /**
181      * Call parser to process required config
182      */

183     protected void processConfig() throws JFigException {
184         log.debug("Processing file "+getConfigLocator().getConfigFileName());
185         getParser().processConfig();
186
187         getParser().resolveSymbolicValues();
188         getParser().addPropertyValues();
189         log.debug("Complete ");
190         log.debug("");
191     }
192
193     /**
194      * Reprocess the configuration creating a new config dictionary
195      */

196     public void reprocessConfiguration() throws JFigException {
197         reprocessConfiguration(null);
198     }
199     /**
200      * Reprocess the configuration with the specified JFigLocator, creating a new config dictionary
201      */

202     public void reprocessConfiguration(JFigLocator locator) throws JFigException {
203         initialize(locator);
204         fireConfigUpdateEvent();
205     }
206     /**
207      * Initialize configuration
208      */

209     public static JFigIF initialize() throws JFigException {
210             return initialize(null);
211     }
212
213     /**
214      * Initialize configuration.
215      * It is recommended that JFig is explicitly initialized by this method.
216      * The alternative is to let getInstance() lazily initialize.
217      * The difference is that this will throw a JFigException if there is a problem
218      * in the initialization process while getInstance() will not.
219      */

220     public static JFigIF initialize(JFigLocator locator) throws JFigException {
221             JFig newConfigSingleton = new JFig(locator);
222             configSingleton = newConfigSingleton;
223             return configSingleton;
224     }
225
226     /**
227      * return the ConfigurationDictionary
228      * Made public so we can access this from a jsp and show the configuration
229      * via html.
230      */

231     public JFigDictionary getConfigDictionary() {
232         return configDictionary;
233     }
234
235     /**
236      * Convenience method for getting values as array.
237      * The value is tokenized depending on the first token found in
238      * the following order: comma, semicolon, colon, space
239      *
240      */

241     public String JavaDoc[] getArrayValue(String JavaDoc section, String JavaDoc key) throws JFigException {
242         String JavaDoc value = getValue(section, key);
243
244         return JFigUtility.stringToArray(value);
245     }
246
247     /**
248       * Convenience method for getting values as boolean
249       */

250     public boolean getBooleanValue(String JavaDoc section, String JavaDoc key, String JavaDoc notFoundValue) {
251         String JavaDoc value = getValue(section, key, notFoundValue);
252
253         return Boolean.valueOf(value).booleanValue();
254     }
255
256     /**
257      * Convenience method for getting values as float
258      *
259      *@param section Description of Parameter
260      *@param key Description of Parameter
261      *@param notFoundValue Description of Parameter
262      *@return The FloatValue value
263      *@exception JFigException Description of Exception
264      */

265     public float getFloatValue(String JavaDoc section, String JavaDoc key, String JavaDoc notFoundValue) throws JFigException {
266         String JavaDoc value = getValue(section, key, notFoundValue);
267
268         try {
269             return Float.valueOf(value).floatValue();
270         } catch (ArithmeticException JavaDoc e) {
271             throw new JFigException(e.getMessage());
272         }
273     }
274
275     /**
276      * Convenience method for getting values as int
277      */

278     public int getIntegerValue(String JavaDoc section, String JavaDoc key)
279         throws JFigException {
280         String JavaDoc value = getValue(section, key);
281
282         try {
283             return Integer.parseInt(value);
284         } catch (ArithmeticException JavaDoc e) {
285             throw new JFigException(e.getMessage());
286         }
287     }
288
289     /**
290      * Convenience method for getting values as int, with default value
291      */

292     public int getIntegerValue(String JavaDoc section, String JavaDoc key, String JavaDoc notFoundValue) {
293         String JavaDoc value = getValue(section, key, notFoundValue);
294
295         try {
296             return Integer.parseInt(value);
297         } catch (ArithmeticException JavaDoc e) {
298             log.info(
299                 "Caught ArithmenticException for section "
300                     + section
301                     + " key "
302                     + key
303                     + " defaultValue "
304                     + notFoundValue
305                     + ". Returning 0");
306
307             return 0;
308         } catch (NumberFormatException JavaDoc e) {
309             log.info(
310                 "Caught NumberFormatException for section "
311                     + section
312                     + " key "
313                     + key
314                     + " defaultValue "
315                     + notFoundValue
316                     + ". Returning 0");
317
318             return 0;
319         }
320     }
321
322     /**
323      * Return the JFig parser
324      */

325     protected JFigParser getParser() {
326         if (configParser == null) {
327             if (isXML()) {
328                 log.debug("Create XMLConfigParser");
329                 configParser = new XMLJFigParser(this, getConfigLocator());
330             } else {
331                 log.debug("create ConfigParser");
332                 configParser = new IniJFigParser(this, getConfigLocator());
333             }
334         }
335
336         return configParser;
337     }
338
339     /**
340      * Is the configuration file in XML format or ini format.
341      * @return boolean
342      */

343     protected boolean isXML() {
344         return (getConfigFileName() != null)
345             && (getConfigFileName().indexOf("xml") > -1);
346     }
347
348     /**
349      * Return the value for this section and key. If none found, return the
350      * default value.
351          *
352          *@param section Description of Parameter
353          *@param key Description of Parameter
354          *@param defaultValue Description of Parameter
355          *@return The Value value
356          */

357     public String JavaDoc getValue(String JavaDoc section, String JavaDoc key, String JavaDoc defaultValue) {
358         String JavaDoc value = null;
359
360         try {
361             value = getValue(section, key);
362         } catch (JFigException e) {
363             log.debug("Return default value " + defaultValue);
364
365             return defaultValue;
366         }
367
368         return value;
369     }
370
371     /**
372      * Return a list of all values starting with "key" in the section.
373      * If section xxx contains x.1, x.2, and x.3,
374      * getValuesStartingWith("xxx", "x.") returns a list containing
375      * x.1, x.2, and x.3.
376      *
377      * @param section
378      * @param key
379      * @param defaultValue
380      * @return List
381      */

382     public List JavaDoc getValuesStartingWith(String JavaDoc section, String JavaDoc key) {
383         log.debug("section " + section + " key " + key);
384
385         List JavaDoc list = new ArrayList JavaDoc();
386         TreeMap JavaDoc map = getConfigDictionary().getSectionNamed(section, false);
387
388         if (map != null) {
389             Iterator JavaDoc iterator = map.keySet().iterator();
390
391             while (iterator.hasNext()) {
392                 String JavaDoc compareKey = (String JavaDoc) iterator.next();
393                 log.debug("compareKey " + compareKey);
394
395                 if (compareKey.startsWith(key)) {
396                     list.add(map.get(compareKey));
397                 }
398             }
399         }
400
401         return list;
402     }
403
404     /**
405      * Return a map of all values starting with "key" in the scetcion.
406      * If section xxx contains x.1=a, x.2=b, and x.3=c,
407      * getValuesStartingWith("xxx", "x.") returns a map containing
408      * x.1,a x.2,b and x.3,c.
409      *
410      * @param section
411      * @param key
412      * @param defaultValue
413      * @return List
414      */

415     public Map JavaDoc getEntriesStartingWith(String JavaDoc section, String JavaDoc key) {
416         log.debug("section " + section + " key " + key);
417
418         List JavaDoc list = new ArrayList JavaDoc();
419         TreeMap JavaDoc map = getConfigDictionary().getSectionNamed(section, false);
420         HashMap JavaDoc returnMap = new HashMap JavaDoc();
421         if (map != null) {
422             Iterator JavaDoc iterator = map.keySet().iterator();
423
424             while (iterator.hasNext()) {
425                 String JavaDoc compareKey = (String JavaDoc) iterator.next();
426                 log.debug("compareKey " + compareKey);
427
428                 if (compareKey.startsWith(key)) {
429                     returnMap.put(compareKey, map.get(compareKey));
430                 }
431             }
432         }
433
434         return returnMap;
435     }
436
437     /**
438      * Return an entire section as a Map
439      */

440     public Map JavaDoc getSection(String JavaDoc section) {
441         log.debug("section " + section );
442         return getConfigDictionary().getSectionNamed(section, false);
443     }
444
445     /**
446      * Return a section as a Properties object
447      */

448     public Properties JavaDoc getSectionAsProperties(String JavaDoc section) {
449         return getSectionAsProperties(section, new Properties JavaDoc());
450     }
451
452     /**
453      * Return a section populated in a supplied Properties object.
454      */

455     public Properties JavaDoc getSectionAsProperties(String JavaDoc section, Properties JavaDoc properties) {
456         log.debug("section " + section );
457         if (properties == null) {
458             return null;
459         }
460         // can't use putAll in case of null values
461
Map JavaDoc map = getSection(section);
462         Iterator JavaDoc iterator = map.keySet().iterator();
463         while (iterator.hasNext()) {
464             String JavaDoc key = (String JavaDoc) iterator.next();
465             String JavaDoc value = (String JavaDoc) map.get(key);
466             if (value != null) {
467                 properties.put(key, value);
468             }
469             
470         }
471         
472         return properties;
473     }
474
475     /**
476      * Call configParser to get the value for a key in a given section.
477      *
478      */

479     public String JavaDoc getValue(String JavaDoc section, String JavaDoc key) throws JFigException {
480         String JavaDoc value = getConfigDictionary().getValue(section, key);
481         log.debug(value);
482
483         return value;
484     }
485
486     /**
487      * Set a configuration value.
488      * Most values are set during initial parsing so this is rarely used.
489      */

490     public void setConfigurationValue(String JavaDoc sectionName, String JavaDoc keyString, String JavaDoc valueString) {
491         getConfigDictionary().setConfigurationValue(sectionName, keyString, valueString);
492     }
493
494     /**
495      * Convenience method for getting values as array with default value.
496      */

497     public String JavaDoc[] getArrayValue(String JavaDoc section, String JavaDoc key, String JavaDoc notFoundValue) {
498         String JavaDoc value = getValue(section, key, notFoundValue);
499
500         return JFigUtility.stringToArray(value);
501     }
502
503     /**
504      * Sets the configDictionary.
505      * @param configDictionary
506      */

507     protected void setConfigDictionary(JFigDictionary configDictionary) {
508         this.configDictionary = configDictionary;
509     }
510
511     /**
512      * Returns the list of all config files that have been processed.
513      * Used to prevent processing the same file multiple times
514      * esp in case of circular includes.
515      * @return List
516      */

517     protected Map JavaDoc getAllConfigFiles() {
518         return allConfigFiles;
519     }
520
521     protected void setAllConfigFiles(HashMap JavaDoc map) {
522         allConfigFiles = map;
523     }
524
525     /**
526      * @return
527      */

528     protected JFigLocatorIF getConfigLocator() {
529         return configLocator;
530     }
531
532     protected String JavaDoc getConfigFileName() {
533         return getConfigLocator().getConfigFileName();
534     }
535 }
536
Popular Tags