KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mr > core > configuration > ConfigManager


1 /*
2  * Copyright 2002 by
3  * <a HREF="http://www.coridan.com">Coridan</a>
4  * <a HREF="mailto: support@coridan.com ">support@coridan.com</a>
5  *
6  * The contents of this file are subject to the Mozilla Public License Version
7  * 1.1 (the "License"); you may not use this file except in compliance with the
8  * License. You may obtain a copy of the License at
9  * http://www.mozilla.org/MPL/
10  *
11  * Software distributed under the License is distributed on an "AS IS" basis,
12  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13  * for the specific language governing rights and limitations under the
14  * License.
15  *
16  * The Original Code is "MantaRay" (TM).
17  *
18  * The Initial Developer of the Original Code is Amir Shevat.
19  * Portions created by the Initial Developer are Copyright (C) 2006
20  * Coridan Inc. All Rights Reserved.
21  *
22  * Contributor(s): all the names of the contributors are added in the source
23  * code where applicable.
24  *
25  * Alternatively, the contents of this file may be used under the terms of the
26  * LGPL license (the "GNU LESSER GENERAL PUBLIC LICENSE"), in which case the
27  * provisions of LGPL are applicable instead of those above. If you wish to
28  * allow use of your version of this file only under the terms of the LGPL
29  * License and not to allow others to use your version of this file under
30  * the MPL, indicate your decision by deleting the provisions above and
31  * replace them with the notice and other provisions required by the LGPL.
32  * If you do not delete the provisions above, a recipient may use your version
33  * of this file under either the MPL or the GNU LESSER GENERAL PUBLIC LICENSE.
34  
35  *
36  * This library is free software; you can redistribute it and/or modify it
37  * under the terms of the MPL as stated above or under the terms of the GNU
38  * Lesser General Public License as published by the Free Software Foundation;
39  * either version 2.1 of the License, or any later version.
40  *
41  * This library is distributed in the hope that it will be useful, but WITHOUT
42  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
43  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
44  * License for more details.
45  */

46 /*
47  * Created on Dec 15, 2003
48  *
49  * holds a map of all the configuration properties in the system
50  */

51 package org.mr.core.configuration;
52
53 import java.io.File JavaDoc;
54 import java.io.IOException JavaDoc;
55 import java.util.ArrayList JavaDoc;
56 import org.mr.core.log.StartupLogger;
57
58 import org.apache.commons.logging.Log;
59 import org.apache.commons.logging.LogFactory;
60 import org.w3c.dom.Document JavaDoc;
61 import org.w3c.dom.Element JavaDoc;
62 import org.w3c.dom.NodeList JavaDoc;
63
64 import javax.management.*;
65 import javax.xml.parsers.DocumentBuilder JavaDoc;
66 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
67
68 /**
69  * ConfigManager hold the configuration info , there are 2 config files that we merge together
70  * @author Amir Shevat
71  *
72  */

73 public class ConfigManager extends StandardMBean implements ConfigManagerMBean {
74     String JavaDoc configFileName ;
75     Element JavaDoc configurationDOMElement; // in case there is no config file and configuration is given through a DOM element
76

77     ConfigurationElement root;
78     Log log ;
79     // list of ConfigurationChangeListener to be notified of changes
80
ArrayList JavaDoc configurationChangeListeners = new ArrayList JavaDoc();
81
82     private boolean haslog4JConfig;
83     
84     public ConfigManager(String JavaDoc propertyFile)throws NotCompliantMBeanException {
85         super(ConfigManagerMBean.class);
86         File JavaDoc f = new File JavaDoc(propertyFile);
87         if(!f.exists()){
88             //System.out.println("FATAL: Did not find configuration file-"+propertyFile);
89
StartupLogger.log.fatal("Did not find configuration file-"+propertyFile, "ConfigManager");
90             return;
91         }
92         loadConfiguration(f);
93         configFileName = propertyFile;
94     }// ConfigManager
95

96
97     /**
98      * Creates a new instance of ConfigManager, with the configuration given as a DOM element.
99      *
100      * @param element
101      * Configuration DOM element
102      */

103     public ConfigManager(Element JavaDoc element) throws NotCompliantMBeanException {
104         super(ConfigManagerMBean.class);
105         // save the DOM element given as a memeber. Will be fetched later by LoggerLoader.init() using
106
// getConfigurationDOMElement().
107
configurationDOMElement = element;
108         // clone the DOM element, and use it. Element is cloned because it will be changed - "log4j:configuration"
109
// element will be removed.
110
loadConfiguration((Element JavaDoc) element.cloneNode(true));
111     }
112
113     private void loadConfiguration(File JavaDoc f) {
114         Element JavaDoc rootElement;
115         DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
116         factory.setIgnoringElementContentWhitespace(true);
117
118         try{
119             DocumentBuilder JavaDoc xmlBuilder= factory.newDocumentBuilder();
120             Document JavaDoc xmlDoc = xmlBuilder.parse(f);
121
122             rootElement = xmlDoc.getDocumentElement();
123             loadConfiguration(rootElement);
124         } catch(Exception JavaDoc e){
125             //System.out.println("FATAL: can not load configuration file " );
126
StartupLogger.log.fatal("Can not load configuration file.", "ConfigManager");
127             e.printStackTrace();
128         }
129     }
130
131     private void loadConfiguration(Element JavaDoc element){
132         try {
133             // log4j configuration is no the the same format as the rest of the config
134
NodeList JavaDoc logConfig = element.getElementsByTagName("log4j:configuration");
135             Element JavaDoc logConfigElement = (Element JavaDoc) logConfig.item(0);
136             
137             if(logConfigElement != null){
138                     haslog4JConfig =true;
139 // logConfiguration = (Element) element.removeChild(logConfigElement);
140
element.removeChild(logConfigElement);
141             }
142             // load the rest of the configuration
143
root = new ConfigurationElement(element);
144         }
145         catch (Exception JavaDoc e){
146             StartupLogger.log.fatal("Can not load configuration DOM element.", "ConfigManager");
147             e.printStackTrace();
148         }
149     }
150
151     
152     /**
153      * Returns the property value of key, or null if key is not found
154      */

155     public String JavaDoc getStringProperty(String JavaDoc key) {
156         String JavaDoc result = null;
157         ArrayList JavaDoc element = getConfigurationElements(key);
158         if(element != null && element.size() ==1){
159             ConfigurationElement ce = (ConfigurationElement) element.get(0);
160             if(ce.isLeaf()){
161                 result = ce.getValue();
162             }
163         }
164         if(result!= null){
165             result = result.trim();
166         }
167         return result;
168     }
169     
170     public ArrayList JavaDoc getConfigurationElements(String JavaDoc key) {
171         ConfigurationElement element =root;
172         ArrayList JavaDoc result = null;
173         String JavaDoc[] subKeys = key.split("\\.");
174         for (int i = 0; i < subKeys.length; i++) {
175             String JavaDoc subKey = subKeys[i];
176             if(element != null)
177                 result = element.getSubConfigurationElementsByName(subKey);
178             if(result == null){
179                 return null;
180             }else{
181                 element = (ConfigurationElement) result.get(0);
182             }
183         }
184         return result;
185     }
186     
187     public ConfigurationElement getConfigurationElement(String JavaDoc key) {
188         ConfigurationElement element =root;
189         ArrayList JavaDoc result = null;
190         String JavaDoc[] subKeys = key.split("\\.");
191         for (int i = 0; i < subKeys.length; i++) {
192             String JavaDoc subKey = subKeys[i];
193             result = element.getSubConfigurationElementsByName(subKey);
194             if(result == null){
195                 return null;
196             }else{
197                 element = (ConfigurationElement) result.get(0);
198             }
199         }
200         return (ConfigurationElement) result.get(0);
201     }
202
203     /**
204      * adds a property with the key and value inserted. if 'commitToFile' is true the new property
205      * will be writen in the configuration files and added permanently.
206      */

207     public boolean setStringProperty(String JavaDoc key ,String JavaDoc value , boolean commitToFile ) {
208         if(key==null||value==null||key.length()==0||value.length()==0){
209             throw new IllegalArgumentException JavaDoc("Can't create a new property without values for both 'key' and 'value'.");
210         }
211         try {
212             changeConfigProperty( key , value , commitToFile);
213         } catch (IOException JavaDoc e) {
214             return false;
215         }
216         return true;
217     }
218
219     /**
220      * Returns the property value of key, or defaultValue if key is not found
221      */

222     public String JavaDoc getStringProperty(String JavaDoc key, String JavaDoc defaultValue) {
223         String JavaDoc value = getStringProperty(key) ;
224         if(value == null){
225              if(log != null && log.isDebugEnabled()){
226                 log.debug("Configuration value not found for key '"+key+"'. Returning default value "+defaultValue+".");
227             }
228             return defaultValue;
229         }else{
230             return value;
231         }
232     }
233
234     /**
235      * Returns the property value of key, or null if key is not found
236      */

237     public int getIntProperty(String JavaDoc key) {
238
239         String JavaDoc value = getStringProperty(key) ;
240         
241         int i = Integer.parseInt(value) ;
242         
243         return i ;
244     }
245     
246     /**
247      * adds a property with the key and value inserted. if 'commitToFile' is true the new property
248      * will be writen in the configuration files and added permanently.
249      */

250     public boolean setIntProperty(String JavaDoc key ,int value , boolean commitToFile ) {
251         try {
252             changeConfigProperty( key ,String.valueOf(value) , commitToFile);
253         } catch (IOException JavaDoc e) {
254             return false;
255         }
256         return true;
257     }
258
259     /**
260      * @return int - the property value of key, or defaultValue if key is not found.
261      */

262     public int getIntProperty(String JavaDoc key, int defaultValue) {
263         String JavaDoc value = getStringProperty(key) ;
264         if (value == null)
265             return defaultValue ;
266         int i ;
267         try {
268             i = Integer.parseInt(value) ;
269         } catch (Throwable JavaDoc t) {
270             if(log != null && log.isWarnEnabled()){
271                 log.warn("Problem while trying to return int for property key '"+key+"' and value '"+value+"'. Returning default value "+defaultValue+".");
272             }
273             return defaultValue;
274         }
275         return i ;
276     }
277     
278     /**
279      * Returns the property value of key, or null if key is not found
280      */

281     public long getLongProperty(String JavaDoc key) {
282
283         String JavaDoc value = getStringProperty(key) ;
284         
285         long i = Long.parseLong(value) ;
286         
287         return i ;
288     }
289     
290     
291     
292     
293     /**
294      * adds a property with the key and value inserted. if 'commitToFile' is true the new property
295      * will be writen in the configuration files and added permanently.
296      */

297     public boolean setLongProperty(String JavaDoc key ,long value , boolean commitToFile ) {
298         try {
299             changeConfigProperty( key ,String.valueOf(value) , commitToFile);
300         } catch (IOException JavaDoc e) {
301             return false;
302         }
303         return true;
304     }
305
306     /**
307      * Returns the property value of key, or defaultValue if key is not found
308      */

309     public long getLongProperty(String JavaDoc key, long defaultValue) {
310
311         String JavaDoc value = getStringProperty(key) ;
312         if (value == null)
313             return defaultValue ;
314         long i ;
315         try {
316             i = Long.parseLong(value) ;
317         } catch (Throwable JavaDoc t) {
318             if(log != null && log.isWarnEnabled()){
319                 log.warn("Problem while trying to return long for property key '"+key+"' and value '"+value+"'. Returning default value "+defaultValue+".");
320             }
321             return defaultValue;
322         }
323         return i ;
324     }
325     
326     /**
327      * Returns the property value of key, or null if key is not found
328      */

329     public short getShortProperty(String JavaDoc key) {
330
331         String JavaDoc value = getStringProperty(key) ;
332         
333         short i = Short.parseShort(value) ;
334         
335         return i ;
336     }
337     
338     /**
339      * adds a property with the key and value inserted. if 'commitToFile' is true the new property
340      * will be writen in the configuration files and added permanently.
341      */

342     public boolean setShortProperty(String JavaDoc key ,short value , boolean commitToFile ) {
343         try {
344             changeConfigProperty( key ,String.valueOf(value) , commitToFile);
345         } catch (IOException JavaDoc e) {
346             return false;
347         }
348         return true;
349     }
350     
351
352     /**
353      * Returns the property value of key, or defaultValue if key is not found
354      */

355     public short getShortProperty(String JavaDoc key, short defaultValue) {
356
357         String JavaDoc value = getStringProperty(key) ;
358         if (value == null)
359             return defaultValue ;
360         short i ;
361         try {
362             i = Short.parseShort(value) ;
363         } catch (Throwable JavaDoc t) {
364             if(log != null && log.isWarnEnabled()){
365                 log.warn("Problem while trying to return short for property key '"+key+"' and value '"+value+"'. Returning default value "+defaultValue+".");
366             }
367             return defaultValue;
368         }
369         return i ;
370     }
371     /**
372      * Returns the property value of key, or false if key is not found
373      */

374     public boolean getBooleanProperty(String JavaDoc key) {
375
376         String JavaDoc value = getStringProperty(key) ;
377         if (value == null)
378             return false;
379         if (value.equalsIgnoreCase("true"))
380             return true;
381         if (value.equalsIgnoreCase("false"))
382             return false;
383         if(log != null && log.isWarnEnabled()){
384             log.warn("Problem while trying to return boolean for property key '"+key+"' and value '"+value+"'. Returning false.");
385         }
386         return false;
387     }
388     
389     /**
390      * adds a property with the key and value inserted. if 'commitToFile' is true the new property
391      * will be writen in the configuration files and added permanently.
392      */

393     public boolean setBooleanProperty(String JavaDoc key ,boolean value , boolean commitToFile ) {
394         try {
395             changeConfigProperty( key ,String.valueOf(value) , commitToFile);
396         } catch (IOException JavaDoc e) {
397             return false;
398         }
399         return true;
400     }
401
402     /**
403      * Returns the property value of key, or defaultValue if key is not found
404      */

405     public boolean getBooleanProperty(String JavaDoc key, boolean defaultValue) {
406
407         String JavaDoc value = getStringProperty(key) ;
408         if (value == null)
409             return defaultValue;
410         if (value.equalsIgnoreCase("true"))
411             return true;
412         if (value.equalsIgnoreCase("false"))
413             return false;
414         
415         if(log != null && log.isWarnEnabled()){
416             log.warn("Problem while trying to return boolean for property key '"+key+"' and value '"+value+"'. Returning given default "+defaultValue+".");
417         }
418         return defaultValue;
419     }
420     
421     /**
422      * returns all the keys of the properties and it's values
423      * @return HashMap of the keys
424     
425     //the next method was added by lital kasif
426     public HashMap getAllProperties(){
427         HashMap map = new HashMap();
428         map.putAll(config);
429                 
430         return map;
431     }//getAllProperties
432      */

433     /**
434      * when property is changed we call this listener
435      * @see ConfigurationChangeEvent
436      * @see ConfigurationChangeListener
437      */

438     public void registerAsConfigChangeListener(ConfigurationChangeListener listener){
439         configurationChangeListeners.add(listener);
440     }
441     
442     /**
443      * changes configuration of a given key in the component map
444      * @param key the key of the property
445      * @param value the new value
446      * @param commitToFile true if commit to coponent config file (not default config file)
447      */

448     public void changeConfigProperty(String JavaDoc key ,String JavaDoc value , boolean commitToFile) throws IOException JavaDoc{
449         key = key.trim();
450         value = value.trim();
451         /*
452         String oldValue = getStringProperty(key);
453         String defaultValue = config.getProperty(key);
454         config.put(key ,value );
455         // notify listeners
456         ConfigurationChangeEvent event = new ConfigurationChangeEvent();
457         event.setKey(key);
458         event.setNewValue(value);
459         event.setOldValue(oldValue);
460         event.setDefaultValue(defaultValue);
461         int size = configurationChangeListeners.size();
462         for(int index = 0 ; index < size ; index ++){
463             ConfigurationChangeListener listener =
464                 (ConfigurationChangeListener) configurationChangeListeners.get(index);
465             listener.refresh(event);
466         }// for
467         // save secondery to file
468         if(commitToFile){
469             saveProperties();
470         }
471         */

472     }//changeConfigProperty
473

474
475
476     protected String JavaDoc getDescription(MBeanInfo i_mBeanInfo) {
477         return "manages the properties in the system .";
478     }
479
480     protected String JavaDoc getDescription(MBeanAttributeInfo i_mBeanAttributeInfo) {
481         if(i_mBeanAttributeInfo.getName().equals("PropertiesKeys"))
482             return "returns the keys of all the properties of the system";
483         if(i_mBeanAttributeInfo.getName().equals("AllProperties"))
484             return "returns the keys and values of all the properties of the system";
485         return "";
486     }
487
488     protected String JavaDoc getDescription(MBeanOperationInfo i_mBeanOperationInfo, MBeanParameterInfo i_mBeanParameterInfo, int i) {
489
490         if (i==0 && i_mBeanOperationInfo.getName().equals("getStringProperty"))
491             return "enter the key of the requested property";
492         if (i==0 && i_mBeanOperationInfo.getName().equals("setStringProperty"))
493             return "the key of the property";
494         if (i==1)
495             return "the value of the property";
496         if (i==2)
497             return "determins wether the property will be written permanently in the configuration files";
498         return "the new value of the managed string";
499     }
500
501     protected String JavaDoc getDescription(MBeanOperationInfo i_mBeanOperationInfo) {
502         if(i_mBeanOperationInfo.getName().equals("setStringProperty"))
503             return "sets the value of a given property name in the system ";
504         if(i_mBeanOperationInfo.getName().equals("getStringProperty"))
505             return "gets the value of a given property name in the system ";
506         return "general seters and geters";
507     }
508
509
510     protected String JavaDoc getParameterName(MBeanOperationInfo i_mBeanOperationInfo, MBeanParameterInfo i_mBeanParameterInfo, int i) {
511         if (i==0)
512             return "key";
513         if (i==1)
514             return "value";
515         if (i==2)
516             return "commitToFile";
517         return "val";
518     }
519
520     public String JavaDoc getConfigFileName() {
521         return configFileName;
522     }
523
524     public Element JavaDoc getConfigurationDOMElement(){
525         return configurationDOMElement;
526     }
527
528     public boolean hasLog4JConfig() {
529         return haslog4JConfig;
530     }
531
532     public void initLogger() {
533         this.log = LogFactory.getLog("ConfigManager");
534     }
535 }
536
Popular Tags