1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.struts2.config;
19
20 import java.io.IOException;
21 import java.net.URL;
22 import java.util.Iterator;
23 import java.util.Properties;
24
25 import org.apache.struts2.StrutsException;
26
27
28 /***
29 * A class to handle settings via a properties file.
30 */
31 public class PropertiesSettings extends Settings {
32
33 Properties settings;
34
35
36 /***
37 * Creates a new properties config given the name of a properties file. The name is expected to NOT have
38 * the ".properties" file extension. So when <tt>new PropertiesSettings("foo")</tt> is called
39 * this class will look in the classpath for the <tt>foo.properties</tt> file.
40 *
41 * @param name the name of the properties file, excluding the ".properties" extension.
42 */
43 public PropertiesSettings(String name) {
44 settings = new Properties();
45
46 URL settingsUrl = Thread.currentThread().getContextClassLoader().getResource(name + ".properties");
47
48 if (settingsUrl == null) {
49 throw new IllegalStateException(name + ".properties missing");
50 }
51
52
53 try {
54 settings.load(settingsUrl.openStream());
55 } catch (IOException e) {
56 throw new StrutsException("Could not load " + name + ".properties:" + e, e);
57 }
58 }
59
60
61 /***
62 * Sets a property in the properties file.
63 *
64 * @see #set(String, String)
65 */
66 public void setImpl(String aName, String aValue) {
67 settings.setProperty(aName, aValue);
68 }
69
70 /***
71 * Gets a property from the properties file.
72 *
73 * @see #get(String)
74 */
75 public String getImpl(String aName) throws IllegalArgumentException {
76 String setting = settings.getProperty(aName);
77
78 if (setting == null) {
79 throw new IllegalArgumentException("No such setting:" + aName);
80 }
81
82 return setting;
83 }
84
85 /***
86 * Tests to see if a property exists in the properties file.
87 *
88 * @see #isSet(String)
89 */
90 public boolean isSetImpl(String aName) {
91 if (settings.get(aName) != null) {
92 return true;
93 } else {
94 return false;
95 }
96 }
97
98 /***
99 * Lists all keys in the properties file.
100 *
101 * @see #list()
102 */
103 public Iterator listImpl() {
104 return settings.keySet().iterator();
105 }
106 }