KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hsqldb > persist > HsqlProperties


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

30
31
32 package org.hsqldb.persist;
33
34 import java.io.FileNotFoundException JavaDoc;
35 import java.io.IOException JavaDoc;
36 import java.io.InputStream JavaDoc;
37 import java.io.OutputStream JavaDoc;
38 import java.util.Enumeration JavaDoc;
39 import java.util.Properties JavaDoc;
40
41 import org.hsqldb.Trace;
42 import org.hsqldb.lib.ArrayUtil;
43 import org.hsqldb.lib.FileAccess;
44 import org.hsqldb.lib.FileUtil;
45 import org.hsqldb.lib.java.JavaSystem;
46
47 /**
48  * Wrapper for java.util.Properties to limit values to Specific types and
49  * allow saving and loading.<p>
50  *
51  * @author fredt@users
52  * @version 1.7.2
53  * @since 1.7.0
54  */

55 public class HsqlProperties {
56
57     public static final int NO_VALUE_FOR_KEY = 1;
58     protected String JavaDoc fileName;
59     protected Properties JavaDoc stringProps;
60     protected int[] errorCodes = new int[0];
61     protected String JavaDoc[] errorKeys = new String JavaDoc[0];
62     protected boolean resource = false;
63     protected FileAccess fa;
64
65     public HsqlProperties() {
66         stringProps = new Properties JavaDoc();
67         fileName = null;
68     }
69
70     public HsqlProperties(String JavaDoc name) {
71
72         stringProps = new Properties JavaDoc();
73         fileName = name;
74         fa = FileUtil.getDefaultInstance();
75     }
76
77     public HsqlProperties(String JavaDoc name, FileAccess accessor, boolean b) {
78
79         stringProps = new Properties JavaDoc();
80         fileName = name;
81         resource = b;
82         fa = accessor;
83     }
84
85     public HsqlProperties(Properties JavaDoc props) {
86         stringProps = props;
87     }
88
89     public void setFileName(String JavaDoc name) {
90         fileName = name;
91     }
92
93     public String JavaDoc setProperty(String JavaDoc key, int value) {
94         return setProperty(key, Integer.toString(value));
95     }
96
97     public String JavaDoc setProperty(String JavaDoc key, boolean value) {
98         return setProperty(key, String.valueOf(value));
99     }
100
101     public String JavaDoc setProperty(String JavaDoc key, String JavaDoc value) {
102         return (String JavaDoc) stringProps.put(key, value);
103     }
104
105     public String JavaDoc setPropertyIfNotExists(String JavaDoc key, String JavaDoc value) {
106
107         value = getProperty(key, value);
108
109         return setProperty(key, value);
110     }
111
112     public Properties JavaDoc getProperties() {
113         return stringProps;
114     }
115
116     public String JavaDoc getProperty(String JavaDoc key) {
117         return stringProps.getProperty(key);
118     }
119
120     public String JavaDoc getProperty(String JavaDoc key, String JavaDoc defaultValue) {
121         return stringProps.getProperty(key, defaultValue);
122     }
123
124     public int getIntegerProperty(String JavaDoc key, int defaultValue) {
125
126         String JavaDoc prop = getProperty(key);
127
128         try {
129             if (prop != null) {
130                 defaultValue = Integer.parseInt(prop);
131             }
132         } catch (NumberFormatException JavaDoc e) {}
133
134         return defaultValue;
135     }
136
137     public int getIntegerProperty(String JavaDoc key, int defaultValue, int minimum,
138                                   int maximum) {
139
140         String JavaDoc prop = getProperty(key);
141         boolean badvalue = false;
142
143         try {
144             defaultValue = Integer.parseInt(prop);
145         } catch (NumberFormatException JavaDoc e) {}
146
147         if (defaultValue < minimum) {
148             defaultValue = minimum;
149             badvalue = true;
150         } else if (defaultValue > maximum) {
151             defaultValue = maximum;
152             badvalue = true;
153         }
154
155         return defaultValue;
156     }
157
158     /**
159      * Choice limited to values list, defaultValue must be in the values list.
160      */

161     public int getIntegerProperty(String JavaDoc key, int defaultValue,
162                                   int[] values) {
163
164         String JavaDoc prop = getProperty(key);
165         int value = defaultValue;
166
167         try {
168             if (prop != null) {
169                 value = Integer.parseInt(prop);
170             }
171         } catch (NumberFormatException JavaDoc e) {}
172
173         if (ArrayUtil.find(values, value) == -1) {
174             return defaultValue;
175         }
176
177         return value;
178     }
179
180     public boolean isPropertyTrue(String JavaDoc key) {
181         return isPropertyTrue(key, false);
182     }
183
184     public boolean isPropertyTrue(String JavaDoc key, boolean defaultValue) {
185
186         String JavaDoc value = stringProps.getProperty(key);
187
188         if (value == null) {
189             return defaultValue;
190         }
191
192         return value.toLowerCase().equals("true");
193     }
194
195     public void removeProperty(String JavaDoc key) {
196         stringProps.remove(key);
197     }
198
199     public void addProperties(Properties JavaDoc props) {
200
201         if (props == null) {
202             return;
203         }
204
205         Enumeration JavaDoc keys = props.keys();
206
207         while (keys.hasMoreElements()) {
208             Object JavaDoc key = keys.nextElement();
209
210             this.stringProps.put(key, props.get(key));
211         }
212     }
213
214     public void addProperties(HsqlProperties props) {
215
216         if (props == null) {
217             return;
218         }
219
220         addProperties(props.stringProps);
221     }
222
223 // oj@openoffice.org
224
public boolean checkFileExists() throws IOException JavaDoc {
225
226         String JavaDoc propFilename = fileName + ".properties";
227
228         return fa.isStreamElement(propFilename);
229     }
230
231     public boolean load() throws Exception JavaDoc {
232
233         if (!checkFileExists()) {
234             return false;
235         }
236
237         if (fileName == null || fileName.length() == 0) {
238             throw new FileNotFoundException JavaDoc(
239                 Trace.getMessage(Trace.HsqlProperties_load));
240         }
241
242         InputStream JavaDoc fis = null;
243         String JavaDoc propsFilename = fileName + ".properties";
244
245 // oj@openoffice.org
246
try {
247             fis = resource ? getClass().getResourceAsStream(propsFilename)
248                            : fa.openInputStreamElement(propsFilename);
249
250             stringProps.load(fis);
251         } finally {
252             if (fis != null) {
253                 fis.close();
254             }
255         }
256
257         return true;
258     }
259
260     /**
261      * Saves the properties.
262      */

263     public void save() throws Exception JavaDoc {
264
265         if (fileName == null || fileName.length() == 0) {
266             throw new java.io.FileNotFoundException JavaDoc(
267                 Trace.getMessage(Trace.HsqlProperties_load));
268         }
269
270         String JavaDoc filestring = fileName + ".properties";
271
272         save(filestring);
273     }
274
275     /**
276      * Saves the properties using JDK2 method if present, otherwise JDK1.
277      */

278     public void save(String JavaDoc fileString) throws Exception JavaDoc {
279
280 // oj@openoffice.org
281
fa.createParentDirs(fileString);
282
283         OutputStream JavaDoc fos = fa.openOutputStreamElement(fileString);
284
285         JavaSystem.saveProperties(
286             stringProps,
287             HsqlDatabaseProperties.PRODUCT_NAME + " "
288             + HsqlDatabaseProperties.THIS_FULL_VERSION, fos);
289         fos.close();
290
291         return;
292     }
293
294     /**
295      * Adds the error code and the key to the list of errors. This list
296      * is populated during construction or addition of elements and is used
297      * outside this class to act upon the errors.
298      */

299     private void addError(int code, String JavaDoc key) {
300
301         errorCodes = (int[]) ArrayUtil.resizeArray(errorCodes,
302                 errorCodes.length + 1);
303         errorKeys = (String JavaDoc[]) ArrayUtil.resizeArray(errorKeys,
304                 errorKeys.length + 1);
305         errorCodes[errorCodes.length - 1] = code;
306         errorKeys[errorKeys.length - 1] = key;
307     }
308
309     /**
310      * Creates and populates an HsqlProperties Object from the arguments
311      * array of a Main method. Properties are in the form of "-key value"
312      * pairs. Each key is prefixed with the type argument and a dot before
313      * being inserted into the properties Object. <p>
314      *
315      * "-?" is treated as a key with no value and not inserted.
316      */

317     public static HsqlProperties argArrayToProps(String JavaDoc[] arg, String JavaDoc type) {
318
319         HsqlProperties props = new HsqlProperties();
320
321         for (int i = 0; i < arg.length; i++) {
322             String JavaDoc p = arg[i];
323
324             if (p.startsWith("-?")) {
325                 props.addError(NO_VALUE_FOR_KEY, p.substring(1));
326             } else if (p.charAt(0) == '-') {
327                 props.setProperty(type + "." + p.substring(1), arg[i + 1]);
328
329                 i++;
330             }
331         }
332
333         return props;
334     }
335
336     /**
337      * Creates and populates a new HsqlProperties Object using a string
338      * such as "key1=value1;key2=value2". <p>
339      *
340      * The string that represents the = sign above is specified as pairsep
341      * and the one that represents the semicolon is specified as delimiter,
342      * allowing any string to be used for either.<p>
343      *
344      * Leading / trailing spaces around the keys and values are discarded.<p>
345      *
346      * The string is parsed by (1) subdividing into segments by delimiter
347      * (2) subdividing each segment in two by finding the first instance of
348      * the pairsep (3) trimming each pair of segments from step 2 and
349      * inserting into the properties object.<p>
350      *
351      * Each key is prefixed with the type argument and a dot before being
352      * inserted.<p>
353      *
354      * Any key without a value is added to the list of errors.
355      */

356     public static HsqlProperties delimitedArgPairsToProps(String JavaDoc s,
357             String JavaDoc pairsep, String JavaDoc dlimiter, String JavaDoc type) {
358
359         HsqlProperties props = new HsqlProperties();
360         int currentpair = 0;
361
362         while (true) {
363             int nextpair = s.indexOf(dlimiter, currentpair);
364
365             if (nextpair == -1) {
366                 nextpair = s.length();
367             }
368
369             // find value within the segment
370
int valindex = s.substring(0, nextpair).indexOf(pairsep,
371                                        currentpair);
372
373             if (valindex == -1) {
374                 props.addError(NO_VALUE_FOR_KEY,
375                                s.substring(currentpair, nextpair).trim());
376             } else {
377                 String JavaDoc key = s.substring(currentpair, valindex).trim();
378                 String JavaDoc value = s.substring(valindex + pairsep.length(),
379                                            nextpair).trim();
380
381                 if (type != null) {
382                     key = type + "." + key;
383                 }
384
385                 props.setProperty(key, value);
386             }
387
388             if (nextpair == s.length()) {
389                 break;
390             }
391
392             currentpair = nextpair + dlimiter.length();
393         }
394
395         return props;
396     }
397
398     public Enumeration JavaDoc propertyNames() {
399         return stringProps.propertyNames();
400     }
401
402     public boolean isEmpty() {
403         return stringProps.isEmpty();
404     }
405
406     public String JavaDoc[] getErrorKeys() {
407         return errorKeys;
408     }
409 /*
410     public static void main(String[] argv) {
411
412         HsqlProperties props1 = delimitedArgPairsToProps("-dbname.0", "=",
413             ";", "server");
414         HsqlProperties props2 = delimitedArgPairsToProps(
415             "filename.cvs;a=123 ; b=\\delta ;c= another; derrorkey;", "=",
416             ";", "textdb");
417     }
418 */

419 }
420
Popular Tags