001 package nl.cwi.sen1.util;
002
003 import java.awt.Color;
004 import java.awt.Font;
005 import java.io.File;
006 import java.io.FileInputStream;
007 import java.io.FileNotFoundException;
008 import java.io.IOException;
009 import java.io.InputStream;
010 import java.net.URL;
011 import java.util.Properties;
012
013 import javax.swing.Icon;
014 import javax.swing.ImageIcon;
015 import javax.swing.filechooser.FileSystemView;
016
017 // consider using java.util.prefs.Preferences as a replacement
018 public class Preferences {
019 private Properties properties;
020
021 public Preferences(InputStream propertyStream) {
022 Properties defaultProperties = readDefaultProperties(propertyStream);
023 this.properties = addUserProperties(defaultProperties);
024 }
025
026 private Properties readDefaultProperties(InputStream stream) {
027 Properties defaultProperties = new Properties();
028 loadProperties(defaultProperties, stream);
029 return defaultProperties;
030 }
031
032 private Properties addUserProperties(Properties defaultProperties) {
033 Properties props = new Properties(defaultProperties);
034
035 File homeDir = FileSystemView.getFileSystemView().getHomeDirectory();
036 File userPropertyFile = new File(homeDir, ".metarc");
037 if (userPropertyFile.canRead()) {
038 try {
039 loadProperties(props, new FileInputStream(userPropertyFile));
040 } catch (FileNotFoundException e) {
041 e.printStackTrace();
042 }
043 }
044
045 return props;
046 }
047
048 private Properties loadProperties(Properties props, InputStream stream) {
049 try {
050 props.load(stream);
051 } catch (IOException e) {
052 e.printStackTrace();
053 }
054 return props;
055 }
056
057 public String getString(String key) {
058 return properties.getProperty(key);
059 }
060
061 public void setString(String key, String value) {
062 properties.setProperty(key, value);
063 }
064
065 public Color getColor(String key) {
066 String spec = properties.getProperty(key);
067 return spec == null ? null : Color.decode(spec);
068 }
069
070 public Font getFont(String key) {
071 return Font.decode(getString(key));
072 }
073
074 public Icon getIcon(String key) {
075 String path = properties.getProperty(key);
076 URL url = path.getClass().getResource(path);
077
078 return url == null ? null : new ImageIcon(url);
079 }
080
081 public int getInt(String key) {
082 String spec = properties.getProperty(key);
083
084 return Integer.parseInt(spec);
085 }
086
087 public double getDouble(String key) {
088 String spec = properties.getProperty(key);
089 return Double.parseDouble(spec);
090 }
091
092 public float getFloat(String key) {
093 String spec = properties.getProperty(key);
094 return Float.parseFloat(spec);
095 }
096
097 public boolean getBoolean(String key) {
098
099 String spec = properties.getProperty(key);
100
101 return "true".equals(spec);
102 }
103 }