Revision 0:db30144f8f31

View differences:

.hgtags
1
440b3cf5fe0ed0142220153e9c5fd9817610c4e9 RELEASE_2.0.0
2
5c34b82fa00787c624b66c325a43a061f0a83fea RELEASE_3.0.0
3
6edb547ff3e49efaa31aa99fd0beda3f2eacf209 RELEASE_3.0.1
4
1934ee0c2818dd8613cb8ce7b66a1819fb6cede0 RELEASE_3.0.2
5
b07fc0b9ae6d7b5f8eda448e36a2e902da8f0e26 RELEASE_3.0.4
pom.xml
3 3
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4 4
    <modelVersion>4.0.0</modelVersion>
5 5

  
6
    <groupId>cz.agents.alite</groupId>
7
    <!--<version>3.0.4</version>-->
8
    <version>3.0-SNAPSHOT</version>
9
    <artifactId>configreader</artifactId>
6
    <groupId>cz.agents.alite.configreader</groupId>
7
    <version>0.0.1-SNAPSHOT</version>
8
    <artifactId>config</artifactId>
10 9
    <packaging>jar</packaging>
11
    
12
    <parent>
13
        <groupId>cz.agents</groupId>
14
        <artifactId>atgparent</artifactId>
15
        <version>1.1.0</version>
16
    </parent>
10

  
11
    <build>
12
        <plugins>
13
            <plugin>
14
                <groupId>org.apache.maven.plugins</groupId>
15
                <artifactId>maven-compiler-plugin</artifactId>
16
                <version>2.3.2</version>
17
                <configuration>
18
                    <source>1.6</source>
19
                    <target>1.6</target>
20
                </configuration>
21
            </plugin>
22
        </plugins>
23
    </build>
24

  
25
    <distributionManagement>
26
        <snapshotRepository>
27
            <uniqueVersion>true</uniqueVersion>
28
            <id>atg-repo</id>
29
            <name>jones.felk.cvut.cz-snapshots</name>
30
            <url>http://jones.felk.cvut.cz:8080/artifactory/libs-snapshot-local</url>
31
        </snapshotRepository>
32
    </distributionManagement>
17 33

  
18 34
    <name>Config Reader</name>
19 35
    <url>http://maven.apache.org</url>
20
    <description>
21
        Config Reader is small library built over Groovy utility ConfigSlurper. It provides convenient
22
        methods to read configuration files.
23
    </description>
24 36

  
25 37
    <properties>
26 38
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
......
28 40

  
29 41
    <dependencies>
30 42
        <dependency>
31
            <groupId>cz.agents.alite</groupId>
32
            <artifactId>alite</artifactId>
33
            <version>1.1.0</version>
34
        </dependency>
35
        <dependency>
36 43
            <groupId>org.codehaus.groovy</groupId>
37 44
            <artifactId>groovy</artifactId> 
38
            <version>2.2.2</version>
39
        </dependency>
40
        <dependency>
41
            <groupId>junit</groupId>
42
            <artifactId>junit</artifactId>
43
            <version>4.11</version>
44
            <scope>test</scope>
45
            <version>1.8.1</version> 
45 46
        </dependency>
46 47
    </dependencies>
47 48

  
src/main/java/cz/agents/alite/configreader/Config.java
1
package cz.agents.alite.configreader;
2

  
3
import java.math.BigDecimal;
4
import java.util.List;
5
import java.util.Map;
6

  
7
/**
8
 *
9
 * @author Ondrej Hrstka <hrstka at agents.felk.cvut.cz>
10
 */
11
public interface Config {
12

  
13
    /**
14
     * Returns true if Config contains key, else false
15
     * @param key
16
     * @return 
17
     */
18
    public boolean containsKey(String key);
19
    
20
    /**
21
     * Retrieves boolean value for given key.
22
     * @param key
23
     * @return
24
     * @throws IllegalArgumentException if value is not found or cannot be cast to boolean.
25
     */
26
    public boolean getBoolean(String key);
27

  
28
    /**
29
     * Retrieves boolean value for given key. If value is not found or cannot be
30
     * cast to boolean, defaultValue is returned
31
     * @param key
32
     * @param defaultValue
33
     * @return
34
     */
35
    public boolean getBoolean(String key, boolean defaultValue);
36

  
37
    /**
38
     * Retrieves double value for given key.
39
     * @param key
40
     * @return
41
     * @throws IllegalArgumentException if value is not found or cannot be cast to BigDecimal.
42
     */
43
    public double getDouble(String key);
44

  
45
    /**
46
     * Retrieves double value for given key. If value is not found or cannot be
47
     * cast to BigDecimal, defaultValue is returned
48
     * @param key
49
     * @param defaultValue
50
     * @return
51
     */
52
    public double getDouble(String key, double defaultValue);
53

  
54
    /**
55
     * Retrieves float value for given key.
56
     * @param key
57
     * @return
58
     * @throws IllegalArgumentException if value is not found or cannot be cast to BigDecimal.
59
     */
60
    public float getFloat(String key);
61

  
62
    /**
63
     * Retrieves integer value for given key. If value is not found or cannot be
64
     * cast to float, defaultValue is returned
65
     * @param key
66
     * @param defaultValue
67
     * @return
68
     */
69
    public float getFloat(String key, float defaultValue);
70

  
71
    /**
72
     * Retrieves integer value for given key.
73
     * @param key
74
     * @return
75
     * @throws IllegalArgumentException if value is not found or cannot be cast to integer.
76
     */
77
    public int getInt(String key);
78

  
79
    /**
80
     * Retrieves integer value for given key. If value is not found or cannot be
81
     * cast to integer, defaultValue is returned
82
     * @param key
83
     * @param defaultValue
84
     * @return
85
     */
86
    public int getInt(String key, int defaultValue);
87

  
88
    /**
89
     * Retrieves value for given key.
90
     * @param key
91
     * @return
92
     * @throws IllegalArgumentException if value is not found
93
     */
94
    public Object getObject(String key);
95

  
96
    /**
97
     * Retrieves value for given key. If value is not found, defaultValue is
98
     * returned
99
     * @param key
100
     * @param defaultValue
101
     * @return
102
     */
103
    public Object getObject(String key, Object defaultValue);
104

  
105
    /**
106
     * Gets sorted key list from {@link ConfigMap}
107
     * @return
108
     */
109
    public List<String> getSortedKeyList();
110

  
111
    /**
112
     * Retrieves String value for given key.
113
     * @param key
114
     * @return
115
     * @throws IllegalArgumentException if value is not found or cannot be cast to String.
116
     */
117
    public String getString(String key);
118

  
119
    /**
120
     * Retrieves String value for given key. If value is not found or cannot be
121
     * cast to String, defaultValue is returned
122
     * @param key
123
     * @param defaultValue
124
     * @return
125
     */
126
    public String getString(String key, String defaultValue);
127

  
128
    /**
129
     * Retrieves BigDecimal value for given key.
130
     * @param key
131
     * @return
132
     * @throws IllegalArgumentException if value is not found or cannot be cast to BigDecimal.
133
     */
134
    public BigDecimal getBigDecimal(String key);
135

  
136
    /**
137
     * Retrieves BigDecimal value for given key. If value is not found or cannot be
138
     * cast to BigDecimal, defaultValue is returned
139
     * @param key
140
     * @param defaultValue
141
     * @return
142
     */
143
    public BigDecimal getBigDecimal(String key, BigDecimal defaultValue);
144
    
145
    /**
146
     * Retrieves Map value for given key.
147
     * @param <TKey> type of maps key
148
     * @param <TValue> type of maps value
149
     * @param key 
150
     * @throws IllegalArgumentException if value is not found or cannot be cast to Map.
151
     * @return 
152
     */
153
    public <TKey, TValue> Map<TKey, TValue> getMap(String key);
154
    
155
    /**
156
     * Retrieves Map value for given key. If value is not found or cannot be
157
     * cast to Map, defaultValue is returned
158
     * @param <TKey> type of maps key
159
     * @param <TValue> type of maps value
160
     * @param key 
161
     * @return 
162
     */
163
    public <TKey, TValue> Map<TKey, TValue> getMap(String key, Map<TKey, TValue> defaultValue);
164
    
165
    /**
166
     * Retrieves subtree for given prefix.
167
     * @param prefix
168
     * @return 
169
     * @throws IllegalArgumentException if value with given prefix is not found.
170
     */
171
    public Config getSubTree(String prefix);
172
}
src/main/java/cz/agents/alite/configreader/ConfigMap.java
1 1
package cz.agents.alite.configreader;
2 2

  
3
import cz.agents.alite.configurator.ConfigurationInterface;
4 3
import groovy.util.ConfigObject;
5

  
6
import java.io.IOException;
7
import java.io.Writer;
8 4
import java.math.BigDecimal;
9 5
import java.util.ArrayList;
10
import java.util.HashMap;
6
import java.util.Collections;
11 7
import java.util.List;
12 8
import java.util.Map;
13 9

  
14 10
/**
15
 *
16
 * @author Ondrej Hrstka (ondrej.hrstka at agents.fel.cvut.cz)
11
 * Class that provides access to data retrieved from {@link AisConfig} object.
12
 * @author Ondrej Hrstka <hrstka at agents.felk.cvut.cz>
17 13
 */
18
class ConfigMap implements ConfigurationInterface {
14
public class ConfigMap implements Config {
19 15

  
20
    private final ConfigObject configObject;
21
    private final Map<String, Object> map;
16
    private ConfigObject configObject;
17
    private Map<String, Object> map;
22 18

  
23 19
    ConfigMap(ConfigObject configObject) {
24 20
        this.configObject = configObject;
25
        this.map = getFlattenMap(configObject);
26
    }
27

  
28
    private Map<String, Object> getFlattenMap(ConfigObject configObject) {
29
        Map<String, Object> out = new HashMap<String, Object>();
30
        String prefix = "";
31

  
32
        getFlattenMap(out, configObject, prefix);
33
        return out;
34
    }
35

  
36
    private void getFlattenMap(Map<String, Object> map, ConfigObject subTree, String prefix) {
37
        for (Object o : subTree.keySet()) {
38
            String key = (String) o;
39

  
40
            Object o1 = subTree.get(key);
41

  
42
            if (o1 instanceof ConfigObject) {
43
                ConfigObject subTree1 = (ConfigObject) o1;
44
                getFlattenMap(map, subTree1, prefix + "." + key);
45
            } else {
46
                map.put((prefix + "." + key).substring(1), o1);
47
            }
48
        }
49
    }
50

  
51
    @Override
52
    public void writeTo(Writer writer) {
53
        try {
54
            configObject.writeTo(writer);
55
        } catch (IOException e) {
56
            //HACK because of wrong ConfigurationInterface design we cannot throw IOException.
57
            //will be fixed with newer release of ConfigurationInterface
58
            throw new RuntimeException(e);
59
        }
21
        this.map = configObject.flatten();
60 22
    }
61 23

  
62 24
    @Override
63 25
    public boolean containsKey(String key) {
64
        return map.containsKey(key);
26
        return configObject.containsKey(key);
65 27
    }
66 28

  
67 29
    @Override
68 30
    public int getInt(String key) {
69 31
        int out;
70 32
        try {
71
            out = getNumber(key).intValue();
33
            out = (Integer) getObject(key);
72 34
            return out;
73 35
        } catch (ClassCastException ex) {
74 36
            throw new IllegalArgumentException("Item with key " + key + " cannot be cast to int");
......
79 41
    public int getInt(String key, int defaultValue) {
80 42
        Object o = getObjectOrNull(key);
81 43

  
82
        if (o == null || o instanceof Number == false) {
44
        if (o == null || o instanceof Integer == false) {
83 45
            return defaultValue;
84 46
        } else {
85
            return ((Number) o).intValue();
47
            return (Integer) o;
86 48
        }
87 49
    }
88 50

  
89 51
    @Override
90 52
    public float getFloat(String key) {
91
        return getNumber(key).floatValue();
53
        return getBigDecimal(key).floatValue();
92 54
    }
93 55

  
94 56
    @Override
95 57
    public float getFloat(String key, float defaultValue) {
96
        return getNumber(key, defaultValue).floatValue();
58
        Object o = getObjectOrNull(key);
59

  
60
        if (o == null || o instanceof BigDecimal == false) {
61
            return defaultValue;
62
        } else {
63
            return ((BigDecimal) o).floatValue();
64
        }
97 65
    }
98 66

  
99 67
    @Override
100 68
    public double getDouble(String key) {
101
        return getNumber(key).doubleValue();
69
        return getBigDecimal(key).doubleValue();
102 70
    }
103 71

  
104 72
    @Override
105 73
    public double getDouble(String key, double defaultValue) {
106
        return getNumber(key, defaultValue).doubleValue();
74
        Object o = getObjectOrNull(key);
75

  
76
        if (o == null || o instanceof BigDecimal == false) {
77
            return defaultValue;
78
        } else {
79
            return ((BigDecimal) o).doubleValue();
80
        }
107 81
    }
108 82

  
109 83
    @Override
......
130 104

  
131 105
    @Override
132 106
    public BigDecimal getBigDecimal(String key) {
133
        Number out = getNumber(key);
134
        if (out instanceof BigDecimal) {
135
            return (BigDecimal) out;
136
        } else {
107
        BigDecimal out;
108
        try {
109
            Object o = getObject(key);
110

  
111
            if (o instanceof Integer) {
112
                out = new BigDecimal((Integer) o);
113
            } else {
114
                out = (BigDecimal) o;
115
            }
116

  
117
            return out;
118
        } catch (ClassCastException ex) {
137 119
            throw new IllegalArgumentException("Item with key " + key + " cannot be cast to BigDecimal");
138 120
        }
139 121
    }
......
149 131
        }
150 132
    }
151 133

  
152
    public Number getNumber(String key) {
153
        Number out;
154
        try {
155
            out = (Number) getObject(key);
156
            return out;
157
        } catch (ClassCastException ex) {
158
            throw new IllegalArgumentException("Item with key " + key + " cannot be cast to Number");
159
        }
160
    }
161

  
162
    public Number getNumber(String key, Number defaultValue) {
163
        Object o = getObjectOrNull(key);
164

  
165
        if (o == null || o instanceof Number == false) {
166
            return defaultValue;
167
        } else {
168
            return (Number) o;
169
        }
170
    }
171

  
172 134
    @Override
173 135
    public Object getObject(String key) {
174 136
        if (!map.containsKey(key)) { // FIXED: Entry can be null!
......
190 152
    }
191 153

  
192 154
    @Override
193
    public List<String> getKeyList() {
155
    public List<String> getSortedKeyList() {
194 156
        List<String> list = new ArrayList<String>(map.keySet());
157
        Collections.sort(list);
195 158
        return list;
196 159
    }
197 160

  
......
219 182

  
220 183
    @Override
221 184
    public <TKey, TValue> Map<TKey, TValue> getMap(String key) {
222
        try {
223
            Map<TKey, TValue> out = (Map<TKey, TValue>) getObject(key);
224
            return out;
225
        } catch (ClassCastException ex) {
226
            throw new IllegalArgumentException("Item with key " + key + " cannot be cast to Map");
185
        if (configObject.containsKey(key)) {
186
            Object object = configObject.getProperty(key);
187
            try {
188
                Map<TKey, TValue> out = (Map<TKey, TValue>) object;
189
                return out;
190
            } catch (ClassCastException ex) {
191
                throw new IllegalArgumentException("Item with key " + key + " cannot be cast to Map");
192
            }
193

  
194
        } else {
195
            throw new IllegalArgumentException("Item with key " + key + " does not exist");
227 196
        }
228 197
    }
229 198

  
230 199
    @Override
231 200
    public <TKey, TValue> Map<TKey, TValue> getMap(String key, Map<TKey, TValue> defaultValue) {
232
        Object o = getObjectOrNull(key);
201
        if (configObject.containsKey(key)) {
202
            Object object = configObject.getProperty(key);
233 203

  
234
        if (o != null) {
235 204
            try {
236
                Map<TKey, TValue> out = (Map<TKey, TValue>) o;
205
                Map<TKey, TValue> out = (Map<TKey, TValue>) object;
237 206
                return out;
238 207
            } catch (ClassCastException ex) {
239 208
                return defaultValue;
......
244 213
    }
245 214

  
246 215
    @Override
247
    public <TValue> List<TValue> getList(String key) {
248
        try {
249
            List<TValue> out = (List<TValue>) getObject(key);
250
            return out;
251
        } catch (ClassCastException ex) {
252
            throw new IllegalArgumentException("Item with key " + key + " cannot be cast to List");
253
        }
254
    }
255

  
256
    @Override
257
    public <TValue> List<TValue> getList(String key, List<TValue> defaultValue) {
258
        Object o = getObjectOrNull(key);
259

  
260
        if (o != null) {
261
            try {
262
                List<TValue> out = (List<TValue>) o;
263
                return out;
264
            } catch (ClassCastException ex) {
265
                return defaultValue;
266
            }
267
        } else {
268
            return defaultValue;
269
        }
270
    }
271

  
272
    @Override
273
    public ConfigurationInterface getSubTree(String prefix) {
216
    public Config getSubTree(String prefix) {
274 217
        String[] keys = prefix.split("\\.");
275 218
        ConfigObject temp = configObject;
276 219
        for (String key : keys) {
src/main/java/cz/agents/alite/configreader/ConfigReader.java
1 1
package cz.agents.alite.configreader;
2 2

  
3
import cz.agents.alite.configurator.ConfigurationInterface;
4
import groovy.lang.GroovyClassLoader;
5
import groovy.lang.GroovyCodeSource;
6
import groovy.lang.GroovySystem;
7
import groovy.lang.Script;
8 3
import groovy.util.ConfigObject;
9 4
import groovy.util.ConfigSlurper;
10 5

  
11 6
import java.io.File;
12
import java.io.IOException;
13
import java.io.Writer;
14 7
import java.math.BigDecimal;
15 8
import java.net.MalformedURLException;
16 9
import java.net.URI;
17 10
import java.net.URL;
18
import java.nio.file.Files;
19
import java.nio.file.Paths;
20 11
import java.util.List;
21 12
import java.util.Map;
22 13

  
23 14
/**
24 15
 *
25
 * @author Ondrej Hrstka (ondrej.hrstka at agents.fel.cvut.cz)
16
 * @author Ondrej Hrstka <hrstka at agents.felk.cvut.cz>
26 17
 */
27
public class ConfigReader implements ConfigurationInterface {
18
public class ConfigReader implements Config {
28 19

  
29
    private final ConfigObject config;
30
    private final ConfigSlurper slurper;
20
    private ConfigObject config;
21
    private ConfigSlurper slurper;
31 22
    private boolean flatten;
32 23
    private ConfigMap configMap;
33
    private String source = "";
34 24

  
35 25
    public ConfigReader() {
36 26
        config = new ConfigObject();
37 27
        slurper = new ConfigSlurper();
38 28
        flatten = false;
39 29
    }
40
    
41
    @Override
42
    public void writeTo(Writer writer) {
43
        try {
44
            //HACK because of wrong ConfigurationInterface design we cannot throw IOException.
45
            //will be fixed with newer release of ConfigurationInterface
46
            config.writeTo(writer);
47
        } catch (IOException e) {
48
            throw new RuntimeException(e);
49
        }
50
    }
51

  
52
    public String getSourceConfig() {
53
        return source;
54
    }
55 30

  
56 31
    @Override
57 32
    public int getInt(String key) {
......
126 101
    }
127 102
    
128 103
    @Override
129
    public List<String> getKeyList() {
104
    public List<String> getSortedKeyList() {
130 105
        ensureConfigMap();
131
        return configMap.getKeyList();
106
        return configMap.getSortedKeyList();
132 107
    }
133 108

  
134 109
    @Override
......
143 118
        return configMap.getBigDecimal(key, defaultValue);
144 119
    }
145 120

  
146
    @Override
147
    public <TKey, TValue> Map<TKey, TValue> getMap(String key) {
148
        ensureConfigMap();
149
        return configMap.getMap(key);
150
    }
151 121

  
152 122
    @Override
153
    public <TKey, TValue> Map<TKey, TValue> getMap(String key, Map<TKey, TValue> defaultValue) {
154
        ensureConfigMap();
155
        return configMap.getMap(key, defaultValue);
156
    }
157

  
158
    @Override
159
    public <TValue> List<TValue> getList(String key) {
160
        ensureConfigMap();
161
        return configMap.getList(key);
162
    }
163

  
164
    @Override
165
    public <TValue> List<TValue> getList(String key, List<TValue> defaultValue) {
166
        ensureConfigMap();
167
        return configMap.getList(key, defaultValue);
168
    }
169

  
170
    @Override
171
    public ConfigurationInterface getSubTree(String prefix) {
123
    public Config getSubTree(String prefix) {
172 124
        ensureConfigMap();
173 125
        return configMap.getSubTree(prefix);
174 126
    }
175 127

  
176 128
    /**
177 129
     * Loads config script and merge it into config object
178
     * @param scriptText String containing script to be loaded
130
     * @param script String containing script to be loaded
179 131
     */
180
    public void loadAndMergeScriptText(String scriptText) {
181
        //This ugly code is because of the bug in ConfigSlurper class.
182
        //See http://groovy.329449.n5.nabble.com/ConfigSlurper-GroovyClassLoader-memory-leak-td364279.html
183
        // for details
184

  
185
        GroovyClassLoader classLoader = new GroovyClassLoader();
186
        Script script = null;
187
        try {
188
            script = (Script) classLoader.parseClass(scriptText).newInstance();
189
        }  catch (InstantiationException e) {
190
            throw new ConfigurationLoadException(e);
191
        } catch (IllegalAccessException e) {
192
            throw new ConfigurationLoadException(e);
193
        }
194

  
195
        ConfigObject configObject = slurper.parse(script);
196
        config.merge(configObject);
132
    public void loadString(String script) {
133
        config.merge(slurper.parse(script));
197 134
        flatten = false;
198

  
199
        GroovySystem.getMetaClassRegistry().removeMetaClass(script.getClass());
200
        classLoader.clearCache();
201

  
202
        appendToSource(scriptText);
203 135
    }
204 136

  
205 137
    /**
206 138
     * Loads config script and merge it into config object
207 139
     * @param file filename of config script
208 140
     */
209
    public void loadAndMerge(String file) {
210
        loadAndMerge(new File(file));
141
    public void loadFile(String file) throws MalformedURLException {
142
        loadFile(new File(file));
211 143
    }
212 144

  
213 145
    /**
214 146
     * Loads config script and merge it into config object
215 147
     * @param file file with configuration
216 148
     */
217
    public void loadAndMerge(File file) {
218
        loadAndMerge(file.toURI());
149
    public void loadFile(File file) throws MalformedURLException {
150
        loadFile(file.toURI());
219 151
    }
220 152

  
221 153
    /**
222 154
     * Loads config script and merge it into config object
223 155
     * @param file uri to configuration file
224 156
     */
225
    public void loadAndMerge(URI file) {
226
        //This ugly code is because of the bug in ConfigSlurper class.
227
        //See http://groovy.329449.n5.nabble.com/ConfigSlurper-GroovyClassLoader-memory-leak-td364279.html
228
        // for details
229

  
230
        URL url;
231
        try {
232
            url = file.toURL();
233
        } catch (MalformedURLException e) {
234
            throw new ConfigurationLoadException();
235
        }
236

  
237
        GroovyClassLoader classLoader = new GroovyClassLoader();
238
        GroovyCodeSource codeSource;
239
        Script script;
240
        try {
241
            codeSource = new GroovyCodeSource(url);
242
            script = (Script) classLoader.parseClass(codeSource).newInstance();
243
        } catch (IOException | InstantiationException | IllegalAccessException e) {
244
            throw new ConfigurationLoadException(e);
245
        }
246

  
247
        ConfigObject configObject = slurper.parse(script);
248
        config.merge(configObject);
157
    public void loadFile(URI file) throws MalformedURLException {
158
        URL url = file.toURL();
159
        config.merge(slurper.parse(url));
249 160
        flatten = false;
250

  
251
        GroovySystem.getMetaClassRegistry().removeMetaClass(script.getClass());
252
        classLoader.clearCache();
253

  
254
        try {
255
            List<String> data = Files.readAllLines(Paths.get(file));
256
            appendToSource(String.join("\n", data));
257
        } catch (IOException e) {
258
            throw new ConfigurationLoadException(e);
259
        }
260
    }
261

  
262
    private void appendToSource(String toAppend) {
263
        if (source.isEmpty()) {
264
            source = toAppend;
265
        } else {
266
            source = source + "\n" + toAppend;
267
        }
268 161
    }
269 162

  
270 163
    private void ensureConfigMap() {
......
279 172
        ensureConfigMap();
280 173
        return configMap.containsKey(key);
281 174
    }
175

  
176
    @Override
177
    public <TKey, TValue> Map<TKey, TValue> getMap(String key) {
178
        ensureConfigMap();
179
        return configMap.getMap(key);
180
    }
181

  
182
    @Override
183
    public <TKey, TValue> Map<TKey, TValue> getMap(String key, Map<TKey, TValue> defaultValue) {
184
        ensureConfigMap();
185
        return configMap.getMap(key, defaultValue);
186
    }
282 187
}
src/main/java/cz/agents/alite/configreader/ConfigurationLoadException.java
1
package cz.agents.alite.configreader;
2

  
3
/**
4
 * @author Ondrej Hrstka (ondrej.hrstka at agents.fel.cvut.cz)
5
 */
6
public class ConfigurationLoadException extends RuntimeException {
7

  
8
    public ConfigurationLoadException() {
9
    }
10

  
11
    public ConfigurationLoadException(String message) {
12
        super(message);
13
    }
14

  
15
    public ConfigurationLoadException(String message, Throwable cause) {
16
        super(message, cause);
17
    }
18

  
19
    public ConfigurationLoadException(Throwable cause) {
20
        super(cause);
21
    }
22
}
src/test/java/cz/agents/alite/configreader/ConfigTest.java
1
package cz.agents.alite.configreader;
2

  
3
import cz.agents.alite.configurator.ConfigurationInterface;
4
import org.junit.Before;
5
import org.junit.ComparisonFailure;
6
import org.junit.Test;
7

  
8
import java.io.ByteArrayOutputStream;
9
import java.io.IOException;
10
import java.io.OutputStreamWriter;
11
import java.math.BigDecimal;
12
import java.net.URI;
13
import java.net.URISyntaxException;
14
import java.nio.file.Files;
15
import java.nio.file.Paths;
16
import java.util.*;
17

  
18
import static org.junit.Assert.*;
19

  
20
/**
21
 * @author Ondrej Hrstka <hrstka at agents.felk.cvut.cz>
22
 */
23
public class ConfigTest {
24

  
25
    private static final double DOUBLE_DELTA = 0.00000000001;
26
    private static final float FLOAT_DELTA = (float)0.000001;
27
    public static final double SOME_DOUBLE = 3.14159265358;
28
    public static final double DOUBLE_DEFAULT = 2.718281828459045;
29
    public static final float FLOAT_DEFAULT = (float) 2.71;
30
    public static final float SOME_FLOAT = 3.14f;
31
    public static final int INT_DEFAULT = 21;
32
    public static final int SOME_INT = 42;
33
    public static final String TEST_CONFIG_FILE = "/TestConfig.groovy";
34

  
35
    private ConfigReader testConfig;
36
    private final String[] shortKeysArray = new String[]{"someInt", "someIntDoubleFormat", "someFloat", "someDouble", "someBoolean",
37
            "someObject", "someString", "someMap", "mapStringString", "someList", "anotherObject"};
38

  
39
    @Before
40
    public void setUp() throws Exception {
41
        URI file = ConfigTest.class.getResource(TEST_CONFIG_FILE).toURI();
42
        testConfig = new ConfigReader();
43
        testConfig.loadAndMerge(file);
44
    }
45

  
46
    @Test
47
    public void testWriteTo() throws Exception {
48
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
49
        OutputStreamWriter writer = new OutputStreamWriter(bos);
50
        testConfig.writeTo(writer);
51
        writer.close();
52
        
53
        ConfigReader readConfig = new ConfigReader();
54
        readConfig.loadAndMergeScriptText(new String(bos.toByteArray()));
55

  
56
        for (String key : testConfig.getKeyList()) {
57
            assertEquals(testConfig.getObject(key), readConfig.getObject(key));
58
        }
59
    }
60

  
61
    @Test
62
    public void getSourceConfig() throws IOException, URISyntaxException {
63
        byte[] expected = Files.readAllBytes(Paths.get(ConfigTest.class.getResource(TEST_CONFIG_FILE).toURI()));
64
        byte[] actual = testConfig.getSourceConfig().getBytes();
65
        assertArrayEquals(expected, actual);
66
    }
67

  
68
    @Test
69
    public void getSourceConfigWithLoadAndMerge() throws IOException, URISyntaxException {
70
        URI uri = ConfigTest.class.getResource(TEST_CONFIG_FILE).toURI();
71
        String scriptText = "a.b.c=4;";
72

  
73

  
74
        List<String> expected = new ArrayList<>(Files.readAllLines(Paths.get(uri)));
75
        expected.add(scriptText);
76

  
77
        testConfig.loadAndMergeScriptText(scriptText);
78

  
79
        String actual = testConfig.getSourceConfig();
80
        assertEquals(String.join("\n", expected), actual);
81
    }
82

  
83
    @Test
84
    public void testGetInt() throws Exception {
85
        int testInt = testConfig.getInt(getWholeKey("someInt"));
86
        assertEquals(SOME_INT, testInt);
87
    }
88

  
89
    @Test
90
    public void testGetIntWithDefaultValueCall() {
91
        int testInt = testConfig.getInt(getWholeKey("someInt"), INT_DEFAULT);
92
        assertEquals(SOME_INT, testInt);
93
    }
94

  
95
    @Test
96
    public void testGetIntDefault() throws Exception {
97
        int testInt = testConfig.getInt(getWholeKey("nonExistentInt"), INT_DEFAULT);
98
        assertEquals(INT_DEFAULT, testInt);
99
    }
100

  
101
    @Test
102
    public void testGetIntDoubleFormat() throws Exception {
103
        int testInt = testConfig.getInt(getWholeKey("someIntDoubleFormat"));
104
        assertEquals(SOME_INT, testInt);
105
    }
106

  
107
    @Test
108
    public void testGetFloat() throws Exception {
109
        float testFloat = testConfig.getFloat(getWholeKey("someFloat"));
110
        assertEquals(SOME_FLOAT, testFloat, FLOAT_DELTA);
111
    }
112

  
113
    @Test
114
    public void testGetFloatDefault() throws Exception {
115
        float testFloat = testConfig.getFloat(getWholeKey("nonExistentFloat"), FLOAT_DEFAULT);
116
        assertEquals(FLOAT_DEFAULT, testFloat, FLOAT_DELTA);
117
    }
118

  
119
    @Test
120
    public void testGetFloatWithDefaultValueCall() {
121
        float testFloat = testConfig.getFloat(getWholeKey("someFloat"), FLOAT_DEFAULT);
122
        assertEquals(SOME_FLOAT, testFloat, FLOAT_DELTA);
123
    }
124

  
125
    @Test
126
    public void testGetDouble() throws Exception {
127
        double testDouble = testConfig.getDouble(getWholeKey("someDouble"));
128
        assertEquals(SOME_DOUBLE, testDouble, DOUBLE_DELTA);
129
    }
130

  
131
    @Test
132
    public void testGetDoubleDefault() throws Exception {
133
        double testDouble = testConfig.getDouble(getWholeKey("nonExistentDouble"), DOUBLE_DEFAULT);
134
        assertEquals(DOUBLE_DEFAULT, testDouble, DOUBLE_DELTA);
135
    }
136

  
137
    @Test
138
    public void testGetDoubleWithDefaultValueCall() {
139
        double testDouble = testConfig.getDouble(getWholeKey("someDouble"), DOUBLE_DEFAULT);
140
        assertEquals(SOME_DOUBLE, testDouble, DOUBLE_DELTA);
141
    }
142

  
143
    @Test
144
    public void testGetBoolean() throws Exception {
145
        boolean someBoolean = testConfig.getBoolean(getWholeKey("someBoolean"));
146
        assertEquals(true, someBoolean);
147
    }
148

  
149
    @Test
150
    public void testGetBooleanDefault() throws Exception {
151
        boolean someBoolean = testConfig.getBoolean("nonExistentBoolean", true);
152
        assertEquals(true, someBoolean);
153
    }
154

  
155
    @Test
156
    public void testGetObject() throws Exception {
157
        Object someObject = testConfig.getObject(getWholeKey("someObject"));
158
        assertEquals(Arrays.asList(new String[]{"HelloWorld", "BlaBlaBla"}), someObject);
159
    }
160

  
161
    @Test
162
    public void testGetObjectDefault() throws Exception {
163
        Object trueObject = new Object();
164
        Object someObject = testConfig.getObject("nonExistentObject", trueObject);
165
        assertEquals(trueObject, someObject);
166
    }
167

  
168
    @Test
169
    public void testGetString() throws Exception {
170
        String someString = testConfig.getString(getWholeKey("someString"));
171
        assertEquals("ConfigReaderIsTheBest", someString);
172
    }
173

  
174
    @Test
175
    public void testGetStringDefault() throws Exception {
176
        String someString = testConfig.getString("nonExistentString", "defaultString");
177
        assertEquals("defaultString", someString);
178
    }
179

  
180
    @Test
181
    public void testGetSortedKeyList() throws Exception {
182
        List<String> keysList = new ArrayList<String>(shortKeysArray.length);
183
        for (String shortKey : shortKeysArray) {
184
            keysList.add(getWholeKey(shortKey));
185
        }
186
        Collections.sort(keysList);
187

  
188
        List<String> keyList = testConfig.getKeyList();
189
        Collections.sort(keyList);
190

  
191
        assertEquals(keysList, keyList);
192
    }
193

  
194
    @Test
195
    public void testGetBigDecimal() throws Exception {
196
        BigDecimal someBigDecimal = testConfig.getBigDecimal(getWholeKey("someDouble"));
197
        testBigDecimals(new BigDecimal(SOME_DOUBLE), someBigDecimal, DOUBLE_DELTA);
198
    }
199

  
200
    @Test
201
    public void testGetBigDecimalDefault() throws Exception {
202
        BigDecimal someBigDecimal = testConfig.getBigDecimal(getWholeKey("nonExistentDouble"), new BigDecimal(DOUBLE_DEFAULT));
203
        testBigDecimals(new BigDecimal(DOUBLE_DEFAULT), someBigDecimal, DOUBLE_DELTA);
204
    }
205

  
206
    @Test
207
    public void testGetMap() throws Exception {
208
        Map<String, Integer> map = new HashMap<String, Integer>();
209
        map.put("key1", 12);
210
        map.put("key2", 24);
211
        map.put("key3", 36);
212

  
213
        Map<String, Integer> someMap = testConfig.getMap(getWholeKey("someMap"));
214
        assertEquals(map, someMap);
215
    }
216

  
217
    @Test
218
    public void testGetMapStringString() throws Exception {
219
        Map<String, String> map = new HashMap<String, String>();
220
        map.put("key1String", "value1");
221
        map.put("key2String", "value2");
222
        map.put("key3String", "value3");
223

  
224
        Map<String, String> someMap = testConfig.getMap(getWholeKey("mapStringString"));
225
        assertEquals(map, someMap);
226
    }
227

  
228
    @Test
229
    public void testGetMapDefault() throws Exception {
230
        Map<String, Integer> map = new HashMap<String, Integer>();
231
        map.put("key1", 1);
232
        map.put("key2", 2);
233
        map.put("key3", 3);
234

  
235
        Map<String, Integer> someMap = testConfig.getMap("nonExistentMap", map);
236
        assertEquals(map, someMap);
237
    }
238

  
239
    @Test
240
    public void testGetSubTree() throws Exception {
241
        ConfigurationInterface subTree = testConfig.getSubTree("a");
242
        ConfigReader expectedSubTree = new ConfigReader();
243
        expectedSubTree.loadAndMerge(ConfigTest.class.getResource("/TestSubTree.groovy").toURI());
244

  
245
        for (String key : expectedSubTree.getKeyList()) {
246
            assertEquals(expectedSubTree.getObject(key), subTree.getObject(key));
247
        }
248
    }
249

  
250
    @Test
251
    public void testContainsKey() throws Exception {
252
        for (String shortKey : shortKeysArray) {
253
            System.out.println("Test for existence of key: " + getWholeKey(shortKey));
254
            assertTrue(testConfig.containsKey(getWholeKey(shortKey)));
255

  
256
            System.out.println("Test for NON existence of key: " + shortKey);
257
            assertFalse(testConfig.containsKey(shortKey));
258
        }
259
    }
260

  
261
    @Test
262
    public void testGetList() throws Exception {
263
        List<String> someList = testConfig.getList(getWholeKey("someList"));
264
        assertEquals(Arrays.asList(new String[]{"alpha", "beta", "gama"}), someList);
265
    }
266

  
267
    @Test
268
    public void testGetListDefault() {
269
        List<String> list = Arrays.asList("This", "is", "great");
270

  
271
        List<String> someList = testConfig.getList("nonExistentList", list);
272
        assertEquals(list, someList);
273
    }
274

  
275
    @Test
276
    public void testGetDoubleAsInt() {
277
        int someInt = testConfig.getInt(getWholeKey("someDouble"));
278
        assertEquals(3, someInt);
279
    }
280

  
281
    @Test
282
    public void testDoubleWithDefaultWrittenAsInt() {
283
        double someIntAsDouble = testConfig.getDouble(getWholeKey("someInt"), SOME_DOUBLE);
284
        assertEquals(SOME_INT, someIntAsDouble, DOUBLE_DELTA);
285
    }
286

  
287
    private String getWholeKey(String name) {
288
        return "a.b."+name;
289
    }
290

  
291
    private void testBigDecimals(BigDecimal bigDecimal1, BigDecimal bigDecimal2, double delta) {
292
        BigDecimal subtract = bigDecimal1.subtract(bigDecimal2);
293
        if (subtract.abs().compareTo(new BigDecimal(delta)) > 0) {
294
            throw new ComparisonFailure("", bigDecimal1.toString(), bigDecimal2.toString());
295
        }
296
    }
297
}
src/test/resources/TestConfig.groovy
1
a {
2
    b {
3
        someInt = 42;
4
        someIntDoubleFormat = 42.0;
5
        someFloat = 3.14;
6
        someDouble = 3.14159265358;
7
        someBoolean = true;
8
        someObject = ["HelloWorld", "BlaBlaBla"];
9
        someString = "ConfigReaderIsTheBest";
10
        someMap = [key1:12, key2:24, key3:36];
11
        someList = ["alpha", "beta", "gama"];
12
        mapStringString = ["key1String":"value1", "key2String":"value2", "key3String":"value3"];
13
        anotherObject = String.valueOf("object")
14
    }
15
}
src/test/resources/TestSubTree.groovy
1
b {
2
    someInt = 42;
3
    someFloat = 3.14;
4
    someDouble = 3.14159265358;
5
    someBoolean = true;
6
    someObject = ["HelloWorld", "BlaBlaBla"];
7
    someString = "ConfigReaderIsTheBest";
8
    someMap = ["key1":12, "key2":24, "key3":36];
9
    mapStringString = ["key1String":"value1", "key2String":"value2", "key3String":"value3"];
10
}

Also available in: Unified diff