KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > jforum > util > preferences > SystemGlobals


1 /*
2  * Copyright (c) Rafael Steil
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms,
6  * with or without modification, are permitted provided
7  * that the following conditions are met:
8  *
9  * 1) Redistributions of source code must retain the above
10  * copyright notice, this list of conditions and the
11  * following disclaimer.
12  * 2) Redistributions in binary form must reproduce the
13  * above copyright notice, this list of conditions and
14  * the following disclaimer in the documentation and/or
15  * other materials provided with the distribution.
16  * 3) Neither the name of "Rafael Steil" nor
17  * the names of its contributors may be used to endorse
18  * or promote products derived from this software without
19  * specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT
22  * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
23  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
24  * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
25  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
27  * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES
30  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
32  * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
33  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
34  * IN CONTRACT, STRICT LIABILITY, OR TORT
35  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
36  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
37  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
38  *
39  * This file creating date: Feb 24, 2003 / 8:25:35 PM
40  * The JForum Project
41  * http://www.jforum.net
42  */

43 package net.jforum.util.preferences;
44
45 import java.io.File JavaDoc;
46 import java.io.FileInputStream JavaDoc;
47 import java.io.FileOutputStream JavaDoc;
48 import java.io.IOException JavaDoc;
49 import java.security.InvalidParameterException JavaDoc;
50 import java.util.ArrayList JavaDoc;
51 import java.util.Iterator JavaDoc;
52 import java.util.List JavaDoc;
53 import java.util.Properties JavaDoc;
54
55 import net.jforum.ConfigLoader;
56
57 import org.apache.log4j.Logger;
58
59 /**
60  * <p>Store global configurations used in the system.
61  * This is an helper class used to access the values
62  * defined at SystemGlobals.properties and related
63  * config files.</p>
64  *
65  * <p>
66  * Transient values are stored in a special place, and are not
67  * modified when you change a regular key's value.
68  * </p>
69  *
70  * @author Rafael Steil
71  * @author Pieter Olivier
72  * @version $Id: SystemGlobals.java,v 1.25 2005/08/29 02:13:22 rafaelsteil Exp $
73  */

74 public class SystemGlobals implements VariableStore
75 {
76     private static SystemGlobals globals = new SystemGlobals();
77
78     private String JavaDoc defaultConfig;
79     private String JavaDoc installationConfig;
80
81     private Properties JavaDoc defaults = new Properties JavaDoc();
82     private Properties JavaDoc installation = new Properties JavaDoc();
83     private static List JavaDoc additionalDefaultsList = new ArrayList JavaDoc();
84     private static Properties JavaDoc queries = new Properties JavaDoc();
85     private static Properties JavaDoc transientValues = new Properties JavaDoc();
86
87     private VariableExpander expander = new VariableExpander(this, "${", "}");;
88     
89     private static final Logger logger = Logger.getLogger(SystemGlobals.class);
90     
91     private SystemGlobals() {}
92
93     /**
94      * Initialize the global configuration
95      * @param appPath The application path (normally the path to the webapp base dir
96      * @param defaults The file containing system defaults (when null, defaults to <appPath>/WEB-INF/config/default.conf)
97      * @param installation The specific installation realm (when null, defaults to System.getProperty("user"))
98      */

99     public static void initGlobals(String JavaDoc appPath, String JavaDoc defaults) throws IOException JavaDoc
100     {
101         globals = new SystemGlobals();
102         globals.buildSystem(appPath, defaults);
103     }
104     
105     private void buildSystem(String JavaDoc appPath, String JavaDoc defaultConfig) throws IOException JavaDoc
106     {
107         if (defaultConfig == null) {
108             throw new InvalidParameterException JavaDoc("defaultConfig could not be null");
109         }
110
111         this.defaultConfig = defaultConfig;
112         this.defaults = new Properties JavaDoc();
113
114         this.defaults.put(ConfigKeys.APPLICATION_PATH, appPath);
115         this.defaults.put(ConfigKeys.DEFAULT_CONFIG, defaultConfig);
116         
117         SystemGlobals.loadDefaults();
118     
119         this.installation = new Properties JavaDoc();
120         this.installationConfig = getVariableValue(ConfigKeys.INSTALLATION_CONFIG);
121
122         for (Iterator JavaDoc iter = additionalDefaultsList.iterator(); iter.hasNext(); ) {
123             loadAdditionalDefaults((String JavaDoc)iter.next());
124         }
125         
126         if (new File JavaDoc(this.installationConfig).exists()) {
127             loadAdditionalDefaults(this.installationConfig);
128         }
129     }
130     
131     /**
132      * Sets a value for some property
133      *
134      * @param field The property name
135      * @param value The property value
136      * @see #getVariableValue(String)
137      * */

138     public static void setValue(String JavaDoc field, String JavaDoc value)
139     {
140         globals.installation.put(field, value);
141         globals.expander.clearCache();
142     }
143
144     /**
145      * Set a transient configuration value (a value that will not be saved)
146      * @param field The name of the configuration option
147      * @param value The value of the configuration option
148      */

149     public static void setTransientValue(String JavaDoc field, String JavaDoc value)
150     {
151         transientValues.put(field, value);
152     }
153
154     /**
155      * Load system defaults
156      *
157      * @throws IOException
158      */

159     public static void loadDefaults() throws IOException JavaDoc
160     {
161         FileInputStream JavaDoc input = new FileInputStream JavaDoc(globals.defaultConfig);
162         globals.defaults.load(input);
163         input.close();
164         globals.expander.clearCache();
165     }
166     
167     /**
168      * Merge additional configuration defaults
169      *
170      * @param file File from which to load the additional defaults
171      * @throws IOException
172      */

173     public static void loadAdditionalDefaults(String JavaDoc file) throws IOException JavaDoc
174     {
175         if (!new File JavaDoc(file).exists()) {
176             logger.info("Cannot find file " + file + ". Will ignore it");
177             return;
178         }
179         
180         FileInputStream JavaDoc input = new FileInputStream JavaDoc(file);
181         globals.installation.load(input);
182         input.close();
183         
184         if (!additionalDefaultsList.contains(file)) {
185             additionalDefaultsList.add(file);
186         }
187     }
188
189     /**
190      * Save installation defaults
191      *
192      * @throws IOException when the file could not be written
193      */

194     public static void saveInstallation() throws IOException JavaDoc
195     {
196         // We need this temporary "p" because, when
197
// new FileOutputStream() is called, it will
198
// raise an event to the TimerTask who is listen
199
// for file modifications, which then reloads the
200
// configurations from the filesystem, overwriting
201
// our new keys.
202
Properties JavaDoc p = new Properties JavaDoc();
203         p.putAll(globals.installation);
204         FileOutputStream JavaDoc out = new FileOutputStream JavaDoc(globals.installationConfig);
205         p.store(out, "Installation specific configuration options");
206         out.close();
207         
208         ConfigLoader.listenInstallationConfig();
209     }
210
211     /**
212      * Gets the value of some property
213      *
214      * @param field The property name to retrieve the value
215      * @return String with the value, or <code>null</code> if not found
216      * @see #setValue(String, String)
217      * */

218     public static String JavaDoc getValue(String JavaDoc field)
219     {
220         return globals.getVariableValue(field);
221     }
222     
223     public static String JavaDoc getTransientValue(String JavaDoc field)
224     {
225         return transientValues.getProperty(field);
226     }
227
228     /**
229      * Retrieve an integer-valued configuration field
230      *
231      * @param field Name of the configuration option
232      * @return The value of the configuration option
233      * @exception NullPointerException when the field does not exists
234      */

235     public static int getIntValue(String JavaDoc field)
236     {
237         return Integer.parseInt(getValue(field));
238     }
239
240     /**
241      * Retrieve an boolean-values configuration field
242      *
243      * @param field name of the configuration option
244      * @return The value of the configuration option
245      * @exception NullPointerException when the field does not exists
246      */

247     public static boolean getBoolValue(String JavaDoc field)
248     {
249         return "true".equals(getValue(field));
250     }
251
252     /**
253      * Return the value of a configuration value as a variable. Variable expansion is performe
254      * on the result.
255      *
256      * @param field The field name to retrieve
257      * @return The value of the field if present or null if not
258      */

259
260     public String JavaDoc getVariableValue(String JavaDoc field)
261     {
262         String JavaDoc preExpansion = globals.installation.getProperty(field);
263         
264         if (preExpansion == null) {
265             preExpansion = this.defaults.getProperty(field);
266
267             if (preExpansion == null) {
268                 return null;
269             }
270         }
271
272         return expander.expandVariables(preExpansion);
273     }
274
275     /**
276      * Sets the application's root directory
277      *
278      * @param ap String containing the complete path to the root dir
279      * @see #getApplicationPath
280      * */

281     public static void setApplicationPath(String JavaDoc ap)
282     {
283         setValue(ConfigKeys.APPLICATION_PATH, ap);
284     }
285
286     /**
287      * Getst the complete path to the application's root dir
288      *
289      * @return String with the path
290      * @see #setApplicationPath
291      * */

292     public static String JavaDoc getApplicationPath()
293     {
294         return getValue(ConfigKeys.APPLICATION_PATH);
295     }
296
297     /**
298      * Gets the path to the resource's directory.
299      * This method returns the directory name where the config
300      * files are stored.
301      * Caso queira saber o caminho absoluto do diretorio, voce precisa
302      * usar
303      * Note that this method does not return the complete path. If you
304      * want the full path, you must use
305      * <blockquote><pre>SystemGlobals.getApplicationPath() + SystemGlobals.getApplicationResourcedir()</pre></blockquote>
306      *
307      * @return String with the name of the resource dir, relative
308      * to application's root dir.
309      * @see #setApplicationResourceDir
310      * @see #getApplicationPath
311      * */

312     public static String JavaDoc getApplicationResourceDir()
313     {
314         return getValue(ConfigKeys.RESOURCE_DIR);
315     }
316
317     /**
318      * Load the SQL queries
319      *
320      * @param queryFile Complete path to the SQL queries file.
321      * @throws java.io.IOException
322      **/

323     public static void loadQueries(String JavaDoc queryFile) throws IOException JavaDoc
324     {
325         queries.load(new FileInputStream JavaDoc(queryFile));
326     }
327
328     /**
329      * Gets some SQL statement.
330      *
331      * @param sql The query's name, as defined in the file loaded by
332      * {@link #loadQueries(String)}
333      * @return The SQL statement, or <code>null</code> if not found.
334      * */

335     public static String JavaDoc getSql(String JavaDoc sql)
336     {
337         return queries.getProperty(sql);
338     }
339
340     /**
341      * Retrieve an iterator that iterates over all known configuration keys
342      *
343      * @return An iterator that iterates over all known configuration keys
344      */

345     public static Iterator JavaDoc fetchConfigKeyIterator()
346     {
347         return globals.defaults.keySet().iterator();
348     }
349     
350     public static Properties JavaDoc getConfigData()
351     {
352         return new Properties JavaDoc(globals.defaults);
353     }
354 }
Popular Tags