KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > snipsnap > config > ConfigurationMap


1 /*
2  * This file is part of "SnipSnap Wiki/Weblog".
3  *
4  * Copyright (c) 2002 Stephan J. Schmidt, Matthias L. Jugel
5  * All Rights Reserved.
6  *
7  * Please visit http://snipsnap.org/ for updates and contact.
8  *
9  * --LICENSE NOTICE--
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23  * --LICENSE NOTICE--
24  */

25 package org.snipsnap.config;
26
27 import org.snipsnap.app.Application;
28
29 import java.io.File JavaDoc;
30 import java.io.IOException JavaDoc;
31 import java.io.InputStream JavaDoc;
32 import java.io.OutputStream JavaDoc;
33 import java.net.InetAddress JavaDoc;
34 import java.net.MalformedURLException JavaDoc;
35 import java.net.URL JavaDoc;
36 import java.net.UnknownHostException JavaDoc;
37 import java.util.Iterator JavaDoc;
38 import java.util.Locale JavaDoc;
39 import java.util.Properties JavaDoc;
40
41 /**
42  * Implementation of a configuration map which is used as storage for configuration parameters.
43  * @see Configuration
44  * @version $Id: ConfigurationMap.java 1606 2004-05-17 10:56:18Z leo $
45  */

46 public class ConfigurationMap {
47
48   private final static String JavaDoc GLOBALS_CONF = "/org/snipsnap/config/globals.conf";
49   private final static String JavaDoc DEFAULTS_CONF = "/org/snipsnap/config/defaults.conf";
50   private final static String JavaDoc TRANSPOSE_MAP = "/org/snipsnap/config/transpose.map";
51
52
53   // local settings available for a specific instance
54
private Properties JavaDoc properties = null;
55   private Properties JavaDoc defaults = null;
56
57   // internal transposition map for old property file versions
58
private Properties JavaDoc transposeMap = null;
59
60   // static content, global values
61
private static File JavaDoc webInfDir = null;
62   private static Properties JavaDoc globals = null;
63   private static Properties JavaDoc globalDefaults = null;
64
65   // initialize global defaults and globals itself
66
static {
67     globalDefaults = new Properties JavaDoc();
68     try {
69       globalDefaults.load(ConfigurationMap.class.getResourceAsStream(GLOBALS_CONF));
70     } catch (IOException JavaDoc e) {
71       System.err.println("Configuration: unable to load global defaults: " + e.getMessage());
72     }
73     globals = new Properties JavaDoc(globalDefaults);
74   }
75
76   public void setGlobal(String JavaDoc name, String JavaDoc value) {
77     ConfigurationMap.globals.setProperty(name, value);
78   }
79
80   public String JavaDoc getGlobal(String JavaDoc name) {
81     String JavaDoc value = replaceTokens(ConfigurationMap.globals.getProperty(name));
82     return "".equals(value) ? null : value;
83   }
84
85   public String JavaDoc getGlobalDefault(String JavaDoc name) {
86     String JavaDoc value = globalDefaults.getProperty(name);
87     return ("".equals(value) ? null : value);
88   }
89
90
91   // get all properties
92
public Properties JavaDoc getGlobals() {
93     return globals;
94   }
95
96   // Globals handling
97
public void loadGlobals(InputStream JavaDoc stream) throws IOException JavaDoc {
98     ConfigurationMap.globals.load(stream);
99   }
100
101   public void storeGlobals(OutputStream JavaDoc stream) throws IOException JavaDoc {
102     ConfigurationMap.globals.store(stream, "SnipSnap Globals Configuration $Revision: 1606 $");
103   }
104
105   /**
106    * Sets the WEB-INF directory, where information is stored.
107    * @param dir
108    */

109   public void setWebInfDir(File JavaDoc dir) {
110     ConfigurationMap.webInfDir = dir;
111   }
112
113   /**
114    * Returns the configuration directory which is identical to the parent directory of the
115    * configuration file or null.
116    * @return the configuration directory
117    */

118   public File JavaDoc getWebInfDir() {
119     return ConfigurationMap.webInfDir;
120   }
121
122   public String JavaDoc getFileStore() {
123     return getFileStore((String JavaDoc)Application.get().getObject(Application.OID)).getPath();
124   }
125
126   public File JavaDoc getFileStore(String JavaDoc applicationOid) {
127     return new File JavaDoc(getGlobal(Globals.APP_FILE_STORE), applicationOid);
128   }
129
130   public String JavaDoc getVersion() {
131     String JavaDoc version = System.getProperty(ServerConfiguration.VERSION);
132     if (null == version) {
133       version = getGlobal(ServerConfiguration.VERSION);
134     }
135     return version;
136   }
137
138   /**
139    * Initialize new configuration map
140    * @param init
141    */

142   public ConfigurationMap(Configuration init) {
143     initDefaults();
144     webInfDir = init.getWebInfDir();
145     initialize((Properties JavaDoc) init.getProperties().clone());
146   }
147
148   public ConfigurationMap() {
149     initDefaults();
150     // instantiate properties with defaults
151
initialize((Properties JavaDoc) defaults.clone());
152   }
153
154   private void initDefaults() {
155     defaults = new Properties JavaDoc();
156     try {
157       defaults.load(Configuration.class.getResourceAsStream(DEFAULTS_CONF));
158     } catch (Exception JavaDoc e) {
159       System.err.println("Configuration: unable to load defaults: " + e.getMessage());
160     }
161   }
162
163   private void initialize(Properties JavaDoc initProperties) {
164     properties = initProperties;
165
166     try {
167       transposeMap = new Properties JavaDoc();
168       transposeMap.load(Configuration.class.getResourceAsStream(TRANSPOSE_MAP));
169     } catch (Exception JavaDoc e) {
170       System.err.println("Configuration: unable to load transposition map: " + e.getMessage());
171     }
172   }
173
174
175   /**
176    * Stores the configuration in a properties to the stream given.
177    * @param stream the output stream to write the configuration to
178    * @throws IOException
179    */

180   public void store(OutputStream JavaDoc stream) throws IOException JavaDoc {
181     properties.store(stream, "SnipSnap Configuration $Revision: 1606 $");
182   }
183
184   /**
185    * Load configuration from input stream. This method returns true if the load was
186    * successful as is and false if a change has occurred and the configuration should
187    * be stored back in its new form.
188    * @param stream the input stream where properties are contained
189    * @return true for as is loading and false for internally changed content
190    * @throws IOException
191    */

192   public boolean load(InputStream JavaDoc stream) throws IOException JavaDoc {
193     properties.load(stream);
194     return !convertOldProperties();
195   }
196
197   private boolean convertOldProperties() {
198     boolean hasChanged = false;
199     Iterator JavaDoc propIt = transposeMap.keySet().iterator();
200     while (propIt.hasNext()) {
201       String JavaDoc oldProperty = (String JavaDoc) propIt.next();
202       String JavaDoc newProperty = transposeMap.getProperty(oldProperty);
203       String JavaDoc value = properties.getProperty(oldProperty);
204       if (value != null) {
205         if (newProperty != null) {
206           if (newProperty.startsWith("@DEPRECATED")) {
207             if (convertDeprecatedProperty(oldProperty, value)) {
208               properties.remove(oldProperty);
209               hasChanged = true;
210             } else {
211               System.out.println("INFO: Configuration option '" + oldProperty + "' is deprecated:");
212               System.out.println("INFO: " + newProperty.substring("@DEPRECATED".length()));
213               System.out.println("INFO: Please edit configuration file manually.");
214             }
215           }
216           if (newProperty.startsWith("@DUPLICATE")) {
217             newProperty = newProperty.substring("@DUPLICATE".length());
218             String JavaDoc newValue = properties.getProperty(newProperty);
219             //System.out.println("INFO: "+newProperty+"="+newValue);
220
if (null == newValue || "".equals(newValue)) {
221               System.out.println("INFO: duplicating value of '" + oldProperty + "' to '" + newProperty + "'");
222               properties.setProperty(newProperty, value);
223               hasChanged = true;
224             }
225           } else {
226             System.out.println("INFO: converting '" + oldProperty + "' to '" + newProperty + "'");
227             properties.remove(oldProperty);
228             properties.setProperty(newProperty, value);
229             hasChanged = true;
230           }
231         }
232       }
233     }
234     return hasChanged;
235   }
236
237   private boolean convertDeprecatedProperty(String JavaDoc oldProperty, String JavaDoc value) {
238     if ("app.domain".equals(oldProperty) || "app.url".equals(oldProperty)) {
239       if (value != null && value.length() > 0) {
240         try {
241           URL JavaDoc url = new URL JavaDoc(value);
242           System.out.println("INFO: converting '" + oldProperty + "' to 'app.real.*'");
243           properties.setProperty(Configuration.APP_REAL_HOST, url.getHost());
244           if (url.getPort() >= 0 && url.getPort() != 80) {
245             properties.setProperty(Configuration.APP_REAL_PORT, "" + url.getPort());
246           }
247           properties.setProperty(Configuration.APP_REAL_PATH, url.getPath());
248         } catch (MalformedURLException JavaDoc e) {
249           System.out.println("WARNING: unable to convert '" + oldProperty + "': malformed URL: '" + value + "'");
250           return false;
251         }
252       }
253       return true;
254     }
255     return false;
256   }
257
258   /**
259    * Set configuration parameter.
260    * @param name the configuration parameter name as in Configuration interface
261    * @see Configuration
262    * @param value the new value
263    */

264   public void set(String JavaDoc name, String JavaDoc value) {
265     properties.setProperty(name, value);
266   }
267
268   /**
269    * Get configuration parameter. This method ensures that a parameter that is empty
270    * (null or null sized string) is returned as NULL.
271    * @param name the configuration parameter name as in Configuration interface
272    * @see Configuration
273    * @return the value of the configuration parameter
274    */

275   public String JavaDoc get(String JavaDoc name) {
276     String JavaDoc value = replaceTokens(properties.getProperty(name));
277     return "".equals(value) ? null : value;
278   }
279
280   // TODO replace with generic replacement method
281
private String JavaDoc replaceTokens(String JavaDoc value) {
282     if (value != null) {
283       int idx = value.indexOf("%WEBINF%");
284       if (idx != -1) {
285         StringBuffer JavaDoc replaced = new StringBuffer JavaDoc();
286         if (idx > 0) {
287           replaced.append(value.substring(0, idx));
288         }
289         replaced.append(getWebInfDir().getPath());
290         int endIdx = idx + "%WEBINF%".length();
291         if (endIdx < value.length()) {
292           replaced.append(value.substring(endIdx));
293         }
294         return replaced.toString();
295       }
296     }
297
298     return value;
299   }
300
301   public String JavaDoc get(String JavaDoc name, String JavaDoc defaultValue) {
302     String JavaDoc value = get(name);
303     if (value == null) {
304       return defaultValue;
305     }
306     return value;
307   }
308
309   public Properties JavaDoc getProperties() {
310     return properties;
311   }
312
313   public String JavaDoc getDefault(String JavaDoc name) {
314     String JavaDoc value = defaults.getProperty(name);
315     return ("".equals(value) ? null : value);
316   }
317
318   public File JavaDoc getFilePath(String JavaDoc applicationOid) {
319     return new File JavaDoc(getFileStore(applicationOid), "snips");
320   }
321
322   public File JavaDoc getFilePath() {
323     return getFilePath((String JavaDoc) Application.get().getObject(Application.OID));
324   }
325
326   public File JavaDoc getIndexPath() {
327     return new File JavaDoc(getFileStore(), "index");
328   }
329
330   public File JavaDoc getUserPath(String JavaDoc applicationOid) {
331     return new File JavaDoc(getFileStore(applicationOid), "users");
332   }
333
334   /**
335    * Create a real locale object from the strings in our configuration.
336    * @return the locale configured
337    */

338   public Locale JavaDoc getLocale() {
339     String JavaDoc language = get(Configuration.APP_LANGUAGE, "en");
340     String JavaDoc country = get(Configuration.APP_COUNTRY, "US");
341     return new Locale JavaDoc(language, country);
342   }
343
344   public String JavaDoc getPath() {
345     if ("true".equals(get(Configuration.APP_REAL_AUTODETECT))) {
346       String JavaDoc realPath = get(Configuration.APP_REAL_PATH);
347       if (null != realPath) {
348         return realPath;
349       }
350     }
351     return getGlobal(Globals.APP_PATH);
352   }
353
354   /**
355    * Return base url to Snipsnap instance
356    */

357   public String JavaDoc getUrl() {
358     URL JavaDoc url = (URL JavaDoc)Application.get().getObject(Application.URL);
359     if(null != url) {
360       return url.toExternalForm();
361     }
362
363     String JavaDoc prot = get(Configuration.APP_REAL_PROTOCOL, "http");
364     String JavaDoc host = get(Configuration.APP_REAL_HOST);
365     String JavaDoc port = get(Configuration.APP_REAL_PORT);
366     String JavaDoc path = get(Configuration.APP_REAL_PATH);
367
368     if (null == host) {
369       host = getGlobal(Globals.APP_HOST);
370       port = getGlobal(Globals.APP_PORT);
371       path = getGlobal(Globals.APP_PATH);
372     }
373
374     StringBuffer JavaDoc tmp = new StringBuffer JavaDoc();
375     tmp.append(prot).append("://");
376     try {
377       tmp.append(host == null || host.length() == 0 /*|| "localhost".equals(host)*/ ? InetAddress.getLocalHost().getHostName() : host);
378     } catch (UnknownHostException JavaDoc e) {
379       tmp.append(System.getProperty("host", "localhost"));
380     }
381     if (port != null && !"80".equals(port)) {
382       tmp.append(":");
383       tmp.append(port);
384     }
385     tmp.append(path != null ? path : "");
386     return tmp.toString();
387   }
388
389   /**
390    * Returns an external URL to this instance of SnipSnap
391    *
392    * @param target Path to add to url, e.g. "/exec/"
393    */

394   public String JavaDoc getUrl(String JavaDoc target) {
395     return getUrl() + target;
396   }
397
398   /**
399    * Returns an external URL of a snip
400    * @param snipName Name of the snip
401    */

402   public String JavaDoc getSnipUrl(String JavaDoc snipName) {
403     return getUrl("/space/" + snipName);
404   }
405
406   // PERMISSIONS
407
public boolean allow(String JavaDoc action) {
408     return "allow".equals(get(action));
409   }
410
411   public boolean deny(String JavaDoc action) {
412     return "deny".equals(get(action));
413   }
414
415   public boolean getAllowRegister() {
416     return !deny(Configuration.APP_PERM_REGISTER);
417   }
418
419   public boolean isConfigured() {
420     return "true".equals(properties.getProperty(Configuration.APP_CONFIGURED));
421   }
422
423   public boolean isInstalled() {
424     return "true".equals(ConfigurationMap.globals.getProperty(Globals.APP_INSTALLED));
425   }
426
427
428   public String JavaDoc toString() {
429     StringBuffer JavaDoc result = new StringBuffer JavaDoc();
430     Iterator JavaDoc it = properties.keySet().iterator();
431     result.append("{");
432     while (it.hasNext()) {
433       String JavaDoc key = (String JavaDoc) it.next();
434       result.append(key).append("=" + properties.get(key)).append(",");
435     }
436     result.append("}");
437     return result.toString();
438   }
439 }
440
Popular Tags