ConfigAccess.java
001 /* This file is part of the project "Hilbert II" - http://www.qedeq.org
002  *
003  * Copyright 2000-2011,  Michael Meyling <mime@qedeq.org>.
004  *
005  * "Hilbert II" is free software; you can redistribute
006  * it and/or modify it under the terms of the GNU General Public
007  * License as published by the Free Software Foundation; either
008  * version 2 of the License, or (at your option) any later version.
009  *
010  * This program is distributed in the hope that it will be useful,
011  * but WITHOUT ANY WARRANTY; without even the implied warranty of
012  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
013  * GNU General Public License for more details.
014  */
015 
016 package org.qedeq.kernel.se.config;
017 
018 import java.io.File;
019 import java.io.FileInputStream;
020 import java.io.FileOutputStream;
021 import java.io.IOException;
022 import java.io.InputStream;
023 import java.io.OutputStream;
024 import java.util.ArrayList;
025 import java.util.Collections;
026 import java.util.Enumeration;
027 import java.util.HashMap;
028 import java.util.Iterator;
029 import java.util.List;
030 import java.util.Map;
031 import java.util.Properties;
032 
033 import org.qedeq.base.io.IoUtility;
034 
035 
036 /**
037  * This class reads entries from property files. This class should not
038  * be used outside this package.
039  *
040  @version $Revision: 1.6 $
041  @author  Michael Meyling
042  */
043 final class ConfigAccess {
044 
045     /** Config file. */
046     private final File configFile;
047 
048     /** Collector for properties. */
049     private Properties properties = new Properties();
050 
051     /** Config file description. */
052     private final String description;
053 
054     /**
055      * Get access for a config file.
056      *
057      @param   configFile              Config file.
058      @param   description             Config file description
059      @throws  IOException             Config file couldn't be loaded.
060      */
061     public ConfigAccess(final File configFile, final String descriptionthrows IOException {
062         this.configFile = configFile;
063         this.description = description;
064         FileInputStream stream = null;
065         try {
066             stream = new FileInputStream(configFile);
067             load(stream);
068         catch (IOException e) {
069             System.out.println("no config file found, using default values");
070         finally {
071             IoUtility.close(stream);
072         }
073         setString("configFileLocation", configFile.getCanonicalPath());
074     }
075 
076     /**
077      * Get config file.
078      *
079      @return  Config file.
080      */
081     public final File getConfigFile() {
082         return configFile;
083     }
084 
085     /**
086      * Get description for config file.
087      *
088      @return  Config file description.
089      */
090     public final String getConfigDescription() {
091         return description;
092     }
093 
094     /**
095      * Get properties.
096      *
097      @return  properties.
098      */
099     private final Properties getProperties() {
100         return properties;
101     }
102 
103     /**
104      * Load properties from stream. The properties are
105      * added to the previous ones.
106      *
107      @param   inStream    load from this stream
108      @throws  IOException loading failed
109      */
110     private final void load(final InputStream inStreamthrows IOException {
111         getProperties().load(inStream);
112     }
113 
114     /**
115      * Store properties in config file.
116      *
117      @throws  IOException Saving failed.
118      */
119     public final void store() throws IOException {
120         OutputStream out = null;
121         try {
122             out = new FileOutputStream(getConfigFile());
123             getProperties().store(out, getConfigDescription());
124         finally {
125             if (out != null) {
126                 try {
127                     out.close();
128                 catch (IOException e) {
129                     throw e;
130                 catch (Exception e) {
131                     throw new IOException(e.toString());
132                 }
133             }
134         }
135     }
136 
137     /**
138      * Return String property.
139      *
140      @param   name    Get this property.
141      @return  String for looked property. <code>null</code>, if property is missing.
142      */
143     public final String getString(final String name) {
144         return getProperties().getProperty(name);
145     }
146 
147     /**
148      * Return String property.
149      *
150      @param   name            Look for this String property.
151      @param   defaultValue    Return this value if property doesn't exist.
152      @return  Value of property. Equal to default value if parameter doesn't exist.
153      */
154     public final String getString(final String name, final String defaultValue) {
155         final String value = getProperties().getProperty(name);
156         if (value == null) {
157             setString(name, defaultValue);
158             return defaultValue;
159         else {
160             return value;
161         }
162     }
163 
164     /**
165      * Set String property.
166      *
167      @param name   Set this property.
168      @param value  Set property to this value.
169      */
170     public final void setString(final String name, final String value) {
171         getProperties().setProperty(name, value);
172     }
173 
174     /**
175      * Get list of String properties with certain prefix.
176      * Example:
177      <ul>
178      <li>qeq=green</li>
179      <li>module2=tiger</li>
180      <li>module3=tulip</li>
181      <li>modula=green</li>
182      <li>module1=bluebird</li>
183      </ul>
184      * If namePrefix == "module" we get:
185      <ul>
186      <li>module1=bluebird</li>
187      <li>module2=tiger</li>
188      <li>module3=tulip</li>
189      </ul>
190      * The sequence of resulting properties is sorted by their keys.
191      *
192      @param   namePrefix  Prefix of seek property name.
193      @return  List of key sorted string properties (maybe empty).
194      */
195     public final String[] getStringProperties(final String namePrefix) {
196         final List list = new ArrayList();
197         final Enumeration keys = getProperties().keys();
198         final List keyList = Collections.list(keys);
199         Collections.sort(keyList);
200         for (int i = 0; i < keyList.size(); i++) {
201             final String key = (StringkeyList.get(i);
202             if (key.startsWith(namePrefix)) {
203                 list.add(getProperties().get(key));
204             }
205         }
206         return (String []) list.toArray(new String[list.size()]);
207     }
208 
209     /**
210      * Get map of String properties with certain prefix.
211      *
212      @param   namePrefix  Prefix of seek property name.
213      @return  Map of properties that have String keys that start with <code>namePrefix</code>.
214      *          The prefix is removed of for the resulting map.
215      */
216     public final Map getProperties(final String namePrefix) {
217         final Map result = new HashMap(getProperties());
218         Iterator i = getProperties().entrySet().iterator();
219         while (i.hasNext()) {
220             Map.Entry entry = (Map.Entryi.next();
221             final String name = String.valueOf(entry.getKey());
222             if (name.startsWith(namePrefix)) {
223                 result.put(name.substring(namePrefix.length()), entry.getValue());
224             }
225         }
226         return result;
227     }
228 
229     /**
230      * Set int property.
231      *
232      @param name   Set this property.
233      @param value  Set property to this value.
234      */
235     public final void setInteger(final String name, final int value) {
236         setString(name, "" + value);
237     }
238 
239 
240     /**
241      * Get int property.
242      *
243      @param   name    look for this property
244      @return  property
245      @throws  IllegalArgumentException    Property is no valid int value
246      @throws  NullPointerException        Property doesn't exist
247      */
248     public final int getInteger(final String name) {
249         final String intPropAsString = getProperties().getProperty(name);
250         if (intPropAsString != null) {
251             try {
252                 return Integer.parseInt(intPropAsString);
253             catch (NumberFormatException ex) {
254                 throw new IllegalArgumentException(
255                     "int property " + intPropAsString + " has invalid format");
256             }
257         else {
258             throw new NullPointerException("property \"" + name + "\" not found");
259         }
260     }
261 
262     /**
263      * Return int property.
264      *
265      @param   name            Look for this integer property.
266      @param   defaultValue    Return this value if property doesn't exist.
267      @return  int value of property. Equal to default value if parameter doesn't exist.
268      @throws  IllegalArgumentException    Property is no valid int value.
269      */
270     public final int getInteger(final String name, final int defaultValue) {
271         final String intPropAsString = getProperties().getProperty(name);
272         if (intPropAsString != null && intPropAsString.length() 0) {
273             try {
274                 return Integer.parseInt(intPropAsString);
275             catch (NumberFormatException ex) {
276                 throw new IllegalArgumentException(
277                     "Integer-Property " + intPropAsString + " has invalid format");
278             }
279         else {
280             setInteger(name, defaultValue);
281             return defaultValue;
282         }
283     }
284 
285     /**
286      * Remove property.
287      *
288      @param   name    Property to delete.
289      */
290     public final void removeProperty(final String name) {
291         getProperties().remove(name);
292     }
293 
294     /**
295      * Remove properties with certain prefix.
296      *
297      * Example:
298      <ul>
299      <li>module1=bluebird</li>
300      <li>module2=tiger</li>
301      <li>module3=tulip</li>
302      </ul>
303      * Calling with value <code>module</code> deletes all.
304      *
305      @param   namePrefix  Prefix of seeked property name.
306      */
307     public final void removeProperties(final String namePrefix) {
308         final Enumeration keys = getProperties().keys();
309         while (keys.hasMoreElements()) {
310             final String key = (Stringkeys.nextElement();
311             if (key.startsWith(namePrefix)) {
312                 getProperties().remove(key);
313             }
314         }
315     }
316 
317 }