View Javadoc

1   /*
2    * JDiskCatalog
3    *
4    * Copyright 2007 Przemek Więch
5    *
6    * This file is part of JDiskCatalog.
7    *
8    * JDiskCatalog is free software; you can redistribute it and/or modify
9    * it under the terms of the GNU General Public License as published by
10   * the Free Software Foundation; either version 2 of the License, or
11   * (at your option) any later version.
12   *
13   * This program is distributed in the hope that it will be useful,
14   * but WITHOUT ANY WARRANTY; without even the implied warranty of
15   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   * GNU General Public License for more details.
17  
18   * You should have received a copy of the GNU General Public License
19   * along with this program; if not, write to the Free Software
20   * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21   */
22  
23  package net.sf.jdiskcatalog.config;
24  
25  import java.io.FileInputStream;
26  import java.io.FileOutputStream;
27  import java.io.IOException;
28  import java.util.Collections;
29  import java.util.HashMap;
30  import java.util.Map;
31  import java.util.Properties;
32  
33  public class Configuration extends Properties
34  {
35  	/**
36  	 * Configuration file name.
37  	 */
38  	private static final String CONFIG_FILE = "config.xml";
39  
40  	private Map<String, Class> propertyTypes = new HashMap<String, Class>();
41  
42  	public void load()
43  	{
44  		try
45  		{
46  			loadFromXML(new FileInputStream(CONFIG_FILE));
47  		}
48  		catch (IOException e)
49  		{
50  			// config file not read. Default values will be used.
51  		}
52  	}
53  
54  	public void save() throws IOException
55  	{
56  		storeToXML(new FileOutputStream(CONFIG_FILE), "JDiskCatalog configuration");
57  	}
58  
59  	public Integer getInt(String key)
60  	{
61  		String value = getProperty(key);
62  		if (value == null)
63  			return null;
64  		return Integer.parseInt(value);
65  	}
66  
67  	public void set(String key, Object value)
68  	{
69  		setProperty(key, value.toString());
70  		propertyTypes.put(key, value.getClass());
71  	}
72  
73  	public Map<String, Class> getPropertyTypes()
74  	{
75  		return Collections.unmodifiableMap(propertyTypes);
76  	}
77  
78  	public void declareProperty(String key, Object value)
79  	{
80  		if (getProperty(key) == null)
81  			set(key, value);
82  		else if (propertyTypes.get(key) == null)
83  			propertyTypes.put(key, value.getClass());
84  	}
85  
86  	public void configure(Configurable configurable)
87  	{
88  		if (configurable.getDeclaredProperties() != null)
89  			for (Map.Entry<String, Object> entry : configurable.getDeclaredProperties().entrySet())
90  				declareProperty(entry.getKey(), entry.getValue());
91  		configurable.setConfiguration(this);
92  	}
93  }