1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.ini4j;
17
18 import java.io.InputStream;
19
20 import java.net.URI;
21 import java.net.URL;
22
23 import java.util.Properties;
24 import java.util.prefs.Preferences;
25 import java.util.prefs.PreferencesFactory;
26
27 public class IniPreferencesFactory implements PreferencesFactory
28 {
29 public static final String PROPERTIES = "ini4j.properties";
30 public static final String KEY_USER = "org.ini4j.prefs.user";
31 public static final String KEY_SYSTEM = "org.ini4j.prefs.system";
32 private Preferences _system;
33 private Preferences _user;
34
35 @Override public synchronized Preferences systemRoot()
36 {
37 if (_system == null)
38 {
39 _system = newIniPreferences(KEY_SYSTEM);
40 }
41
42 return _system;
43 }
44
45 @Override public synchronized Preferences userRoot()
46 {
47 if (_user == null)
48 {
49 _user = newIniPreferences(KEY_USER);
50 }
51
52 return _user;
53 }
54
55 String getIniLocation(String key)
56 {
57 String location = Config.getSystemProperty(key);
58
59 if (location == null)
60 {
61 try
62 {
63 Properties props = new Properties();
64
65 props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(PROPERTIES));
66 location = props.getProperty(key);
67 }
68 catch (Exception x)
69 {
70 assert true;
71 }
72 }
73
74 return location;
75 }
76
77 URL getResource(String location) throws IllegalArgumentException
78 {
79 try
80 {
81 URI uri = new URI(location);
82 URL url;
83
84 if (uri.getScheme() == null)
85 {
86 url = Thread.currentThread().getContextClassLoader().getResource(location);
87 }
88 else
89 {
90 url = uri.toURL();
91 }
92
93 return url;
94 }
95 catch (Exception x)
96 {
97 throw (IllegalArgumentException) new IllegalArgumentException().initCause(x);
98 }
99 }
100
101 InputStream getResourceAsStream(String location) throws IllegalArgumentException
102 {
103 try
104 {
105 return getResource(location).openStream();
106 }
107 catch (Exception x)
108 {
109 throw (IllegalArgumentException) new IllegalArgumentException().initCause(x);
110 }
111 }
112
113 Preferences newIniPreferences(String key)
114 {
115 Ini ini = new Ini();
116 String location = getIniLocation(key);
117
118 if (location != null)
119 {
120 try
121 {
122 ini.load(getResourceAsStream(location));
123 }
124 catch (Exception x)
125 {
126 throw (IllegalArgumentException) new IllegalArgumentException().initCause(x);
127 }
128 }
129
130 return new IniPreferences(ini);
131 }
132 }