KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jonas > common > JProp


1 /*
2  * JOnAS: Java(TM) Open Application Server
3  * Copyright (C) 1999 Bull S.A.
4  * Contact: jonas-team@objectweb.org
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19  * USA
20  *
21  * Initial developer(s): ____________________________________.
22  * Contributor(s): Adriana Danes
23  *
24  * --------------------------------------------------------------------------
25  * $Id: JProp.java,v 1.19 2004/03/22 13:09:00 benoitf Exp $
26  * --------------------------------------------------------------------------
27  */

28
29
30 package org.objectweb.jonas.common;
31
32 import java.io.BufferedWriter JavaDoc;
33 import java.io.File JavaDoc;
34 import java.io.FileInputStream JavaDoc;
35 import java.io.FileOutputStream JavaDoc;
36 import java.io.FileNotFoundException JavaDoc;
37 import java.io.FileWriter JavaDoc;
38 import java.io.IOException JavaDoc;
39 import java.util.Enumeration JavaDoc;
40 import java.util.Hashtable JavaDoc;
41 import java.util.Properties JavaDoc;
42 import java.util.StringTokenizer JavaDoc;
43 import javax.naming.Context JavaDoc;
44
45
46 /**
47  * This class manages configuration properties for a JOnAS Server.
48  * It adopts the singleton design-pattern. Configuration parameters
49  * are read from .properties file (jonas.properties or resource.properties).
50  * In order to support dynamically created resources, JProp also allows for
51  * a .properties file generation using a java.lang.Properties object content
52  * @author jonas-team
53  * @author Adriana Danes
54  * @author Florent Benoit
55  * <ul>
56  * <li>
57  * ../03/2003 Adriana Danes
58  * <ol>
59  * <li>Manage unique instances for resource.properties
60  * <li>Replace 'config' with 'conf'
61  * <li>Change initial configuration policy : read properties file in a sole location : JONAS_BASE/CONFIG_DIR/
62  * <li>Replace method name <code>getFilesEnv</code> to <code>getConfigFileEnv</code>
63  * </ol>
64  * <li>
65  * 05/05/2003 Adriana Danes. Support JProp instance creation for dynamically created resources.
66  * </ul>
67  * 05/2003 Florent Benoit. Add support of xml files and checkstyle
68  */

69 public class JProp {
70
71     /**
72      * Prefix for jonas.properties file
73      */

74     public static final String JavaDoc JONASPREFIX = "jonas";
75
76     /**
77      * Domain name
78      */

79     public static final String JavaDoc DOMAIN_NAME = "domain.name";
80
81     /**
82      * JOnAS server name
83      */

84     public static final String JavaDoc JONAS_NAME = "jonas.name";
85
86     /**
87      * Default server name
88      */

89     public static final String JavaDoc JONAS_DEF_NAME = "jonas";
90
91     /**
92      * -Djonas.base property
93      */

94     private static final String JavaDoc JONAS_BASE = "jonas.base";
95     
96     /**
97      * configuration directory name (changed from 'config' to 'conf' !!)
98      */

99     private static final String JavaDoc CONFIG_DIR = "conf";
100
101     /**
102      * System properties
103      */

104     private static Properties JavaDoc systEnv = System.getProperties();
105
106     /**
107      * JONAS_BASE
108      */

109     private static String JavaDoc jonasBase = systEnv.getProperty(JONAS_BASE);
110
111     /**
112      * JONAS_ROOT
113      */

114     private static String JavaDoc installRoot = systEnv.getProperty("install.root");
115
116     /**
117      * Separator of file
118      */

119     private static String JavaDoc fileSeparator = systEnv.getProperty("file.separator");
120
121     /**
122      * User home directory
123      */

124     private static String JavaDoc homeUser = systEnv.getProperty("user.home");
125
126     /**
127      * Content of the file (xml)
128      */

129     private String JavaDoc configFileXml = null;
130
131     /**
132      * Properties of the config file
133      */

134     private Properties JavaDoc configFileEnv = new Properties JavaDoc();
135
136     /**
137      * System properties + properties of the file
138      */

139     private Properties JavaDoc allEnv = null;
140
141     /**
142      * Name of the property file
143      */

144     private String JavaDoc propFileName = null;
145
146     /**
147      * The JProp singleton for jonas.properties file
148      */

149     private static JProp unique = null;
150
151     /**
152      * The multiple JProp objects for the resources configuration files (resource.properties)
153      * the keys are the configuration file names and the values, the JProp objects
154      */

155     private static Hashtable JavaDoc multiple = new Hashtable JavaDoc();
156
157     /**
158      * Private constructor which reads a resource.properties file.
159      * @param fileName the file name to read (the resource name)
160      * @throws Exception if it fails
161      */

162     private JProp(String JavaDoc fileName) throws Exception JavaDoc {
163         readFile(fileName);
164     }
165
166     /**
167      * Private constructor which reads the JONAS properties file (jonas.properties).
168      * @throws Exception if it fails
169      */

170     private JProp() throws Exception JavaDoc {
171         readFile(JONASPREFIX);
172     }
173
174     /**
175      * private constructor which writes properties in the provided file.
176      * @param fileName the file name in which configuration properties are written
177      * @param props configuration properties used to initialize the resource
178      * @throws Exception if it fails
179      */

180     private JProp(String JavaDoc fileName, Properties JavaDoc props) throws Exception JavaDoc {
181         writePropsToFile(fileName, props);
182     }
183
184     /**
185      * private constructor which writes text in the provided file.
186      * @param fileName the file name in which configuration is written
187      * @param txt xml configuration for this resource
188      * @throws Exception if it fails
189      */

190     private JProp(String JavaDoc fileName, String JavaDoc txt) throws Exception JavaDoc {
191         writeXmlToFile(fileName, txt);
192     }
193
194     /**
195      * Get the unique instance corresponding to the JOnAS server.
196      * Create it at first call.
197      * @return unique instance corresponding to the JOnAS server.
198      * @throws Exception if no JProp can be built
199      */

200     public static JProp getInstance() throws Exception JavaDoc {
201         if (unique == null) {
202             unique = new JProp();
203         }
204         return unique;
205     }
206
207     /**
208      * Get one of the multiple instances corresponding to a given resource.
209      * Create it at first call with a given configuration file name
210      * @param fileName the name of the configuration file which is given by the resource name
211      * @return one of the multiple instances corresponding to a given resource.
212      * @throws Exception if no JProp can be built
213      */

214     public static JProp getInstance(String JavaDoc fileName) throws Exception JavaDoc {
215         if (!multiple.containsKey(fileName)) {
216             multiple.put(fileName, new JProp(fileName));
217         }
218         return (JProp) multiple.get(fileName);
219     }
220
221     /**
222      * Get one of the multiple instances corresponding to a given resource.
223      * Create it at first call with a given configuration file name
224      * @param fileName the name of the configuration file
225      * @param props the content of the configuration file to be written in fileName
226      * @return one of the multiple instances corresponding to a given resource.
227      * @throws Exception if no JProp can be built
228      */

229     public static JProp getInstance(String JavaDoc fileName, Properties JavaDoc props) throws Exception JavaDoc {
230         if (!multiple.containsKey(fileName)) {
231             multiple.put(fileName, new JProp(fileName, props));
232         }
233         return (JProp) multiple.get(fileName);
234     }
235
236     /**
237      * Write configuration properties in file getProperty(JONAS_BASE)/conf/fileName
238      * @param fileName name of the configuration file to write
239      * @param props Properties to register in the fileName file
240      * @throws Exception if it can't write to the specified file
241      */

242     private void writePropsToFile(String JavaDoc fileName, Properties JavaDoc props) throws Exception JavaDoc {
243
244         // Check the JONAS_BASE environment property
245
if (jonasBase == null) {
246             throw new Exception JavaDoc("JOnAS configuration error: environment property jonas.base not set!");
247         }
248         jonasBase = jonasBase.trim();
249
250         // JONAS_BASE/conf/fileName
251
propFileName = jonasBase + fileSeparator + CONFIG_DIR + fileSeparator + fileName + ".properties";
252
253         try {
254             FileOutputStream JavaDoc os = new FileOutputStream JavaDoc(propFileName);
255             props.store(os, "This file is generated by JOnAS");
256             os.close();
257         } catch (FileNotFoundException JavaDoc e) {
258             // File propFileName could not be opened
259
propFileName = null;
260             throw e;
261         }
262         configFileEnv = (Properties JavaDoc) props.clone();
263         allEnv = configFileEnv;
264     }
265
266
267     /**
268      * Write xml configuration in file getProperty(JONAS_BASE)/conf/fileName
269      * @param fileName name of the configuration file to write
270      * @param txt text to write
271      * @throws Exception if it can't write to the specified file
272      */

273     private void writeXmlToFile(String JavaDoc fileName, String JavaDoc txt) throws Exception JavaDoc {
274
275         // Check the JONAS_BASE environment property
276
if (jonasBase == null) {
277             throw new Exception JavaDoc("JOnAS configuration error: environment property jonas.base not set!");
278         }
279         jonasBase = jonasBase.trim();
280
281         // JONAS_BASE/conf/fileName
282
propFileName = jonasBase + fileSeparator + CONFIG_DIR + fileSeparator + fileName + ".properties";
283
284         try {
285             BufferedWriter JavaDoc out = new BufferedWriter JavaDoc(new FileWriter JavaDoc(new File JavaDoc(propFileName)));
286             out.write(txt);
287             out.flush();
288             out.close();
289         } catch (FileNotFoundException JavaDoc e) {
290             // File propFileName could not be opened
291
propFileName = null;
292             throw e;
293         }
294     }
295
296
297     /**
298      * Read the content of the specified file. It can be an xml or properties file
299      * @param fileName name of the properties configuration file to read
300      * @throws Exception if it fails
301      */

302     private void readFile(String JavaDoc fileName) throws Exception JavaDoc {
303
304         // Check the JONAS_BASE environment property
305
if (jonasBase == null) {
306             throw new Exception JavaDoc("JOnAS configuration error: environment property jonas.base not set!");
307         }
308         jonasBase = jonasBase.trim();
309
310         // JONAS_BASE/conf/fileName
311
String JavaDoc fileFullPathname = jonasBase + fileSeparator + CONFIG_DIR + fileSeparator + fileName;
312
313         if (fileFullPathname.toLowerCase().endsWith(".xml")) {
314             readXmlFile(fileFullPathname);
315         } else {
316             readPropsFile(fileFullPathname);
317         }
318     }
319
320
321     /**
322      * Read initial configuration properties in file getProperty(JONAS_BASE)/conf/fileName
323      * These properties may be overridden by system properties, provided on the java command line.
324      * @param fileName name of the configuration file to read
325      * @throws Exception if it fails
326      */

327     private void readPropsFile(String JavaDoc fileName) throws Exception JavaDoc {
328
329         // Update filename of this JProp
330
this.propFileName = fileName;
331
332         if (!fileName.endsWith(".properties")) {
333             propFileName += ".properties";
334         }
335
336         File JavaDoc f = null;
337         try {
338             f = new File JavaDoc(propFileName);
339             FileInputStream JavaDoc is = new FileInputStream JavaDoc(f);
340             configFileEnv.load(is);
341         } catch (FileNotFoundException JavaDoc e) {
342             throw new FileNotFoundException JavaDoc("Cannot find properties for " + propFileName);
343         } catch (IOException JavaDoc e) {
344             System.err.println(e);
345         }
346
347         allEnv = (Properties JavaDoc) configFileEnv.clone();
348         // Overriddes with syst properties
349
if (f.getName().equalsIgnoreCase("jonas.properties")) {
350             for (Enumeration JavaDoc e = systEnv.keys(); e.hasMoreElements();) {
351                 Object JavaDoc key = e.nextElement();
352                 String JavaDoc value = ((String JavaDoc) systEnv.get(key)).trim();
353                 allEnv.put(key, (Object JavaDoc) value);
354             }
355
356             String JavaDoc serverName;
357             if (!systEnv.containsKey(JONAS_NAME)) {
358                 allEnv.put(JONAS_NAME, JONAS_DEF_NAME);
359             }
360             serverName = ((String JavaDoc) allEnv.get(JONAS_NAME)).trim();
361
362             if (!allEnv.containsKey(DOMAIN_NAME) && !systEnv.containsKey(DOMAIN_NAME)) {
363                 allEnv.put(DOMAIN_NAME, serverName);
364             }
365         }
366     }
367
368     /**
369      * Read initial configuration in file getProperty(JONAS_BASE)/conf/fileName
370      * @param fileName name of the xml configuration file to read
371      * @throws Exception if it fails
372      */

373     private void readXmlFile(String JavaDoc fileName) throws Exception JavaDoc {
374
375         // Update filename of this JProp
376
this.propFileName = fileName;
377    
378         try {
379             File JavaDoc f = new File JavaDoc(propFileName);
380             int length = (int) f.length();
381             FileInputStream JavaDoc fis = new FileInputStream JavaDoc(f);
382             byte[] buffer = new byte[length];
383             fis.read(buffer);
384             fis.close();
385             configFileXml = new String JavaDoc(buffer);
386         } catch (FileNotFoundException JavaDoc e) {
387             throw new FileNotFoundException JavaDoc("Cannot find file " + propFileName);
388         } catch (IOException JavaDoc e) {
389             System.err.println(e);
390         }
391     }
392
393     /**
394      * Static method which return the JOnAS install root value.
395      * @return the JOnAS install root value.
396      */

397     public static String JavaDoc getInstallRoot() {
398         // Check install.root system property
399
if (installRoot == null) {
400             throw new RuntimeException JavaDoc("JOnAS configuration error: System property install.root not set!");
401         }
402         return installRoot;
403     }
404
405     /**
406      * Static method which return the jonas.base property
407      * @return the jonas.base property
408      */

409     public static String JavaDoc getJonasBase() {
410         return jonasBase;
411     }
412
413     /**
414      * Static method which return the working directory in jonas.base
415      * @return the jonas.base property
416      */

417     public static String JavaDoc getWorkDir() {
418         return jonasBase + File.separator + "work";
419     }
420
421     /**
422      * Returns properties filename
423      *
424      * @return JOnAS properties filename
425      */

426     public String JavaDoc getPropFile() {
427         return propFileName;
428     }
429
430     /**
431      * Returns JOnAS environment as configured with configuration file properties content and
432      * system properties.
433      * @return JOnAS properties
434      */

435     public Properties JavaDoc getEnv() {
436         return allEnv;
437     }
438
439
440     /**
441      * Returns JOnAS environment as configured with files properties only.
442      *
443      * @return JOnAS properties
444      */

445     public Properties JavaDoc getConfigFileEnv() {
446         return configFileEnv;
447     }
448
449     /**
450      * Returns xml content of the resource file
451      *
452      * @return xml content of the resource file
453      */

454     public String JavaDoc getConfigFileXml() {
455         return configFileXml;
456     }
457
458     /**
459      * Returns the value of the related property. With default values.
460      * @param key the search key
461      * @param defaultVal if the key is not found return this default value
462      * @return property value
463      */

464     public String JavaDoc getValue(String JavaDoc key, String JavaDoc defaultVal) {
465         String JavaDoc retProperty = allEnv.getProperty(key, defaultVal);
466         return retProperty.trim();
467     }
468
469     /**
470      * Returns the value of the related property.
471      * The method returns null if the property is not found.
472      * @param key the wanted key
473      * @return property value, null if not exist
474      */

475     public String JavaDoc getValue(String JavaDoc key) {
476
477         String JavaDoc retProperty = allEnv.getProperty(key);
478         if (retProperty != null) {
479             retProperty = retProperty.trim();
480         }
481         return retProperty;
482     }
483
484     /**
485      * Returns the value of the related property as boolean.
486      * @param key the wanted key
487      * @param def default run if not found
488      * @return property value, true or false.
489      */

490     public boolean getValueAsBoolean(String JavaDoc key, boolean def) {
491         boolean ret = def;
492         String JavaDoc value = this.getValue(key);
493         if (value != null && value.equalsIgnoreCase("true")) {
494             ret = true;
495         }
496         return ret;
497     }
498
499     /**
500      * Returns the value of the related property as String [].
501      * The method returns null if the property is not found.
502      * @param key the wanted key
503      * @return property value, null if not exist
504      */

505     public String JavaDoc[] getValueAsArray(String JavaDoc key) {
506
507         String JavaDoc [] res = null;
508         String JavaDoc value = this.getValue(key);
509         if (value != null) {
510             StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(value, ",");
511             res = new String JavaDoc [st.countTokens()];
512             int i = 0;
513             while (st.hasMoreTokens()) {
514                 res[i++] = st.nextToken().trim();
515             }
516         }
517         return res;
518     }
519
520     /**
521      * String representation of the object for trace purpose
522      * @return String representation of this object
523      */

524     public String JavaDoc toString() {
525         String JavaDoc s = new String JavaDoc();
526         for (Enumeration JavaDoc e = this.configFileEnv.keys(); e.hasMoreElements();) {
527             Object JavaDoc key = e.nextElement();
528             Object JavaDoc value = this.configFileEnv.get(key);
529             s = s.concat(" " + key + " = " + value + "\n");
530         }
531         if (s.length() > 0) {
532             // take of the last '\n'
533
s = s.substring(0, s.length() - 1);
534         }
535         return s;
536     }
537
538     /**
539      * Bind all the properties found in file properties in a naming context
540      * the naming context must be allocated by the caller
541      * @param ctx given context for bindings properties
542      * @throws Exception if it fails
543      */

544     public void env2Ctx(Context JavaDoc ctx) throws Exception JavaDoc {
545         Enumeration JavaDoc e = configFileEnv.propertyNames();
546         String JavaDoc key = null;
547         while (e.hasMoreElements()) {
548             key = (String JavaDoc) e.nextElement();
549             ctx.bind(key, configFileEnv.getProperty(key, ""));
550         }
551     }
552
553     /**
554      * Displays the JOnAS properties values, as they are set by the
555      * different property files.
556      * @param args the arguments for launching this program
557      */

558     public static void main(String JavaDoc args[]) {
559
560         JProp jonasProperties = null;
561         try {
562             jonasProperties = JProp.getInstance();
563         } catch (Exception JavaDoc e) {
564             System.err.println(e);
565             System.exit(2);
566         }
567         for (Enumeration JavaDoc e = jonasProperties.configFileEnv.keys(); e.hasMoreElements();) {
568             Object JavaDoc key = e.nextElement();
569             Object JavaDoc value = jonasProperties.configFileEnv.get(key);
570             System.out.println(key.toString() + "=" + value.toString());
571         }
572     }
573
574
575 }
576
Popular Tags