KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jacorb > config > Configuration


1 package org.jacorb.config;
2
3 /*
4  * JacORB - a free Java ORB
5  *
6  * Copyright (C) 1997-2004 Gerald Brose.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the Free
20  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  */

22
23 import org.apache.avalon.framework.configuration.DefaultConfiguration;
24 import org.apache.avalon.framework.configuration.ConfigurationException;
25 import org.apache.avalon.framework.logger.*;
26
27 import java.io.*;
28 import java.util.*;
29
30 import org.jacorb.orb.ORB;
31 import org.jacorb.util.ObjectUtil;
32
33 /**
34  * ORB configuration objects are read-only representations of files with
35  * configuration properties.
36  *
37  * ORB configuration options for a given name are looked up and loaded as follows:
38  * <ol>
39  * <li>System properties are loaded first, but only to get properties
40  * that affect further property loading
41  * <li>the file <tt>orb.properties</tt> is loaded from java.home/lib
42  * and user.home if it exists
43  * <li>if the ORBid is property is set, the file <tt>ORBid.properties</tt> is
44  * loaded from jacorb.config.dir/etc, if that exists, or jacorb.home/etc, or '.'
45  * If ORBid is not set, the default file <tt>jacorb.properties</tt>
46  * is loaded from these places.
47  * <li>Custom properties are loaded from each file name listed int the system property
48  * <tt>custom.props</tt>
49  * <li>To also support packaged servers in jar files, the configuration
50  * file lookup mechanism finally tries to load named properties files
51  * (<tt>ORBid.properties</tt>, or <tt>jacorb.properties</tt>) from
52  * the classpath, if it cannot find them in the config dictionary.
53  * <li> After all property files have been loaded, the System properties are
54  * loaded again, so that command-line properties take precedence
55  * <li> Finally, properties hard-coded and passed in through ORB.init() are
56  * loaded.
57  *</ol>
58  *
59  * The Configuration object is also used by JacORB components to
60  * retreive their Logger objects.
61  *
62  * @author Gerald Brose, XTRADYNE Technologies
63  * @version $Id: Configuration.java,v 1.14 2005/03/25 13:08:32 andre.spiegel Exp $
64  */

65
66 public class Configuration
67     extends org.apache.avalon.framework.configuration.DefaultConfiguration
68 {
69     private static final String JavaDoc fileSuffix = ".properties";
70     private static final String JavaDoc COMMON_PROPS = "orb" + fileSuffix;
71
72     private static final String JavaDoc TRUE = "true";
73     private static final String JavaDoc ON = "on";
74     private static final String JavaDoc EMPTY_STR = "";
75     
76     private static final int DEFAULT_LOG_LEVEL = 0;
77
78     private Configuration config;
79     private String JavaDoc configName;
80     private ORB orb = null;
81
82     /** root logger instance for this configuration */
83     private Logger logger = null;
84     
85     /** logger factory used to create loggers */
86     private LoggerFactory loggerFactory = null;
87
88     /** default class name for logger factory */
89     private final String JavaDoc loggerFactoryClzName =
90        "org.jacorb.config.LogKitLoggerFactory";
91
92
93     /**
94      * Create a configuration with a given name and load configuration
95      * properties from the file <name>.properties
96      */

97
98 // Configuration(String name)
99
// throws ConfigurationException
100
// {
101
// super(name);
102
// init(name, null);
103
// initLogging();
104
// }
105

106     /**
107      * Factory method
108      */

109
110     public static Configuration getConfiguration(Properties props,
111                                                  ORB orb,
112                                                  boolean isApplet)
113         throws ConfigurationException
114     {
115         // determine the ORBId, if set, so we can locate the corresponding
116
// configuration
117
String JavaDoc orbID = "jacorb"; // default id
118
String JavaDoc myOrbID = isApplet ? null : System.getProperty("ORBid");
119
120         if( props != null )
121         {
122             // props override system properties
123
String JavaDoc tmp = (String JavaDoc)props.get("ORBid");
124             if( tmp != null )
125                 myOrbID = tmp;
126         }
127
128         if (myOrbID != null )
129         {
130             // check for legal values
131
if (myOrbID.equals("orb") || myOrbID.equals("jacorb"))
132                 throw new ConfigurationException("Illegal orbID, <" +
133                                                   myOrbID + "> is reserved");
134             else
135                 orbID = myOrbID;
136         }
137
138         return new Configuration(orbID, props, orb, isApplet);
139     }
140
141
142     /**
143      * Create a configuration using the properties passed
144      * into ORB.init()
145      */

146
147     private Configuration(String JavaDoc name,
148                           Properties orbProperties,
149                           ORB orb,
150                           boolean isApplet)
151         throws ConfigurationException
152     {
153         super(name);
154         this.orb = orb;
155         
156         if (isApplet)
157         {
158             initApplet(name, orbProperties);
159         }
160         else
161         {
162             init(name, orbProperties);
163         }
164
165         initLogging();
166     }
167
168     /**
169      * loads properties from files.
170      *
171      * Properties are loaded in the following order, with later
172      * properties overriding earlier ones: 1) System properties
173      * (incl. command line), to get properties that affect further
174      * property loading 2) orb.properties file 3) specific
175      * configuration file for the ORB (if any) 4) System properties
176      * again, so that command line args take precedence over the above
177      * 5) the ORB properties set in the client code and passed in
178      * through ORB.init().
179      * (Note that these will thus always take effect!)
180      *
181      * @param name the name for the ORB instance, may not be null.
182      */

183
184     private void init(String JavaDoc name, Properties orbProperties)
185         throws ConfigurationException
186    {
187        if( name == null )
188            throw new ConfigurationException("Illegal null value for ORB name!");
189        String JavaDoc separator = System.getProperty("file.separator");
190        String JavaDoc home = System.getProperty("user.home");
191        String JavaDoc lib = System.getProperty("java.home");
192        boolean loaded = false;
193
194        // 1) load system properties to grab any command line properties
195
// that will influence further property loading
196
setAttributes(System.getProperties());
197
198        int logLevel = getAttributeAsInteger("jacorb.config.log.verbosity",DEFAULT_LOG_LEVEL);
199        
200        // 2) look for orb.properties
201
// look for common properties files in java.home/lib first
202
Properties commonProps =
203            loadPropertiesFromFile( lib + separator + "lib" + separator + COMMON_PROPS);
204        
205        if (commonProps!= null)
206        {
207             setAttributes(commonProps);
208             // we don't have proper logging at this stage yet, so we can only
209
// log to the console, but we check if that is explicitly disallowed
210
logLevel = getAttributeAsInteger("jacorb.config.log.verbosity",DEFAULT_LOG_LEVEL);
211             loaded = true;
212
213             if (logLevel > 2)
214                 System.out.println("[ base configuration loaded from file " +
215                                    lib + separator + "lib" + separator + COMMON_PROPS + " ]");
216        }
217        
218        // look for common properties files in user.home next
219
commonProps =
220            loadPropertiesFromFile( home + separator + COMMON_PROPS );
221        
222        if (commonProps!= null)
223        {
224            setAttributes(commonProps);
225            loaded = true;
226
227            logLevel = getAttributeAsInteger("jacorb.config.log.verbosity",DEFAULT_LOG_LEVEL);
228            if (logLevel > 2)
229                System.out.println("[ base configuration loaded from file " +
230                                    home + separator + COMMON_PROPS + " ]");
231        }
232        
233        // look for common properties files on the classpath next
234
commonProps =
235            loadPropertiesFromClassPath( COMMON_PROPS );
236        
237        if (commonProps!= null)
238        {
239            loaded = true;
240            setAttributes(commonProps);
241            logLevel = getAttributeAsInteger("jacorb.config.log.verbosity",DEFAULT_LOG_LEVEL);
242            if (logLevel > 2)
243                System.out.println("[ base configuration loaded from classpath " +
244                                     COMMON_PROPS + " ]");
245        }
246        
247  
248        // 3) look for specific properties file
249
String JavaDoc configDir =
250            getAttribute("jacorb.config.dir", "");
251        
252        if (configDir.length() == 0)
253            configDir = getAttribute ("jacorb.home", "");
254        
255        if (configDir.length() != 0 )
256            configDir += separator + "etc";
257        else
258        {
259            logLevel = getAttributeAsInteger("jacorb.config.log.verbosity",DEFAULT_LOG_LEVEL);
260            if (logLevel > 0)
261                System.err.println("[ jacorb.home unset! Will use '.' ]");
262            configDir = ".";
263        }
264        
265        String JavaDoc propFileName = configDir + separator + name + fileSuffix;
266        
267        // now load properties file from file system
268
Properties orbConfig = loadPropertiesFromFile(propFileName );
269        
270        if (orbConfig!= null)
271        {
272            setAttributes(orbConfig);
273            loaded = true;
274
275            logLevel = getAttributeAsInteger("jacorb.config.log.verbosity",DEFAULT_LOG_LEVEL);
276            if (logLevel > 2)
277                System.out.println("[ configuration " + name +
278                                   " loaded from file " + propFileName + " ]");
279        }
280        else
281        {
282            logLevel = getAttributeAsInteger("jacorb.config.log.verbosity",DEFAULT_LOG_LEVEL);
283            if (logLevel > 0)
284                System.err.println("[ File " + propFileName + " for configuration " + name +
285                                   " not found ]");
286        }
287        
288        // 4) look for additional custom properties files
289
List customPropFileNames = getAttributeList("custom.props");
290
291        if (!customPropFileNames.isEmpty())
292        {
293            for (Iterator iter = customPropFileNames.iterator(); iter.hasNext();)
294            {
295                 String JavaDoc fileName = ((String JavaDoc)iter.next());
296                 Properties customProps = loadPropertiesFromFile(fileName);
297                 if (customProps!= null)
298                 {
299                     setAttributes(customProps);
300                     loaded = true;
301
302                     logLevel = getAttributeAsInteger("jacorb.config.log.verbosity",DEFAULT_LOG_LEVEL);
303                     if (logLevel > 2)
304                         System.out.println("[ custom properties loaded from file " +
305                                            fileName + " ]");
306                 }
307                 else
308                 {
309                     if (logLevel > 0)
310                         System.err.println("[ custom properties not found in " +
311                                            fileName + " ]");
312                 }
313            }
314        }
315
316        // now load properties file from classpath
317
orbConfig = loadPropertiesFromClassPath( name + fileSuffix );
318        if (orbConfig!= null)
319        {
320            setAttributes(orbConfig);
321            loaded = true;
322
323            logLevel =
324                getAttributeAsInteger("jacorb.config.log.verbosity",DEFAULT_LOG_LEVEL);
325            if (logLevel > 2)
326                System.out.println("[ configuration " + name + " loaded from classpath]");
327        }
328
329        // 5) load system properties again, so that
330
// command line args override properties from files
331
setAttributes( System.getProperties() );
332        
333        // 6) load properties passed to ORB.init(), these will override any
334
// settings in config files or system properties!
335
if (orbProperties != null)
336        {
337            loaded = true;
338            setAttributes(orbProperties);
339        }
340
341        if (!loaded)
342        {
343            // print a warning....
344
System.out.println("[ No configuration properties found for configuration " + name + " ]");
345        }
346
347     }
348
349     /**
350      * loads properties via classloader.
351      *
352      * Properties are loaded in the following order, with later properties
353      * overriding earlier ones: 1) Properties from ORB.init(), to get
354      * properties that affect further property loading 2) orb.properties 3)
355      * specific configuration file for the ORB (if any) 4) the ORB properties
356      * set in the client code and passed in through ORB.init(). (Note that
357      * these will thus always take effect!)
358      *
359      * @param name the name for the ORB instance, may not be null.
360      */

361
362     private void initApplet(String JavaDoc name, Properties orbProperties)
363         throws ConfigurationException
364    {
365        if( name == null )
366            throw new ConfigurationException("Illegal null value for ORB name!");
367        boolean loaded = false;
368
369        // 1) load system properties to grab any command line properties
370
// that will influence further property loading
371
setAttributes(orbProperties);
372
373        int logLevel = getAttributeAsInteger("jacorb.config.log.verbosity",
374                                             DEFAULT_LOG_LEVEL);
375        
376        // 2) look for orb.properties
377
// look for common properties files on the classpath next
378
Properties commonProps =
379            loadPropertiesFromClassPath( COMMON_PROPS );
380        
381        if (commonProps!= null)
382        {
383            loaded = true;
384            setAttributes(commonProps);
385            logLevel = getAttributeAsInteger("jacorb.config.log.verbosity",
386                                             DEFAULT_LOG_LEVEL);
387            if (logLevel > 2)
388                System.out.println("[ base configuration loaded from classpath " +
389                                     COMMON_PROPS + " ]");
390        }
391        
392  
393        // 3) look for specific properties file
394
String JavaDoc propFileName = name + fileSuffix;
395        Properties orbConfig = loadPropertiesFromClassPath(propFileName );
396        
397        if (orbConfig!= null)
398        {
399            setAttributes(orbConfig);
400            loaded = true;
401
402            logLevel = getAttributeAsInteger("jacorb.config.log.verbosity",
403                                             DEFAULT_LOG_LEVEL);
404            if (logLevel > 2)
405                System.out.println("[ configuration " + name +
406                                   " loaded from classpath " + propFileName +
407                                   " ]");
408        }
409        else
410        {
411            logLevel = getAttributeAsInteger("jacorb.config.log.verbosity",
412                                             DEFAULT_LOG_LEVEL);
413            if (logLevel > 0)
414                System.err.println("[ File " + propFileName +
415                                   " for configuration " + name +
416                                   " not found in classpath]");
417        }
418        
419        // 4) look for additional custom properties files
420
List customPropFileNames = getAttributeList("custom.props");
421
422        if (!customPropFileNames.isEmpty())
423        {
424            for (Iterator iter = customPropFileNames.iterator(); iter.hasNext();)
425            {
426                 String JavaDoc fileName = ((String JavaDoc)iter.next());
427                 Properties customProps = loadPropertiesFromClassPath(fileName);
428                 if (customProps!= null)
429                 {
430                     setAttributes(customProps);
431                     loaded = true;
432
433                     logLevel =
434                         getAttributeAsInteger("jacorb.config.log.verbosity",
435                                               DEFAULT_LOG_LEVEL);
436                     if (logLevel > 2)
437                         System.out.println(
438                             "[ custom properties loaded from classpath " +
439                             fileName + " ]");
440                 }
441                 else
442                 {
443                     if (logLevel > 0)
444                         System.err.println(
445                             "[ custom properties " + fileName +
446                             "not found in classpath ]");
447                 }
448            }
449        }
450        
451        // 5) load properties passed to ORB.init(), these will override any
452
// settings in config files or system properties!
453
if (orbProperties != null)
454        {
455            loaded = true;
456            setAttributes(orbProperties);
457        }
458
459        if (!loaded)
460        {
461            // print a warning....
462
System.out.println(
463                "[ No configuration properties found for configuration " +
464                name + " ]");
465        }
466     }
467
468
469     /**
470      * set attributes of this configuration using properties
471      */

472
473     void setAttributes(Properties properties)
474     {
475         for (Iterator iter=properties.keySet().iterator(); iter.hasNext();)
476         {
477             Object JavaDoc k = iter.next();
478             // Some lunatics illegally put non String objects into System props
479
// as keys / values - we check for both and ignore them.
480
if (!(k instanceof String JavaDoc)) continue;
481             String JavaDoc key = (String JavaDoc)k;
482             Object JavaDoc value = properties.get(key);
483             if (value instanceof String JavaDoc || value == null)
484             {
485                 setAttribute(key, (String JavaDoc)value);
486             }
487         }
488     }
489
490
491     /**
492      * Loads properties from a file
493      * @param fileName the name of a properties file
494      * @return a properties object or null, if fileName not found
495      */

496
497     private static Properties loadPropertiesFromFile(String JavaDoc fileName)
498     {
499         try
500         {
501             BufferedInputStream bin =
502                 new BufferedInputStream( new FileInputStream(fileName));
503             Properties result = new Properties();
504             result.load(bin);
505             return result;
506         }
507         catch( java.io.IOException JavaDoc io )
508         {
509             // io.printStackTrace(); //debug only
510
return null;
511         }
512     }
513
514
515     /**
516      * load properties file from classpath
517      * @param name the name of the properties file.
518      * @return a properties object or null, if name not found
519      */

520
521     private static Properties loadPropertiesFromClassPath(String JavaDoc name)
522     {
523         Properties result = null;
524         try
525         {
526             java.net.URL JavaDoc url =
527                 Thread.currentThread().getContextClassLoader().getResource(name);
528             if (url!=null)
529             {
530                 result = new Properties();
531                 result.load( url.openStream() );
532             }
533         }
534         catch (java.io.IOException JavaDoc ioe)
535         {
536             ioe.printStackTrace(); //debug only
537
}
538         return result;
539     }
540
541
542     /**
543      * Set up JacORB logging. Will create logger factory and root
544      * logger object according to configuration parameters. The value
545      * of the property <tt>jacorb.log.loggerFactory</tt> determines the
546      * logger factory class name that is used to create the root logger.
547      *
548      * @since 2.0 beta 3
549      */

550
551     private void initLogging()
552         throws ConfigurationException
553     {
554         String JavaDoc logFileName =
555             getAttribute("jacorb.logfile", "");
556
557         int maxLogSize =
558             getAttributeAsInteger( "jacorb.logfile.maxLogSize", 0 );
559
560         if ( !logFileName.equals(""))
561         {
562             // Convert $implname postfix to implementation name
563
if (logFileName.endsWith("$implname"))
564             {
565                 logFileName = logFileName.substring (0, logFileName.length () - 9);
566
567                 if ( !getAttribute("jacorb.implname","").equals(""))
568                 {
569                     logFileName += getAttribute("jacorb.implname","");
570                 }
571                 else
572                 {
573                     // Just in case implname has not been set
574
logFileName += "log";
575                 }
576             }
577         }
578
579         String JavaDoc clzName = getAttribute("jacorb.log.loggerFactory","");
580         Class JavaDoc loggerFactoryClz = null;
581
582         try
583         {
584             if ( !clzName.equals(""))
585             {
586                 loggerFactoryClz = org.jacorb.util.ObjectUtil.classForName(clzName);
587             }
588             else
589             {
590                 loggerFactoryClz = org.jacorb.util.ObjectUtil.classForName(loggerFactoryClzName);
591             }
592             loggerFactory = (LoggerFactory)loggerFactoryClz.newInstance();
593             loggerFactory.configure( this );
594         }
595         catch (Exception JavaDoc e)
596         {
597             e.printStackTrace();
598         }
599
600         if (loggerFactory == null)
601         {
602             System.err.println("Configuration Error, could not create logger!");
603         }
604
605         if (!logFileName.equals(""))
606         {
607             try
608             {
609                 loggerFactory.setDefaultLogFile(logFileName, maxLogSize);
610                 //logger = loggerFactory.getNamedRootLogger("jacorb");
611
logger =
612                     loggerFactory.getNamedLogger("jacorb",logFileName, maxLogSize);
613             }
614             catch (IOException e)
615             {
616                 logger = loggerFactory.getNamedRootLogger("jacorb");
617                 if( logger.isErrorEnabled())
618                 {
619                     logger.error("Could not create logger with file target: " + logFileName +
620                                  ", falling back to console log!");
621                 }
622             }
623         }
624         else
625         {
626             logger = loggerFactory.getNamedRootLogger("jacorb" );
627         }
628     }
629
630     /**
631      * @return the ORB for which this configuration was created
632      */

633
634     public ORB getORB()
635     {
636         return orb;
637     }
638
639
640     /**
641      * @param name the name of the logger, which also functions
642      * as a log category
643      * @return a Logger for a given name
644      */

645
646     public Logger getNamedLogger(String JavaDoc name)
647     {
648         return loggerFactory.getNamedLogger(name);
649     }
650     
651     public static final String JavaDoc getLoggerName(Class JavaDoc clz)
652     {
653         String JavaDoc packageName = clz.getPackage().getName();
654         if (packageName != null && packageName.startsWith("org.jacorb"))
655         {
656             return packageName.substring(4);
657         }
658         return packageName;
659     }
660
661     /**
662      * For a property that has a list of comma-separated values,
663      * this method returns these values as a list of Strings.
664      * If the property is not set, an empty list is returned.
665      */

666
667     public List getAttributeList(String JavaDoc key)
668     {
669         List result = new ArrayList();
670         String JavaDoc value = null;
671
672         try
673         {
674             value = getAttribute(key);
675         }
676         catch( ConfigurationException ce)
677         {
678             // ignore
679
}
680
681         if (value != null)
682         {
683             StringTokenizer tok = new StringTokenizer(value, ",");
684             while (tok.hasMoreTokens())
685                 result.add(tok.nextToken().trim());
686         }
687         return result;
688     }
689
690     /**
691      * Create an object from the given property. The class's default
692      * constructor will be used.
693      *
694      * @return an object of the class of the keys value, or null, if
695      * no class name is found for the key
696      * @throws ConfigurationException if object creation fails.
697      */

698
699     public Object JavaDoc getAttributeAsObject( String JavaDoc key )
700         throws ConfigurationException
701     {
702         String JavaDoc className = null;
703         try
704         {
705             className = getAttribute( key );
706         }
707         catch( Exception JavaDoc e )
708         {
709             // ignore
710
}
711
712         if( className != null && className.length() > 0 )
713         {
714             try
715             {
716                 Class JavaDoc c = ObjectUtil.classForName(className);
717                 return c.newInstance();
718             }
719             catch( Exception JavaDoc e )
720             {
721                 throw new ConfigurationException( "Unable to build class from key >" +
722                                                   key +"<: " + e );
723             }
724         }
725         else
726         {
727             return null;
728         }
729     }
730
731     public boolean getAttributeAsBoolean(String JavaDoc key)
732         throws ConfigurationException
733     {
734         String JavaDoc s = getAttribute(key);
735         
736         if (s != null && s.length() > 0)
737         {
738             s = s.trim().toLowerCase();
739             return ON.equals(s) || TRUE.equals(s);
740         }
741         else
742         {
743             return false;
744         }
745     }
746
747     public boolean getAttributeAsBoolean(String JavaDoc key, boolean defaultValue)
748     {
749         String JavaDoc s = getAttribute(key, EMPTY_STR);
750         
751         if (s.length() > 0)
752         {
753             s = s.trim().toLowerCase();
754             return ON.equals(s) || TRUE.equals(s);
755         }
756         else
757         {
758             return defaultValue;
759         }
760     }
761 }
762
Popular Tags