From 3fd73a1e52e5478303d66173d5e6caaff1802ea0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Iv=C3=A1n=20SZKIBA?= Date: Fri, 30 Jan 2026 15:37:53 +0000 Subject: [PATCH 1/3] feat(devcontainer): enhance VS Code settings for Java and XML formatting --- .devcontainer/devcontainer.json | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 85a07c8..b321fd2 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -19,8 +19,21 @@ "customizations": { "vscode": { "settings": { + "editor.formatOnSave": true, + + // Java settings "java.configuration.updateBuildConfiguration": "automatic", "java.compile.nullAnalysis.mode": "automatic", + "[java]": { + "editor.defaultFormatter": "JoseVSeb.google-java-format-for-vs-code" + }, + // explicitly turn off the Red Hat formatter engine + "java.format.enabled": false, + + // XML settings + "[xml]": { + "editor.defaultFormatter": "redhat.vscode-xml" + }, // Website development settings "[typescript]": { @@ -58,6 +71,10 @@ // Java Language Support "vscjava.vscode-java-pack", + "JoseVSeb.google-java-format-for-vs-code", + + // XML Support + "redhat.vscode-xml", // Website development support "astro-build.astro-vscode", From d7763b3eb4186c00e27a8d028004575b7e6092e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Iv=C3=A1n=20SZKIBA?= Date: Fri, 30 Jan 2026 15:38:04 +0000 Subject: [PATCH 2/3] feat(pom): add Spotless plugin for code formatting and XML support --- pom.xml | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index e0fea25..b4fdda7 100755 --- a/pom.xml +++ b/pom.xml @@ -1,5 +1,7 @@ - + 4.0.0 org.ini4j ini4j @@ -156,6 +158,38 @@ + + + com.diffplug.spotless + spotless-maven-plugin + 3.2.1 + + + + 1.24.0 + + true + + + + + pom.xml + src/**/*.xml + + + XML + + + + + + + check + + verify + + + From 0a9451e9bf185ff7a7384bf3386298eb07a80d16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Iv=C3=A1n=20SZKIBA?= Date: Fri, 30 Jan 2026 15:41:28 +0000 Subject: [PATCH 3/3] style: bulk reformat codebase to Google Java Style Apply Google Java Style Guide formatting to entire codebase. - Formatted all .java files with googleJavaFormat() - Formatted all .xml files with eclipseWtp() - 113 files reformatted (47 main, 66 test) - No functional changes, purely cosmetic formatting This is the initial bulk reformat as part of #8. Future commits will enforce this style automatically via Maven verify phase and VS Code format-on-save. --- src/main/java/org/ini4j/BasicMultiMap.java | 357 ++++---- src/main/java/org/ini4j/BasicOptionMap.java | 542 ++++++------ src/main/java/org/ini4j/BasicProfile.java | 535 ++++++------ .../java/org/ini4j/BasicProfileSection.java | 199 ++--- src/main/java/org/ini4j/BasicRegistry.java | 155 ++-- src/main/java/org/ini4j/BasicRegistryKey.java | 80 +- src/main/java/org/ini4j/CommentedMap.java | 9 +- src/main/java/org/ini4j/CommonMultiMap.java | 169 ++-- src/main/java/org/ini4j/Config.java | 704 +++++++-------- src/main/java/org/ini4j/ConfigParser.java | 747 +++++++--------- src/main/java/org/ini4j/Configurable.java | 7 +- src/main/java/org/ini4j/Ini.java | 297 +++---- src/main/java/org/ini4j/IniPreferences.java | 621 ++++++------- .../java/org/ini4j/IniPreferencesFactory.java | 166 ++-- .../org/ini4j/InvalidFileFormatException.java | 12 +- src/main/java/org/ini4j/MultiMap.java | 19 +- src/main/java/org/ini4j/OptionMap.java | 49 +- src/main/java/org/ini4j/Options.java | 315 ++++--- src/main/java/org/ini4j/Persistable.java | 26 +- src/main/java/org/ini4j/Profile.java | 53 +- src/main/java/org/ini4j/Reg.java | 479 +++++----- src/main/java/org/ini4j/Registry.java | 165 ++-- src/main/java/org/ini4j/Wini.java | 84 +- .../spi/AbstractBeanInvocationHandler.java | 397 ++++----- .../java/org/ini4j/spi/AbstractFormatter.java | 172 ++-- .../java/org/ini4j/spi/AbstractParser.java | 188 ++-- .../org/ini4j/spi/AbstractProfileBuilder.java | 170 ++-- src/main/java/org/ini4j/spi/BeanAccess.java | 17 +- src/main/java/org/ini4j/spi/BeanTool.java | 511 +++++------ src/main/java/org/ini4j/spi/EscapeTool.java | 270 +++--- src/main/java/org/ini4j/spi/HandlerBase.java | 7 +- src/main/java/org/ini4j/spi/IniBuilder.java | 60 +- src/main/java/org/ini4j/spi/IniFormatter.java | 81 +- src/main/java/org/ini4j/spi/IniHandler.java | 17 +- src/main/java/org/ini4j/spi/IniParser.java | 163 ++-- src/main/java/org/ini4j/spi/IniSource.java | 309 +++---- .../java/org/ini4j/spi/OptionsBuilder.java | 143 ++- .../java/org/ini4j/spi/OptionsFormatter.java | 40 +- .../java/org/ini4j/spi/OptionsHandler.java | 13 +- .../java/org/ini4j/spi/OptionsParser.java | 79 +- src/main/java/org/ini4j/spi/RegBuilder.java | 72 +- .../java/org/ini4j/spi/RegEscapeTool.java | 389 ++++----- .../java/org/ini4j/spi/ServiceFinder.java | 224 +++-- .../java/org/ini4j/spi/TypeValuesPair.java | 32 +- .../ini4j/spi/UnicodeInputStreamReader.java | 199 ++--- src/main/java/org/ini4j/spi/Warnings.java | 12 +- .../java/org/ini4j/spi/WinEscapeTool.java | 81 +- .../java/org/ini4j/BasicMultiMapTest.java | 311 ++++--- .../java/org/ini4j/BasicOptionMapGate.java | 21 +- .../java/org/ini4j/BasicOptionMapTest.java | 660 +++++++------- .../org/ini4j/BasicProfileSectionTest.java | 121 ++- src/test/java/org/ini4j/BasicProfileTest.java | 817 +++++++++--------- .../java/org/ini4j/BasicRegistryKeyTest.java | 48 +- .../java/org/ini4j/BasicRegistryTest.java | 67 +- .../java/org/ini4j/CommonMultiMapTest.java | 174 ++-- src/test/java/org/ini4j/ConfigParserTest.java | 806 ++++++++--------- src/test/java/org/ini4j/ConfigTest.java | 281 +++--- src/test/java/org/ini4j/Ini4jCase.java | 23 +- .../org/ini4j/IniPreferencesFactoryTest.java | 119 ++- .../java/org/ini4j/IniPreferencesTest.java | 351 ++++---- src/test/java/org/ini4j/IniTest.java | 407 +++++---- src/test/java/org/ini4j/OptionsTest.java | 398 ++++----- src/test/java/org/ini4j/RegTest.java | 434 +++++----- src/test/java/org/ini4j/WiniTest.java | 172 ++-- src/test/java/org/ini4j/demo/Demo.java | 402 ++++----- src/test/java/org/ini4j/demo/DemoApplet.java | 31 +- src/test/java/org/ini4j/demo/DemoMain.java | 46 +- src/test/java/org/ini4j/demo/DemoModel.java | 206 ++--- .../org/ini4j/sample/BeanEventSample.java | 76 +- .../java/org/ini4j/sample/BeanSample.java | 63 +- .../java/org/ini4j/sample/DumpSample.java | 61 +- src/test/java/org/ini4j/sample/Dwarf.java | 90 +- src/test/java/org/ini4j/sample/DwarfBean.java | 289 +++---- src/test/java/org/ini4j/sample/Dwarfs.java | 65 +- .../java/org/ini4j/sample/DwarfsBean.java | 142 ++- .../java/org/ini4j/sample/FromSample.java | 63 +- src/test/java/org/ini4j/sample/IniSample.java | 55 +- .../java/org/ini4j/sample/ListenerSample.java | 88 +- .../java/org/ini4j/sample/NoImportSample.java | 59 +- .../java/org/ini4j/sample/PyReadSample.java | 55 +- .../org/ini4j/sample/ReadPrimitiveSample.java | 60 +- .../org/ini4j/sample/ReadStringSample.java | 52 +- .../java/org/ini4j/sample/StreamSample.java | 57 +- src/test/java/org/ini4j/sample/ToSample.java | 61 +- .../java/org/ini4j/sample/package-info.java | 22 +- .../AbstractBeanInvocationHandlerTest.java | 415 +++++---- src/test/java/org/ini4j/spi/BeanToolTest.java | 412 +++++---- .../java/org/ini4j/spi/EscapeToolTest.java | 122 ++- .../java/org/ini4j/spi/IniFormatterTest.java | 401 +++++---- .../java/org/ini4j/spi/IniParserTest.java | 438 +++++----- .../java/org/ini4j/spi/IniSourceTest.java | 219 +++-- .../org/ini4j/spi/OptionsFormatterTest.java | 711 +++++++-------- .../java/org/ini4j/spi/OptionsParserTest.java | 378 ++++---- .../java/org/ini4j/spi/RegEscapeToolTest.java | 37 +- .../java/org/ini4j/spi/ServiceFinderTest.java | 97 +-- .../spi/UnicodeInputStreamReaderTest.java | 299 +++---- .../java/org/ini4j/spi/WinEscapeToolTest.java | 125 ++- src/test/java/org/ini4j/test/DwarfsData.java | 418 ++++----- src/test/java/org/ini4j/test/Helper.java | 578 ++++++------- .../java/org/ini4j/test/SampleRunnerTest.java | 483 +++++------ src/test/java/org/ini4j/test/TaleData.java | 58 +- .../org/ini4j/tutorial/AbstractTutorial.java | 14 +- .../java/org/ini4j/tutorial/BeanTutorial.java | 428 +++++---- .../java/org/ini4j/tutorial/IniTutorial.java | 419 +++++---- .../org/ini4j/tutorial/OneMinuteTutorial.java | 208 +++-- .../java/org/ini4j/tutorial/OptTutorial.java | 263 +++--- .../org/ini4j/tutorial/OptionMapTutorial.java | 253 +++--- .../org/ini4j/tutorial/PrefsTutorial.java | 112 ++- .../java/org/ini4j/tutorial/RegTutorial.java | 229 +++-- .../tutorial/WindowsRegistryTutorial.java | 139 ++- .../java/org/ini4j/tutorial/package-info.java | 20 +- 111 files changed, 11300 insertions(+), 12665 deletions(-) diff --git a/src/main/java/org/ini4j/BasicMultiMap.java b/src/main/java/org/ini4j/BasicMultiMap.java index 74a9a99..866559a 100644 --- a/src/main/java/org/ini4j/BasicMultiMap.java +++ b/src/main/java/org/ini4j/BasicMultiMap.java @@ -15,10 +15,7 @@ */ package org.ini4j; -import org.ini4j.spi.Warnings; - import java.io.Serializable; - import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; @@ -27,241 +24,221 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Set; +import org.ini4j.spi.Warnings; -public class BasicMultiMap implements MultiMap, Serializable -{ - private static final long serialVersionUID = 4716749660560043989L; - private final Map> _impl; +public class BasicMultiMap implements MultiMap, Serializable { + private static final long serialVersionUID = 4716749660560043989L; + private final Map> _impl; - public BasicMultiMap() - { - this(new LinkedHashMap>()); - } + public BasicMultiMap() { + this(new LinkedHashMap>()); + } - public BasicMultiMap(Map> impl) - { - _impl = impl; - } + public BasicMultiMap(Map> impl) { + _impl = impl; + } - @Override public List getAll(Object key) - { - return _impl.get(key); - } + @Override + public List getAll(Object key) { + return _impl.get(key); + } - @Override public boolean isEmpty() - { - return _impl.isEmpty(); - } + @Override + public boolean isEmpty() { + return _impl.isEmpty(); + } - @Override public void add(K key, V value) - { - getList(key, true).add(value); - } + @Override + public void add(K key, V value) { + getList(key, true).add(value); + } - @Override public void add(K key, V value, int index) - { - getList(key, true).add(index, value); - } + @Override + public void add(K key, V value, int index) { + getList(key, true).add(index, value); + } + + @Override + public void clear() { + _impl.clear(); + } + + @Override + public boolean containsKey(Object key) { + return _impl.containsKey(key); + } - @Override public void clear() - { - _impl.clear(); + @Override + public boolean containsValue(Object value) { + boolean ret = false; + + for (List all : _impl.values()) { + if (all.contains(value)) { + ret = true; + + break; + } } - @Override public boolean containsKey(Object key) - { - return _impl.containsKey(key); + return ret; + } + + @Override + public Set> entrySet() { + Set> ret = new HashSet>(); + + for (K key : keySet()) { + ret.add(new ShadowEntry(key)); } - @Override public boolean containsValue(Object value) - { - boolean ret = false; + return ret; + } - for (List all : _impl.values()) - { - if (all.contains(value)) - { - ret = true; + @Override + public V get(Object key) { + List values = getList(key, false); - break; - } - } + return (values == null) ? null : values.get(values.size() - 1); + } - return ret; - } + @Override + public V get(Object key, int index) { + List values = getList(key, false); - @Override public Set> entrySet() - { - Set> ret = new HashSet>(); + return (values == null) ? null : values.get(index); + } - for (K key : keySet()) - { - ret.add(new ShadowEntry(key)); - } + @Override + public Set keySet() { + return _impl.keySet(); + } - return ret; - } + @Override + public int length(Object key) { + List values = getList(key, false); - @Override public V get(Object key) - { - List values = getList(key, false); + return (values == null) ? 0 : values.size(); + } - return (values == null) ? null : values.get(values.size() - 1); + @Override + public V put(K key, V value) { + V ret = null; + List values = getList(key, true); + + if (values.isEmpty()) { + values.add(value); + } else { + ret = values.set(values.size() - 1, value); } - @Override public V get(Object key, int index) - { - List values = getList(key, false); + return ret; + } - return (values == null) ? null : values.get(index); - } + @Override + public V put(K key, V value, int index) { + return getList(key, false).set(index, value); + } - @Override public Set keySet() - { - return _impl.keySet(); + @SuppressWarnings(Warnings.UNCHECKED) + @Override + public void putAll(Map map) { + if (map instanceof MultiMap) { + MultiMap mm = (MultiMap) map; + + for (Object key : mm.keySet()) { + putAll((K) key, mm.getAll(key)); + } + } else { + for (K key : map.keySet()) { + put(key, map.get(key)); + } } + } - @Override public int length(Object key) - { - List values = getList(key, false); + @Override + public List putAll(K key, List values) { + List ret = _impl.get(key); - return (values == null) ? 0 : values.size(); - } + _impl.put(key, new ArrayList(values)); - @Override public V put(K key, V value) - { - V ret = null; - List values = getList(key, true); - - if (values.isEmpty()) - { - values.add(value); - } - else - { - ret = values.set(values.size() - 1, value); - } - - return ret; - } + return ret; + } - @Override public V put(K key, V value, int index) - { - return getList(key, false).set(index, value); - } + @Override + public V remove(Object key) { + List prev = _impl.remove(key); - @SuppressWarnings(Warnings.UNCHECKED) - @Override public void putAll(Map map) - { - if (map instanceof MultiMap) - { - MultiMap mm = (MultiMap) map; - - for (Object key : mm.keySet()) - { - putAll((K) key, mm.getAll(key)); - } - } - else - { - for (K key : map.keySet()) - { - put(key, map.get(key)); - } - } + return (prev == null) ? null : prev.get(0); + } + + @Override + public V remove(Object key, int index) { + V ret = null; + List values = getList(key, false); + + if (values != null) { + ret = values.remove(index); + if (values.isEmpty()) { + _impl.remove(key); + } } - @Override public List putAll(K key, List values) - { - List ret = _impl.get(key); + return ret; + } - _impl.put(key, new ArrayList(values)); + @Override + public int size() { + return _impl.size(); + } - return ret; - } + @Override + public String toString() { + return _impl.toString(); + } - @Override public V remove(Object key) - { - List prev = _impl.remove(key); + @Override + public Collection values() { + List all = new ArrayList(_impl.size()); - return (prev == null) ? null : prev.get(0); + for (List values : _impl.values()) { + all.addAll(values); } - @Override public V remove(Object key, int index) - { - V ret = null; - List values = getList(key, false); - - if (values != null) - { - ret = values.remove(index); - if (values.isEmpty()) - { - _impl.remove(key); - } - } - - return ret; - } + return all; + } - @Override public int size() - { - return _impl.size(); - } + @SuppressWarnings(Warnings.UNCHECKED) + private List getList(Object key, boolean create) { + List values = _impl.get(key); - @Override public String toString() - { - return _impl.toString(); + if ((values == null) && create) { + values = new ArrayList(); + _impl.put((K) key, values); } - @Override public Collection values() - { - List all = new ArrayList(_impl.size()); + return values; + } - for (List values : _impl.values()) - { - all.addAll(values); - } + class ShadowEntry implements Map.Entry { + private final K _key; - return all; + ShadowEntry(K key) { + _key = key; } - @SuppressWarnings(Warnings.UNCHECKED) - private List getList(Object key, boolean create) - { - List values = _impl.get(key); - - if ((values == null) && create) - { - values = new ArrayList(); - _impl.put((K) key, values); - } + @Override + public K getKey() { + return _key; + } - return values; + @Override + public V getValue() { + return get(_key); } - class ShadowEntry implements Map.Entry - { - private final K _key; - - ShadowEntry(K key) - { - _key = key; - } - - @Override public K getKey() - { - return _key; - } - - @Override public V getValue() - { - return get(_key); - } - - @Override public V setValue(V value) - { - return put(_key, value); - } + @Override + public V setValue(V value) { + return put(_key, value); } + } } diff --git a/src/main/java/org/ini4j/BasicOptionMap.java b/src/main/java/org/ini4j/BasicOptionMap.java index d7e665d..c62de09 100644 --- a/src/main/java/org/ini4j/BasicOptionMap.java +++ b/src/main/java/org/ini4j/BasicOptionMap.java @@ -15,350 +15,324 @@ */ package org.ini4j; -import org.ini4j.spi.BeanAccess; -import org.ini4j.spi.BeanTool; -import org.ini4j.spi.Warnings; - import java.lang.reflect.Array; - import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.ini4j.spi.BeanAccess; +import org.ini4j.spi.BeanTool; +import org.ini4j.spi.Warnings; -public class BasicOptionMap extends CommonMultiMap implements OptionMap -{ - private static final char SUBST_CHAR = '$'; - private static final String SYSTEM_PROPERTY_PREFIX = "@prop/"; - private static final String ENVIRONMENT_PREFIX = "@env/"; - private static final int SYSTEM_PROPERTY_PREFIX_LEN = SYSTEM_PROPERTY_PREFIX.length(); - private static final int ENVIRONMENT_PREFIX_LEN = ENVIRONMENT_PREFIX.length(); - private static final Pattern EXPRESSION = Pattern.compile("(? implements OptionMap { + private static final char SUBST_CHAR = '$'; + private static final String SYSTEM_PROPERTY_PREFIX = "@prop/"; + private static final String ENVIRONMENT_PREFIX = "@env/"; + private static final int SYSTEM_PROPERTY_PREFIX_LEN = SYSTEM_PROPERTY_PREFIX.length(); + private static final int ENVIRONMENT_PREFIX_LEN = ENVIRONMENT_PREFIX.length(); + private static final Pattern EXPRESSION = + Pattern.compile("(? T getAll(Object key, Class clazz) { + requireArray(clazz); + T value; + + value = (T) Array.newInstance(clazz.getComponentType(), length(key)); + for (int i = 0; i < length(key); i++) { + Array.set(value, i, BeanTool.getInstance().parse(get(key, i), clazz.getComponentType())); + } + + return value; + } + + @Override + public void add(String key, Object value) { + super.add( + key, + ((value == null) || (value instanceof String)) ? (String) value : String.valueOf(value)); + } + + @Override + public void add(String key, Object value, int index) { + super.add( + key, + ((value == null) || (value instanceof String)) ? (String) value : String.valueOf(value), + index); + } + + @Override + public T as(Class clazz) { + return BeanTool.getInstance().proxy(clazz, getDefaultBeanAccess()); + } + + @Override + public T as(Class clazz, String keyPrefix) { + return BeanTool.getInstance().proxy(clazz, newBeanAccess(keyPrefix)); + } + + @Override + public String fetch(Object key) { + int len = length(key); + + return (len == 0) ? null : fetch(key, len - 1); + } + + @Override + public String fetch(Object key, String defaultValue) { + String str = get(key); + + return (str == null) ? defaultValue : str; + } + + @Override + public String fetch(Object key, int index) { + String value = get(key, index); + + if ((value != null) && (value.indexOf(SUBST_CHAR) >= 0)) { + StringBuilder buffer = new StringBuilder(value); + + resolve(buffer); + value = buffer.toString(); + } + + return value; + } + + @Override + public T fetch(Object key, Class clazz) { + return BeanTool.getInstance().parse(fetch(key), clazz); + } + + @Override + public T fetch(Object key, Class clazz, T defaultValue) { + String str = fetch(key); + + return (str == null) ? defaultValue : BeanTool.getInstance().parse(str, clazz); + } + + @Override + public T fetch(Object key, int index, Class clazz) { + return BeanTool.getInstance().parse(fetch(key, index), clazz); + } + + @Override + @SuppressWarnings(Warnings.UNCHECKED) + public T fetchAll(Object key, Class clazz) { + requireArray(clazz); + T value; - public BasicOptionMap(boolean propertyFirstUpper) - { - _propertyFirstUpper = propertyFirstUpper; + value = (T) Array.newInstance(clazz.getComponentType(), length(key)); + for (int i = 0; i < length(key); i++) { + Array.set(value, i, BeanTool.getInstance().parse(fetch(key, i), clazz.getComponentType())); } - @Override - @SuppressWarnings(Warnings.UNCHECKED) - public T getAll(Object key, Class clazz) - { - requireArray(clazz); - T value; - - value = (T) Array.newInstance(clazz.getComponentType(), length(key)); - for (int i = 0; i < length(key); i++) - { - Array.set(value, i, BeanTool.getInstance().parse(get(key, i), clazz.getComponentType())); - } - - return value; - } + return value; + } - @Override public void add(String key, Object value) - { - super.add(key, ((value == null) || (value instanceof String)) ? (String) value : String.valueOf(value)); - } + @Override + public void from(Object bean) { + BeanTool.getInstance().inject(getDefaultBeanAccess(), bean); + } - @Override public void add(String key, Object value, int index) - { - super.add(key, ((value == null) || (value instanceof String)) ? (String) value : String.valueOf(value), index); - } + @Override + public void from(Object bean, String keyPrefix) { + BeanTool.getInstance().inject(newBeanAccess(keyPrefix), bean); + } + + @Override + public T get(Object key, Class clazz) { + return BeanTool.getInstance().parse(get(key), clazz); + } + + @Override + public String get(Object key, String defaultValue) { + String str = get(key); + + return (str == null) ? defaultValue : str; + } - @Override public T as(Class clazz) - { - return BeanTool.getInstance().proxy(clazz, getDefaultBeanAccess()); - } + @Override + public T get(Object key, Class clazz, T defaultValue) { + String str = get(key); - @Override public T as(Class clazz, String keyPrefix) - { - return BeanTool.getInstance().proxy(clazz, newBeanAccess(keyPrefix)); - } + return (str == null) ? defaultValue : BeanTool.getInstance().parse(str, clazz); + } - @Override public String fetch(Object key) - { - int len = length(key); + @Override + public T get(Object key, int index, Class clazz) { + return BeanTool.getInstance().parse(get(key, index), clazz); + } - return (len == 0) ? null : fetch(key, len - 1); - } + @Override + public String put(String key, Object value) { + return super.put( + key, + ((value == null) || (value instanceof String)) ? (String) value : String.valueOf(value)); + } - @Override public String fetch(Object key, String defaultValue) - { - String str = get(key); + @Override + public String put(String key, Object value, int index) { + return super.put( + key, + ((value == null) || (value instanceof String)) ? (String) value : String.valueOf(value), + index); + } - return (str == null) ? defaultValue : str; + @Override + public void putAll(String key, Object value) { + if (value != null) { + requireArray(value.getClass()); } - @Override public String fetch(Object key, int index) - { - String value = get(key, index); - - if ((value != null) && (value.indexOf(SUBST_CHAR) >= 0)) - { - StringBuilder buffer = new StringBuilder(value); - - resolve(buffer); - value = buffer.toString(); - } + remove(key); + if (value != null) { + int n = Array.getLength(value); - return value; + for (int i = 0; i < n; i++) { + add(key, Array.get(value, i)); + } } + } - @Override public T fetch(Object key, Class clazz) - { - return BeanTool.getInstance().parse(fetch(key), clazz); - } + @Override + public void to(Object bean) { + BeanTool.getInstance().inject(bean, getDefaultBeanAccess()); + } - @Override public T fetch(Object key, Class clazz, T defaultValue) - { - String str = fetch(key); + @Override + public void to(Object bean, String keyPrefix) { + BeanTool.getInstance().inject(bean, newBeanAccess(keyPrefix)); + } - return (str == null) ? defaultValue : BeanTool.getInstance().parse(str, clazz); + synchronized BeanAccess getDefaultBeanAccess() { + if (_defaultBeanAccess == null) { + _defaultBeanAccess = newBeanAccess(); } - @Override public T fetch(Object key, int index, Class clazz) - { - return BeanTool.getInstance().parse(fetch(key, index), clazz); - } + return _defaultBeanAccess; + } - @Override - @SuppressWarnings(Warnings.UNCHECKED) - public T fetchAll(Object key, Class clazz) - { - requireArray(clazz); - T value; - - value = (T) Array.newInstance(clazz.getComponentType(), length(key)); - for (int i = 0; i < length(key); i++) - { - Array.set(value, i, BeanTool.getInstance().parse(fetch(key, i), clazz.getComponentType())); - } + boolean isPropertyFirstUpper() { + return _propertyFirstUpper; + } - return value; - } + BeanAccess newBeanAccess() { + return new Access(); + } - @Override public void from(Object bean) - { - BeanTool.getInstance().inject(getDefaultBeanAccess(), bean); - } + BeanAccess newBeanAccess(String propertyNamePrefix) { + return new Access(propertyNamePrefix); + } - @Override public void from(Object bean, String keyPrefix) - { - BeanTool.getInstance().inject(newBeanAccess(keyPrefix), bean); - } + void resolve(StringBuilder buffer) { + Matcher m = EXPRESSION.matcher(buffer); - @Override public T get(Object key, Class clazz) - { - return BeanTool.getInstance().parse(get(key), clazz); - } + while (m.find()) { + String name = m.group(G_OPTION); + int index = (m.group(G_INDEX) == null) ? -1 : Integer.parseInt(m.group(G_INDEX)); + String value; - @Override public String get(Object key, String defaultValue) - { - String str = get(key); + if (name.startsWith(ENVIRONMENT_PREFIX)) { + value = Config.getEnvironment(name.substring(ENVIRONMENT_PREFIX_LEN)); + } else if (name.startsWith(SYSTEM_PROPERTY_PREFIX)) { + value = Config.getSystemProperty(name.substring(SYSTEM_PROPERTY_PREFIX_LEN)); + } else { + value = (index == -1) ? fetch(name) : fetch(name, index); + } - return (str == null) ? defaultValue : str; + if (value != null) { + buffer.replace(m.start(), m.end(), value); + m.reset(buffer); + } } + } - @Override public T get(Object key, Class clazz, T defaultValue) - { - String str = get(key); - - return (str == null) ? defaultValue : BeanTool.getInstance().parse(str, clazz); + private void requireArray(Class clazz) { + if (!clazz.isArray()) { + throw new IllegalArgumentException("Array required"); } + } - @Override public T get(Object key, int index, Class clazz) - { - return BeanTool.getInstance().parse(get(key, index), clazz); - } + class Access implements BeanAccess { + private final String _prefix; - @Override public String put(String key, Object value) - { - return super.put(key, ((value == null) || (value instanceof String)) ? (String) value : String.valueOf(value)); + Access() { + this(null); } - @Override public String put(String key, Object value, int index) - { - return super.put(key, ((value == null) || (value instanceof String)) ? (String) value : String.valueOf(value), index); + Access(String prefix) { + _prefix = prefix; } - @Override public void putAll(String key, Object value) - { - if (value != null) - { - requireArray(value.getClass()); - } - - remove(key); - if (value != null) - { - int n = Array.getLength(value); - - for (int i = 0; i < n; i++) - { - add(key, Array.get(value, i)); - } - } - } - - @Override public void to(Object bean) - { - BeanTool.getInstance().inject(bean, getDefaultBeanAccess()); - } - - @Override public void to(Object bean, String keyPrefix) - { - BeanTool.getInstance().inject(bean, newBeanAccess(keyPrefix)); + @Override + public void propAdd(String propertyName, String value) { + add(transform(propertyName), value); } - synchronized BeanAccess getDefaultBeanAccess() - { - if (_defaultBeanAccess == null) - { - _defaultBeanAccess = newBeanAccess(); - } - - return _defaultBeanAccess; + @Override + public String propDel(String propertyName) { + return remove(transform(propertyName)); } - boolean isPropertyFirstUpper() - { - return _propertyFirstUpper; + @Override + public String propGet(String propertyName) { + return fetch(transform(propertyName)); } - BeanAccess newBeanAccess() - { - return new Access(); + @Override + public String propGet(String propertyName, int index) { + return fetch(transform(propertyName), index); } - BeanAccess newBeanAccess(String propertyNamePrefix) - { - return new Access(propertyNamePrefix); + @Override + public int propLength(String propertyName) { + return length(transform(propertyName)); } - void resolve(StringBuilder buffer) - { - Matcher m = EXPRESSION.matcher(buffer); - - while (m.find()) - { - String name = m.group(G_OPTION); - int index = (m.group(G_INDEX) == null) ? -1 : Integer.parseInt(m.group(G_INDEX)); - String value; - - if (name.startsWith(ENVIRONMENT_PREFIX)) - { - value = Config.getEnvironment(name.substring(ENVIRONMENT_PREFIX_LEN)); - } - else if (name.startsWith(SYSTEM_PROPERTY_PREFIX)) - { - value = Config.getSystemProperty(name.substring(SYSTEM_PROPERTY_PREFIX_LEN)); - } - else - { - value = (index == -1) ? fetch(name) : fetch(name, index); - } - - if (value != null) - { - buffer.replace(m.start(), m.end(), value); - m.reset(buffer); - } - } + @Override + public String propSet(String propertyName, String value) { + return put(transform(propertyName), value); } - private void requireArray(Class clazz) - { - if (!clazz.isArray()) - { - throw new IllegalArgumentException("Array required"); - } + @Override + public String propSet(String propertyName, String value, int index) { + return put(transform(propertyName), value, index); } - class Access implements BeanAccess - { - private final String _prefix; - - Access() - { - this(null); - } - - Access(String prefix) - { - _prefix = prefix; - } + private String transform(String orig) { + String ret = orig; - @Override public void propAdd(String propertyName, String value) - { - add(transform(propertyName), value); - } + if (((_prefix != null) || isPropertyFirstUpper()) && (orig != null)) { + StringBuilder buff = new StringBuilder(); - @Override public String propDel(String propertyName) - { - return remove(transform(propertyName)); + if (_prefix != null) { + buff.append(_prefix); } - @Override public String propGet(String propertyName) - { - return fetch(transform(propertyName)); + if (isPropertyFirstUpper()) { + buff.append(Character.toUpperCase(orig.charAt(0))); + buff.append(orig.substring(1)); + } else { + buff.append(orig); } - @Override public String propGet(String propertyName, int index) - { - return fetch(transform(propertyName), index); - } + ret = buff.toString(); + } - @Override public int propLength(String propertyName) - { - return length(transform(propertyName)); - } - - @Override public String propSet(String propertyName, String value) - { - return put(transform(propertyName), value); - } - - @Override public String propSet(String propertyName, String value, int index) - { - return put(transform(propertyName), value, index); - } - - private String transform(String orig) - { - String ret = orig; - - if (((_prefix != null) || isPropertyFirstUpper()) && (orig != null)) - { - StringBuilder buff = new StringBuilder(); - - if (_prefix != null) - { - buff.append(_prefix); - } - - if (isPropertyFirstUpper()) - { - buff.append(Character.toUpperCase(orig.charAt(0))); - buff.append(orig.substring(1)); - } - else - { - buff.append(orig); - } - - ret = buff.toString(); - } - - return ret; - } + return ret; } + } } diff --git a/src/main/java/org/ini4j/BasicProfile.java b/src/main/java/org/ini4j/BasicProfile.java index 6edd825..8e74f90 100644 --- a/src/main/java/org/ini4j/BasicProfile.java +++ b/src/main/java/org/ini4j/BasicProfile.java @@ -15,337 +15,300 @@ */ package org.ini4j; -import org.ini4j.spi.AbstractBeanInvocationHandler; -import org.ini4j.spi.BeanTool; -import org.ini4j.spi.IniHandler; - import java.lang.reflect.Array; import java.lang.reflect.Proxy; - import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.ini4j.spi.AbstractBeanInvocationHandler; +import org.ini4j.spi.BeanTool; +import org.ini4j.spi.IniHandler; -public class BasicProfile extends CommonMultiMap implements Profile -{ - private static final String SECTION_SYSTEM_PROPERTIES = "@prop"; - private static final String SECTION_ENVIRONMENT = "@env"; - private static final Pattern EXPRESSION = Pattern.compile( - "(? 0) - { - String parent = name.substring(0, idx); - - if (!containsKey(parent)) - { - add(parent); - } - } +public class BasicProfile extends CommonMultiMap implements Profile { + private static final String SECTION_SYSTEM_PROPERTIES = "@prop"; + private static final String SECTION_ENVIRONMENT = "@env"; + private static final Pattern EXPRESSION = + Pattern.compile( + "(? 0) { + String parent = name.substring(0, idx); + + if (!containsKey(parent)) { + add(parent); } - - Section section = newSection(name); - - add(name, section); - - return section; - } - - @Override public void add(String section, String option, Object value) - { - getOrAdd(section).add(option, value); + } } - @Override public T as(Class clazz) - { - return as(clazz, null); - } + Section section = newSection(name); - @Override public T as(Class clazz, String prefix) - { - return clazz.cast(Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] { clazz }, - new BeanInvocationHandler(prefix))); + add(name, section); + + return section; + } + + @Override + public void add(String section, String option, Object value) { + getOrAdd(section).add(option, value); + } + + @Override + public T as(Class clazz) { + return as(clazz, null); + } + + @Override + public T as(Class clazz, String prefix) { + return clazz.cast( + Proxy.newProxyInstance( + Thread.currentThread().getContextClassLoader(), + new Class[] {clazz}, + new BeanInvocationHandler(prefix))); + } + + @Override + public String fetch(Object sectionName, Object optionName) { + Section sec = get(sectionName); + + return (sec == null) ? null : sec.fetch(optionName); + } + + @Override + public T fetch(Object sectionName, Object optionName, Class clazz) { + Section sec = get(sectionName); + + return (sec == null) ? BeanTool.getInstance().zero(clazz) : sec.fetch(optionName, clazz); + } + + @Override + public String get(Object sectionName, Object optionName) { + Section sec = get(sectionName); + + return (sec == null) ? null : sec.get(optionName); + } + + @Override + public T get(Object sectionName, Object optionName, Class clazz) { + Section sec = get(sectionName); + + return (sec == null) ? BeanTool.getInstance().zero(clazz) : sec.get(optionName, clazz); + } + + @Override + public String put(String sectionName, String optionName, Object value) { + return getOrAdd(sectionName).put(optionName, value); + } + + @Override + public Section remove(Section section) { + return remove((Object) section.getName()); + } + + @Override + public String removeOption(Object sectionName, Object optionName) { + Section sec = get(sectionName); + + return (sec == null) ? null : sec.remove(optionName); + } + + boolean isTreeMode() { + return _treeMode; + } + + char getPathSeparator() { + return PATH_SEPARATOR; + } + + boolean isPropertyFirstUpper() { + return _propertyFirstUpper; + } + + Section newSection(String name) { + return new BasicProfileSection(this, name); + } + + void resolve(StringBuilder buffer, Section owner) { + Matcher m = EXPRESSION.matcher(buffer); + + while (m.find()) { + String sectionName = m.group(G_SECTION); + String optionName = m.group(G_OPTION); + int optionIndex = parseOptionIndex(m); + Section section = parseSection(m, owner); + String value = null; + + if (SECTION_ENVIRONMENT.equals(sectionName)) { + value = Config.getEnvironment(optionName); + } else if (SECTION_SYSTEM_PROPERTIES.equals(sectionName)) { + value = Config.getSystemProperty(optionName); + } else if (section != null) { + value = + (optionIndex == -1) + ? section.fetch(optionName) + : section.fetch(optionName, optionIndex); + } + + if (value != null) { + buffer.replace(m.start(), m.end(), value); + m.reset(buffer); + } } + } - @Override public String fetch(Object sectionName, Object optionName) - { - Section sec = get(sectionName); - - return (sec == null) ? null : sec.fetch(optionName); + void store(IniHandler formatter) { + formatter.startIni(); + store(formatter, getComment()); + for (Ini.Section s : values()) { + store(formatter, s); } - @Override public T fetch(Object sectionName, Object optionName, Class clazz) - { - Section sec = get(sectionName); + formatter.endIni(); + } - return (sec == null) ? BeanTool.getInstance().zero(clazz) : sec.fetch(optionName, clazz); + void store(IniHandler formatter, Section s) { + store(formatter, getComment(s.getName())); + formatter.startSection(s.getName()); + for (String name : s.keySet()) { + store(formatter, s, name); } - @Override public String get(Object sectionName, Object optionName) - { - Section sec = get(sectionName); + formatter.endSection(); + } - return (sec == null) ? null : sec.get(optionName); - } + void store(IniHandler formatter, String comment) { + formatter.handleComment(comment); + } - @Override public T get(Object sectionName, Object optionName, Class clazz) - { - Section sec = get(sectionName); + void store(IniHandler formatter, Section section, String option) { + store(formatter, section.getComment(option)); + int n = section.length(option); - return (sec == null) ? BeanTool.getInstance().zero(clazz) : sec.get(optionName, clazz); + for (int i = 0; i < n; i++) { + store(formatter, section, option, i); } + } - @Override public String put(String sectionName, String optionName, Object value) - { - return getOrAdd(sectionName).put(optionName, value); - } + void store(IniHandler formatter, Section section, String option, int index) { + formatter.handleOption(option, section.get(option, index)); + } - @Override public Section remove(Section section) - { - return remove((Object) section.getName()); - } + private Section getOrAdd(String sectionName) { + Section section = get(sectionName); - @Override public String removeOption(Object sectionName, Object optionName) - { - Section sec = get(sectionName); + return ((section == null)) ? add(sectionName) : section; + } - return (sec == null) ? null : sec.remove(optionName); - } + private int parseOptionIndex(Matcher m) { + return (m.group(G_OPTION_IDX) == null) ? -1 : Integer.parseInt(m.group(G_OPTION_IDX)); + } - boolean isTreeMode() - { - return _treeMode; - } + private Section parseSection(Matcher m, Section owner) { + String sectionName = m.group(G_SECTION); + int sectionIndex = parseSectionIndex(m); - char getPathSeparator() - { - return PATH_SEPARATOR; - } + return (sectionName == null) + ? owner + : ((sectionIndex == -1) ? get(sectionName) : get(sectionName, sectionIndex)); + } - boolean isPropertyFirstUpper() - { - return _propertyFirstUpper; - } + private int parseSectionIndex(Matcher m) { + return (m.group(G_SECTION_IDX) == null) ? -1 : Integer.parseInt(m.group(G_SECTION_IDX)); + } - Section newSection(String name) - { - return new BasicProfileSection(this, name); - } + private final class BeanInvocationHandler extends AbstractBeanInvocationHandler { + private final String _prefix; - void resolve(StringBuilder buffer, Section owner) - { - Matcher m = EXPRESSION.matcher(buffer); - - while (m.find()) - { - String sectionName = m.group(G_SECTION); - String optionName = m.group(G_OPTION); - int optionIndex = parseOptionIndex(m); - Section section = parseSection(m, owner); - String value = null; - - if (SECTION_ENVIRONMENT.equals(sectionName)) - { - value = Config.getEnvironment(optionName); - } - else if (SECTION_SYSTEM_PROPERTIES.equals(sectionName)) - { - value = Config.getSystemProperty(optionName); - } - else if (section != null) - { - value = (optionIndex == -1) ? section.fetch(optionName) : section.fetch(optionName, optionIndex); - } - - if (value != null) - { - buffer.replace(m.start(), m.end(), value); - m.reset(buffer); - } - } + private BeanInvocationHandler(String prefix) { + _prefix = prefix; } - void store(IniHandler formatter) - { - formatter.startIni(); - store(formatter, getComment()); - for (Ini.Section s : values()) - { - store(formatter, s); + @Override + protected Object getPropertySpi(String property, Class clazz) { + String key = transform(property); + Object o = null; + + if (containsKey(key)) { + if (clazz.isArray()) { + o = Array.newInstance(clazz.getComponentType(), length(key)); + for (int i = 0; i < length(key); i++) { + Array.set(o, i, get(key, i).as(clazz.getComponentType())); + } + } else { + o = get(key).as(clazz); } + } - formatter.endIni(); + return o; } - void store(IniHandler formatter, Section s) - { - store(formatter, getComment(s.getName())); - formatter.startSection(s.getName()); - for (String name : s.keySet()) - { - store(formatter, s, name); - } - - formatter.endSection(); - } + @Override + protected void setPropertySpi(String property, Object value, Class clazz) { + String key = transform(property); - void store(IniHandler formatter, String comment) - { - formatter.handleComment(comment); - } + remove(key); + if (value != null) { + if (clazz.isArray()) { + for (int i = 0; i < Array.getLength(value); i++) { + Section sec = add(key); - void store(IniHandler formatter, Section section, String option) - { - store(formatter, section.getComment(option)); - int n = section.length(option); + sec.from(Array.get(value, i)); + } + } else { + Section sec = add(key); - for (int i = 0; i < n; i++) - { - store(formatter, section, option, i); + sec.from(value); } + } } - void store(IniHandler formatter, Section section, String option, int index) - { - formatter.handleOption(option, section.get(option, index)); - } - - private Section getOrAdd(String sectionName) - { - Section section = get(sectionName); - - return ((section == null)) ? add(sectionName) : section; - } - - private int parseOptionIndex(Matcher m) - { - return (m.group(G_OPTION_IDX) == null) ? -1 : Integer.parseInt(m.group(G_OPTION_IDX)); - } - - private Section parseSection(Matcher m, Section owner) - { - String sectionName = m.group(G_SECTION); - int sectionIndex = parseSectionIndex(m); - - return (sectionName == null) ? owner : ((sectionIndex == -1) ? get(sectionName) : get(sectionName, sectionIndex)); - } - - private int parseSectionIndex(Matcher m) - { - return (m.group(G_SECTION_IDX) == null) ? -1 : Integer.parseInt(m.group(G_SECTION_IDX)); + @Override + protected boolean hasPropertySpi(String property) { + return containsKey(transform(property)); } - private final class BeanInvocationHandler extends AbstractBeanInvocationHandler - { - private final String _prefix; - - private BeanInvocationHandler(String prefix) - { - _prefix = prefix; - } - - @Override protected Object getPropertySpi(String property, Class clazz) - { - String key = transform(property); - Object o = null; - - if (containsKey(key)) - { - if (clazz.isArray()) - { - o = Array.newInstance(clazz.getComponentType(), length(key)); - for (int i = 0; i < length(key); i++) - { - Array.set(o, i, get(key, i).as(clazz.getComponentType())); - } - } - else - { - o = get(key).as(clazz); - } - } - - return o; - } - - @Override protected void setPropertySpi(String property, Object value, Class clazz) - { - String key = transform(property); - - remove(key); - if (value != null) - { - if (clazz.isArray()) - { - for (int i = 0; i < Array.getLength(value); i++) - { - Section sec = add(key); - - sec.from(Array.get(value, i)); - } - } - else - { - Section sec = add(key); - - sec.from(value); - } - } - } + String transform(String property) { + String ret = (_prefix == null) ? property : (_prefix + property); - @Override protected boolean hasPropertySpi(String property) - { - return containsKey(transform(property)); - } + if (isPropertyFirstUpper()) { + StringBuilder buff = new StringBuilder(); - String transform(String property) - { - String ret = (_prefix == null) ? property : (_prefix + property); + buff.append(Character.toUpperCase(property.charAt(0))); + buff.append(property.substring(1)); + ret = buff.toString(); + } - if (isPropertyFirstUpper()) - { - StringBuilder buff = new StringBuilder(); - - buff.append(Character.toUpperCase(property.charAt(0))); - buff.append(property.substring(1)); - ret = buff.toString(); - } - - return ret; - } + return ret; } + } } diff --git a/src/main/java/org/ini4j/BasicProfileSection.java b/src/main/java/org/ini4j/BasicProfileSection.java index 18f513e..c524a82 100644 --- a/src/main/java/org/ini4j/BasicProfileSection.java +++ b/src/main/java/org/ini4j/BasicProfileSection.java @@ -19,133 +19,124 @@ import java.util.List; import java.util.regex.Pattern; -class BasicProfileSection extends BasicOptionMap implements Profile.Section -{ - private static final long serialVersionUID = 985800697957194374L; - private static final String[] EMPTY_STRING_ARRAY = {}; - private static final char REGEXP_ESCAPE_CHAR = '\\'; - private final Pattern _childPattern; - private final String _name; - private final BasicProfile _profile; - - protected BasicProfileSection(BasicProfile profile, String name) - { - _profile = profile; - _name = name; - _childPattern = newChildPattern(name); +class BasicProfileSection extends BasicOptionMap implements Profile.Section { + private static final long serialVersionUID = 985800697957194374L; + private static final String[] EMPTY_STRING_ARRAY = {}; + private static final char REGEXP_ESCAPE_CHAR = '\\'; + private final Pattern _childPattern; + private final String _name; + private final BasicProfile _profile; + + protected BasicProfileSection(BasicProfile profile, String name) { + _profile = profile; + _name = name; + _childPattern = newChildPattern(name); + } + + @Override + public Profile.Section getChild(String key) { + return _profile.get(childName(key)); + } + + @Override + public String getName() { + return _name; + } + + @Override + public Profile.Section getParent() { + Profile.Section ret = null; + int idx = _name.lastIndexOf(_profile.getPathSeparator()); + + if (idx >= 0) { + String name = _name.substring(0, idx); + + ret = _profile.get(name); } - @Override public Profile.Section getChild(String key) - { - return _profile.get(childName(key)); - } + return ret; + } - @Override public String getName() - { - return _name; - } + @Override + public String getSimpleName() { + int idx = _name.lastIndexOf(_profile.getPathSeparator()); - @Override public Profile.Section getParent() - { - Profile.Section ret = null; - int idx = _name.lastIndexOf(_profile.getPathSeparator()); + return (idx < 0) ? _name : _name.substring(idx + 1); + } - if (idx >= 0) - { - String name = _name.substring(0, idx); + @Override + public Profile.Section addChild(String key) { + String name = childName(key); - ret = _profile.get(name); - } + return _profile.add(name); + } - return ret; - } + @Override + public String[] childrenNames() { + List names = new ArrayList(); - @Override public String getSimpleName() - { - int idx = _name.lastIndexOf(_profile.getPathSeparator()); - - return (idx < 0) ? _name : _name.substring(idx + 1); + for (String key : _profile.keySet()) { + if (_childPattern.matcher(key).matches()) { + names.add(key.substring(_name.length() + 1)); + } } - @Override public Profile.Section addChild(String key) - { - String name = childName(key); - - return _profile.add(name); - } + return names.toArray(EMPTY_STRING_ARRAY); + } - @Override public String[] childrenNames() - { - List names = new ArrayList(); + @Override + public Profile.Section lookup(String... parts) { + StringBuilder buff = new StringBuilder(); - for (String key : _profile.keySet()) - { - if (_childPattern.matcher(key).matches()) - { - names.add(key.substring(_name.length() + 1)); - } - } + for (String part : parts) { + if (buff.length() != 0) { + buff.append(_profile.getPathSeparator()); + } - return names.toArray(EMPTY_STRING_ARRAY); + buff.append(part); } - @Override public Profile.Section lookup(String... parts) - { - StringBuilder buff = new StringBuilder(); + return _profile.get(childName(buff.toString())); + } - for (String part : parts) - { - if (buff.length() != 0) - { - buff.append(_profile.getPathSeparator()); - } + @Override + public void removeChild(String key) { + String name = childName(key); - buff.append(part); - } + _profile.remove(name); + } - return _profile.get(childName(buff.toString())); - } + @Override + boolean isPropertyFirstUpper() { + return _profile.isPropertyFirstUpper(); + } - @Override public void removeChild(String key) - { - String name = childName(key); + @Override + void resolve(StringBuilder buffer) { + _profile.resolve(buffer, this); + } - _profile.remove(name); - } + private String childName(String key) { + StringBuilder buff = new StringBuilder(_name); - @Override boolean isPropertyFirstUpper() - { - return _profile.isPropertyFirstUpper(); - } + buff.append(_profile.getPathSeparator()); + buff.append(key); - @Override void resolve(StringBuilder buffer) - { - _profile.resolve(buffer, this); - } - - private String childName(String key) - { - StringBuilder buff = new StringBuilder(_name); + return buff.toString(); + } - buff.append(_profile.getPathSeparator()); - buff.append(key); - - return buff.toString(); - } + private Pattern newChildPattern(String name) { + StringBuilder buff = new StringBuilder(); - private Pattern newChildPattern(String name) - { - StringBuilder buff = new StringBuilder(); + buff.append('^'); + buff.append(Pattern.quote(name)); + buff.append(REGEXP_ESCAPE_CHAR); + buff.append(_profile.getPathSeparator()); + buff.append("[^"); + buff.append(REGEXP_ESCAPE_CHAR); + buff.append(_profile.getPathSeparator()); + buff.append("]+$"); - buff.append('^'); - buff.append(Pattern.quote(name)); - buff.append(REGEXP_ESCAPE_CHAR); - buff.append(_profile.getPathSeparator()); - buff.append("[^"); - buff.append(REGEXP_ESCAPE_CHAR); - buff.append(_profile.getPathSeparator()); - buff.append("]+$"); - - return Pattern.compile(buff.toString()); - } + return Pattern.compile(buff.toString()); + } } diff --git a/src/main/java/org/ini4j/BasicRegistry.java b/src/main/java/org/ini4j/BasicRegistry.java index 5395d6b..a13bd7a 100644 --- a/src/main/java/org/ini4j/BasicRegistry.java +++ b/src/main/java/org/ini4j/BasicRegistry.java @@ -16,90 +16,87 @@ package org.ini4j; import org.ini4j.Profile.Section; - import org.ini4j.spi.IniHandler; import org.ini4j.spi.RegEscapeTool; import org.ini4j.spi.TypeValuesPair; -public class BasicRegistry extends BasicProfile implements Registry -{ - private static final long serialVersionUID = -6432826330714504802L; - private String _version; - - public BasicRegistry() - { - _version = VERSION; - } - - @Override public String getVersion() - { - return _version; - } - - @Override public void setVersion(String value) - { - _version = value; - } - - @Override public Key add(String name) - { - return (Key) super.add(name); - } - - @Override public Key get(Object key) - { - return (Key) super.get(key); +public class BasicRegistry extends BasicProfile implements Registry { + private static final long serialVersionUID = -6432826330714504802L; + private String _version; + + public BasicRegistry() { + _version = VERSION; + } + + @Override + public String getVersion() { + return _version; + } + + @Override + public void setVersion(String value) { + _version = value; + } + + @Override + public Key add(String name) { + return (Key) super.add(name); + } + + @Override + public Key get(Object key) { + return (Key) super.get(key); + } + + @Override + public Key get(Object key, int index) { + return (Key) super.get(key, index); + } + + @Override + public Key put(String key, Section value) { + return (Key) super.put(key, value); + } + + @Override + public Key put(String key, Section value, int index) { + return (Key) super.put(key, value, index); + } + + @Override + public Key remove(Section section) { + return (Key) super.remove(section); + } + + @Override + public Key remove(Object key) { + return (Key) super.remove(key); + } + + @Override + public Key remove(Object key, int index) { + return (Key) super.remove(key, index); + } + + @Override + Key newSection(String name) { + return new BasicRegistryKey(this, name); + } + + @Override + void store(IniHandler formatter, Section section, String option) { + store(formatter, section.getComment(option)); + Type type = ((Key) section).getType(option, Type.REG_SZ); + String rawName = + option.equals(Key.DEFAULT_NAME) ? option : RegEscapeTool.getInstance().quote(option); + String[] values = new String[section.length(option)]; + + for (int i = 0; i < values.length; i++) { + values[i] = section.get(option, i); } - @Override public Key get(Object key, int index) - { - return (Key) super.get(key, index); - } + String rawValue = RegEscapeTool.getInstance().encode(new TypeValuesPair(type, values)); - @Override public Key put(String key, Section value) - { - return (Key) super.put(key, value); - } - - @Override public Key put(String key, Section value, int index) - { - return (Key) super.put(key, value, index); - } - - @Override public Key remove(Section section) - { - return (Key) super.remove(section); - } - - @Override public Key remove(Object key) - { - return (Key) super.remove(key); - } - - @Override public Key remove(Object key, int index) - { - return (Key) super.remove(key, index); - } - - @Override Key newSection(String name) - { - return new BasicRegistryKey(this, name); - } - - @Override void store(IniHandler formatter, Section section, String option) - { - store(formatter, section.getComment(option)); - Type type = ((Key) section).getType(option, Type.REG_SZ); - String rawName = option.equals(Key.DEFAULT_NAME) ? option : RegEscapeTool.getInstance().quote(option); - String[] values = new String[section.length(option)]; - - for (int i = 0; i < values.length; i++) - { - values[i] = section.get(option, i); - } - - String rawValue = RegEscapeTool.getInstance().encode(new TypeValuesPair(type, values)); - - formatter.handleOption(rawName, rawValue); - } + formatter.handleOption(rawName, rawValue); + } } diff --git a/src/main/java/org/ini4j/BasicRegistryKey.java b/src/main/java/org/ini4j/BasicRegistryKey.java index ea74de2..5f79ccd 100644 --- a/src/main/java/org/ini4j/BasicRegistryKey.java +++ b/src/main/java/org/ini4j/BasicRegistryKey.java @@ -17,55 +17,53 @@ import org.ini4j.Registry.Key; -class BasicRegistryKey extends BasicProfileSection implements Registry.Key -{ - private static final long serialVersionUID = -1390060044244350928L; - private static final String META_TYPE = "type"; +class BasicRegistryKey extends BasicProfileSection implements Registry.Key { + private static final long serialVersionUID = -1390060044244350928L; + private static final String META_TYPE = "type"; - public BasicRegistryKey(BasicRegistry registry, String name) - { - super(registry, name); - } + public BasicRegistryKey(BasicRegistry registry, String name) { + super(registry, name); + } - @Override public Key getChild(String key) - { - return (Key) super.getChild(key); - } + @Override + public Key getChild(String key) { + return (Key) super.getChild(key); + } - @Override public Key getParent() - { - return (Key) super.getParent(); - } + @Override + public Key getParent() { + return (Key) super.getParent(); + } - @Override public Registry.Type getType(Object key) - { - return (Registry.Type) getMeta(META_TYPE, key); - } + @Override + public Registry.Type getType(Object key) { + return (Registry.Type) getMeta(META_TYPE, key); + } - @Override public Registry.Type getType(Object key, Registry.Type defaultType) - { - Registry.Type type = getType(key); + @Override + public Registry.Type getType(Object key, Registry.Type defaultType) { + Registry.Type type = getType(key); - return (type == null) ? defaultType : type; - } + return (type == null) ? defaultType : type; + } - @Override public Key addChild(String key) - { - return (Key) super.addChild(key); - } + @Override + public Key addChild(String key) { + return (Key) super.addChild(key); + } - @Override public Key lookup(String... path) - { - return (Key) super.lookup(path); - } + @Override + public Key lookup(String... path) { + return (Key) super.lookup(path); + } - @Override public Registry.Type putType(String key, Registry.Type type) - { - return (Registry.Type) putMeta(META_TYPE, key, type); - } + @Override + public Registry.Type putType(String key, Registry.Type type) { + return (Registry.Type) putMeta(META_TYPE, key, type); + } - @Override public Registry.Type removeType(Object key) - { - return (Registry.Type) removeMeta(META_TYPE, key); - } + @Override + public Registry.Type removeType(Object key) { + return (Registry.Type) removeMeta(META_TYPE, key); + } } diff --git a/src/main/java/org/ini4j/CommentedMap.java b/src/main/java/org/ini4j/CommentedMap.java index a35ccd4..fbed485 100644 --- a/src/main/java/org/ini4j/CommentedMap.java +++ b/src/main/java/org/ini4j/CommentedMap.java @@ -17,11 +17,10 @@ import java.util.Map; -public interface CommentedMap extends Map -{ - String getComment(Object key); +public interface CommentedMap extends Map { + String getComment(Object key); - String putComment(K key, String comment); + String putComment(K key, String comment); - String removeComment(Object key); + String removeComment(Object key); } diff --git a/src/main/java/org/ini4j/CommonMultiMap.java b/src/main/java/org/ini4j/CommonMultiMap.java index 7ac6171..530145d 100644 --- a/src/main/java/org/ini4j/CommonMultiMap.java +++ b/src/main/java/org/ini4j/CommonMultiMap.java @@ -19,116 +19,103 @@ import java.util.SortedMap; import java.util.TreeMap; -public class CommonMultiMap extends BasicMultiMap implements CommentedMap -{ - private static final long serialVersionUID = 3012579878005541746L; - private static final String SEPARATOR = ";#;"; - private static final String FIRST_CATEGORY = ""; - private static final String LAST_CATEGORY = "zzzzzzzzzzzzzzzzzzzzzz"; - private static final String META_COMMENT = "comment"; - private SortedMap _meta; - - @Override public String getComment(Object key) - { - return (String) getMeta(META_COMMENT, key); +public class CommonMultiMap extends BasicMultiMap implements CommentedMap { + private static final long serialVersionUID = 3012579878005541746L; + private static final String SEPARATOR = ";#;"; + private static final String FIRST_CATEGORY = ""; + private static final String LAST_CATEGORY = "zzzzzzzzzzzzzzzzzzzzzz"; + private static final String META_COMMENT = "comment"; + private SortedMap _meta; + + @Override + public String getComment(Object key) { + return (String) getMeta(META_COMMENT, key); + } + + @Override + public void clear() { + super.clear(); + if (_meta != null) { + _meta.clear(); } - - @Override public void clear() - { - super.clear(); - if (_meta != null) - { - _meta.clear(); - } - } - - @SuppressWarnings("unchecked") - @Override public void putAll(Map map) - { - super.putAll(map); - if (map instanceof CommonMultiMap) - { - Map meta = ((CommonMultiMap) map)._meta; - - if (meta != null) - { - meta().putAll(meta); - } - } + } + + @SuppressWarnings("unchecked") + @Override + public void putAll(Map map) { + super.putAll(map); + if (map instanceof CommonMultiMap) { + Map meta = ((CommonMultiMap) map)._meta; + + if (meta != null) { + meta().putAll(meta); + } } + } - @Override public String putComment(K key, String comment) - { - return (String) putMeta(META_COMMENT, key, comment); - } - - @Override public V remove(Object key) - { - V ret = super.remove(key); + @Override + public String putComment(K key, String comment) { + return (String) putMeta(META_COMMENT, key, comment); + } - removeMeta(key); + @Override + public V remove(Object key) { + V ret = super.remove(key); - return ret; - } + removeMeta(key); - @Override public V remove(Object key, int index) - { - V ret = super.remove(key, index); + return ret; + } - if (length(key) == 0) - { - removeMeta(key); - } + @Override + public V remove(Object key, int index) { + V ret = super.remove(key, index); - return ret; + if (length(key) == 0) { + removeMeta(key); } - @Override public String removeComment(Object key) - { - return (String) removeMeta(META_COMMENT, key); - } + return ret; + } - Object getMeta(String category, Object key) - { - return (_meta == null) ? null : _meta.get(makeKey(category, key)); - } + @Override + public String removeComment(Object key) { + return (String) removeMeta(META_COMMENT, key); + } - Object putMeta(String category, K key, Object value) - { - return meta().put(makeKey(category, key), value); - } + Object getMeta(String category, Object key) { + return (_meta == null) ? null : _meta.get(makeKey(category, key)); + } - void removeMeta(Object key) - { - if (_meta != null) - { - _meta.subMap(makeKey(FIRST_CATEGORY, key), makeKey(LAST_CATEGORY, key)).clear(); - } - } + Object putMeta(String category, K key, Object value) { + return meta().put(makeKey(category, key), value); + } - Object removeMeta(String category, Object key) - { - return (_meta == null) ? null : _meta.remove(makeKey(category, key)); + void removeMeta(Object key) { + if (_meta != null) { + _meta.subMap(makeKey(FIRST_CATEGORY, key), makeKey(LAST_CATEGORY, key)).clear(); } + } - private String makeKey(String category, Object key) - { - StringBuilder buff = new StringBuilder(); + Object removeMeta(String category, Object key) { + return (_meta == null) ? null : _meta.remove(makeKey(category, key)); + } - buff.append(String.valueOf(key)); - buff.append(SEPARATOR); - buff.append(category); + private String makeKey(String category, Object key) { + StringBuilder buff = new StringBuilder(); - return buff.toString(); - } + buff.append(String.valueOf(key)); + buff.append(SEPARATOR); + buff.append(category); - private Map meta() - { - if (_meta == null) - { - _meta = new TreeMap(); - } + return buff.toString(); + } - return _meta; + private Map meta() { + if (_meta == null) { + _meta = new TreeMap(); } + + return _meta; + } } diff --git a/src/main/java/org/ini4j/Config.java b/src/main/java/org/ini4j/Config.java index 8dde0f3..bb254d2 100644 --- a/src/main/java/org/ini4j/Config.java +++ b/src/main/java/org/ini4j/Config.java @@ -16,401 +16,337 @@ package org.ini4j; import java.io.Serializable; - import java.nio.charset.Charset; @SuppressWarnings("PMD.ExcessivePublicCount") -public class Config implements Cloneable, Serializable -{ - public static final String KEY_PREFIX = "org.ini4j.config."; - public static final String PROP_EMPTY_OPTION = "emptyOption"; - public static final String PROP_EMPTY_SECTION = "emptySection"; - public static final String PROP_GLOBAL_SECTION = "globalSection"; - public static final String PROP_GLOBAL_SECTION_NAME = "globalSectionName"; - public static final String PROP_INCLUDE = "include"; - public static final String PROP_LOWER_CASE_OPTION = "lowerCaseOption"; - public static final String PROP_LOWER_CASE_SECTION = "lowerCaseSection"; - public static final String PROP_MULTI_OPTION = "multiOption"; - public static final String PROP_MULTI_SECTION = "multiSection"; - public static final String PROP_STRICT_OPERATOR = "strictOperator"; - public static final String PROP_UNNAMED_SECTION = "unnamedSection"; - public static final String PROP_ESCAPE = "escape"; - public static final String PROP_ESCAPE_NEWLINE = "escapeNewline"; - public static final String PROP_ESCAPE_KEY_ONLY = "escapeKey"; - public static final String PROP_PATH_SEPARATOR = "pathSeparator"; - public static final String PROP_TREE = "tree"; - public static final String PROP_PROPERTY_FIRST_UPPER = "propertyFirstUpper"; - public static final String PROP_FILE_ENCODING = "fileEncoding"; - public static final String PROP_LINE_SEPARATOR = "lineSeparator"; - public static final String PROP_COMMENT = "comment"; - public static final String PROP_HEADER_COMMENT = "headerComment"; - public static final boolean DEFAULT_EMPTY_OPTION = false; - public static final boolean DEFAULT_EMPTY_SECTION = false; - public static final boolean DEFAULT_GLOBAL_SECTION = false; - public static final String DEFAULT_GLOBAL_SECTION_NAME = "?"; - public static final boolean DEFAULT_INCLUDE = false; - public static final boolean DEFAULT_LOWER_CASE_OPTION = false; - public static final boolean DEFAULT_LOWER_CASE_SECTION = false; - public static final boolean DEFAULT_MULTI_OPTION = true; - public static final boolean DEFAULT_MULTI_SECTION = false; - public static final boolean DEFAULT_STRICT_OPERATOR = false; - public static final boolean DEFAULT_UNNAMED_SECTION = false; - public static final boolean DEFAULT_ESCAPE = true; - public static final boolean DEFAULT_ESCAPE_NEWLINE = true; - public static final boolean DEFAULT_ESCAPE_KEY_ONLY = false; - public static final boolean DEFAULT_TREE = true; - public static final boolean DEFAULT_PROPERTY_FIRST_UPPER = false; - public static final boolean DEFAULT_COMMENT = true; - public static final boolean DEFAULT_HEADER_COMMENT = true; - public static final char DEFAULT_PATH_SEPARATOR = '/'; - public static final String DEFAULT_LINE_SEPARATOR = getSystemProperty("line.separator", "\n"); - public static final Charset DEFAULT_FILE_ENCODING = Charset.forName("UTF-8"); - private static final Config GLOBAL = new Config(); - private static final long serialVersionUID = 2865793267410367814L; - private boolean _comment; - private boolean _emptyOption; - private boolean _emptySection; - private boolean _escape; - private boolean _escapeKeyOnly; - private boolean _escapeNewline; - private Charset _fileEncoding; - private boolean _globalSection; - private String _globalSectionName; - private boolean _headerComment; - private boolean _include; - private String _lineSeparator; - private boolean _lowerCaseOption; - private boolean _lowerCaseSection; - private boolean _multiOption; - private boolean _multiSection; - private char _pathSeparator; - private boolean _propertyFirstUpper; - private boolean _strictOperator; - private boolean _tree; - private boolean _unnamedSection; - - public Config() - { - reset(); - } - - public static String getEnvironment(String name) - { - return getEnvironment(name, null); - } - - public static String getEnvironment(String name, String defaultValue) - { - String value; - - try - { - value = System.getenv(name); - } - catch (SecurityException x) - { - value = null; - } - - return (value == null) ? defaultValue : value; - } +public class Config implements Cloneable, Serializable { + public static final String KEY_PREFIX = "org.ini4j.config."; + public static final String PROP_EMPTY_OPTION = "emptyOption"; + public static final String PROP_EMPTY_SECTION = "emptySection"; + public static final String PROP_GLOBAL_SECTION = "globalSection"; + public static final String PROP_GLOBAL_SECTION_NAME = "globalSectionName"; + public static final String PROP_INCLUDE = "include"; + public static final String PROP_LOWER_CASE_OPTION = "lowerCaseOption"; + public static final String PROP_LOWER_CASE_SECTION = "lowerCaseSection"; + public static final String PROP_MULTI_OPTION = "multiOption"; + public static final String PROP_MULTI_SECTION = "multiSection"; + public static final String PROP_STRICT_OPERATOR = "strictOperator"; + public static final String PROP_UNNAMED_SECTION = "unnamedSection"; + public static final String PROP_ESCAPE = "escape"; + public static final String PROP_ESCAPE_NEWLINE = "escapeNewline"; + public static final String PROP_ESCAPE_KEY_ONLY = "escapeKey"; + public static final String PROP_PATH_SEPARATOR = "pathSeparator"; + public static final String PROP_TREE = "tree"; + public static final String PROP_PROPERTY_FIRST_UPPER = "propertyFirstUpper"; + public static final String PROP_FILE_ENCODING = "fileEncoding"; + public static final String PROP_LINE_SEPARATOR = "lineSeparator"; + public static final String PROP_COMMENT = "comment"; + public static final String PROP_HEADER_COMMENT = "headerComment"; + public static final boolean DEFAULT_EMPTY_OPTION = false; + public static final boolean DEFAULT_EMPTY_SECTION = false; + public static final boolean DEFAULT_GLOBAL_SECTION = false; + public static final String DEFAULT_GLOBAL_SECTION_NAME = "?"; + public static final boolean DEFAULT_INCLUDE = false; + public static final boolean DEFAULT_LOWER_CASE_OPTION = false; + public static final boolean DEFAULT_LOWER_CASE_SECTION = false; + public static final boolean DEFAULT_MULTI_OPTION = true; + public static final boolean DEFAULT_MULTI_SECTION = false; + public static final boolean DEFAULT_STRICT_OPERATOR = false; + public static final boolean DEFAULT_UNNAMED_SECTION = false; + public static final boolean DEFAULT_ESCAPE = true; + public static final boolean DEFAULT_ESCAPE_NEWLINE = true; + public static final boolean DEFAULT_ESCAPE_KEY_ONLY = false; + public static final boolean DEFAULT_TREE = true; + public static final boolean DEFAULT_PROPERTY_FIRST_UPPER = false; + public static final boolean DEFAULT_COMMENT = true; + public static final boolean DEFAULT_HEADER_COMMENT = true; + public static final char DEFAULT_PATH_SEPARATOR = '/'; + public static final String DEFAULT_LINE_SEPARATOR = getSystemProperty("line.separator", "\n"); + public static final Charset DEFAULT_FILE_ENCODING = Charset.forName("UTF-8"); + private static final Config GLOBAL = new Config(); + private static final long serialVersionUID = 2865793267410367814L; + private boolean _comment; + private boolean _emptyOption; + private boolean _emptySection; + private boolean _escape; + private boolean _escapeKeyOnly; + private boolean _escapeNewline; + private Charset _fileEncoding; + private boolean _globalSection; + private String _globalSectionName; + private boolean _headerComment; + private boolean _include; + private String _lineSeparator; + private boolean _lowerCaseOption; + private boolean _lowerCaseSection; + private boolean _multiOption; + private boolean _multiSection; + private char _pathSeparator; + private boolean _propertyFirstUpper; + private boolean _strictOperator; + private boolean _tree; + private boolean _unnamedSection; + + public Config() { + reset(); + } + + public static String getEnvironment(String name) { + return getEnvironment(name, null); + } + + public static String getEnvironment(String name, String defaultValue) { + String value; + + try { + value = System.getenv(name); + } catch (SecurityException x) { + value = null; + } + + return (value == null) ? defaultValue : value; + } + + public static Config getGlobal() { + return GLOBAL; + } + + public static String getSystemProperty(String name) { + return getSystemProperty(name, null); + } + + public static String getSystemProperty(String name, String defaultValue) { + String value; + + try { + value = System.getProperty(name); + } catch (SecurityException x) { + value = null; + } + + return (value == null) ? defaultValue : value; + } + + public void setComment(boolean value) { + _comment = value; + } + + public boolean isEscape() { + return _escape; + } + + public boolean isEscapeNewline() { + return _escapeNewline; + } + + public boolean isInclude() { + return _include; + } + + public boolean isTree() { + return _tree; + } + + public void setEmptyOption(boolean value) { + _emptyOption = value; + } + + public void setEmptySection(boolean value) { + _emptySection = value; + } + + public void setEscape(boolean value) { + _escape = value; + } + + public void setEscapeKeyOnly(boolean value) { + _escapeKeyOnly = value; + } + + public void setEscapeNewline(boolean value) { + _escapeNewline = value; + } + + public Charset getFileEncoding() { + return _fileEncoding; + } + + public void setFileEncoding(Charset value) { + _fileEncoding = value; + } - public static Config getGlobal() - { - return GLOBAL; - } + public void setGlobalSection(boolean value) { + _globalSection = value; + } - public static String getSystemProperty(String name) - { - return getSystemProperty(name, null); - } + public String getGlobalSectionName() { + return _globalSectionName; + } - public static String getSystemProperty(String name, String defaultValue) - { - String value; + public void setGlobalSectionName(String value) { + _globalSectionName = value; + } - try - { - value = System.getProperty(name); - } - catch (SecurityException x) - { - value = null; - } + public void setHeaderComment(boolean value) { + _headerComment = value; + } - return (value == null) ? defaultValue : value; - } + public void setInclude(boolean value) { + _include = value; + } - public void setComment(boolean value) - { - _comment = value; - } + public String getLineSeparator() { + return _lineSeparator; + } - public boolean isEscape() - { - return _escape; - } + public void setLineSeparator(String value) { + _lineSeparator = value; + } - public boolean isEscapeNewline() - { - return _escapeNewline; - } + public void setLowerCaseOption(boolean value) { + _lowerCaseOption = value; + } - public boolean isInclude() - { - return _include; - } - - public boolean isTree() - { - return _tree; - } - - public void setEmptyOption(boolean value) - { - _emptyOption = value; - } - - public void setEmptySection(boolean value) - { - _emptySection = value; - } - - public void setEscape(boolean value) - { - _escape = value; - } - - public void setEscapeKeyOnly(boolean value) - { - _escapeKeyOnly = value; - } - - public void setEscapeNewline(boolean value) - { - _escapeNewline = value; - } - - public Charset getFileEncoding() - { - return _fileEncoding; - } - - public void setFileEncoding(Charset value) - { - _fileEncoding = value; - } - - public void setGlobalSection(boolean value) - { - _globalSection = value; - } - - public String getGlobalSectionName() - { - return _globalSectionName; - } - - public void setGlobalSectionName(String value) - { - _globalSectionName = value; - } - - public void setHeaderComment(boolean value) - { - _headerComment = value; - } - - public void setInclude(boolean value) - { - _include = value; - } - - public String getLineSeparator() - { - return _lineSeparator; - } - - public void setLineSeparator(String value) - { - _lineSeparator = value; - } - - public void setLowerCaseOption(boolean value) - { - _lowerCaseOption = value; - } - - public void setLowerCaseSection(boolean value) - { - _lowerCaseSection = value; - } - - public void setMultiOption(boolean value) - { - _multiOption = value; - } - - public void setMultiSection(boolean value) - { - _multiSection = value; - } + public void setLowerCaseSection(boolean value) { + _lowerCaseSection = value; + } - public boolean isEmptyOption() - { - return _emptyOption; - } - - public boolean isEmptySection() - { - return _emptySection; - } - - public boolean isGlobalSection() - { - return _globalSection; - } - - public boolean isLowerCaseOption() - { - return _lowerCaseOption; - } - - public boolean isLowerCaseSection() - { - return _lowerCaseSection; - } - - public boolean isMultiOption() - { - return _multiOption; - } - - public boolean isMultiSection() - { - return _multiSection; - } - - public boolean isUnnamedSection() - { - return _unnamedSection; - } - - public char getPathSeparator() - { - return _pathSeparator; - } - - public void setPathSeparator(char value) - { - _pathSeparator = value; - } - - public void setPropertyFirstUpper(boolean value) - { - _propertyFirstUpper = value; - } - - public boolean isPropertyFirstUpper() - { - return _propertyFirstUpper; - } - - public boolean isStrictOperator() - { - return _strictOperator; - } - - public void setStrictOperator(boolean value) - { - _strictOperator = value; - } - - public boolean isComment() - { - return _comment; - } - - public boolean isHeaderComment() - { - return _headerComment; - } - - public void setTree(boolean value) - { - _tree = value; - } - - public void setUnnamedSection(boolean value) - { - _unnamedSection = value; - } - - public boolean isEscapeKeyOnly() - { - return _escapeKeyOnly; - } - - @Override public Config clone() - { - try - { - return (Config) super.clone(); - } - catch (CloneNotSupportedException x) - { - throw new AssertionError(x); - } - } - - public final void reset() - { - _emptyOption = getBoolean(PROP_EMPTY_OPTION, DEFAULT_EMPTY_OPTION); - _emptySection = getBoolean(PROP_EMPTY_SECTION, DEFAULT_EMPTY_SECTION); - _globalSection = getBoolean(PROP_GLOBAL_SECTION, DEFAULT_GLOBAL_SECTION); - _globalSectionName = getString(PROP_GLOBAL_SECTION_NAME, DEFAULT_GLOBAL_SECTION_NAME); - _include = getBoolean(PROP_INCLUDE, DEFAULT_INCLUDE); - _lowerCaseOption = getBoolean(PROP_LOWER_CASE_OPTION, DEFAULT_LOWER_CASE_OPTION); - _lowerCaseSection = getBoolean(PROP_LOWER_CASE_SECTION, DEFAULT_LOWER_CASE_SECTION); - _multiOption = getBoolean(PROP_MULTI_OPTION, DEFAULT_MULTI_OPTION); - _multiSection = getBoolean(PROP_MULTI_SECTION, DEFAULT_MULTI_SECTION); - _strictOperator = getBoolean(PROP_STRICT_OPERATOR, DEFAULT_STRICT_OPERATOR); - _unnamedSection = getBoolean(PROP_UNNAMED_SECTION, DEFAULT_UNNAMED_SECTION); - _escape = getBoolean(PROP_ESCAPE, DEFAULT_ESCAPE); - _escapeKeyOnly = getBoolean(PROP_ESCAPE_KEY_ONLY, DEFAULT_ESCAPE_KEY_ONLY); - _escapeNewline = getBoolean(PROP_ESCAPE_NEWLINE, DEFAULT_ESCAPE_NEWLINE); - _pathSeparator = getChar(PROP_PATH_SEPARATOR, DEFAULT_PATH_SEPARATOR); - _tree = getBoolean(PROP_TREE, DEFAULT_TREE); - _propertyFirstUpper = getBoolean(PROP_PROPERTY_FIRST_UPPER, DEFAULT_PROPERTY_FIRST_UPPER); - _lineSeparator = getString(PROP_LINE_SEPARATOR, DEFAULT_LINE_SEPARATOR); - _fileEncoding = getCharset(PROP_FILE_ENCODING, DEFAULT_FILE_ENCODING); - _comment = getBoolean(PROP_COMMENT, DEFAULT_COMMENT); - _headerComment = getBoolean(PROP_HEADER_COMMENT, DEFAULT_HEADER_COMMENT); - } - - private boolean getBoolean(String name, boolean defaultValue) - { - String value = getSystemProperty(KEY_PREFIX + name); - - return (value == null) ? defaultValue : Boolean.parseBoolean(value); - } - - private char getChar(String name, char defaultValue) - { - String value = getSystemProperty(KEY_PREFIX + name); - - return (value == null) ? defaultValue : value.charAt(0); - } - - private Charset getCharset(String name, Charset defaultValue) - { - String value = getSystemProperty(KEY_PREFIX + name); - - return (value == null) ? defaultValue : Charset.forName(value); - } - - private String getString(String name, String defaultValue) - { - return getSystemProperty(KEY_PREFIX + name, defaultValue); - } + public void setMultiOption(boolean value) { + _multiOption = value; + } + + public void setMultiSection(boolean value) { + _multiSection = value; + } + + public boolean isEmptyOption() { + return _emptyOption; + } + + public boolean isEmptySection() { + return _emptySection; + } + + public boolean isGlobalSection() { + return _globalSection; + } + + public boolean isLowerCaseOption() { + return _lowerCaseOption; + } + + public boolean isLowerCaseSection() { + return _lowerCaseSection; + } + + public boolean isMultiOption() { + return _multiOption; + } + + public boolean isMultiSection() { + return _multiSection; + } + + public boolean isUnnamedSection() { + return _unnamedSection; + } + + public char getPathSeparator() { + return _pathSeparator; + } + + public void setPathSeparator(char value) { + _pathSeparator = value; + } + + public void setPropertyFirstUpper(boolean value) { + _propertyFirstUpper = value; + } + + public boolean isPropertyFirstUpper() { + return _propertyFirstUpper; + } + + public boolean isStrictOperator() { + return _strictOperator; + } + + public void setStrictOperator(boolean value) { + _strictOperator = value; + } + + public boolean isComment() { + return _comment; + } + + public boolean isHeaderComment() { + return _headerComment; + } + + public void setTree(boolean value) { + _tree = value; + } + + public void setUnnamedSection(boolean value) { + _unnamedSection = value; + } + + public boolean isEscapeKeyOnly() { + return _escapeKeyOnly; + } + + @Override + public Config clone() { + try { + return (Config) super.clone(); + } catch (CloneNotSupportedException x) { + throw new AssertionError(x); + } + } + + public final void reset() { + _emptyOption = getBoolean(PROP_EMPTY_OPTION, DEFAULT_EMPTY_OPTION); + _emptySection = getBoolean(PROP_EMPTY_SECTION, DEFAULT_EMPTY_SECTION); + _globalSection = getBoolean(PROP_GLOBAL_SECTION, DEFAULT_GLOBAL_SECTION); + _globalSectionName = getString(PROP_GLOBAL_SECTION_NAME, DEFAULT_GLOBAL_SECTION_NAME); + _include = getBoolean(PROP_INCLUDE, DEFAULT_INCLUDE); + _lowerCaseOption = getBoolean(PROP_LOWER_CASE_OPTION, DEFAULT_LOWER_CASE_OPTION); + _lowerCaseSection = getBoolean(PROP_LOWER_CASE_SECTION, DEFAULT_LOWER_CASE_SECTION); + _multiOption = getBoolean(PROP_MULTI_OPTION, DEFAULT_MULTI_OPTION); + _multiSection = getBoolean(PROP_MULTI_SECTION, DEFAULT_MULTI_SECTION); + _strictOperator = getBoolean(PROP_STRICT_OPERATOR, DEFAULT_STRICT_OPERATOR); + _unnamedSection = getBoolean(PROP_UNNAMED_SECTION, DEFAULT_UNNAMED_SECTION); + _escape = getBoolean(PROP_ESCAPE, DEFAULT_ESCAPE); + _escapeKeyOnly = getBoolean(PROP_ESCAPE_KEY_ONLY, DEFAULT_ESCAPE_KEY_ONLY); + _escapeNewline = getBoolean(PROP_ESCAPE_NEWLINE, DEFAULT_ESCAPE_NEWLINE); + _pathSeparator = getChar(PROP_PATH_SEPARATOR, DEFAULT_PATH_SEPARATOR); + _tree = getBoolean(PROP_TREE, DEFAULT_TREE); + _propertyFirstUpper = getBoolean(PROP_PROPERTY_FIRST_UPPER, DEFAULT_PROPERTY_FIRST_UPPER); + _lineSeparator = getString(PROP_LINE_SEPARATOR, DEFAULT_LINE_SEPARATOR); + _fileEncoding = getCharset(PROP_FILE_ENCODING, DEFAULT_FILE_ENCODING); + _comment = getBoolean(PROP_COMMENT, DEFAULT_COMMENT); + _headerComment = getBoolean(PROP_HEADER_COMMENT, DEFAULT_HEADER_COMMENT); + } + + private boolean getBoolean(String name, boolean defaultValue) { + String value = getSystemProperty(KEY_PREFIX + name); + + return (value == null) ? defaultValue : Boolean.parseBoolean(value); + } + + private char getChar(String name, char defaultValue) { + String value = getSystemProperty(KEY_PREFIX + name); + + return (value == null) ? defaultValue : value.charAt(0); + } + + private Charset getCharset(String name, Charset defaultValue) { + String value = getSystemProperty(KEY_PREFIX + name); + + return (value == null) ? defaultValue : Charset.forName(value); + } + + private String getString(String name, String defaultValue) { + return getSystemProperty(KEY_PREFIX + name, defaultValue); + } } diff --git a/src/main/java/org/ini4j/ConfigParser.java b/src/main/java/org/ini4j/ConfigParser.java index 83c76de..1791d7d 100644 --- a/src/main/java/org/ini4j/ConfigParser.java +++ b/src/main/java/org/ini4j/ConfigParser.java @@ -15,9 +15,6 @@ */ package org.ini4j; -import org.ini4j.spi.IniHandler; -import org.ini4j.spi.Warnings; - import java.io.File; import java.io.FileReader; import java.io.FileWriter; @@ -27,9 +24,7 @@ import java.io.Reader; import java.io.Serializable; import java.io.Writer; - import java.net.URL; - import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -37,519 +32,447 @@ import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.ini4j.spi.IniHandler; +import org.ini4j.spi.Warnings; -public class ConfigParser implements Serializable -{ - private static final long serialVersionUID = 9118857036229164353L; - private PyIni _ini; +public class ConfigParser implements Serializable { + private static final long serialVersionUID = 9118857036229164353L; + private PyIni _ini; + + @SuppressWarnings(Warnings.UNCHECKED) + public ConfigParser() { + this(Collections.EMPTY_MAP); + } + + public ConfigParser(Map defaults) { + _ini = new PyIni(defaults); + } + + public boolean getBoolean(String section, String option) + throws NoSectionException, NoOptionException, InterpolationException { + boolean ret; + String value = get(section, option); + + if ("1".equalsIgnoreCase(value) + || "yes".equalsIgnoreCase(value) + || "true".equalsIgnoreCase(value) + || "on".equalsIgnoreCase(value)) { + ret = true; + } else if ("0".equalsIgnoreCase(value) + || "no".equalsIgnoreCase(value) + || "false".equalsIgnoreCase(value) + || "off".equalsIgnoreCase(value)) { + ret = false; + } else { + throw new IllegalArgumentException(value); + } + + return ret; + } + + public double getDouble(String section, String option) + throws NoSectionException, NoOptionException, InterpolationException { + return Double.parseDouble(get(section, option)); + } + + public float getFloat(String section, String option) + throws NoSectionException, NoOptionException, InterpolationException { + return Float.parseFloat(get(section, option)); + } + + public int getInt(String section, String option) + throws NoSectionException, NoOptionException, InterpolationException { + return Integer.parseInt(get(section, option)); + } + + public long getLong(String section, String option) + throws NoSectionException, NoOptionException, InterpolationException { + return Long.parseLong(get(section, option)); + } + + public void addSection(String section) throws DuplicateSectionException { + if (_ini.containsKey(section)) { + throw new DuplicateSectionException(section); + } else if (PyIni.DEFAULT_SECTION_NAME.equalsIgnoreCase(section)) { + throw new IllegalArgumentException(section); + } + + _ini.add(section); + } + + public Map defaults() { + return _ini.getDefaults(); + } + + @SuppressWarnings(Warnings.UNCHECKED) + public String get(String section, String option) + throws NoSectionException, NoOptionException, InterpolationException { + return get(section, option, false, Collections.EMPTY_MAP); + } + + @SuppressWarnings(Warnings.UNCHECKED) + public String get(String section, String option, boolean raw) + throws NoSectionException, NoOptionException, InterpolationException { + return get(section, option, raw, Collections.EMPTY_MAP); + } + + public String get( + String sectionName, String optionName, boolean raw, Map variables) + throws NoSectionException, NoOptionException, InterpolationException { + String value = requireOption(sectionName, optionName); - @SuppressWarnings(Warnings.UNCHECKED) - public ConfigParser() - { - this(Collections.EMPTY_MAP); + if (!raw && (value != null) && (value.indexOf(PyIni.SUBST_CHAR) >= 0)) { + value = _ini.fetch(sectionName, optionName, variables); } - public ConfigParser(Map defaults) - { - _ini = new PyIni(defaults); - } + return value; + } - public boolean getBoolean(String section, String option) throws NoSectionException, NoOptionException, InterpolationException - { - boolean ret; - String value = get(section, option); + public boolean hasOption(String sectionName, String optionName) { + Ini.Section section = _ini.get(sectionName); - if ("1".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value) || "on".equalsIgnoreCase(value)) - { - ret = true; - } - else if ("0".equalsIgnoreCase(value) || "no".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value) - || "off".equalsIgnoreCase(value)) - { - ret = false; - } - else - { - throw new IllegalArgumentException(value); - } + return (section != null) && section.containsKey(optionName); + } - return ret; - } + public boolean hasSection(String sectionName) { + return _ini.containsKey(sectionName); + } - public double getDouble(String section, String option) throws NoSectionException, NoOptionException, InterpolationException - { - return Double.parseDouble(get(section, option)); - } + @SuppressWarnings(Warnings.UNCHECKED) + public List> items(String sectionName) + throws NoSectionException, InterpolationMissingOptionException { + return items(sectionName, false, Collections.EMPTY_MAP); + } - public float getFloat(String section, String option) throws NoSectionException, NoOptionException, InterpolationException - { - return Float.parseFloat(get(section, option)); - } + @SuppressWarnings(Warnings.UNCHECKED) + public List> items(String sectionName, boolean raw) + throws NoSectionException, InterpolationMissingOptionException { + return items(sectionName, raw, Collections.EMPTY_MAP); + } - public int getInt(String section, String option) throws NoSectionException, NoOptionException, InterpolationException - { - return Integer.parseInt(get(section, option)); - } + public List> items( + String sectionName, boolean raw, Map variables) + throws NoSectionException, InterpolationMissingOptionException { + Ini.Section section = requireSection(sectionName); + Map ret; - public long getLong(String section, String option) throws NoSectionException, NoOptionException, InterpolationException - { - return Long.parseLong(get(section, option)); + if (raw) { + ret = new HashMap(section); + } else { + ret = new HashMap(); + for (String key : section.keySet()) { + ret.put(key, _ini.fetch(section, key, variables)); + } } - public void addSection(String section) throws DuplicateSectionException - { - if (_ini.containsKey(section)) - { - throw new DuplicateSectionException(section); - } - else if (PyIni.DEFAULT_SECTION_NAME.equalsIgnoreCase(section)) - { - throw new IllegalArgumentException(section); - } + return new ArrayList>(ret.entrySet()); + } - _ini.add(section); - } + public List options(String sectionName) throws NoSectionException { + requireSection(sectionName); - public Map defaults() - { - return _ini.getDefaults(); - } + return new ArrayList(_ini.get(sectionName).keySet()); + } - @SuppressWarnings(Warnings.UNCHECKED) - public String get(String section, String option) throws NoSectionException, NoOptionException, InterpolationException - { - return get(section, option, false, Collections.EMPTY_MAP); + public void read(String... filenames) throws IOException, ParsingException { + for (String filename : filenames) { + read(new File(filename)); } + } - @SuppressWarnings(Warnings.UNCHECKED) - public String get(String section, String option, boolean raw) throws NoSectionException, NoOptionException, InterpolationException - { - return get(section, option, raw, Collections.EMPTY_MAP); + public void read(Reader reader) throws IOException, ParsingException { + try { + _ini.load(reader); + } catch (InvalidFileFormatException x) { + throw new ParsingException(x); } + } - public String get(String sectionName, String optionName, boolean raw, Map variables) throws NoSectionException, - NoOptionException, InterpolationException - { - String value = requireOption(sectionName, optionName); - - if (!raw && (value != null) && (value.indexOf(PyIni.SUBST_CHAR) >= 0)) - { - value = _ini.fetch(sectionName, optionName, variables); - } - - return value; + public void read(URL url) throws IOException, ParsingException { + try { + _ini.load(url); + } catch (InvalidFileFormatException x) { + throw new ParsingException(x); } + } - public boolean hasOption(String sectionName, String optionName) - { - Ini.Section section = _ini.get(sectionName); - - return (section != null) && section.containsKey(optionName); + public void read(File file) throws IOException, ParsingException { + try { + _ini.load(new FileReader(file)); + } catch (InvalidFileFormatException x) { + throw new ParsingException(x); } + } - public boolean hasSection(String sectionName) - { - return _ini.containsKey(sectionName); + public void read(InputStream stream) throws IOException, ParsingException { + try { + _ini.load(stream); + } catch (InvalidFileFormatException x) { + throw new ParsingException(x); } + } - @SuppressWarnings(Warnings.UNCHECKED) - public List> items(String sectionName) throws NoSectionException, InterpolationMissingOptionException - { - return items(sectionName, false, Collections.EMPTY_MAP); - } + public boolean removeOption(String sectionName, String optionName) throws NoSectionException { + Ini.Section section = requireSection(sectionName); + boolean ret = section.containsKey(optionName); - @SuppressWarnings(Warnings.UNCHECKED) - public List> items(String sectionName, boolean raw) throws NoSectionException, - InterpolationMissingOptionException - { - return items(sectionName, raw, Collections.EMPTY_MAP); - } + section.remove(optionName); - public List> items(String sectionName, boolean raw, Map variables) throws NoSectionException, - InterpolationMissingOptionException - { - Ini.Section section = requireSection(sectionName); - Map ret; + return ret; + } - if (raw) - { - ret = new HashMap(section); - } - else - { - ret = new HashMap(); - for (String key : section.keySet()) - { - ret.put(key, _ini.fetch(section, key, variables)); - } - } + public boolean removeSection(String sectionName) { + boolean ret = _ini.containsKey(sectionName); - return new ArrayList>(ret.entrySet()); - } + _ini.remove(sectionName); - public List options(String sectionName) throws NoSectionException - { - requireSection(sectionName); + return ret; + } - return new ArrayList(_ini.get(sectionName).keySet()); - } + public List sections() { + return new ArrayList(_ini.keySet()); + } - public void read(String... filenames) throws IOException, ParsingException - { - for (String filename : filenames) - { - read(new File(filename)); - } - } + public void set(String sectionName, String optionName, Object value) throws NoSectionException { + Ini.Section section = requireSection(sectionName); - public void read(Reader reader) throws IOException, ParsingException - { - try - { - _ini.load(reader); - } - catch (InvalidFileFormatException x) - { - throw new ParsingException(x); - } + if (value == null) { + section.remove(optionName); + } else { + section.put(optionName, value.toString()); } + } - public void read(URL url) throws IOException, ParsingException - { - try - { - _ini.load(url); - } - catch (InvalidFileFormatException x) - { - throw new ParsingException(x); - } - } + public void write(Writer writer) throws IOException { + _ini.store(writer); + } - public void read(File file) throws IOException, ParsingException - { - try - { - _ini.load(new FileReader(file)); - } - catch (InvalidFileFormatException x) - { - throw new ParsingException(x); - } - } + public void write(OutputStream stream) throws IOException { + _ini.store(stream); + } - public void read(InputStream stream) throws IOException, ParsingException - { - try - { - _ini.load(stream); - } - catch (InvalidFileFormatException x) - { - throw new ParsingException(x); - } - } + public void write(File file) throws IOException { + _ini.store(new FileWriter(file)); + } - public boolean removeOption(String sectionName, String optionName) throws NoSectionException - { - Ini.Section section = requireSection(sectionName); - boolean ret = section.containsKey(optionName); + protected Ini getIni() { + return _ini; + } - section.remove(optionName); + private String requireOption(String sectionName, String optionName) + throws NoSectionException, NoOptionException { + Ini.Section section = requireSection(sectionName); + String option = section.get(optionName); - return ret; + if (option == null) { + throw new NoOptionException(optionName); } - public boolean removeSection(String sectionName) - { - boolean ret = _ini.containsKey(sectionName); + return option; + } - _ini.remove(sectionName); + private Ini.Section requireSection(String sectionName) throws NoSectionException { + Ini.Section section = _ini.get(sectionName); - return ret; + if (section == null) { + throw new NoSectionException(sectionName); } - public List sections() - { - return new ArrayList(_ini.keySet()); - } + return section; + } - public void set(String sectionName, String optionName, Object value) throws NoSectionException - { - Ini.Section section = requireSection(sectionName); + public static class ConfigParserException extends Exception { - if (value == null) - { - section.remove(optionName); - } - else - { - section.put(optionName, value.toString()); - } - } + /** Use serialVersionUID for interoperability. */ + private static final long serialVersionUID = -6845546313519392093L; - public void write(Writer writer) throws IOException - { - _ini.store(writer); + public ConfigParserException(String message) { + super(message); } + } - public void write(OutputStream stream) throws IOException - { - _ini.store(stream); - } + public static final class DuplicateSectionException extends ConfigParserException { - public void write(File file) throws IOException - { - _ini.store(new FileWriter(file)); - } + /** Use serialVersionUID for interoperability. */ + private static final long serialVersionUID = -5244008445735700699L; - protected Ini getIni() - { - return _ini; + private DuplicateSectionException(String message) { + super(message); } + } - private String requireOption(String sectionName, String optionName) throws NoSectionException, NoOptionException - { - Ini.Section section = requireSection(sectionName); - String option = section.get(optionName); + public static class InterpolationException extends ConfigParserException { - if (option == null) - { - throw new NoOptionException(optionName); - } + /** Use serialVersionUID for interoperability. */ + private static final long serialVersionUID = 8924443303158546939L; - return option; + protected InterpolationException(String message) { + super(message); } + } - private Ini.Section requireSection(String sectionName) throws NoSectionException - { - Ini.Section section = _ini.get(sectionName); + public static final class InterpolationMissingOptionException extends InterpolationException { - if (section == null) - { - throw new NoSectionException(sectionName); - } + /** Use serialVersionUID for interoperability. */ + private static final long serialVersionUID = 2903136975820447879L; - return section; + private InterpolationMissingOptionException(String message) { + super(message); } + } - public static class ConfigParserException extends Exception - { + public static final class NoOptionException extends ConfigParserException { - /** Use serialVersionUID for interoperability. */ private static final long serialVersionUID = -6845546313519392093L; + /** Use serialVersionUID for interoperability. */ + private static final long serialVersionUID = 8460082078809425858L; - public ConfigParserException(String message) - { - super(message); - } + private NoOptionException(String message) { + super(message); } + } - public static final class DuplicateSectionException extends ConfigParserException - { + public static final class NoSectionException extends ConfigParserException { - /** Use serialVersionUID for interoperability. */ private static final long serialVersionUID = -5244008445735700699L; + /** Use serialVersionUID for interoperability. */ + private static final long serialVersionUID = 8553627727493146118L; - private DuplicateSectionException(String message) - { - super(message); - } + private NoSectionException(String message) { + super(message); } + } - public static class InterpolationException extends ConfigParserException - { + public static final class ParsingException extends IOException { - /** Use serialVersionUID for interoperability. */ private static final long serialVersionUID = 8924443303158546939L; + /** Use serialVersionUID for interoperability. */ + private static final long serialVersionUID = -5395990242007205038L; - protected InterpolationException(String message) - { - super(message); - } + private ParsingException(Throwable cause) { + super(cause.getMessage()); + initCause(cause); } + } - public static final class InterpolationMissingOptionException extends InterpolationException - { + static class PyIni extends Ini { + private static final char SUBST_CHAR = '%'; + private static final Pattern EXPRESSION = Pattern.compile("(? _defaults; + private Ini.Section _defaultSection; - /** Use serialVersionUID for interoperability. */ private static final long serialVersionUID = 2903136975820447879L; + public PyIni(Map defaults) { + _defaults = defaults; + Config cfg = getConfig().clone(); - private InterpolationMissingOptionException(String message) - { - super(message); - } + cfg.setEscape(false); + cfg.setMultiOption(false); + cfg.setMultiSection(false); + cfg.setLowerCaseOption(true); + cfg.setLowerCaseSection(true); + super.setConfig(cfg); } - public static final class NoOptionException extends ConfigParserException - { - - /** Use serialVersionUID for interoperability. */ private static final long serialVersionUID = 8460082078809425858L; - - private NoOptionException(String message) - { - super(message); - } + @Override + public void setConfig(Config value) { + assert true; } - public static final class NoSectionException extends ConfigParserException - { + public Map getDefaults() { + return _defaults; + } - /** Use serialVersionUID for interoperability. */ private static final long serialVersionUID = 8553627727493146118L; + @Override + public Section add(String name) { + Section section; - private NoSectionException(String message) - { - super(message); + if (DEFAULT_SECTION_NAME.equalsIgnoreCase(name)) { + if (_defaultSection == null) { + _defaultSection = newSection(name); } - } - public static final class ParsingException extends IOException - { + section = _defaultSection; + } else { + section = super.add(name); + } - /** Use serialVersionUID for interoperability. */ private static final long serialVersionUID = -5395990242007205038L; + return section; + } - private ParsingException(Throwable cause) - { - super(cause.getMessage()); - initCause(cause); - } + public String fetch(String sectionName, String optionName, Map variables) + throws InterpolationMissingOptionException { + return fetch(get(sectionName), optionName, variables); } - static class PyIni extends Ini - { - private static final char SUBST_CHAR = '%'; - private static final Pattern EXPRESSION = Pattern.compile("(? _defaults; - private Ini.Section _defaultSection; - - public PyIni(Map defaults) - { - _defaults = defaults; - Config cfg = getConfig().clone(); - - cfg.setEscape(false); - cfg.setMultiOption(false); - cfg.setMultiSection(false); - cfg.setLowerCaseOption(true); - cfg.setLowerCaseSection(true); - super.setConfig(cfg); - } + protected Ini.Section getDefaultSection() { + return _defaultSection; + } - @Override public void setConfig(Config value) - { - assert true; - } + protected String fetch(Ini.Section section, String optionName, Map variables) + throws InterpolationMissingOptionException { + String value = section.get(optionName); - public Map getDefaults() - { - return _defaults; - } + if ((value != null) && (value.indexOf(SUBST_CHAR) >= 0)) { + StringBuilder buffer = new StringBuilder(value); - @Override public Section add(String name) - { - Section section; - - if (DEFAULT_SECTION_NAME.equalsIgnoreCase(name)) - { - if (_defaultSection == null) - { - _defaultSection = newSection(name); - } - - section = _defaultSection; - } - else - { - section = super.add(name); - } - - return section; - } + resolve(buffer, section, variables); + value = buffer.toString(); + } - public String fetch(String sectionName, String optionName, Map variables) throws InterpolationMissingOptionException - { - return fetch(get(sectionName), optionName, variables); - } + return value; + } - protected Ini.Section getDefaultSection() - { - return _defaultSection; - } + protected void resolve(StringBuilder buffer, Ini.Section owner, Map vars) + throws InterpolationMissingOptionException { + Matcher m = EXPRESSION.matcher(buffer); - protected String fetch(Ini.Section section, String optionName, Map variables) - throws InterpolationMissingOptionException - { - String value = section.get(optionName); + while (m.find()) { + String optionName = m.group(G_OPTION); + String value = owner.get(optionName); - if ((value != null) && (value.indexOf(SUBST_CHAR) >= 0)) - { - StringBuilder buffer = new StringBuilder(value); + if (value == null) { + value = vars.get(optionName); + } - resolve(buffer, section, variables); - value = buffer.toString(); - } + if (value == null) { + value = _defaults.get(optionName); + } - return value; + if ((value == null) && (_defaultSection != null)) { + value = _defaultSection.get(optionName); } - protected void resolve(StringBuilder buffer, Ini.Section owner, Map vars) throws InterpolationMissingOptionException - { - Matcher m = EXPRESSION.matcher(buffer); - - while (m.find()) - { - String optionName = m.group(G_OPTION); - String value = owner.get(optionName); - - if (value == null) - { - value = vars.get(optionName); - } - - if (value == null) - { - value = _defaults.get(optionName); - } - - if ((value == null) && (_defaultSection != null)) - { - value = _defaultSection.get(optionName); - } - - if (value == null) - { - throw new InterpolationMissingOptionException(optionName); - } - - buffer.replace(m.start(), m.end(), value); - m.reset(buffer); - } + if (value == null) { + throw new InterpolationMissingOptionException(optionName); } - @Override protected void store(IniHandler formatter) - { - formatter.startIni(); - if (_defaultSection != null) - { - store(formatter, _defaultSection); - } + buffer.replace(m.start(), m.end(), value); + m.reset(buffer); + } + } - for (Ini.Section s : values()) - { - store(formatter, s); - } + @Override + protected void store(IniHandler formatter) { + formatter.startIni(); + if (_defaultSection != null) { + store(formatter, _defaultSection); + } - formatter.endIni(); - } + for (Ini.Section s : values()) { + store(formatter, s); + } + + formatter.endIni(); + } - @Override protected void store(IniHandler formatter, Section section) - { - formatter.startSection(section.getName()); - for (String name : section.keySet()) - { - formatter.handleOption(name, section.get(name)); - } + @Override + protected void store(IniHandler formatter, Section section) { + formatter.startSection(section.getName()); + for (String name : section.keySet()) { + formatter.handleOption(name, section.get(name)); + } - formatter.endSection(); - } + formatter.endSection(); } + } } diff --git a/src/main/java/org/ini4j/Configurable.java b/src/main/java/org/ini4j/Configurable.java index b0ec2bc..074d7a5 100644 --- a/src/main/java/org/ini4j/Configurable.java +++ b/src/main/java/org/ini4j/Configurable.java @@ -15,9 +15,8 @@ */ package org.ini4j; -public interface Configurable -{ - Config getConfig(); +public interface Configurable { + Config getConfig(); - void setConfig(Config value); + void setConfig(Config value); } diff --git a/src/main/java/org/ini4j/Ini.java b/src/main/java/org/ini4j/Ini.java index 39562a2..2eb4976 100755 --- a/src/main/java/org/ini4j/Ini.java +++ b/src/main/java/org/ini4j/Ini.java @@ -15,11 +15,6 @@ */ package org.ini4j; -import org.ini4j.spi.IniBuilder; -import org.ini4j.spi.IniFormatter; -import org.ini4j.spi.IniHandler; -import org.ini4j.spi.IniParser; - import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; @@ -30,156 +25,148 @@ import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; - import java.net.URL; +import org.ini4j.spi.IniBuilder; +import org.ini4j.spi.IniFormatter; +import org.ini4j.spi.IniHandler; +import org.ini4j.spi.IniParser; -public class Ini extends BasicProfile implements Persistable, Configurable -{ - private static final long serialVersionUID = -6029486578113700585L; - private Config _config; - private File _file; - - public Ini() - { - _config = Config.getGlobal(); - } - - public Ini(Reader input) throws IOException, InvalidFileFormatException - { - this(); - load(input); - } - - public Ini(InputStream input) throws IOException, InvalidFileFormatException - { - this(); - load(input); - } - - public Ini(URL input) throws IOException, InvalidFileFormatException - { - this(); - load(input); - } - - public Ini(File input) throws IOException, InvalidFileFormatException - { - this(); - _file = input; - load(); - } - - @Override public Config getConfig() - { - return _config; - } - - @Override public void setConfig(Config value) - { - _config = value; - } - - @Override public File getFile() - { - return _file; - } - - @Override public void setFile(File value) - { - _file = value; - } - - @Override public void load() throws IOException, InvalidFileFormatException - { - if (_file == null) - { - throw new FileNotFoundException(); - } - - load(_file); - } - - @Override public void load(InputStream input) throws IOException, InvalidFileFormatException - { - load(new InputStreamReader(input, getConfig().getFileEncoding())); - } - - @Override public void load(Reader input) throws IOException, InvalidFileFormatException - { - IniParser.newInstance(getConfig()).parse(input, newBuilder()); - } - - @Override public void load(File input) throws IOException, InvalidFileFormatException - { - load(input.toURI().toURL()); - } - - @Override public void load(URL input) throws IOException, InvalidFileFormatException - { - IniParser.newInstance(getConfig()).parse(input, newBuilder()); - } - - @Override public void store() throws IOException - { - if (_file == null) - { - throw new FileNotFoundException(); - } - - store(_file); - } - - @Override public void store(OutputStream output) throws IOException - { - store(new OutputStreamWriter(output, getConfig().getFileEncoding())); - } - - @Override public void store(Writer output) throws IOException - { - store(IniFormatter.newInstance(output, getConfig())); - } - - @Override public void store(File output) throws IOException - { - OutputStream stream = new FileOutputStream(output); - - store(stream); - stream.close(); - } - - protected IniHandler newBuilder() - { - return IniBuilder.newInstance(this); - } - - @Override protected void store(IniHandler formatter, Profile.Section section) - { - if (getConfig().isEmptySection() || (section.size() != 0)) - { - super.store(formatter, section); - } - } - - @Override protected void store(IniHandler formatter, Profile.Section section, String option, int index) - { - if (getConfig().isMultiOption() || (index == (section.length(option) - 1))) - { - super.store(formatter, section, option, index); - } - } - - @Override boolean isTreeMode() - { - return getConfig().isTree(); - } - - @Override char getPathSeparator() - { - return getConfig().getPathSeparator(); - } - - @Override boolean isPropertyFirstUpper() - { - return getConfig().isPropertyFirstUpper(); - } +public class Ini extends BasicProfile implements Persistable, Configurable { + private static final long serialVersionUID = -6029486578113700585L; + private Config _config; + private File _file; + + public Ini() { + _config = Config.getGlobal(); + } + + public Ini(Reader input) throws IOException, InvalidFileFormatException { + this(); + load(input); + } + + public Ini(InputStream input) throws IOException, InvalidFileFormatException { + this(); + load(input); + } + + public Ini(URL input) throws IOException, InvalidFileFormatException { + this(); + load(input); + } + + public Ini(File input) throws IOException, InvalidFileFormatException { + this(); + _file = input; + load(); + } + + @Override + public Config getConfig() { + return _config; + } + + @Override + public void setConfig(Config value) { + _config = value; + } + + @Override + public File getFile() { + return _file; + } + + @Override + public void setFile(File value) { + _file = value; + } + + @Override + public void load() throws IOException, InvalidFileFormatException { + if (_file == null) { + throw new FileNotFoundException(); + } + + load(_file); + } + + @Override + public void load(InputStream input) throws IOException, InvalidFileFormatException { + load(new InputStreamReader(input, getConfig().getFileEncoding())); + } + + @Override + public void load(Reader input) throws IOException, InvalidFileFormatException { + IniParser.newInstance(getConfig()).parse(input, newBuilder()); + } + + @Override + public void load(File input) throws IOException, InvalidFileFormatException { + load(input.toURI().toURL()); + } + + @Override + public void load(URL input) throws IOException, InvalidFileFormatException { + IniParser.newInstance(getConfig()).parse(input, newBuilder()); + } + + @Override + public void store() throws IOException { + if (_file == null) { + throw new FileNotFoundException(); + } + + store(_file); + } + + @Override + public void store(OutputStream output) throws IOException { + store(new OutputStreamWriter(output, getConfig().getFileEncoding())); + } + + @Override + public void store(Writer output) throws IOException { + store(IniFormatter.newInstance(output, getConfig())); + } + + @Override + public void store(File output) throws IOException { + OutputStream stream = new FileOutputStream(output); + + store(stream); + stream.close(); + } + + protected IniHandler newBuilder() { + return IniBuilder.newInstance(this); + } + + @Override + protected void store(IniHandler formatter, Profile.Section section) { + if (getConfig().isEmptySection() || (section.size() != 0)) { + super.store(formatter, section); + } + } + + @Override + protected void store(IniHandler formatter, Profile.Section section, String option, int index) { + if (getConfig().isMultiOption() || (index == (section.length(option) - 1))) { + super.store(formatter, section, option, index); + } + } + + @Override + boolean isTreeMode() { + return getConfig().isTree(); + } + + @Override + char getPathSeparator() { + return getConfig().getPathSeparator(); + } + + @Override + boolean isPropertyFirstUpper() { + return getConfig().isPropertyFirstUpper(); + } } diff --git a/src/main/java/org/ini4j/IniPreferences.java b/src/main/java/org/ini4j/IniPreferences.java index 1cfe275..bb92be6 100755 --- a/src/main/java/org/ini4j/IniPreferences.java +++ b/src/main/java/org/ini4j/IniPreferences.java @@ -18,389 +18,398 @@ import java.io.IOException; import java.io.InputStream; import java.io.Reader; - import java.net.URL; - import java.util.ArrayList; import java.util.List; import java.util.prefs.AbstractPreferences; import java.util.prefs.BackingStoreException; -public class IniPreferences extends AbstractPreferences -{ +public class IniPreferences extends AbstractPreferences { + + /** frequently used empty String array */ + private static final String[] EMPTY = {}; + + /** underlaying Ini implementation */ + private final Ini _ini; + + /** + * Constructs a new preferences node on top of Ini instance. + * + * @param ini underlaying Ini instance + */ + public IniPreferences(Ini ini) { + super(null, ""); + _ini = ini; + } + + /** + * Constructs a new preferences node based on newly loaded Ini instance. + * + *

This is just a helper constructor, to make simpler constructing IniPreferences + * directly from Reader. + * + * @param input the Reader containing Ini data + * @throws IOException if an I/O error occured + * @throws InvalidFileFormatException if Ini parsing error occured + */ + public IniPreferences(Reader input) throws IOException, InvalidFileFormatException { + super(null, ""); + _ini = new Ini(input); + } + + /** + * Constructs a new preferences node based on newly loaded Ini instance. + * + *

This is just a helper constructor, to make simpler constructing IniPreferences + * directly from InputStream. + * + * @param input the InputStream containing Ini data + * @throws IOException if an I/O error occured + * @throws InvalidFileFormatException if Ini parsing error occured + */ + public IniPreferences(InputStream input) throws IOException, InvalidFileFormatException { + super(null, ""); + _ini = new Ini(input); + } + + /** + * Constructs a new preferences node based on newly loaded Ini instance. + * + *

This is just a helper constructor, to make simpler constructing IniPreferences + * directly from URL. + * + * @param input the URL containing Ini data + * @throws IOException if an I/O error occured + * @throws InvalidFileFormatException if Ini parsing error occured + */ + public IniPreferences(URL input) throws IOException, InvalidFileFormatException { + super(null, ""); + _ini = new Ini(input); + } + + /** + * Provide access to underlaying {@link org.ini4j.Ini} implementation. + * + * @return Ini implementation + */ + protected Ini getIni() { + return _ini; + } + + /** + * Implements the getSpi method as per the specification in {@link + * java.util.prefs.AbstractPreferences#getSpi(String)}. + * + *

This implementation doesn't support this operation, so allways throws + * UnsupportedOperationException. + * + * @return if the value associated with the specified key at this preference node, or null if + * there is no association for this key, or the association cannot be determined at this time. + * @param key key to getvalue for + * @throws UnsupportedOperationException this implementation allways throws this exception + */ + @Override + protected String getSpi(String key) throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + } + + /** + * Implements the childrenNamesSpi method as per the specification in {@link + * java.util.prefs.AbstractPreferences#childrenNamesSpi()}. + * + * @return an array containing the names of the children of this preference node. + * @throws BackingStoreException if this operation cannot be completed due to a failure in the + * backing store, or inability to communicate with it. + */ + @Override + protected String[] childrenNamesSpi() throws BackingStoreException { + List names = new ArrayList(); + + for (String name : _ini.keySet()) { + if (name.indexOf(_ini.getPathSeparator()) < 0) { + names.add(name); + } + } - /** frequently used empty String array */ - private static final String[] EMPTY = {}; + return names.toArray(EMPTY); + } + + /** + * Implements the childSpi method as per the specification in {@link + * java.util.prefs.AbstractPreferences#childSpi(String)}. + * + * @param name child name + * @return child node + */ + @Override + protected SectionPreferences childSpi(String name) { + Ini.Section sec = _ini.get(name); + boolean isNew = sec == null; + + if (isNew) { + sec = _ini.add(name); + } - /** underlaying Ini implementation */ - private final Ini _ini; + return new SectionPreferences(this, sec, isNew); + } + + /** + * Implements the flushSpi method as per the specification in {@link + * java.util.prefs.AbstractPreferences#flushSpi()}. + * + *

This implementation does nothing. + * + * @throws BackingStoreException if this operation cannot be completed due to a failure in the + * backing store, or inability to communicate with it. + */ + @Override + protected void flushSpi() throws BackingStoreException { + assert true; + } + + /** + * Implements the keysSpi method as per the specification in {@link + * java.util.prefs.AbstractPreferences#keysSpi()}. + * + *

This implementation allways return an empty array. + * + * @return an empty array. + * @throws BackingStoreException if this operation cannot be completed due to a failure in the + * backing store, or inability to communicate with it. + */ + @Override + protected String[] keysSpi() throws BackingStoreException { + return EMPTY; + } + + /** + * Implements the putSpi method as per the specification in {@link + * java.util.prefs.AbstractPreferences#putSpi(String,String)}. + * + *

This implementation doesn;t support this operation, so allways throws + * UnsupportedOperationException. + * + * @param key key to set value for + * @param value new value for key + * @throws UnsupportedOperationException this implementation allways throws this exception + */ + @Override + protected void putSpi(String key, String value) throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + } + + /** + * Implements the removeNodeSpi method as per the specification in {@link + * java.util.prefs.AbstractPreferences#removeNodeSpi()}. + * + *

This implementation doesn;t support this operation, so allways throws + * UnsupportedOperationException. + * + * @throws UnsupportedOperationException this implementation allways throws this exception + * @throws BackingStoreException this implementation never throws this exception + */ + @Override + protected void removeNodeSpi() throws BackingStoreException, UnsupportedOperationException { + throw new UnsupportedOperationException(); + } + + /** + * Implements the removeSpi method as per the specification in {@link + * java.util.prefs.AbstractPreferences#removeSpi(String)}. + * + * @param key key to remove + * @throws UnsupportedOperationException this implementation allways throws this exception + */ + @Override + protected void removeSpi(String key) throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + } + + /** + * Implements the syncSpi method as per the specification in {@link + * java.util.prefs.AbstractPreferences#syncSpi()}. + * + *

This implementation does nothing. + * + * @throws BackingStoreException if this operation cannot be completed due to a failure in the + * backing store, or inability to communicate with it. + */ + @Override + protected void syncSpi() throws BackingStoreException { + assert true; + } + + protected class SectionPreferences extends AbstractPreferences { + + /** underlaying Section implementation */ + private final Ini.Section _section; /** - * Constructs a new preferences node on top of Ini instance. + * Constructs a new SectionPreferences instance on top of Ini.Section instance. * - * @param ini underlaying Ini instance + * @param parent parent preferences node + * @parem section underlaying Ini.Section instance + * @param isNew indicate is this a new node or already existing one */ - public IniPreferences(Ini ini) - { - super(null, ""); - _ini = ini; + SectionPreferences(AbstractPreferences parent, Ini.Section section, boolean isNew) { + super(parent, section.getSimpleName()); + _section = section; + newNode = isNew; } /** - * Constructs a new preferences node based on newly loaded Ini instance. + * Implements the flush method as per the specification in {@link + * java.util.prefs.Preferences#flush()}. * - * This is just a helper constructor, to make simpler constructing IniPreferences - * directly from Reader. + *

This implementation just call parent's flush() method. * - * @param input the Reader containing Ini data - * @throws IOException if an I/O error occured - * @throws InvalidFileFormatException if Ini parsing error occured + * @throws BackingStoreException if this operation cannot be completed due to a failure in the + * backing store, or inability to communicate with it. */ - public IniPreferences(Reader input) throws IOException, InvalidFileFormatException - { - super(null, ""); - _ini = new Ini(input); + @Override + public void flush() throws BackingStoreException { + parent().flush(); } /** - * Constructs a new preferences node based on newly loaded Ini instance. + * Implements the sync method as per the specification in {@link + * java.util.prefs.Preferences#sync()}. * - * This is just a helper constructor, to make simpler constructing IniPreferences - * directly from InputStream. + *

This implementation just call parent's sync() method. * - * @param input the InputStream containing Ini data - * @throws IOException if an I/O error occured - * @throws InvalidFileFormatException if Ini parsing error occured + * @throws BackingStoreException if this operation cannot be completed due to a failure in the + * backing store, or inability to communicate with it. */ - public IniPreferences(InputStream input) throws IOException, InvalidFileFormatException - { - super(null, ""); - _ini = new Ini(input); + @Override + public void sync() throws BackingStoreException { + parent().sync(); } /** - * Constructs a new preferences node based on newly loaded Ini instance. - * - * This is just a helper constructor, to make simpler constructing IniPreferences - * directly from URL. + * Implements the getSpi method as per the specification in {@link + * java.util.prefs.AbstractPreferences#getSpi(String)}. * - * @param input the URL containing Ini data - * @throws IOException if an I/O error occured - * @throws InvalidFileFormatException if Ini parsing error occured + * @return if the value associated with the specified key at this preference node, or null if + * there is no association for this key, or the association cannot be determined at this + * time. + * @param key key to getvalue for */ - public IniPreferences(URL input) throws IOException, InvalidFileFormatException - { - super(null, ""); - _ini = new Ini(input); + @Override + protected String getSpi(String key) { + return _section.fetch(key); } /** - * Provide access to underlaying {@link org.ini4j.Ini} implementation. + * Implements the childrenNamesSpi method as per the specification in {@link + * java.util.prefs.AbstractPreferences#childrenNamesSpi()}. * - * @return Ini implementation + *

This implementation allways returns an empty array. + * + * @return an emty array. + * @throws BackingStoreException if this operation cannot be completed due to a failure in the + * backing store, or inability to communicate with it. */ - protected Ini getIni() - { - return _ini; + @Override + protected String[] childrenNamesSpi() throws BackingStoreException { + return _section.childrenNames(); } /** - * Implements the getSpi method as per the specification in - * {@link java.util.prefs.AbstractPreferences#getSpi(String)}. + * Implements the childSpi method as per the specification in {@link + * java.util.prefs.AbstractPreferences#childSpi(String)}. * - * This implementation doesn't support this operation, so allways throws UnsupportedOperationException. + *

This implementation doesn't support this operation. * - * @return if the value associated with the specified key at this preference node, or null if there is no association for this key, or the association cannot be determined at this time. - * @param key key to getvalue for * @throws UnsupportedOperationException this implementation allways throws this exception - */ - @Override protected String getSpi(String key) throws UnsupportedOperationException - { - throw new UnsupportedOperationException(); - } - - /** - * Implements the childrenNamesSpi method as per the specification in - * {@link java.util.prefs.AbstractPreferences#childrenNamesSpi()}. - * @return an array containing the names of the children of this preference node. - * @throws BackingStoreException if this operation cannot be completed due to a failure in the backing store, or inability to communicate with it. - */ - @Override protected String[] childrenNamesSpi() throws BackingStoreException - { - List names = new ArrayList(); - - for (String name : _ini.keySet()) - { - if (name.indexOf(_ini.getPathSeparator()) < 0) - { - names.add(name); - } - } - - return names.toArray(EMPTY); - } - - /** - * Implements the childSpi method as per the specification in - * {@link java.util.prefs.AbstractPreferences#childSpi(String)}. * @param name child name * @return child node */ - @Override protected SectionPreferences childSpi(String name) - { - Ini.Section sec = _ini.get(name); - boolean isNew = sec == null; + @Override + protected SectionPreferences childSpi(String name) throws UnsupportedOperationException { + Ini.Section child = _section.getChild(name); + boolean isNew = child == null; - if (isNew) - { - sec = _ini.add(name); - } + if (isNew) { + child = _section.addChild(name); + } - return new SectionPreferences(this, sec, isNew); + return new SectionPreferences(this, child, isNew); } /** - * Implements the flushSpi method as per the specification in - * {@link java.util.prefs.AbstractPreferences#flushSpi()}. + * Implements the flushSpi method as per the specification in {@link + * java.util.prefs.AbstractPreferences#flushSpi()}. * - * This implementation does nothing. + *

This implementation does nothing. * - * @throws BackingStoreException if this operation cannot be completed due to a failure in the backing store, or inability to communicate with it. + * @throws BackingStoreException if this operation cannot be completed due to a failure in the + * backing store, or inability to communicate with it. */ - @Override protected void flushSpi() throws BackingStoreException - { - assert true; + @Override + protected void flushSpi() throws BackingStoreException { + assert true; } /** - * Implements the keysSpi method as per the specification in - * {@link java.util.prefs.AbstractPreferences#keysSpi()}. - * - * This implementation allways return an empty array. + * Implements the keysSpi method as per the specification in {@link + * java.util.prefs.AbstractPreferences#keysSpi()}. * - * @return an empty array. - * @throws BackingStoreException if this operation cannot be completed due to a failure in the backing store, or inability to communicate with it. + * @return an array of the keys that have an associated value in this preference node. + * @throws BackingStoreException if this operation cannot be completed due to a failure in the + * backing store, or inability to communicate with it. */ - @Override protected String[] keysSpi() throws BackingStoreException - { - return EMPTY; + @Override + protected String[] keysSpi() throws BackingStoreException { + return _section.keySet().toArray(EMPTY); } /** - * Implements the putSpi method as per the specification in - * {@link java.util.prefs.AbstractPreferences#putSpi(String,String)}. - * - * This implementation doesn;t support this operation, so allways throws UnsupportedOperationException. + * Implements the putSpi method as per the specification in {@link + * java.util.prefs.AbstractPreferences#putSpi(String,String)}. * * @param key key to set value for - * @param value new value for key - * @throws UnsupportedOperationException this implementation allways throws this exception + * @param value new value of key */ - @Override protected void putSpi(String key, String value) throws UnsupportedOperationException - { - throw new UnsupportedOperationException(); + @Override + protected void putSpi(String key, String value) { + _section.put(key, value); } /** - * Implements the removeNodeSpi method as per the specification in - * {@link java.util.prefs.AbstractPreferences#removeNodeSpi()}. + * Implements the removeNodeSpi method as per the specification in {@link + * java.util.prefs.AbstractPreferences#removeNodeSpi()}. * - * This implementation doesn;t support this operation, so allways throws UnsupportedOperationException. - * @throws UnsupportedOperationException this implementation allways throws this exception - * @throws BackingStoreException this implementation never throws this exception + * @throws BackingStoreException if this operation cannot be completed due to a failure in the + * backing store, or inability to communicate with it. */ - @Override protected void removeNodeSpi() throws BackingStoreException, UnsupportedOperationException - { - throw new UnsupportedOperationException(); + @Override + protected void removeNodeSpi() throws BackingStoreException { + _ini.remove(_section); } /** - * Implements the removeSpi method as per the specification in - * {@link java.util.prefs.AbstractPreferences#removeSpi(String)}. + * Implements the removeSpi method as per the specification in {@link + * java.util.prefs.AbstractPreferences#removeSpi(String)}. + * * @param key key to remove - * @throws UnsupportedOperationException this implementation allways throws this exception */ - @Override protected void removeSpi(String key) throws UnsupportedOperationException - { - throw new UnsupportedOperationException(); + @Override + protected void removeSpi(String key) { + _section.remove(key); } /** - * Implements the syncSpi method as per the specification in - * {@link java.util.prefs.AbstractPreferences#syncSpi()}. + * Implements the syncSpi method as per the specification in {@link + * java.util.prefs.AbstractPreferences#syncSpi()}. * - * This implementation does nothing. + *

This implementation does nothing. * - * @throws BackingStoreException if this operation cannot be completed due to a failure in the backing store, or inability to communicate with it. + * @throws BackingStoreException if this operation cannot be completed due to a failure in the + * backing store, or inability to communicate with it. */ - @Override protected void syncSpi() throws BackingStoreException - { - assert true; - } - - protected class SectionPreferences extends AbstractPreferences - { - - /** underlaying Section implementation */ - private final Ini.Section _section; - - /** - * Constructs a new SectionPreferences instance on top of Ini.Section instance. - * - * @param parent parent preferences node - * @parem section underlaying Ini.Section instance - * @param isNew indicate is this a new node or already existing one - */ - SectionPreferences(AbstractPreferences parent, Ini.Section section, boolean isNew) - { - super(parent, section.getSimpleName()); - _section = section; - newNode = isNew; - } - - /** - * Implements the flush method as per the specification in - * {@link java.util.prefs.Preferences#flush()}. - * - * This implementation just call parent's flush() method. - * - * @throws BackingStoreException if this operation cannot be completed due to a failure in the backing store, or inability to communicate with it. - */ - @Override public void flush() throws BackingStoreException - { - parent().flush(); - } - - /** - * Implements the sync method as per the specification in - * {@link java.util.prefs.Preferences#sync()}. - * - * This implementation just call parent's sync() method. - * - * @throws BackingStoreException if this operation cannot be completed due to a failure in the backing store, or inability to communicate with it. - */ - @Override public void sync() throws BackingStoreException - { - parent().sync(); - } - - /** - * Implements the getSpi method as per the specification in - * {@link java.util.prefs.AbstractPreferences#getSpi(String)}. - * @return if the value associated with the specified key at this preference node, or null if there is no association for this key, or the association cannot be determined at this time. - * @param key key to getvalue for - */ - @Override protected String getSpi(String key) - { - return _section.fetch(key); - } - - /** - * Implements the childrenNamesSpi method as per the specification in - * {@link java.util.prefs.AbstractPreferences#childrenNamesSpi()}. - * - * This implementation allways returns an empty array. - * - * @return an emty array. - * @throws BackingStoreException if this operation cannot be completed due to a failure in the backing store, or inability to communicate with it. - */ - @Override protected String[] childrenNamesSpi() throws BackingStoreException - { - return _section.childrenNames(); - } - - /** - * Implements the childSpi method as per the specification in - * {@link java.util.prefs.AbstractPreferences#childSpi(String)}. - * - * This implementation doesn't support this operation. - * - * @throws UnsupportedOperationException this implementation allways throws this exception - * @param name child name - * @return child node - */ - @Override protected SectionPreferences childSpi(String name) throws UnsupportedOperationException - { - Ini.Section child = _section.getChild(name); - boolean isNew = child == null; - - if (isNew) - { - child = _section.addChild(name); - } - - return new SectionPreferences(this, child, isNew); - } - - /** - * Implements the flushSpi method as per the specification in - * {@link java.util.prefs.AbstractPreferences#flushSpi()}. - * - * This implementation does nothing. - * - * @throws BackingStoreException if this operation cannot be completed due to a failure in the backing store, or inability to communicate with it. - */ - @Override protected void flushSpi() throws BackingStoreException - { - assert true; - } - - /** - * Implements the keysSpi method as per the specification in - * {@link java.util.prefs.AbstractPreferences#keysSpi()}. - * - * @return an array of the keys that have an associated value in this preference node. - * @throws BackingStoreException if this operation cannot be completed due to a failure in the backing store, or inability to communicate with it. - */ - @Override protected String[] keysSpi() throws BackingStoreException - { - return _section.keySet().toArray(EMPTY); - } - - /** - * Implements the putSpi method as per the specification in - * {@link java.util.prefs.AbstractPreferences#putSpi(String,String)}. - * - * @param key key to set value for - * @param value new value of key - */ - @Override protected void putSpi(String key, String value) - { - _section.put(key, value); - } - - /** - * Implements the removeNodeSpi method as per the specification in - * {@link java.util.prefs.AbstractPreferences#removeNodeSpi()}. - * - * @throws BackingStoreException if this operation cannot be completed due to a failure in the backing store, or inability to communicate with it. - */ - @Override protected void removeNodeSpi() throws BackingStoreException - { - _ini.remove(_section); - } - - /** - * Implements the removeSpi method as per the specification in - * {@link java.util.prefs.AbstractPreferences#removeSpi(String)}. - * @param key key to remove - */ - @Override protected void removeSpi(String key) - { - _section.remove(key); - } - - /** - * Implements the syncSpi method as per the specification in - * {@link java.util.prefs.AbstractPreferences#syncSpi()}. - * - * This implementation does nothing. - * - * @throws BackingStoreException if this operation cannot be completed due to a failure in the backing store, or inability to communicate with it. - */ - @Override protected void syncSpi() throws BackingStoreException - { - assert true; - } + @Override + protected void syncSpi() throws BackingStoreException { + assert true; } + } } diff --git a/src/main/java/org/ini4j/IniPreferencesFactory.java b/src/main/java/org/ini4j/IniPreferencesFactory.java index 905ea34..aab462d 100755 --- a/src/main/java/org/ini4j/IniPreferencesFactory.java +++ b/src/main/java/org/ini4j/IniPreferencesFactory.java @@ -16,117 +16,91 @@ package org.ini4j; import java.io.InputStream; - import java.net.URI; import java.net.URL; - import java.util.Properties; import java.util.prefs.Preferences; import java.util.prefs.PreferencesFactory; -public class IniPreferencesFactory implements PreferencesFactory -{ - public static final String PROPERTIES = "ini4j.properties"; - public static final String KEY_USER = "org.ini4j.prefs.user"; - public static final String KEY_SYSTEM = "org.ini4j.prefs.system"; - private Preferences _system; - private Preferences _user; - - @Override public synchronized Preferences systemRoot() - { - if (_system == null) - { - _system = newIniPreferences(KEY_SYSTEM); - } - - return _system; +public class IniPreferencesFactory implements PreferencesFactory { + public static final String PROPERTIES = "ini4j.properties"; + public static final String KEY_USER = "org.ini4j.prefs.user"; + public static final String KEY_SYSTEM = "org.ini4j.prefs.system"; + private Preferences _system; + private Preferences _user; + + @Override + public synchronized Preferences systemRoot() { + if (_system == null) { + _system = newIniPreferences(KEY_SYSTEM); } - @Override public synchronized Preferences userRoot() - { - if (_user == null) - { - _user = newIniPreferences(KEY_USER); - } + return _system; + } - return _user; + @Override + public synchronized Preferences userRoot() { + if (_user == null) { + _user = newIniPreferences(KEY_USER); } - String getIniLocation(String key) - { - String location = Config.getSystemProperty(key); - - if (location == null) - { - try - { - Properties props = new Properties(); - - props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(PROPERTIES)); - location = props.getProperty(key); - } - catch (Exception x) - { - assert true; - } - } - - return location; - } + return _user; + } + + String getIniLocation(String key) { + String location = Config.getSystemProperty(key); + + if (location == null) { + try { + Properties props = new Properties(); - URL getResource(String location) throws IllegalArgumentException - { - try - { - URI uri = new URI(location); - URL url; - - if (uri.getScheme() == null) - { - url = Thread.currentThread().getContextClassLoader().getResource(location); - } - else - { - url = uri.toURL(); - } - - return url; - } - catch (Exception x) - { - throw (IllegalArgumentException) new IllegalArgumentException().initCause(x); - } + props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(PROPERTIES)); + location = props.getProperty(key); + } catch (Exception x) { + assert true; + } } - InputStream getResourceAsStream(String location) throws IllegalArgumentException - { - try - { - return getResource(location).openStream(); - } - catch (Exception x) - { - throw (IllegalArgumentException) new IllegalArgumentException().initCause(x); - } + return location; + } + + URL getResource(String location) throws IllegalArgumentException { + try { + URI uri = new URI(location); + URL url; + + if (uri.getScheme() == null) { + url = Thread.currentThread().getContextClassLoader().getResource(location); + } else { + url = uri.toURL(); + } + + return url; + } catch (Exception x) { + throw (IllegalArgumentException) new IllegalArgumentException().initCause(x); } + } - Preferences newIniPreferences(String key) - { - Ini ini = new Ini(); - String location = getIniLocation(key); - - if (location != null) - { - try - { - ini.load(getResourceAsStream(location)); - } - catch (Exception x) - { - throw (IllegalArgumentException) new IllegalArgumentException().initCause(x); - } - } - - return new IniPreferences(ini); + InputStream getResourceAsStream(String location) throws IllegalArgumentException { + try { + return getResource(location).openStream(); + } catch (Exception x) { + throw (IllegalArgumentException) new IllegalArgumentException().initCause(x); } + } + + Preferences newIniPreferences(String key) { + Ini ini = new Ini(); + String location = getIniLocation(key); + + if (location != null) { + try { + ini.load(getResourceAsStream(location)); + } catch (Exception x) { + throw (IllegalArgumentException) new IllegalArgumentException().initCause(x); + } + } + + return new IniPreferences(ini); + } } diff --git a/src/main/java/org/ini4j/InvalidFileFormatException.java b/src/main/java/org/ini4j/InvalidFileFormatException.java index 43e87ee..5a75dc7 100755 --- a/src/main/java/org/ini4j/InvalidFileFormatException.java +++ b/src/main/java/org/ini4j/InvalidFileFormatException.java @@ -17,12 +17,10 @@ import java.io.IOException; -public class InvalidFileFormatException extends IOException -{ - private static final long serialVersionUID = -4354616830804732309L; +public class InvalidFileFormatException extends IOException { + private static final long serialVersionUID = -4354616830804732309L; - public InvalidFileFormatException(String message) - { - super(message); - } + public InvalidFileFormatException(String message) { + super(message); + } } diff --git a/src/main/java/org/ini4j/MultiMap.java b/src/main/java/org/ini4j/MultiMap.java index b0585a9..d363d20 100644 --- a/src/main/java/org/ini4j/MultiMap.java +++ b/src/main/java/org/ini4j/MultiMap.java @@ -18,21 +18,20 @@ import java.util.List; import java.util.Map; -public interface MultiMap extends Map -{ - List getAll(Object key); +public interface MultiMap extends Map { + List getAll(Object key); - void add(K key, V value); + void add(K key, V value); - void add(K key, V value, int index); + void add(K key, V value, int index); - V get(Object key, int index); + V get(Object key, int index); - int length(Object key); + int length(Object key); - V put(K key, V value, int index); + V put(K key, V value, int index); - List putAll(K key, List values); + List putAll(K key, List values); - V remove(Object key, int index); + V remove(Object key, int index); } diff --git a/src/main/java/org/ini4j/OptionMap.java b/src/main/java/org/ini4j/OptionMap.java index dd48089..8943d00 100644 --- a/src/main/java/org/ini4j/OptionMap.java +++ b/src/main/java/org/ini4j/OptionMap.java @@ -15,51 +15,50 @@ */ package org.ini4j; -public interface OptionMap extends MultiMap, CommentedMap -{ - T getAll(Object key, Class clazz); +public interface OptionMap extends MultiMap, CommentedMap { + T getAll(Object key, Class clazz); - void add(String key, Object value); + void add(String key, Object value); - void add(String key, Object value, int index); + void add(String key, Object value, int index); - T as(Class clazz); + T as(Class clazz); - T as(Class clazz, String keyPrefix); + T as(Class clazz, String keyPrefix); - String fetch(Object key); + String fetch(Object key); - String fetch(Object key, String defaultValue); + String fetch(Object key, String defaultValue); - String fetch(Object key, int index); + String fetch(Object key, int index); - T fetch(Object key, Class clazz); + T fetch(Object key, Class clazz); - T fetch(Object key, Class clazz, T defaultValue); + T fetch(Object key, Class clazz, T defaultValue); - T fetch(Object key, int index, Class clazz); + T fetch(Object key, int index, Class clazz); - T fetchAll(Object key, Class clazz); + T fetchAll(Object key, Class clazz); - void from(Object bean); + void from(Object bean); - void from(Object bean, String keyPrefix); + void from(Object bean, String keyPrefix); - String get(Object key, String defaultValue); + String get(Object key, String defaultValue); - T get(Object key, Class clazz); + T get(Object key, Class clazz); - T get(Object key, Class clazz, T defaultValue); + T get(Object key, Class clazz, T defaultValue); - T get(Object key, int index, Class clazz); + T get(Object key, int index, Class clazz); - String put(String key, Object value); + String put(String key, Object value); - String put(String key, Object value, int index); + String put(String key, Object value, int index); - void putAll(String key, Object value); + void putAll(String key, Object value); - void to(Object bean); + void to(Object bean); - void to(Object bean, String keyPrefix); + void to(Object bean, String keyPrefix); } diff --git a/src/main/java/org/ini4j/Options.java b/src/main/java/org/ini4j/Options.java index 226046f..98ff6ec 100644 --- a/src/main/java/org/ini4j/Options.java +++ b/src/main/java/org/ini4j/Options.java @@ -15,11 +15,6 @@ */ package org.ini4j; -import org.ini4j.spi.OptionsBuilder; -import org.ini4j.spi.OptionsFormatter; -import org.ini4j.spi.OptionsHandler; -import org.ini4j.spi.OptionsParser; - import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; @@ -30,167 +25,155 @@ import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; - import java.net.URL; +import org.ini4j.spi.OptionsBuilder; +import org.ini4j.spi.OptionsFormatter; +import org.ini4j.spi.OptionsHandler; +import org.ini4j.spi.OptionsParser; -public class Options extends BasicOptionMap implements Persistable, Configurable -{ - private static final long serialVersionUID = -1119753444859181822L; - private String _comment; - private Config _config; - private File _file; - - public Options() - { - _config = Config.getGlobal().clone(); - _config.setEmptyOption(true); - } - - public Options(Reader input) throws IOException, InvalidFileFormatException - { - this(); - load(input); - } - - public Options(InputStream input) throws IOException, InvalidFileFormatException - { - this(); - load(input); - } - - public Options(URL input) throws IOException, InvalidFileFormatException - { - this(); - load(input); - } - - public Options(File input) throws IOException, InvalidFileFormatException - { - this(); - _file = input; - load(); - } - - public String getComment() - { - return _comment; - } - - public void setComment(String value) - { - _comment = value; - } - - @Override public Config getConfig() - { - return _config; - } - - @Override public void setConfig(Config value) - { - _config = value; - } - - @Override public File getFile() - { - return _file; - } - - @Override public void setFile(File value) - { - _file = value; - } - - @Override public void load() throws IOException, InvalidFileFormatException - { - if (_file == null) - { - throw new FileNotFoundException(); - } - - load(_file); - } - - @Override public void load(InputStream input) throws IOException, InvalidFileFormatException - { - load(new InputStreamReader(input, getConfig().getFileEncoding())); - } - - @Override public void load(Reader input) throws IOException, InvalidFileFormatException - { - OptionsParser.newInstance(getConfig()).parse(input, newBuilder()); - } - - @Override public void load(URL input) throws IOException, InvalidFileFormatException - { - OptionsParser.newInstance(getConfig()).parse(input, newBuilder()); - } - - @Override public void load(File input) throws IOException, InvalidFileFormatException - { - load(input.toURI().toURL()); - } - - @Override public void store() throws IOException - { - if (_file == null) - { - throw new FileNotFoundException(); - } - - store(_file); - } - - @Override public void store(OutputStream output) throws IOException - { - store(new OutputStreamWriter(output, getConfig().getFileEncoding())); - } - - @Override public void store(Writer output) throws IOException - { - store(OptionsFormatter.newInstance(output, getConfig())); - } - - @Override public void store(File output) throws IOException - { - OutputStream stream = new FileOutputStream(output); - - store(stream); - stream.close(); - } - - protected OptionsHandler newBuilder() - { - return OptionsBuilder.newInstance(this); - } - - protected void store(OptionsHandler formatter) throws IOException - { - formatter.startOptions(); - storeComment(formatter, _comment); - for (String name : keySet()) - { - storeComment(formatter, getComment(name)); - int n = getConfig().isMultiOption() ? length(name) : 1; - - for (int i = 0; i < n; i++) - { - String value = get(name, i); - - formatter.handleOption(name, value); - } - } - - formatter.endOptions(); - } - - @Override boolean isPropertyFirstUpper() - { - return getConfig().isPropertyFirstUpper(); - } - - private void storeComment(OptionsHandler formatter, String comment) - { - formatter.handleComment(comment); - } +public class Options extends BasicOptionMap implements Persistable, Configurable { + private static final long serialVersionUID = -1119753444859181822L; + private String _comment; + private Config _config; + private File _file; + + public Options() { + _config = Config.getGlobal().clone(); + _config.setEmptyOption(true); + } + + public Options(Reader input) throws IOException, InvalidFileFormatException { + this(); + load(input); + } + + public Options(InputStream input) throws IOException, InvalidFileFormatException { + this(); + load(input); + } + + public Options(URL input) throws IOException, InvalidFileFormatException { + this(); + load(input); + } + + public Options(File input) throws IOException, InvalidFileFormatException { + this(); + _file = input; + load(); + } + + public String getComment() { + return _comment; + } + + public void setComment(String value) { + _comment = value; + } + + @Override + public Config getConfig() { + return _config; + } + + @Override + public void setConfig(Config value) { + _config = value; + } + + @Override + public File getFile() { + return _file; + } + + @Override + public void setFile(File value) { + _file = value; + } + + @Override + public void load() throws IOException, InvalidFileFormatException { + if (_file == null) { + throw new FileNotFoundException(); + } + + load(_file); + } + + @Override + public void load(InputStream input) throws IOException, InvalidFileFormatException { + load(new InputStreamReader(input, getConfig().getFileEncoding())); + } + + @Override + public void load(Reader input) throws IOException, InvalidFileFormatException { + OptionsParser.newInstance(getConfig()).parse(input, newBuilder()); + } + + @Override + public void load(URL input) throws IOException, InvalidFileFormatException { + OptionsParser.newInstance(getConfig()).parse(input, newBuilder()); + } + + @Override + public void load(File input) throws IOException, InvalidFileFormatException { + load(input.toURI().toURL()); + } + + @Override + public void store() throws IOException { + if (_file == null) { + throw new FileNotFoundException(); + } + + store(_file); + } + + @Override + public void store(OutputStream output) throws IOException { + store(new OutputStreamWriter(output, getConfig().getFileEncoding())); + } + + @Override + public void store(Writer output) throws IOException { + store(OptionsFormatter.newInstance(output, getConfig())); + } + + @Override + public void store(File output) throws IOException { + OutputStream stream = new FileOutputStream(output); + + store(stream); + stream.close(); + } + + protected OptionsHandler newBuilder() { + return OptionsBuilder.newInstance(this); + } + + protected void store(OptionsHandler formatter) throws IOException { + formatter.startOptions(); + storeComment(formatter, _comment); + for (String name : keySet()) { + storeComment(formatter, getComment(name)); + int n = getConfig().isMultiOption() ? length(name) : 1; + + for (int i = 0; i < n; i++) { + String value = get(name, i); + + formatter.handleOption(name, value); + } + } + + formatter.endOptions(); + } + + @Override + boolean isPropertyFirstUpper() { + return getConfig().isPropertyFirstUpper(); + } + + private void storeComment(OptionsHandler formatter, String comment) { + formatter.handleComment(comment); + } } diff --git a/src/main/java/org/ini4j/Persistable.java b/src/main/java/org/ini4j/Persistable.java index 9a5a8d3..7258b4f 100644 --- a/src/main/java/org/ini4j/Persistable.java +++ b/src/main/java/org/ini4j/Persistable.java @@ -21,30 +21,28 @@ import java.io.OutputStream; import java.io.Reader; import java.io.Writer; - import java.net.URL; -public interface Persistable -{ - File getFile(); +public interface Persistable { + File getFile(); - void setFile(File value); + void setFile(File value); - void load() throws IOException, InvalidFileFormatException; + void load() throws IOException, InvalidFileFormatException; - void load(InputStream input) throws IOException, InvalidFileFormatException; + void load(InputStream input) throws IOException, InvalidFileFormatException; - void load(Reader input) throws IOException, InvalidFileFormatException; + void load(Reader input) throws IOException, InvalidFileFormatException; - void load(File input) throws IOException, InvalidFileFormatException; + void load(File input) throws IOException, InvalidFileFormatException; - void load(URL input) throws IOException, InvalidFileFormatException; + void load(URL input) throws IOException, InvalidFileFormatException; - void store() throws IOException; + void store() throws IOException; - void store(OutputStream output) throws IOException; + void store(OutputStream output) throws IOException; - void store(Writer output) throws IOException; + void store(Writer output) throws IOException; - void store(File output) throws IOException; + void store(File output) throws IOException; } diff --git a/src/main/java/org/ini4j/Profile.java b/src/main/java/org/ini4j/Profile.java index 451c51e..b51ed3d 100644 --- a/src/main/java/org/ini4j/Profile.java +++ b/src/main/java/org/ini4j/Profile.java @@ -15,52 +15,51 @@ */ package org.ini4j; -public interface Profile extends MultiMap, CommentedMap -{ - char PATH_SEPARATOR = '/'; +public interface Profile + extends MultiMap, CommentedMap { + char PATH_SEPARATOR = '/'; - String getComment(); + String getComment(); - void setComment(String value); + void setComment(String value); - Section add(String sectionName); + Section add(String sectionName); - void add(String sectionName, String optionName, Object value); + void add(String sectionName, String optionName, Object value); - T as(Class clazz); + T as(Class clazz); - T as(Class clazz, String prefix); + T as(Class clazz, String prefix); - String fetch(Object sectionName, Object optionName); + String fetch(Object sectionName, Object optionName); - T fetch(Object sectionName, Object optionName, Class clazz); + T fetch(Object sectionName, Object optionName, Class clazz); - String get(Object sectionName, Object optionName); + String get(Object sectionName, Object optionName); - T get(Object sectionName, Object optionName, Class clazz); + T get(Object sectionName, Object optionName, Class clazz); - String put(String sectionName, String optionName, Object value); + String put(String sectionName, String optionName, Object value); - Section remove(Profile.Section section); + Section remove(Profile.Section section); - String removeOption(Object sectionName, Object optionName); + String removeOption(Object sectionName, Object optionName); - interface Section extends OptionMap - { - Section getChild(String key); + interface Section extends OptionMap { + Section getChild(String key); - String getName(); + String getName(); - Section getParent(); + Section getParent(); - String getSimpleName(); + String getSimpleName(); - Section addChild(String key); + Section addChild(String key); - String[] childrenNames(); + String[] childrenNames(); - Section lookup(String... path); + Section lookup(String... path); - void removeChild(String key); - } + void removeChild(String key); + } } diff --git a/src/main/java/org/ini4j/Reg.java b/src/main/java/org/ini4j/Reg.java index fa643a0..1effd77 100644 --- a/src/main/java/org/ini4j/Reg.java +++ b/src/main/java/org/ini4j/Reg.java @@ -15,11 +15,6 @@ */ package org.ini4j; -import org.ini4j.spi.IniFormatter; -import org.ini4j.spi.IniHandler; -import org.ini4j.spi.IniParser; -import org.ini4j.spi.RegBuilder; - import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; @@ -31,284 +26,252 @@ import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; - import java.net.URL; +import org.ini4j.spi.IniFormatter; +import org.ini4j.spi.IniHandler; +import org.ini4j.spi.IniParser; +import org.ini4j.spi.RegBuilder; -public class Reg extends BasicRegistry implements Registry, Persistable, Configurable -{ - private static final long serialVersionUID = -1485602876922985912L; - protected static final String DEFAULT_SUFFIX = ".reg"; - protected static final String TMP_PREFIX = "reg-"; - private static final int STDERR_BUFF_SIZE = 8192; - private static final String PROP_OS_NAME = "os.name"; - private static final boolean WINDOWS = Config.getSystemProperty(PROP_OS_NAME, "Unknown").startsWith("Windows"); - private static final char CR = '\r'; - private static final char LF = '\n'; - private Config _config; - private File _file; - - public Reg() - { - Config cfg = Config.getGlobal().clone(); - - cfg.setEscape(false); - cfg.setGlobalSection(false); - cfg.setEmptyOption(true); - cfg.setMultiOption(true); - cfg.setStrictOperator(true); - cfg.setEmptySection(true); - cfg.setPathSeparator(KEY_SEPARATOR); - cfg.setFileEncoding(FILE_ENCODING); - cfg.setLineSeparator(LINE_SEPARATOR); - _config = cfg; - } - - public Reg(String registryKey) throws IOException - { - this(); - read(registryKey); - } - - public Reg(File input) throws IOException, InvalidFileFormatException - { - this(); - _file = input; - load(); - } - - public Reg(URL input) throws IOException, InvalidFileFormatException - { - this(); - load(input); - } - - public Reg(InputStream input) throws IOException, InvalidFileFormatException - { - this(); - load(input); - } - - public Reg(Reader input) throws IOException, InvalidFileFormatException - { - this(); - load(input); - } - - public static boolean isWindows() - { - return WINDOWS; - } - - @Override public Config getConfig() - { - return _config; - } - - public void setConfig(Config value) - { - _config = value; - } - - @Override public File getFile() - { - return _file; - } - - @Override public void setFile(File value) - { - _file = value; - } - - @Override public void load() throws IOException, InvalidFileFormatException - { - if (_file == null) - { - throw new FileNotFoundException(); - } - - load(_file); - } - - @Override public void load(InputStream input) throws IOException, InvalidFileFormatException - { - load(new InputStreamReader(input, getConfig().getFileEncoding())); - } - - @Override public void load(URL input) throws IOException, InvalidFileFormatException - { - load(new InputStreamReader(input.openStream(), getConfig().getFileEncoding())); - } - - @Override public void load(Reader input) throws IOException, InvalidFileFormatException - { - int newline = 2; - StringBuilder buff = new StringBuilder(); - - for (int c = input.read(); c != -1; c = input.read()) - { - if (c == LF) - { - newline--; - if (newline == 0) - { - break; - } - } - else if ((c != CR) && (newline != 1)) - { - buff.append((char) c); - } - } - - if (buff.length() == 0) - { - throw new InvalidFileFormatException("Missing version header"); - } - - if (!buff.toString().equals(getVersion())) - { - throw new InvalidFileFormatException("Unsupported version: " + buff.toString()); - } - - IniParser.newInstance(getConfig()).parse(input, newBuilder()); - } - - @Override public void load(File input) throws IOException, InvalidFileFormatException - { - load(input.toURI().toURL()); +public class Reg extends BasicRegistry implements Registry, Persistable, Configurable { + private static final long serialVersionUID = -1485602876922985912L; + protected static final String DEFAULT_SUFFIX = ".reg"; + protected static final String TMP_PREFIX = "reg-"; + private static final int STDERR_BUFF_SIZE = 8192; + private static final String PROP_OS_NAME = "os.name"; + private static final boolean WINDOWS = + Config.getSystemProperty(PROP_OS_NAME, "Unknown").startsWith("Windows"); + private static final char CR = '\r'; + private static final char LF = '\n'; + private Config _config; + private File _file; + + public Reg() { + Config cfg = Config.getGlobal().clone(); + + cfg.setEscape(false); + cfg.setGlobalSection(false); + cfg.setEmptyOption(true); + cfg.setMultiOption(true); + cfg.setStrictOperator(true); + cfg.setEmptySection(true); + cfg.setPathSeparator(KEY_SEPARATOR); + cfg.setFileEncoding(FILE_ENCODING); + cfg.setLineSeparator(LINE_SEPARATOR); + _config = cfg; + } + + public Reg(String registryKey) throws IOException { + this(); + read(registryKey); + } + + public Reg(File input) throws IOException, InvalidFileFormatException { + this(); + _file = input; + load(); + } + + public Reg(URL input) throws IOException, InvalidFileFormatException { + this(); + load(input); + } + + public Reg(InputStream input) throws IOException, InvalidFileFormatException { + this(); + load(input); + } + + public Reg(Reader input) throws IOException, InvalidFileFormatException { + this(); + load(input); + } + + public static boolean isWindows() { + return WINDOWS; + } + + @Override + public Config getConfig() { + return _config; + } + + public void setConfig(Config value) { + _config = value; + } + + @Override + public File getFile() { + return _file; + } + + @Override + public void setFile(File value) { + _file = value; + } + + @Override + public void load() throws IOException, InvalidFileFormatException { + if (_file == null) { + throw new FileNotFoundException(); } - public void read(String registryKey) throws IOException - { - File tmp = createTempFile(); - - try - { - regExport(registryKey, tmp); - load(tmp); - } - finally - { - tmp.delete(); + load(_file); + } + + @Override + public void load(InputStream input) throws IOException, InvalidFileFormatException { + load(new InputStreamReader(input, getConfig().getFileEncoding())); + } + + @Override + public void load(URL input) throws IOException, InvalidFileFormatException { + load(new InputStreamReader(input.openStream(), getConfig().getFileEncoding())); + } + + @Override + public void load(Reader input) throws IOException, InvalidFileFormatException { + int newline = 2; + StringBuilder buff = new StringBuilder(); + + for (int c = input.read(); c != -1; c = input.read()) { + if (c == LF) { + newline--; + if (newline == 0) { + break; } + } else if ((c != CR) && (newline != 1)) { + buff.append((char) c); + } } - @Override public void store() throws IOException - { - if (_file == null) - { - throw new FileNotFoundException(); - } - - store(_file); + if (buff.length() == 0) { + throw new InvalidFileFormatException("Missing version header"); } - @Override public void store(OutputStream output) throws IOException - { - store(new OutputStreamWriter(output, getConfig().getFileEncoding())); + if (!buff.toString().equals(getVersion())) { + throw new InvalidFileFormatException("Unsupported version: " + buff.toString()); } - @Override public void store(Writer output) throws IOException - { - output.write(getVersion()); - output.write(getConfig().getLineSeparator()); - output.write(getConfig().getLineSeparator()); - store(IniFormatter.newInstance(output, getConfig())); - } + IniParser.newInstance(getConfig()).parse(input, newBuilder()); + } - @Override public void store(File output) throws IOException - { - OutputStream stream = new FileOutputStream(output); + @Override + public void load(File input) throws IOException, InvalidFileFormatException { + load(input.toURI().toURL()); + } - store(stream); - stream.close(); - } + public void read(String registryKey) throws IOException { + File tmp = createTempFile(); - public void write() throws IOException - { - File tmp = createTempFile(); - - try - { - store(tmp); - regImport(tmp); - } - finally - { - tmp.delete(); - } + try { + regExport(registryKey, tmp); + load(tmp); + } finally { + tmp.delete(); } + } - protected IniHandler newBuilder() - { - return RegBuilder.newInstance(this); + @Override + public void store() throws IOException { + if (_file == null) { + throw new FileNotFoundException(); } - @Override boolean isTreeMode() - { - return getConfig().isTree(); + store(_file); + } + + @Override + public void store(OutputStream output) throws IOException { + store(new OutputStreamWriter(output, getConfig().getFileEncoding())); + } + + @Override + public void store(Writer output) throws IOException { + output.write(getVersion()); + output.write(getConfig().getLineSeparator()); + output.write(getConfig().getLineSeparator()); + store(IniFormatter.newInstance(output, getConfig())); + } + + @Override + public void store(File output) throws IOException { + OutputStream stream = new FileOutputStream(output); + + store(stream); + stream.close(); + } + + public void write() throws IOException { + File tmp = createTempFile(); + + try { + store(tmp); + regImport(tmp); + } finally { + tmp.delete(); } - - @Override char getPathSeparator() - { - return getConfig().getPathSeparator(); + } + + protected IniHandler newBuilder() { + return RegBuilder.newInstance(this); + } + + @Override + boolean isTreeMode() { + return getConfig().isTree(); + } + + @Override + char getPathSeparator() { + return getConfig().getPathSeparator(); + } + + @Override + boolean isPropertyFirstUpper() { + return getConfig().isPropertyFirstUpper(); + } + + void exec(String[] args) throws IOException { + Process proc = Runtime.getRuntime().exec(args); + + try { + int status = proc.waitFor(); + + if (status != 0) { + Reader in = new InputStreamReader(proc.getErrorStream()); + char[] buff = new char[STDERR_BUFF_SIZE]; + int n = in.read(buff); + + in.close(); + throw new IOException(new String(buff, 0, n).trim()); + } + } catch (InterruptedException x) { + throw (IOException) (new InterruptedIOException().initCause(x)); } + } - @Override boolean isPropertyFirstUpper() - { - return getConfig().isPropertyFirstUpper(); - } + private File createTempFile() throws IOException { + File ret = File.createTempFile(TMP_PREFIX, DEFAULT_SUFFIX); - void exec(String[] args) throws IOException - { - Process proc = Runtime.getRuntime().exec(args); + ret.deleteOnExit(); - try - { - int status = proc.waitFor(); + return ret; + } - if (status != 0) - { - Reader in = new InputStreamReader(proc.getErrorStream()); - char[] buff = new char[STDERR_BUFF_SIZE]; - int n = in.read(buff); - - in.close(); - throw new IOException(new String(buff, 0, n).trim()); - } - } - catch (InterruptedException x) - { - throw (IOException) (new InterruptedIOException().initCause(x)); - } - } + private void regExport(String registryKey, File file) throws IOException { + requireWindows(); + exec(new String[] {"cmd", "/c", "reg", "export", registryKey, file.getAbsolutePath()}); + } - private File createTempFile() throws IOException - { - File ret = File.createTempFile(TMP_PREFIX, DEFAULT_SUFFIX); + private void regImport(File file) throws IOException { + requireWindows(); + exec(new String[] {"cmd", "/c", "reg", "import", file.getAbsolutePath()}); + } - ret.deleteOnExit(); - - return ret; - } - - private void regExport(String registryKey, File file) throws IOException - { - requireWindows(); - exec(new String[] { "cmd", "/c", "reg", "export", registryKey, file.getAbsolutePath() }); - } - - private void regImport(File file) throws IOException - { - requireWindows(); - exec(new String[] { "cmd", "/c", "reg", "import", file.getAbsolutePath() }); - } - - private void requireWindows() - { - if (!WINDOWS) - { - throw new UnsupportedOperationException("Unsupported operating system or runtime environment"); - } + private void requireWindows() { + if (!WINDOWS) { + throw new UnsupportedOperationException( + "Unsupported operating system or runtime environment"); } + } } diff --git a/src/main/java/org/ini4j/Registry.java b/src/main/java/org/ini4j/Registry.java index 0839642..398eadc 100644 --- a/src/main/java/org/ini4j/Registry.java +++ b/src/main/java/org/ini4j/Registry.java @@ -16,110 +16,111 @@ package org.ini4j; import java.nio.charset.Charset; - import java.util.HashMap; import java.util.Map; -public interface Registry extends Profile -{ - enum Hive - { - HKEY_CLASSES_ROOT, - HKEY_CURRENT_CONFIG, - HKEY_CURRENT_USER, - HKEY_LOCAL_MACHINE, - HKEY_USERS; +public interface Registry extends Profile { + enum Hive { + HKEY_CLASSES_ROOT, + HKEY_CURRENT_CONFIG, + HKEY_CURRENT_USER, + HKEY_LOCAL_MACHINE, + HKEY_USERS; + } + + // TODO handle delete operations with special Type + enum Type { + REG_NONE("hex(0)"), + REG_SZ(""), + REG_EXPAND_SZ("hex(2)"), + REG_BINARY("hex"), + REG_DWORD("dword"), + REG_DWORD_BIG_ENDIAN("hex(5)"), + REG_LINK("hex(6)"), + REG_MULTI_SZ("hex(7)"), + REG_RESOURCE_LIST("hex(8)"), + REG_FULL_RESOURCE_DESCRIPTOR("hex(9)"), + REG_RESOURCE_REQUIREMENTS_LIST("hex(a)"), + REG_QWORD("hex(b)"); + private static final Map MAPPING; + + static { + MAPPING = new HashMap(); + for (Type t : values()) { + MAPPING.put(t.toString(), t); + } } - // TODO handle delete operations with special Type - enum Type - { - REG_NONE("hex(0)"), - REG_SZ(""), - REG_EXPAND_SZ("hex(2)"), - REG_BINARY("hex"), - REG_DWORD("dword"), - REG_DWORD_BIG_ENDIAN("hex(5)"), - REG_LINK("hex(6)"), - REG_MULTI_SZ("hex(7)"), - REG_RESOURCE_LIST("hex(8)"), - REG_FULL_RESOURCE_DESCRIPTOR("hex(9)"), - REG_RESOURCE_REQUIREMENTS_LIST("hex(a)"), - REG_QWORD("hex(b)"); - private static final Map MAPPING; - - static - { - MAPPING = new HashMap(); - for (Type t : values()) - { - MAPPING.put(t.toString(), t); - } - } - - public static final char SEPARATOR_CHAR = ':'; - public static final String SEPARATOR = String.valueOf(SEPARATOR_CHAR); - public static final char REMOVE_CHAR = '-'; - public static final String REMOVE = String.valueOf(REMOVE_CHAR); - private final String _prefix; - - private Type(String prefix) - { - _prefix = prefix; - } - - public static Type fromString(String str) - { - return MAPPING.get(str); - } - - @Override public String toString() - { - return _prefix; - } + public static final char SEPARATOR_CHAR = ':'; + public static final String SEPARATOR = String.valueOf(SEPARATOR_CHAR); + public static final char REMOVE_CHAR = '-'; + public static final String REMOVE = String.valueOf(REMOVE_CHAR); + private final String _prefix; + + private Type(String prefix) { + _prefix = prefix; } - char ESCAPE_CHAR = '\\'; - Charset FILE_ENCODING = Charset.forName("UnicodeLittle"); - char KEY_SEPARATOR = '\\'; - String LINE_SEPARATOR = "\r\n"; - char TYPE_SEPARATOR = ':'; - String VERSION = "Windows Registry Editor Version 5.00"; + public static Type fromString(String str) { + return MAPPING.get(str); + } - String getVersion(); + @Override + public String toString() { + return _prefix; + } + } - void setVersion(String value); + char ESCAPE_CHAR = '\\'; + Charset FILE_ENCODING = Charset.forName("UnicodeLittle"); + char KEY_SEPARATOR = '\\'; + String LINE_SEPARATOR = "\r\n"; + char TYPE_SEPARATOR = ':'; + String VERSION = "Windows Registry Editor Version 5.00"; - @Override Key get(Object key); + String getVersion(); - @Override Key get(Object key, int index); + void setVersion(String value); - @Override Key put(String key, Section value); + @Override + Key get(Object key); - @Override Key put(String key, Section value, int index); + @Override + Key get(Object key, int index); - @Override Key remove(Object key); + @Override + Key put(String key, Section value); - @Override Key remove(Object key, int index); + @Override + Key put(String key, Section value, int index); - interface Key extends Section - { - String DEFAULT_NAME = "@"; + @Override + Key remove(Object key); - @Override Key getChild(String key); + @Override + Key remove(Object key, int index); - @Override Key getParent(); + interface Key extends Section { + String DEFAULT_NAME = "@"; - Type getType(Object key); + @Override + Key getChild(String key); - Type getType(Object key, Type defaulType); + @Override + Key getParent(); - @Override Key addChild(String key); + Type getType(Object key); - @Override Key lookup(String... path); + Type getType(Object key, Type defaulType); - Type putType(String key, Type type); + @Override + Key addChild(String key); - Type removeType(Object key); - } + @Override + Key lookup(String... path); + + Type putType(String key, Type type); + + Type removeType(Object key); + } } diff --git a/src/main/java/org/ini4j/Wini.java b/src/main/java/org/ini4j/Wini.java index 4267fb4..079f8ad 100644 --- a/src/main/java/org/ini4j/Wini.java +++ b/src/main/java/org/ini4j/Wini.java @@ -15,65 +15,55 @@ */ package org.ini4j; -import org.ini4j.spi.WinEscapeTool; - import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Reader; - import java.net.URL; +import org.ini4j.spi.WinEscapeTool; -public class Wini extends Ini -{ - private static final long serialVersionUID = -2781377824232440728L; - public static final char PATH_SEPARATOR = '\\'; +public class Wini extends Ini { + private static final long serialVersionUID = -2781377824232440728L; + public static final char PATH_SEPARATOR = '\\'; - public Wini() - { - Config cfg = Config.getGlobal().clone(); + public Wini() { + Config cfg = Config.getGlobal().clone(); - cfg.setEscape(false); - cfg.setEscapeNewline(false); - cfg.setGlobalSection(true); - cfg.setEmptyOption(true); - cfg.setMultiOption(false); - cfg.setPathSeparator(PATH_SEPARATOR); - setConfig(cfg); - } + cfg.setEscape(false); + cfg.setEscapeNewline(false); + cfg.setGlobalSection(true); + cfg.setEmptyOption(true); + cfg.setMultiOption(false); + cfg.setPathSeparator(PATH_SEPARATOR); + setConfig(cfg); + } - public Wini(File input) throws IOException, InvalidFileFormatException - { - this(); - setFile(input); - load(); - } + public Wini(File input) throws IOException, InvalidFileFormatException { + this(); + setFile(input); + load(); + } - public Wini(URL input) throws IOException, InvalidFileFormatException - { - this(); - load(input); - } + public Wini(URL input) throws IOException, InvalidFileFormatException { + this(); + load(input); + } - public Wini(InputStream input) throws IOException, InvalidFileFormatException - { - this(); - load(input); - } + public Wini(InputStream input) throws IOException, InvalidFileFormatException { + this(); + load(input); + } - public Wini(Reader input) throws IOException, InvalidFileFormatException - { - this(); - load(input); - } + public Wini(Reader input) throws IOException, InvalidFileFormatException { + this(); + load(input); + } - public String escape(String value) - { - return WinEscapeTool.getInstance().escape(value); - } + public String escape(String value) { + return WinEscapeTool.getInstance().escape(value); + } - public String unescape(String value) - { - return WinEscapeTool.getInstance().unescape(value); - } + public String unescape(String value) { + return WinEscapeTool.getInstance().unescape(value); + } } diff --git a/src/main/java/org/ini4j/spi/AbstractBeanInvocationHandler.java b/src/main/java/org/ini4j/spi/AbstractBeanInvocationHandler.java index 7703cf7..9205aa7 100755 --- a/src/main/java/org/ini4j/spi/AbstractBeanInvocationHandler.java +++ b/src/main/java/org/ini4j/spi/AbstractBeanInvocationHandler.java @@ -21,278 +21,241 @@ import java.beans.PropertyVetoException; import java.beans.VetoableChangeListener; import java.beans.VetoableChangeSupport; - import java.lang.reflect.Array; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; -public abstract class AbstractBeanInvocationHandler implements InvocationHandler -{ - private static final String PROPERTY_CHANGE_LISTENER = "PropertyChangeListener"; - private static final String VETOABLE_CHANGE_LISTENER = "VetoableChangeListener"; - private static final String ADD_PREFIX = "add"; - private static final String READ_PREFIX = "get"; - private static final String REMOVE_PREFIX = "remove"; - private static final String READ_BOOLEAN_PREFIX = "is"; - private static final String WRITE_PREFIX = "set"; - private static final String HAS_PREFIX = "has"; - - private static enum Prefix - { - READ(READ_PREFIX), - READ_BOOLEAN(READ_BOOLEAN_PREFIX), - WRITE(WRITE_PREFIX), - ADD_CHANGE(ADD_PREFIX + PROPERTY_CHANGE_LISTENER), - ADD_VETO(ADD_PREFIX + VETOABLE_CHANGE_LISTENER), - REMOVE_CHANGE(REMOVE_PREFIX + PROPERTY_CHANGE_LISTENER), - REMOVE_VETO(REMOVE_PREFIX + VETOABLE_CHANGE_LISTENER), - HAS(HAS_PREFIX); - private int _len; - private String _value; - - private Prefix(String value) - { - _value = value; - _len = value.length(); - } - - public static Prefix parse(String str) - { - Prefix ret = null; - - for (Prefix p : values()) - { - if (str.startsWith(p.getValue())) - { - ret = p; +public abstract class AbstractBeanInvocationHandler implements InvocationHandler { + private static final String PROPERTY_CHANGE_LISTENER = "PropertyChangeListener"; + private static final String VETOABLE_CHANGE_LISTENER = "VetoableChangeListener"; + private static final String ADD_PREFIX = "add"; + private static final String READ_PREFIX = "get"; + private static final String REMOVE_PREFIX = "remove"; + private static final String READ_BOOLEAN_PREFIX = "is"; + private static final String WRITE_PREFIX = "set"; + private static final String HAS_PREFIX = "has"; + + private static enum Prefix { + READ(READ_PREFIX), + READ_BOOLEAN(READ_BOOLEAN_PREFIX), + WRITE(WRITE_PREFIX), + ADD_CHANGE(ADD_PREFIX + PROPERTY_CHANGE_LISTENER), + ADD_VETO(ADD_PREFIX + VETOABLE_CHANGE_LISTENER), + REMOVE_CHANGE(REMOVE_PREFIX + PROPERTY_CHANGE_LISTENER), + REMOVE_VETO(REMOVE_PREFIX + VETOABLE_CHANGE_LISTENER), + HAS(HAS_PREFIX); + private int _len; + private String _value; + + private Prefix(String value) { + _value = value; + _len = value.length(); + } - break; - } - } + public static Prefix parse(String str) { + Prefix ret = null; - return ret; - } + for (Prefix p : values()) { + if (str.startsWith(p.getValue())) { + ret = p; - public String getTail(String input) - { - return Introspector.decapitalize(input.substring(_len)); + break; } + } - public String getValue() - { - return _value; - } + return ret; } - private PropertyChangeSupport _pcSupport; - private Object _proxy; - private VetoableChangeSupport _vcSupport; + public String getTail(String input) { + return Introspector.decapitalize(input.substring(_len)); + } - @Override public Object invoke(Object proxy, Method method, Object[] args) throws PropertyVetoException - { - Object ret = null; - Prefix prefix = Prefix.parse(method.getName()); + public String getValue() { + return _value; + } + } - if (prefix != null) - { - String tail = prefix.getTail(method.getName()); + private PropertyChangeSupport _pcSupport; + private Object _proxy; + private VetoableChangeSupport _vcSupport; - updateProxy(proxy); - switch (prefix) - { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws PropertyVetoException { + Object ret = null; + Prefix prefix = Prefix.parse(method.getName()); - case READ: - ret = getProperty(prefix.getTail(method.getName()), method.getReturnType()); - break; + if (prefix != null) { + String tail = prefix.getTail(method.getName()); - case READ_BOOLEAN: - ret = getProperty(prefix.getTail(method.getName()), method.getReturnType()); - break; + updateProxy(proxy); + switch (prefix) { + case READ: + ret = getProperty(prefix.getTail(method.getName()), method.getReturnType()); + break; - case WRITE: - setProperty(tail, args[0], method.getParameterTypes()[0]); - break; + case READ_BOOLEAN: + ret = getProperty(prefix.getTail(method.getName()), method.getReturnType()); + break; - case HAS: - ret = Boolean.valueOf(hasProperty(prefix.getTail(method.getName()))); - break; + case WRITE: + setProperty(tail, args[0], method.getParameterTypes()[0]); + break; - case ADD_CHANGE: - addPropertyChangeListener((String) args[0], (PropertyChangeListener) args[1]); - break; + case HAS: + ret = Boolean.valueOf(hasProperty(prefix.getTail(method.getName()))); + break; - case ADD_VETO: - addVetoableChangeListener((String) args[0], (VetoableChangeListener) args[1]); - break; + case ADD_CHANGE: + addPropertyChangeListener((String) args[0], (PropertyChangeListener) args[1]); + break; - case REMOVE_CHANGE: - removePropertyChangeListener((String) args[0], (PropertyChangeListener) args[1]); - break; + case ADD_VETO: + addVetoableChangeListener((String) args[0], (VetoableChangeListener) args[1]); + break; - case REMOVE_VETO: - removeVetoableChangeListener((String) args[0], (VetoableChangeListener) args[1]); - break; + case REMOVE_CHANGE: + removePropertyChangeListener((String) args[0], (PropertyChangeListener) args[1]); + break; - default: - break; - } - } + case REMOVE_VETO: + removeVetoableChangeListener((String) args[0], (VetoableChangeListener) args[1]); + break; - return ret; + default: + break; + } } - protected abstract Object getPropertySpi(String property, Class clazz); - - protected abstract void setPropertySpi(String property, Object value, Class clazz); - - protected abstract boolean hasPropertySpi(String property); - - protected synchronized Object getProperty(String property, Class clazz) - { - Object o; - - try - { - o = getPropertySpi(property, clazz); - if (o == null) - { - o = zero(clazz); - } - else if (clazz.isArray() && (o instanceof String[]) && !clazz.equals(String[].class)) - { - String[] str = (String[]) o; - - o = Array.newInstance(clazz.getComponentType(), str.length); - for (int i = 0; i < str.length; i++) - { - Array.set(o, i, parse(str[i], clazz.getComponentType())); - } - } - else if ((o instanceof String) && !clazz.equals(String.class)) - { - o = parse((String) o, clazz); - } - } - catch (Exception x) - { - o = zero(clazz); - } + return ret; + } - return o; - } + protected abstract Object getPropertySpi(String property, Class clazz); - protected synchronized void setProperty(String property, Object value, Class clazz) throws PropertyVetoException - { - boolean pc = (_pcSupport != null) && _pcSupport.hasListeners(property); - boolean vc = (_vcSupport != null) && _vcSupport.hasListeners(property); - Object oldVal = null; - Object newVal = ((value != null) && clazz.equals(String.class) && !(value instanceof String)) ? value.toString() : value; + protected abstract void setPropertySpi(String property, Object value, Class clazz); - if (pc || vc) - { - oldVal = getProperty(property, clazz); - } + protected abstract boolean hasPropertySpi(String property); - if (vc) - { - fireVetoableChange(property, oldVal, value); - } + protected synchronized Object getProperty(String property, Class clazz) { + Object o; + + try { + o = getPropertySpi(property, clazz); + if (o == null) { + o = zero(clazz); + } else if (clazz.isArray() && (o instanceof String[]) && !clazz.equals(String[].class)) { + String[] str = (String[]) o; - setPropertySpi(property, newVal, clazz); - if (pc) - { - firePropertyChange(property, oldVal, value); + o = Array.newInstance(clazz.getComponentType(), str.length); + for (int i = 0; i < str.length; i++) { + Array.set(o, i, parse(str[i], clazz.getComponentType())); } + } else if ((o instanceof String) && !clazz.equals(String.class)) { + o = parse((String) o, clazz); + } + } catch (Exception x) { + o = zero(clazz); } - protected synchronized Object getProxy() - { - return _proxy; + return o; + } + + protected synchronized void setProperty(String property, Object value, Class clazz) + throws PropertyVetoException { + boolean pc = (_pcSupport != null) && _pcSupport.hasListeners(property); + boolean vc = (_vcSupport != null) && _vcSupport.hasListeners(property); + Object oldVal = null; + Object newVal = + ((value != null) && clazz.equals(String.class) && !(value instanceof String)) + ? value.toString() + : value; + + if (pc || vc) { + oldVal = getProperty(property, clazz); } - protected synchronized void addPropertyChangeListener(String property, PropertyChangeListener listener) - { - if (_pcSupport == null) - { - _pcSupport = new PropertyChangeSupport(_proxy); - } + if (vc) { + fireVetoableChange(property, oldVal, value); + } - _pcSupport.addPropertyChangeListener(property, listener); + setPropertySpi(property, newVal, clazz); + if (pc) { + firePropertyChange(property, oldVal, value); } + } - protected synchronized void addVetoableChangeListener(String property, VetoableChangeListener listener) - { - if (_vcSupport == null) - { - _vcSupport = new VetoableChangeSupport(_proxy); - } + protected synchronized Object getProxy() { + return _proxy; + } - _vcSupport.addVetoableChangeListener(property, listener); + protected synchronized void addPropertyChangeListener( + String property, PropertyChangeListener listener) { + if (_pcSupport == null) { + _pcSupport = new PropertyChangeSupport(_proxy); } - protected synchronized void firePropertyChange(String property, Object oldValue, Object newValue) - { - if (_pcSupport != null) - { - _pcSupport.firePropertyChange(property, oldValue, newValue); - } - } + _pcSupport.addPropertyChangeListener(property, listener); + } - protected synchronized void fireVetoableChange(String property, Object oldValue, Object newValue) throws PropertyVetoException - { - if (_vcSupport != null) - { - _vcSupport.fireVetoableChange(property, oldValue, newValue); - } + protected synchronized void addVetoableChangeListener( + String property, VetoableChangeListener listener) { + if (_vcSupport == null) { + _vcSupport = new VetoableChangeSupport(_proxy); } - protected synchronized boolean hasProperty(String property) - { - boolean ret; - - try - { - ret = hasPropertySpi(property); - } - catch (Exception x) - { - ret = false; - } + _vcSupport.addVetoableChangeListener(property, listener); + } - return ret; + protected synchronized void firePropertyChange( + String property, Object oldValue, Object newValue) { + if (_pcSupport != null) { + _pcSupport.firePropertyChange(property, oldValue, newValue); } + } - protected Object parse(String value, Class clazz) throws IllegalArgumentException - { - return BeanTool.getInstance().parse(value, clazz); + protected synchronized void fireVetoableChange(String property, Object oldValue, Object newValue) + throws PropertyVetoException { + if (_vcSupport != null) { + _vcSupport.fireVetoableChange(property, oldValue, newValue); } + } - protected synchronized void removePropertyChangeListener(String property, PropertyChangeListener listener) - { - if (_pcSupport != null) - { - _pcSupport.removePropertyChangeListener(property, listener); - } + protected synchronized boolean hasProperty(String property) { + boolean ret; + + try { + ret = hasPropertySpi(property); + } catch (Exception x) { + ret = false; } - protected synchronized void removeVetoableChangeListener(String property, VetoableChangeListener listener) - { - if (_vcSupport != null) - { - _vcSupport.removeVetoableChangeListener(property, listener); - } + return ret; + } + + protected Object parse(String value, Class clazz) throws IllegalArgumentException { + return BeanTool.getInstance().parse(value, clazz); + } + + protected synchronized void removePropertyChangeListener( + String property, PropertyChangeListener listener) { + if (_pcSupport != null) { + _pcSupport.removePropertyChangeListener(property, listener); } + } - protected Object zero(Class clazz) - { - return BeanTool.getInstance().zero(clazz); + protected synchronized void removeVetoableChangeListener( + String property, VetoableChangeListener listener) { + if (_vcSupport != null) { + _vcSupport.removeVetoableChangeListener(property, listener); } + } - private synchronized void updateProxy(Object value) - { - if (_proxy == null) - { - _proxy = value; - } + protected Object zero(Class clazz) { + return BeanTool.getInstance().zero(clazz); + } + + private synchronized void updateProxy(Object value) { + if (_proxy == null) { + _proxy = value; } + } } diff --git a/src/main/java/org/ini4j/spi/AbstractFormatter.java b/src/main/java/org/ini4j/spi/AbstractFormatter.java index 6baf888..c4e75b5 100644 --- a/src/main/java/org/ini4j/spi/AbstractFormatter.java +++ b/src/main/java/org/ini4j/spi/AbstractFormatter.java @@ -15,109 +15,95 @@ */ package org.ini4j.spi; -import org.ini4j.Config; - import java.io.PrintWriter; +import org.ini4j.Config; -abstract class AbstractFormatter implements HandlerBase -{ - private static final char OPERATOR = '='; - private static final char COMMENT = '#'; - private static final char SPACE = ' '; - private Config _config = Config.getGlobal(); - private boolean _header = true; - private PrintWriter _output; - - @Override public void handleComment(String comment) - { - if (getConfig().isComment() && (!_header || getConfig().isHeaderComment()) && (comment != null) && (comment.length() != 0)) - { - for (String line : comment.split(getConfig().getLineSeparator())) - { - getOutput().print(COMMENT); - getOutput().print(line); - getOutput().print(getConfig().getLineSeparator()); - } - - if (_header) - { - getOutput().print(getConfig().getLineSeparator()); - } - } - - _header = false; +abstract class AbstractFormatter implements HandlerBase { + private static final char OPERATOR = '='; + private static final char COMMENT = '#'; + private static final char SPACE = ' '; + private Config _config = Config.getGlobal(); + private boolean _header = true; + private PrintWriter _output; + + @Override + public void handleComment(String comment) { + if (getConfig().isComment() + && (!_header || getConfig().isHeaderComment()) + && (comment != null) + && (comment.length() != 0)) { + for (String line : comment.split(getConfig().getLineSeparator())) { + getOutput().print(COMMENT); + getOutput().print(line); + getOutput().print(getConfig().getLineSeparator()); + } + + if (_header) { + getOutput().print(getConfig().getLineSeparator()); + } } - @Override public void handleOption(String optionName, String optionValue) - { - if (getConfig().isStrictOperator()) - { - if (getConfig().isEmptyOption() || (optionValue != null)) - { - getOutput().print(escapeKey(optionName)); - getOutput().print(OPERATOR); - } - - if (optionValue != null) - { - getOutput().print(escapeValue(optionValue)); - } - - if (getConfig().isEmptyOption() || (optionValue != null)) - { - getOutput().print(getConfig().getLineSeparator()); - } - } - else - { - String value = ((optionValue == null) && getConfig().isEmptyOption()) ? "" : optionValue; - - if (value != null) - { - getOutput().print(escapeKey(optionName)); - getOutput().print(SPACE); - getOutput().print(OPERATOR); - getOutput().print(SPACE); - getOutput().print(escapeValue(value)); - getOutput().print(getConfig().getLineSeparator()); - } - } - - setHeader(false); + _header = false; + } + + @Override + public void handleOption(String optionName, String optionValue) { + if (getConfig().isStrictOperator()) { + if (getConfig().isEmptyOption() || (optionValue != null)) { + getOutput().print(escapeKey(optionName)); + getOutput().print(OPERATOR); + } + + if (optionValue != null) { + getOutput().print(escapeValue(optionValue)); + } + + if (getConfig().isEmptyOption() || (optionValue != null)) { + getOutput().print(getConfig().getLineSeparator()); + } + } else { + String value = ((optionValue == null) && getConfig().isEmptyOption()) ? "" : optionValue; + + if (value != null) { + getOutput().print(escapeKey(optionName)); + getOutput().print(SPACE); + getOutput().print(OPERATOR); + getOutput().print(SPACE); + getOutput().print(escapeValue(value)); + getOutput().print(getConfig().getLineSeparator()); + } } - protected Config getConfig() - { - return _config; - } + setHeader(false); + } - protected void setConfig(Config value) - { - _config = value; - } + protected Config getConfig() { + return _config; + } - protected PrintWriter getOutput() - { - return _output; - } + protected void setConfig(Config value) { + _config = value; + } - protected void setOutput(PrintWriter value) - { - _output = value; - } + protected PrintWriter getOutput() { + return _output; + } - void setHeader(boolean value) - { - _header = value; - } + protected void setOutput(PrintWriter value) { + _output = value; + } - String escapeKey(String input) - { - return getConfig().isEscape() ? EscapeTool.getInstance().escape(input) : input; - } + void setHeader(boolean value) { + _header = value; + } - String escapeValue(String input) - { - return getConfig().isEscape() && ! getConfig().isEscapeKeyOnly() ? EscapeTool.getInstance().escape(input) : input; - } + String escapeKey(String input) { + return getConfig().isEscape() ? EscapeTool.getInstance().escape(input) : input; + } + + String escapeValue(String input) { + return getConfig().isEscape() && !getConfig().isEscapeKeyOnly() + ? EscapeTool.getInstance().escape(input) + : input; + } } diff --git a/src/main/java/org/ini4j/spi/AbstractParser.java b/src/main/java/org/ini4j/spi/AbstractParser.java index 9de2bd5..9efedb0 100644 --- a/src/main/java/org/ini4j/spi/AbstractParser.java +++ b/src/main/java/org/ini4j/spi/AbstractParser.java @@ -15,131 +15,111 @@ */ package org.ini4j.spi; -import org.ini4j.Config; -import org.ini4j.InvalidFileFormatException; - import java.io.IOException; import java.io.InputStream; import java.io.Reader; - import java.net.URL; - import java.util.Locale; +import org.ini4j.Config; +import org.ini4j.InvalidFileFormatException; -abstract class AbstractParser -{ - private final String _comments; - private Config _config = Config.getGlobal(); - private final String _operators; - - protected AbstractParser(String operators, String comments) - { - _operators = operators; - _comments = comments; +abstract class AbstractParser { + private final String _comments; + private Config _config = Config.getGlobal(); + private final String _operators; + + protected AbstractParser(String operators, String comments) { + _operators = operators; + _comments = comments; + } + + protected Config getConfig() { + return _config; + } + + protected void setConfig(Config value) { + _config = value; + } + + protected void parseError(String line, int lineNumber) throws InvalidFileFormatException { + throw new InvalidFileFormatException("parse error (at line: " + lineNumber + "): " + line); + } + + IniSource newIniSource(InputStream input, HandlerBase handler) { + return new IniSource(input, handler, _comments, getConfig()); + } + + IniSource newIniSource(Reader input, HandlerBase handler) { + return new IniSource(input, handler, _comments, getConfig()); + } + + IniSource newIniSource(URL input, HandlerBase handler) throws IOException { + return new IniSource(input, handler, _comments, getConfig()); + } + + void parseOptionLine(String line, HandlerBase handler, int lineNumber) + throws InvalidFileFormatException { + int idx = indexOfOperator(line); + String name = null; + String value = null; + + if (idx < 0) { + if (getConfig().isEmptyOption()) { + name = line; + } else { + parseError(line, lineNumber); + } + } else { + name = unescapeKey(line.substring(0, idx)).trim(); + value = unescapeValue(line.substring(idx + 1)).trim(); } - protected Config getConfig() - { - return _config; + if (name.length() == 0) { + parseError(line, lineNumber); } - protected void setConfig(Config value) - { - _config = value; + if (getConfig().isLowerCaseOption()) { + name = name.toLowerCase(Locale.getDefault()); } - protected void parseError(String line, int lineNumber) throws InvalidFileFormatException - { - throw new InvalidFileFormatException("parse error (at line: " + lineNumber + "): " + line); - } + handler.handleOption(name, value); + } - IniSource newIniSource(InputStream input, HandlerBase handler) - { - return new IniSource(input, handler, _comments, getConfig()); - } + String unescapeKey(String line) { + return getConfig().isEscape() ? EscapeTool.getInstance().unescape(line) : line; + } - IniSource newIniSource(Reader input, HandlerBase handler) - { - return new IniSource(input, handler, _comments, getConfig()); - } + String unescapeValue(String line) { + return (getConfig().isEscape() && !getConfig().isEscapeKeyOnly()) + ? EscapeTool.getInstance().unescape(line) + : line; + } - IniSource newIniSource(URL input, HandlerBase handler) throws IOException - { - return new IniSource(input, handler, _comments, getConfig()); - } + private int indexOfOperator(String line) { + int idx = -1; - void parseOptionLine(String line, HandlerBase handler, int lineNumber) throws InvalidFileFormatException - { - int idx = indexOfOperator(line); - String name = null; - String value = null; - - if (idx < 0) - { - if (getConfig().isEmptyOption()) - { - name = line; - } - else - { - parseError(line, lineNumber); - } - } - else - { - name = unescapeKey(line.substring(0, idx)).trim(); - value = unescapeValue(line.substring(idx + 1)).trim(); - } + for (char c : _operators.toCharArray()) { + int index = line.indexOf(c); - if (name.length() == 0) - { - parseError(line, lineNumber); - } + while ((index >= 0)) { + if ((index >= 0) + && ((index == 0) || (line.charAt(index - 1) != '\\')) + && ((idx == -1) || (index < idx))) { + idx = index; - if (getConfig().isLowerCaseOption()) - { - name = name.toLowerCase(Locale.getDefault()); + break; } - handler.handleOption(name, value); - } + index = (index == (line.length() - 1)) ? -1 : line.indexOf(c, index + 1); + } - String unescapeKey(String line) - { - return getConfig().isEscape() ? EscapeTool.getInstance().unescape(line) : line; + // if ((index >= 0) && ((index == 0) || (line.charAt(index - 1) != '\\')) && ((idx == -1) || + // (index < idx))) + // { + // idx = index; + // } } - String unescapeValue(String line) - { - return (getConfig().isEscape() && !getConfig().isEscapeKeyOnly()) ? EscapeTool.getInstance().unescape(line) : line; - } - - private int indexOfOperator(String line) - { - int idx = -1; - - for (char c : _operators.toCharArray()) - { - int index = line.indexOf(c); - - while ((index >= 0)) - { - if ((index >= 0) && ((index == 0) || (line.charAt(index - 1) != '\\')) && ((idx == -1) || (index < idx))) - { - idx = index; - - break; - } - - index = (index == (line.length() - 1)) ? -1 : line.indexOf(c, index + 1); - } - - //if ((index >= 0) && ((index == 0) || (line.charAt(index - 1) != '\\')) && ((idx == -1) || (index < idx))) - // { - // idx = index; - // } - } - - return idx; - } + return idx; + } } diff --git a/src/main/java/org/ini4j/spi/AbstractProfileBuilder.java b/src/main/java/org/ini4j/spi/AbstractProfileBuilder.java index badc263..025ecb1 100644 --- a/src/main/java/org/ini4j/spi/AbstractProfileBuilder.java +++ b/src/main/java/org/ini4j/spi/AbstractProfileBuilder.java @@ -20,117 +20,97 @@ import org.ini4j.Ini; import org.ini4j.Profile; -abstract class AbstractProfileBuilder implements IniHandler -{ - private Profile.Section _currentSection; - private boolean _header; - private String _lastComment; - - @Override public void endIni() - { - - // comment only .ini files.... - if ((_lastComment != null) && _header) - { - setHeaderComment(); - } - } +abstract class AbstractProfileBuilder implements IniHandler { + private Profile.Section _currentSection; + private boolean _header; + private String _lastComment; + + @Override + public void endIni() { - @Override public void endSection() - { - _currentSection = null; + // comment only .ini files.... + if ((_lastComment != null) && _header) { + setHeaderComment(); + } + } + + @Override + public void endSection() { + _currentSection = null; + } + + @Override + public void handleComment(String comment) { + if ((_lastComment != null) && _header) { + _header = false; + setHeaderComment(); } - @Override public void handleComment(String comment) - { - if ((_lastComment != null) && _header) - { - _header = false; - setHeaderComment(); - } + _lastComment = comment; + } - _lastComment = comment; + @Override + public void handleOption(String name, String value) { + _header = false; + if (getConfig().isMultiOption()) { + _currentSection.add(name, value); + } else { + _currentSection.put(name, value); } - @Override public void handleOption(String name, String value) - { - _header = false; - if (getConfig().isMultiOption()) - { - _currentSection.add(name, value); - } - else - { - _currentSection.put(name, value); - } - - if (_lastComment != null) - { - putComment(_currentSection, name); - _lastComment = null; - } + if (_lastComment != null) { + putComment(_currentSection, name); + _lastComment = null; } + } - @Override public void startIni() - { - if (getConfig().isHeaderComment()) - { - _header = true; - } + @Override + public void startIni() { + if (getConfig().isHeaderComment()) { + _header = true; } + } - @Override public void startSection(String sectionName) - { - if (getConfig().isMultiSection()) - { - _currentSection = getProfile().add(sectionName); - } - else - { - Ini.Section s = getProfile().get(sectionName); - - _currentSection = (s == null) ? getProfile().add(sectionName) : s; - } - - if (_lastComment != null) - { - if (_header) - { - setHeaderComment(); - } - else - { - putComment(getProfile(), sectionName); - } - - _lastComment = null; - } - - _header = false; - } + @Override + public void startSection(String sectionName) { + if (getConfig().isMultiSection()) { + _currentSection = getProfile().add(sectionName); + } else { + Ini.Section s = getProfile().get(sectionName); - abstract Config getConfig(); + _currentSection = (s == null) ? getProfile().add(sectionName) : s; + } - abstract Profile getProfile(); + if (_lastComment != null) { + if (_header) { + setHeaderComment(); + } else { + putComment(getProfile(), sectionName); + } - Profile.Section getCurrentSection() - { - return _currentSection; + _lastComment = null; } - private void setHeaderComment() - { - if (getConfig().isComment()) - { - getProfile().setComment(_lastComment); - } + _header = false; + } + + abstract Config getConfig(); + + abstract Profile getProfile(); + + Profile.Section getCurrentSection() { + return _currentSection; + } + + private void setHeaderComment() { + if (getConfig().isComment()) { + getProfile().setComment(_lastComment); } + } - private void putComment(CommentedMap map, String key) - { - if (getConfig().isComment()) - { - map.putComment(key, _lastComment); - } + private void putComment(CommentedMap map, String key) { + if (getConfig().isComment()) { + map.putComment(key, _lastComment); } + } } diff --git a/src/main/java/org/ini4j/spi/BeanAccess.java b/src/main/java/org/ini4j/spi/BeanAccess.java index e49f459..23781a0 100644 --- a/src/main/java/org/ini4j/spi/BeanAccess.java +++ b/src/main/java/org/ini4j/spi/BeanAccess.java @@ -15,19 +15,18 @@ */ package org.ini4j.spi; -public interface BeanAccess -{ - void propAdd(String propertyName, String value); +public interface BeanAccess { + void propAdd(String propertyName, String value); - String propDel(String propertyName); + String propDel(String propertyName); - String propGet(String propertyName); + String propGet(String propertyName); - String propGet(String propertyName, int index); + String propGet(String propertyName, int index); - int propLength(String propertyName); + int propLength(String propertyName); - String propSet(String propertyName, String value); + String propSet(String propertyName, String value); - String propSet(String propertyName, String value, int index); + String propSet(String propertyName, String value, int index); } diff --git a/src/main/java/org/ini4j/spi/BeanTool.java b/src/main/java/org/ini4j/spi/BeanTool.java index 8bce5a4..c465de9 100644 --- a/src/main/java/org/ini4j/spi/BeanTool.java +++ b/src/main/java/org/ini4j/spi/BeanTool.java @@ -18,354 +18,253 @@ import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; - import java.io.File; - import java.lang.reflect.Array; import java.lang.reflect.Method; import java.lang.reflect.Proxy; - import java.net.URI; import java.net.URL; - import java.util.TimeZone; -public class BeanTool -{ - private static final String PARSE_METHOD = "valueOf"; - private static final BeanTool INSTANCE = ServiceFinder.findService(BeanTool.class); +public class BeanTool { + private static final String PARSE_METHOD = "valueOf"; + private static final BeanTool INSTANCE = ServiceFinder.findService(BeanTool.class); - public static final BeanTool getInstance() - { - return INSTANCE; - } + public static final BeanTool getInstance() { + return INSTANCE; + } - public void inject(Object bean, BeanAccess props) - { - for (PropertyDescriptor pd : getPropertyDescriptors(bean.getClass())) - { - try - { - Method method = pd.getWriteMethod(); - String name = pd.getName(); - - if ((method != null) && (props.propLength(name) != 0)) - { - Object value; - - if (pd.getPropertyType().isArray()) - { - value = Array.newInstance(pd.getPropertyType().getComponentType(), props.propLength(name)); - for (int i = 0; i < props.propLength(name); i++) - { - Array.set(value, i, parse(props.propGet(name, i), pd.getPropertyType().getComponentType())); - } - } - else - { - value = parse(props.propGet(name), pd.getPropertyType()); - } - - method.invoke(bean, value); - } - } - catch (Exception x) - { - throw (IllegalArgumentException) (new IllegalArgumentException("Failed to set property: " + pd.getDisplayName()).initCause( - x)); - } - } - } + public void inject(Object bean, BeanAccess props) { + for (PropertyDescriptor pd : getPropertyDescriptors(bean.getClass())) { + try { + Method method = pd.getWriteMethod(); + String name = pd.getName(); - public void inject(BeanAccess props, Object bean) - { - for (PropertyDescriptor pd : getPropertyDescriptors(bean.getClass())) - { - try - { - Method method = pd.getReadMethod(); - - if ((method != null) && !"class".equals(pd.getName())) - { - Object value = method.invoke(bean, (Object[]) null); - - if (value != null) - { - if (pd.getPropertyType().isArray()) - { - for (int i = 0; i < Array.getLength(value); i++) - { - Object v = Array.get(value, i); - - if ((v != null) && !v.getClass().equals(String.class)) - { - v = v.toString(); - } - - props.propAdd(pd.getName(), (String) v); - } - } - else - { - props.propSet(pd.getName(), value.toString()); - } - } - } - } - catch (Exception x) - { - throw new IllegalArgumentException("Failed to set property: " + pd.getDisplayName(), x); + if ((method != null) && (props.propLength(name) != 0)) { + Object value; + + if (pd.getPropertyType().isArray()) { + value = + Array.newInstance(pd.getPropertyType().getComponentType(), props.propLength(name)); + for (int i = 0; i < props.propLength(name); i++) { + Array.set( + value, i, parse(props.propGet(name, i), pd.getPropertyType().getComponentType())); } - } - } + } else { + value = parse(props.propGet(name), pd.getPropertyType()); + } - @SuppressWarnings("unchecked") - public T parse(String value, Class clazz) throws IllegalArgumentException - { - if (clazz == null) - { - throw new IllegalArgumentException("null argument"); + method.invoke(bean, value); } + } catch (Exception x) { + throw (IllegalArgumentException) + (new IllegalArgumentException("Failed to set property: " + pd.getDisplayName()) + .initCause(x)); + } + } + } - Object o = null; - - if (value == null) - { - o = zero(clazz); - } - else if (clazz.isPrimitive()) - { - o = parsePrimitiveValue(value, clazz); - } - else - { - if (clazz == String.class) - { - o = value; - } - else if (clazz == Character.class) - { - o = Character.valueOf(value.charAt(0)); - } - else - { - o = parseSpecialValue(value, clazz); - } - } + public void inject(BeanAccess props, Object bean) { + for (PropertyDescriptor pd : getPropertyDescriptors(bean.getClass())) { + try { + Method method = pd.getReadMethod(); - return (T) o; - } + if ((method != null) && !"class".equals(pd.getName())) { + Object value = method.invoke(bean, (Object[]) null); - public T proxy(Class clazz, BeanAccess props) - { - return clazz.cast(Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] { clazz }, - new BeanInvocationHandler(props))); - } + if (value != null) { + if (pd.getPropertyType().isArray()) { + for (int i = 0; i < Array.getLength(value); i++) { + Object v = Array.get(value, i); - @SuppressWarnings("unchecked") - public T zero(Class clazz) - { - Object o = null; + if ((v != null) && !v.getClass().equals(String.class)) { + v = v.toString(); + } - if (clazz.isPrimitive()) - { - if (clazz == Boolean.TYPE) - { - o = Boolean.FALSE; - } - else if (clazz == Byte.TYPE) - { - o = Byte.valueOf((byte) 0); - } - else if (clazz == Character.TYPE) - { - o = Character.valueOf('\0'); - } - else if (clazz == Double.TYPE) - { - o = Double.valueOf(0.0); - } - else if (clazz == Float.TYPE) - { - o = Float.valueOf(0.0f); - } - else if (clazz == Integer.TYPE) - { - o = Integer.valueOf(0); - } - else if (clazz == Long.TYPE) - { - o = Long.valueOf(0L); - } - else if (clazz == Short.TYPE) - { - o = Short.valueOf((short) 0); + props.propAdd(pd.getName(), (String) v); + } + } else { + props.propSet(pd.getName(), value.toString()); } + } } - - return (T) o; + } catch (Exception x) { + throw new IllegalArgumentException("Failed to set property: " + pd.getDisplayName(), x); + } } + } - @SuppressWarnings(Warnings.UNCHECKED) - protected Object parseSpecialValue(String value, Class clazz) throws IllegalArgumentException - { - Object o; - - try - { - if (clazz == File.class) - { - o = new File(value); - } - else if (clazz == URL.class) - { - o = new URL(value); - } - else if (clazz == URI.class) - { - o = new URI(value); - } - else if (clazz == Class.class) - { - o = Class.forName(value); - } - else if (clazz == TimeZone.class) - { - o = TimeZone.getTimeZone(value); - } - else - { - - // TODO handle constructor with String arg as converter from String - // look for "valueOf" converter method - Method parser = clazz.getMethod(PARSE_METHOD, new Class[] { String.class }); - - o = parser.invoke(null, new Object[] { value }); - } - } - catch (Exception x) - { - throw (IllegalArgumentException) new IllegalArgumentException().initCause(x); - } + @SuppressWarnings("unchecked") + public T parse(String value, Class clazz) throws IllegalArgumentException { + if (clazz == null) { + throw new IllegalArgumentException("null argument"); + } - return o; + Object o = null; + + if (value == null) { + o = zero(clazz); + } else if (clazz.isPrimitive()) { + o = parsePrimitiveValue(value, clazz); + } else { + if (clazz == String.class) { + o = value; + } else if (clazz == Character.class) { + o = Character.valueOf(value.charAt(0)); + } else { + o = parseSpecialValue(value, clazz); + } } - private PropertyDescriptor[] getPropertyDescriptors(Class clazz) - { - try - { - return Introspector.getBeanInfo(clazz).getPropertyDescriptors(); - } - catch (IntrospectionException x) - { - throw new IllegalArgumentException(x); - } + return (T) o; + } + + public T proxy(Class clazz, BeanAccess props) { + return clazz.cast( + Proxy.newProxyInstance( + Thread.currentThread().getContextClassLoader(), + new Class[] {clazz}, + new BeanInvocationHandler(props))); + } + + @SuppressWarnings("unchecked") + public T zero(Class clazz) { + Object o = null; + + if (clazz.isPrimitive()) { + if (clazz == Boolean.TYPE) { + o = Boolean.FALSE; + } else if (clazz == Byte.TYPE) { + o = Byte.valueOf((byte) 0); + } else if (clazz == Character.TYPE) { + o = Character.valueOf('\0'); + } else if (clazz == Double.TYPE) { + o = Double.valueOf(0.0); + } else if (clazz == Float.TYPE) { + o = Float.valueOf(0.0f); + } else if (clazz == Integer.TYPE) { + o = Integer.valueOf(0); + } else if (clazz == Long.TYPE) { + o = Long.valueOf(0L); + } else if (clazz == Short.TYPE) { + o = Short.valueOf((short) 0); + } } - private Object parsePrimitiveValue(String value, Class clazz) throws IllegalArgumentException - { - Object o = null; + return (T) o; + } + + @SuppressWarnings(Warnings.UNCHECKED) + protected Object parseSpecialValue(String value, Class clazz) throws IllegalArgumentException { + Object o; + + try { + if (clazz == File.class) { + o = new File(value); + } else if (clazz == URL.class) { + o = new URL(value); + } else if (clazz == URI.class) { + o = new URI(value); + } else if (clazz == Class.class) { + o = Class.forName(value); + } else if (clazz == TimeZone.class) { + o = TimeZone.getTimeZone(value); + } else { + + // TODO handle constructor with String arg as converter from String + // look for "valueOf" converter method + Method parser = clazz.getMethod(PARSE_METHOD, new Class[] {String.class}); + + o = parser.invoke(null, new Object[] {value}); + } + } catch (Exception x) { + throw (IllegalArgumentException) new IllegalArgumentException().initCause(x); + } - try - { - if (clazz == Boolean.TYPE) - { - o = Boolean.valueOf(value); - } - else if (clazz == Byte.TYPE) - { - o = Byte.valueOf(value); - } - else if (clazz == Character.TYPE) - { - o = Character.valueOf(value.charAt(0)); - } - else if (clazz == Double.TYPE) - { - o = Double.valueOf(value); - } - else if (clazz == Float.TYPE) - { - o = Float.valueOf(value); - } - else if (clazz == Integer.TYPE) - { - o = Integer.valueOf(value); - } - else if (clazz == Long.TYPE) - { - o = Long.valueOf(value); - } - else if (clazz == Short.TYPE) - { - o = Short.valueOf(value); - } - } - catch (Exception x) - { - throw (IllegalArgumentException) new IllegalArgumentException().initCause(x); - } + return o; + } - return o; + private PropertyDescriptor[] getPropertyDescriptors(Class clazz) { + try { + return Introspector.getBeanInfo(clazz).getPropertyDescriptors(); + } catch (IntrospectionException x) { + throw new IllegalArgumentException(x); + } + } + + private Object parsePrimitiveValue(String value, Class clazz) throws IllegalArgumentException { + Object o = null; + + try { + if (clazz == Boolean.TYPE) { + o = Boolean.valueOf(value); + } else if (clazz == Byte.TYPE) { + o = Byte.valueOf(value); + } else if (clazz == Character.TYPE) { + o = Character.valueOf(value.charAt(0)); + } else if (clazz == Double.TYPE) { + o = Double.valueOf(value); + } else if (clazz == Float.TYPE) { + o = Float.valueOf(value); + } else if (clazz == Integer.TYPE) { + o = Integer.valueOf(value); + } else if (clazz == Long.TYPE) { + o = Long.valueOf(value); + } else if (clazz == Short.TYPE) { + o = Short.valueOf(value); + } + } catch (Exception x) { + throw (IllegalArgumentException) new IllegalArgumentException().initCause(x); } - static class BeanInvocationHandler extends AbstractBeanInvocationHandler - { - private final BeanAccess _backend; + return o; + } - BeanInvocationHandler(BeanAccess backend) - { - _backend = backend; - } + static class BeanInvocationHandler extends AbstractBeanInvocationHandler { + private final BeanAccess _backend; - @Override protected Object getPropertySpi(String property, Class clazz) - { - Object ret = null; + BeanInvocationHandler(BeanAccess backend) { + _backend = backend; + } - if (clazz.isArray()) - { - int length = _backend.propLength(property); + @Override + protected Object getPropertySpi(String property, Class clazz) { + Object ret = null; - if (length != 0) - { - String[] all = new String[length]; + if (clazz.isArray()) { + int length = _backend.propLength(property); - for (int i = 0; i < all.length; i++) - { - all[i] = _backend.propGet(property, i); - } + if (length != 0) { + String[] all = new String[length]; - ret = all; - } - } - else - { - ret = _backend.propGet(property); - } + for (int i = 0; i < all.length; i++) { + all[i] = _backend.propGet(property, i); + } - return ret; + ret = all; } + } else { + ret = _backend.propGet(property); + } - @Override protected void setPropertySpi(String property, Object value, Class clazz) - { - if (clazz.isArray()) - { - _backend.propDel(property); - for (int i = 0; i < Array.getLength(value); i++) - { - _backend.propAdd(property, Array.get(value, i).toString()); - } - } - else - { - _backend.propSet(property, value.toString()); - } - } + return ret; + } - @Override protected boolean hasPropertySpi(String property) - { - return _backend.propLength(property) != 0; + @Override + protected void setPropertySpi(String property, Object value, Class clazz) { + if (clazz.isArray()) { + _backend.propDel(property); + for (int i = 0; i < Array.getLength(value); i++) { + _backend.propAdd(property, Array.get(value, i).toString()); } + } else { + _backend.propSet(property, value.toString()); + } + } + + @Override + protected boolean hasPropertySpi(String property) { + return _backend.propLength(property) != 0; } + } } diff --git a/src/main/java/org/ini4j/spi/EscapeTool.java b/src/main/java/org/ini4j/spi/EscapeTool.java index e3d8d5c..10b6943 100644 --- a/src/main/java/org/ini4j/spi/EscapeTool.java +++ b/src/main/java/org/ini4j/spi/EscapeTool.java @@ -15,180 +15,148 @@ */ package org.ini4j.spi; -public class EscapeTool -{ - private static final String ESCAPE_LETTERS = "\\tnfbr:="; - private static final String ESCAPEABLE_CHARS = "\\\t\n\f\b\r:="; - private static final char ESCAPE_CHAR = '\\'; - static final char[] HEX = "0123456789abcdef".toCharArray(); - private static final EscapeTool INSTANCE = ServiceFinder.findService(EscapeTool.class); - private static final char ASCII_MIN = 0x20; - private static final char ASCII_MAX = 0x7e; - static final int HEX_DIGIT_MASK = 0x0f; - static final int HEX_DIGIT_3_OFFSET = 4; - static final int HEX_DIGIT_2_OFFSET = 8; - static final int HEX_DIGIT_1_OFFSET = 12; - static final int HEX_RADIX = 16; - private static final int UNICODE_HEX_DIGITS = 4; - static final char DOUBLE_QUOTE = '"'; - - public static EscapeTool getInstance() - { - return INSTANCE; +public class EscapeTool { + private static final String ESCAPE_LETTERS = "\\tnfbr:="; + private static final String ESCAPEABLE_CHARS = "\\\t\n\f\b\r:="; + private static final char ESCAPE_CHAR = '\\'; + static final char[] HEX = "0123456789abcdef".toCharArray(); + private static final EscapeTool INSTANCE = ServiceFinder.findService(EscapeTool.class); + private static final char ASCII_MIN = 0x20; + private static final char ASCII_MAX = 0x7e; + static final int HEX_DIGIT_MASK = 0x0f; + static final int HEX_DIGIT_3_OFFSET = 4; + static final int HEX_DIGIT_2_OFFSET = 8; + static final int HEX_DIGIT_1_OFFSET = 12; + static final int HEX_RADIX = 16; + private static final int UNICODE_HEX_DIGITS = 4; + static final char DOUBLE_QUOTE = '"'; + + public static EscapeTool getInstance() { + return INSTANCE; + } + + public String escape(String line) { + int len = line.length(); + StringBuilder buffer = new StringBuilder(len * 2); + + for (int i = 0; i < len; i++) { + char c = line.charAt(i); + int idx = ESCAPEABLE_CHARS.indexOf(c); + + if (idx >= 0) { + buffer.append(ESCAPE_CHAR); + buffer.append(ESCAPE_LETTERS.charAt(idx)); + } else { + if ((c < ASCII_MIN) || (c > ASCII_MAX)) { + escapeBinary(buffer, c); + } else { + buffer.append(c); + } + } } - public String escape(String line) - { - int len = line.length(); - StringBuilder buffer = new StringBuilder(len * 2); - - for (int i = 0; i < len; i++) - { - char c = line.charAt(i); - int idx = ESCAPEABLE_CHARS.indexOf(c); - - if (idx >= 0) - { - buffer.append(ESCAPE_CHAR); - buffer.append(ESCAPE_LETTERS.charAt(idx)); - } - else - { - if ((c < ASCII_MIN) || (c > ASCII_MAX)) - { - escapeBinary(buffer, c); - } - else - { - buffer.append(c); - } - } + return buffer.toString(); + } + + public String quote(String value) { + String ret = value; + + if ((value != null) && (value.length() != 0)) { + StringBuilder buff = new StringBuilder(); + + buff.append(DOUBLE_QUOTE); + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + + if ((c == ESCAPE_CHAR) || (c == DOUBLE_QUOTE)) { + buff.append(ESCAPE_CHAR); } - return buffer.toString(); + buff.append(c); + } + + buff.append(DOUBLE_QUOTE); + ret = buff.toString(); } - public String quote(String value) - { - String ret = value; + return ret; + } - if ((value != null) && (value.length() != 0)) - { - StringBuilder buff = new StringBuilder(); + public String unescape(String line) { + int n = line.length(); + StringBuilder buffer = new StringBuilder(n); + int i = 0; - buff.append(DOUBLE_QUOTE); - for (int i = 0; i < value.length(); i++) - { - char c = value.charAt(i); + while (i < n) { + char c = line.charAt(i++); - if ((c == ESCAPE_CHAR) || (c == DOUBLE_QUOTE)) - { - buff.append(ESCAPE_CHAR); - } + if (c == ESCAPE_CHAR) { + c = line.charAt(i++); + int next = unescapeBinary(buffer, c, line, i); - buff.append(c); - } + if (next == i) { + int idx = ESCAPE_LETTERS.indexOf(c); - buff.append(DOUBLE_QUOTE); - ret = buff.toString(); - } + if (idx >= 0) { + c = ESCAPEABLE_CHARS.charAt(idx); + } - return ret; - } - - public String unescape(String line) - { - int n = line.length(); - StringBuilder buffer = new StringBuilder(n); - int i = 0; - - while (i < n) - { - char c = line.charAt(i++); - - if (c == ESCAPE_CHAR) - { - c = line.charAt(i++); - int next = unescapeBinary(buffer, c, line, i); - - if (next == i) - { - int idx = ESCAPE_LETTERS.indexOf(c); - - if (idx >= 0) - { - c = ESCAPEABLE_CHARS.charAt(idx); - } - - buffer.append(c); - } - else - { - i = next; - } - } - else - { - buffer.append(c); - } + buffer.append(c); + } else { + i = next; } - - return buffer.toString(); + } else { + buffer.append(c); + } } - public String unquote(String value) - { - StringBuilder buff = new StringBuilder(); - boolean escape = false; + return buffer.toString(); + } - for (int i = 1; i < (value.length() - 1); i++) - { - char c = value.charAt(i); + public String unquote(String value) { + StringBuilder buff = new StringBuilder(); + boolean escape = false; - if (c == ESCAPE_CHAR) - { - if (!escape) - { - escape = true; + for (int i = 1; i < (value.length() - 1); i++) { + char c = value.charAt(i); - continue; - } + if (c == ESCAPE_CHAR) { + if (!escape) { + escape = true; - escape = false; - } - - buff.append(c); + continue; } - return buff.toString(); - } + escape = false; + } - void escapeBinary(StringBuilder buff, char c) - { - buff.append("\\u"); - buff.append(HEX[(c >>> HEX_DIGIT_1_OFFSET) & HEX_DIGIT_MASK]); - buff.append(HEX[(c >>> HEX_DIGIT_2_OFFSET) & HEX_DIGIT_MASK]); - buff.append(HEX[(c >>> HEX_DIGIT_3_OFFSET) & HEX_DIGIT_MASK]); - buff.append(HEX[c & HEX_DIGIT_MASK]); + buff.append(c); } - int unescapeBinary(StringBuilder buff, char escapeType, String line, int index) - { - int ret = index; - - if (escapeType == 'u') - { - try - { - buff.append((char) Integer.parseInt(line.substring(index, index + UNICODE_HEX_DIGITS), HEX_RADIX)); - ret = index + UNICODE_HEX_DIGITS; - } - catch (Exception x) - { - throw new IllegalArgumentException("Malformed \\uxxxx encoding.", x); - } - } - - return ret; + return buff.toString(); + } + + void escapeBinary(StringBuilder buff, char c) { + buff.append("\\u"); + buff.append(HEX[(c >>> HEX_DIGIT_1_OFFSET) & HEX_DIGIT_MASK]); + buff.append(HEX[(c >>> HEX_DIGIT_2_OFFSET) & HEX_DIGIT_MASK]); + buff.append(HEX[(c >>> HEX_DIGIT_3_OFFSET) & HEX_DIGIT_MASK]); + buff.append(HEX[c & HEX_DIGIT_MASK]); + } + + int unescapeBinary(StringBuilder buff, char escapeType, String line, int index) { + int ret = index; + + if (escapeType == 'u') { + try { + buff.append( + (char) Integer.parseInt(line.substring(index, index + UNICODE_HEX_DIGITS), HEX_RADIX)); + ret = index + UNICODE_HEX_DIGITS; + } catch (Exception x) { + throw new IllegalArgumentException("Malformed \\uxxxx encoding.", x); + } } + + return ret; + } } diff --git a/src/main/java/org/ini4j/spi/HandlerBase.java b/src/main/java/org/ini4j/spi/HandlerBase.java index 30813b8..9ed0525 100644 --- a/src/main/java/org/ini4j/spi/HandlerBase.java +++ b/src/main/java/org/ini4j/spi/HandlerBase.java @@ -15,9 +15,8 @@ */ package org.ini4j.spi; -interface HandlerBase -{ - void handleComment(String comment); +interface HandlerBase { + void handleComment(String comment); - void handleOption(String optionName, String optionValue); + void handleOption(String optionName, String optionValue); } diff --git a/src/main/java/org/ini4j/spi/IniBuilder.java b/src/main/java/org/ini4j/spi/IniBuilder.java index f54b794..f8a7aa6 100644 --- a/src/main/java/org/ini4j/spi/IniBuilder.java +++ b/src/main/java/org/ini4j/spi/IniBuilder.java @@ -19,36 +19,32 @@ import org.ini4j.Ini; import org.ini4j.Profile; -public class IniBuilder extends AbstractProfileBuilder implements IniHandler -{ - private Ini _ini; - - public static IniBuilder newInstance(Ini ini) - { - IniBuilder instance = newInstance(); - - instance.setIni(ini); - - return instance; - } - - public void setIni(Ini value) - { - _ini = value; - } - - @Override Config getConfig() - { - return _ini.getConfig(); - } - - @Override Profile getProfile() - { - return _ini; - } - - private static IniBuilder newInstance() - { - return ServiceFinder.findService(IniBuilder.class); - } +public class IniBuilder extends AbstractProfileBuilder implements IniHandler { + private Ini _ini; + + public static IniBuilder newInstance(Ini ini) { + IniBuilder instance = newInstance(); + + instance.setIni(ini); + + return instance; + } + + public void setIni(Ini value) { + _ini = value; + } + + @Override + Config getConfig() { + return _ini.getConfig(); + } + + @Override + Profile getProfile() { + return _ini; + } + + private static IniBuilder newInstance() { + return ServiceFinder.findService(IniBuilder.class); + } } diff --git a/src/main/java/org/ini4j/spi/IniFormatter.java b/src/main/java/org/ini4j/spi/IniFormatter.java index 4c0d107..b1fca30 100644 --- a/src/main/java/org/ini4j/spi/IniFormatter.java +++ b/src/main/java/org/ini4j/spi/IniFormatter.java @@ -15,52 +15,47 @@ */ package org.ini4j.spi; -import org.ini4j.Config; - import java.io.PrintWriter; import java.io.Writer; +import org.ini4j.Config; -public class IniFormatter extends AbstractFormatter implements IniHandler -{ - public static IniFormatter newInstance(Writer out, Config config) - { - IniFormatter instance = newInstance(); - - instance.setOutput((out instanceof PrintWriter) ? (PrintWriter) out : new PrintWriter(out)); - instance.setConfig(config); - - return instance; - } - - @Override public void endIni() - { - getOutput().flush(); - } - - @Override public void endSection() - { - getOutput().print(getConfig().getLineSeparator()); - } - - @Override public void startIni() - { - assert true; - } - - @Override public void startSection(String sectionName) - { - setHeader(false); - if (!getConfig().isGlobalSection() || !sectionName.equals(getConfig().getGlobalSectionName())) - { - getOutput().print(IniParser.SECTION_BEGIN); - getOutput().print(escapeKey(sectionName)); - getOutput().print(IniParser.SECTION_END); - getOutput().print(getConfig().getLineSeparator()); - } +public class IniFormatter extends AbstractFormatter implements IniHandler { + public static IniFormatter newInstance(Writer out, Config config) { + IniFormatter instance = newInstance(); + + instance.setOutput((out instanceof PrintWriter) ? (PrintWriter) out : new PrintWriter(out)); + instance.setConfig(config); + + return instance; + } + + @Override + public void endIni() { + getOutput().flush(); + } + + @Override + public void endSection() { + getOutput().print(getConfig().getLineSeparator()); + } + + @Override + public void startIni() { + assert true; + } + + @Override + public void startSection(String sectionName) { + setHeader(false); + if (!getConfig().isGlobalSection() || !sectionName.equals(getConfig().getGlobalSectionName())) { + getOutput().print(IniParser.SECTION_BEGIN); + getOutput().print(escapeKey(sectionName)); + getOutput().print(IniParser.SECTION_END); + getOutput().print(getConfig().getLineSeparator()); } + } - private static IniFormatter newInstance() - { - return ServiceFinder.findService(IniFormatter.class); - } + private static IniFormatter newInstance() { + return ServiceFinder.findService(IniFormatter.class); + } } diff --git a/src/main/java/org/ini4j/spi/IniHandler.java b/src/main/java/org/ini4j/spi/IniHandler.java index 83208e6..069552b 100755 --- a/src/main/java/org/ini4j/spi/IniHandler.java +++ b/src/main/java/org/ini4j/spi/IniHandler.java @@ -15,17 +15,18 @@ */ package org.ini4j.spi; -public interface IniHandler extends HandlerBase -{ - void endIni(); +public interface IniHandler extends HandlerBase { + void endIni(); - void endSection(); + void endSection(); - @Override void handleComment(String comment); + @Override + void handleComment(String comment); - @Override void handleOption(String optionName, String optionValue); + @Override + void handleOption(String optionName, String optionValue); - void startIni(); + void startIni(); - void startSection(String sectionName); + void startSection(String sectionName); } diff --git a/src/main/java/org/ini4j/spi/IniParser.java b/src/main/java/org/ini4j/spi/IniParser.java index 938b301..c30b102 100755 --- a/src/main/java/org/ini4j/spi/IniParser.java +++ b/src/main/java/org/ini4j/spi/IniParser.java @@ -15,123 +15,102 @@ */ package org.ini4j.spi; -import org.ini4j.Config; -import org.ini4j.InvalidFileFormatException; - import java.io.IOException; import java.io.InputStream; import java.io.Reader; - import java.net.URL; - import java.util.Locale; +import org.ini4j.Config; +import org.ini4j.InvalidFileFormatException; -public class IniParser extends AbstractParser -{ - private static final String COMMENTS = ";#"; - private static final String OPERATORS = ":="; - static final char SECTION_BEGIN = '['; - static final char SECTION_END = ']'; +public class IniParser extends AbstractParser { + private static final String COMMENTS = ";#"; + private static final String OPERATORS = ":="; + static final char SECTION_BEGIN = '['; + static final char SECTION_END = ']'; - public IniParser() - { - super(OPERATORS, COMMENTS); - } + public IniParser() { + super(OPERATORS, COMMENTS); + } - public static IniParser newInstance() - { - return ServiceFinder.findService(IniParser.class); - } + public static IniParser newInstance() { + return ServiceFinder.findService(IniParser.class); + } - public static IniParser newInstance(Config config) - { - IniParser instance = newInstance(); + public static IniParser newInstance(Config config) { + IniParser instance = newInstance(); - instance.setConfig(config); + instance.setConfig(config); - return instance; - } + return instance; + } - public void parse(InputStream input, IniHandler handler) throws IOException, InvalidFileFormatException - { - parse(newIniSource(input, handler), handler); - } + public void parse(InputStream input, IniHandler handler) + throws IOException, InvalidFileFormatException { + parse(newIniSource(input, handler), handler); + } - public void parse(Reader input, IniHandler handler) throws IOException, InvalidFileFormatException - { - parse(newIniSource(input, handler), handler); - } + public void parse(Reader input, IniHandler handler) + throws IOException, InvalidFileFormatException { + parse(newIniSource(input, handler), handler); + } - public void parse(URL input, IniHandler handler) throws IOException, InvalidFileFormatException - { - parse(newIniSource(input, handler), handler); - } + public void parse(URL input, IniHandler handler) throws IOException, InvalidFileFormatException { + parse(newIniSource(input, handler), handler); + } - private void parse(IniSource source, IniHandler handler) throws IOException, InvalidFileFormatException - { - handler.startIni(); - String sectionName = null; - - for (String line = source.readLine(); line != null; line = source.readLine()) - { - if (line.charAt(0) == SECTION_BEGIN) - { - if (sectionName != null) - { - handler.endSection(); - } - - sectionName = parseSectionLine(line, source, handler); - } - else - { - if (sectionName == null) - { - if (getConfig().isGlobalSection()) - { - sectionName = getConfig().getGlobalSectionName(); - handler.startSection(sectionName); - } - else - { - parseError(line, source.getLineNumber()); - } - } - - parseOptionLine(line, handler, source.getLineNumber()); - } + private void parse(IniSource source, IniHandler handler) + throws IOException, InvalidFileFormatException { + handler.startIni(); + String sectionName = null; + + for (String line = source.readLine(); line != null; line = source.readLine()) { + if (line.charAt(0) == SECTION_BEGIN) { + if (sectionName != null) { + handler.endSection(); } - if (sectionName != null) - { - handler.endSection(); + sectionName = parseSectionLine(line, source, handler); + } else { + if (sectionName == null) { + if (getConfig().isGlobalSection()) { + sectionName = getConfig().getGlobalSectionName(); + handler.startSection(sectionName); + } else { + parseError(line, source.getLineNumber()); + } } - handler.endIni(); + parseOptionLine(line, handler, source.getLineNumber()); + } } - private String parseSectionLine(String line, IniSource source, IniHandler handler) throws InvalidFileFormatException - { - String sectionName; + if (sectionName != null) { + handler.endSection(); + } - if (line.charAt(line.length() - 1) != SECTION_END) - { - parseError(line, source.getLineNumber()); - } + handler.endIni(); + } - sectionName = unescapeKey(line.substring(1, line.length() - 1).trim()); - if ((sectionName.length() == 0) && !getConfig().isUnnamedSection()) - { - parseError(line, source.getLineNumber()); - } + private String parseSectionLine(String line, IniSource source, IniHandler handler) + throws InvalidFileFormatException { + String sectionName; - if (getConfig().isLowerCaseSection()) - { - sectionName = sectionName.toLowerCase(Locale.getDefault()); - } + if (line.charAt(line.length() - 1) != SECTION_END) { + parseError(line, source.getLineNumber()); + } - handler.startSection(sectionName); + sectionName = unescapeKey(line.substring(1, line.length() - 1).trim()); + if ((sectionName.length() == 0) && !getConfig().isUnnamedSection()) { + parseError(line, source.getLineNumber()); + } - return sectionName; + if (getConfig().isLowerCaseSection()) { + sectionName = sectionName.toLowerCase(Locale.getDefault()); } + + handler.startSection(sectionName); + + return sectionName; + } } diff --git a/src/main/java/org/ini4j/spi/IniSource.java b/src/main/java/org/ini4j/spi/IniSource.java index 5c9fb6c..39842af 100644 --- a/src/main/java/org/ini4j/spi/IniSource.java +++ b/src/main/java/org/ini4j/spi/IniSource.java @@ -15,207 +15,170 @@ */ package org.ini4j.spi; -import org.ini4j.Config; - import java.io.IOException; import java.io.InputStream; import java.io.LineNumberReader; import java.io.Reader; - import java.net.URL; +import org.ini4j.Config; -class IniSource -{ - public static final char INCLUDE_BEGIN = '<'; - public static final char INCLUDE_END = '>'; - public static final char INCLUDE_OPTIONAL = '?'; - private static final char ESCAPE_CHAR = '\\'; - private URL _base; - private IniSource _chain; - private final String _commentChars; - private final Config _config; - private final HandlerBase _handler; - private final LineNumberReader _reader; - - IniSource(InputStream input, HandlerBase handler, String comments, Config config) - { - this(new UnicodeInputStreamReader(input, config.getFileEncoding()), handler, comments, config); - } - - IniSource(Reader input, HandlerBase handler, String comments, Config config) - { - _reader = new LineNumberReader(input); - _handler = handler; - _commentChars = comments; - _config = config; - } - - IniSource(URL input, HandlerBase handler, String comments, Config config) throws IOException - { - this(new UnicodeInputStreamReader(input.openStream(), config.getFileEncoding()), handler, comments, config); - _base = input; +class IniSource { + public static final char INCLUDE_BEGIN = '<'; + public static final char INCLUDE_END = '>'; + public static final char INCLUDE_OPTIONAL = '?'; + private static final char ESCAPE_CHAR = '\\'; + private URL _base; + private IniSource _chain; + private final String _commentChars; + private final Config _config; + private final HandlerBase _handler; + private final LineNumberReader _reader; + + IniSource(InputStream input, HandlerBase handler, String comments, Config config) { + this(new UnicodeInputStreamReader(input, config.getFileEncoding()), handler, comments, config); + } + + IniSource(Reader input, HandlerBase handler, String comments, Config config) { + _reader = new LineNumberReader(input); + _handler = handler; + _commentChars = comments; + _config = config; + } + + IniSource(URL input, HandlerBase handler, String comments, Config config) throws IOException { + this( + new UnicodeInputStreamReader(input.openStream(), config.getFileEncoding()), + handler, + comments, + config); + _base = input; + } + + int getLineNumber() { + int ret; + + if (_chain == null) { + ret = _reader.getLineNumber(); + } else { + ret = _chain.getLineNumber(); } - int getLineNumber() - { - int ret; + return ret; + } - if (_chain == null) - { - ret = _reader.getLineNumber(); - } - else - { - ret = _chain.getLineNumber(); - } + String readLine() throws IOException { + String line; - return ret; + if (_chain == null) { + line = readLineLocal(); + } else { + line = _chain.readLine(); + if (line == null) { + _chain = null; + line = readLine(); + } } - String readLine() throws IOException - { - String line; + return line; + } - if (_chain == null) - { - line = readLineLocal(); - } - else - { - line = _chain.readLine(); - if (line == null) - { - _chain = null; - line = readLine(); - } - } + private void close() throws IOException { + _reader.close(); + } - return line; - } + private int countEndingEscapes(String line) { + int escapeCount = 0; - private void close() throws IOException - { - _reader.close(); + for (int i = line.length() - 1; (i >= 0) && (line.charAt(i) == ESCAPE_CHAR); i--) { + escapeCount++; } - private int countEndingEscapes(String line) - { - int escapeCount = 0; + return escapeCount; + } - for (int i = line.length() - 1; (i >= 0) && (line.charAt(i) == ESCAPE_CHAR); i--) - { - escapeCount++; - } - - return escapeCount; - } - - private void handleComment(StringBuilder buff) - { - if (buff.length() != 0) - { - buff.deleteCharAt(buff.length() - 1); - _handler.handleComment(buff.toString()); - buff.delete(0, buff.length()); - } + private void handleComment(StringBuilder buff) { + if (buff.length() != 0) { + buff.deleteCharAt(buff.length() - 1); + _handler.handleComment(buff.toString()); + buff.delete(0, buff.length()); } - - private String handleInclude(String input) throws IOException - { - String line = input; - - if (_config.isInclude() && (line.length() > 2) && (line.charAt(0) == INCLUDE_BEGIN) && (line.charAt(line.length() - 1) == INCLUDE_END)) - { - line = line.substring(1, line.length() - 1).trim(); - boolean optional = line.charAt(0) == INCLUDE_OPTIONAL; - - if (optional) - { - line = line.substring(1).trim(); - } - - URL loc = (_base == null) ? new URL(line) : new URL(_base, line); - - if (optional) - { - try - { - _chain = new IniSource(loc, _handler, _commentChars, _config); - } - catch (IOException x) - { - assert true; - } - finally - { - line = readLine(); - } - } - else - { - _chain = new IniSource(loc, _handler, _commentChars, _config); - line = readLine(); - } + } + + private String handleInclude(String input) throws IOException { + String line = input; + + if (_config.isInclude() + && (line.length() > 2) + && (line.charAt(0) == INCLUDE_BEGIN) + && (line.charAt(line.length() - 1) == INCLUDE_END)) { + line = line.substring(1, line.length() - 1).trim(); + boolean optional = line.charAt(0) == INCLUDE_OPTIONAL; + + if (optional) { + line = line.substring(1).trim(); + } + + URL loc = (_base == null) ? new URL(line) : new URL(_base, line); + + if (optional) { + try { + _chain = new IniSource(loc, _handler, _commentChars, _config); + } catch (IOException x) { + assert true; + } finally { + line = readLine(); } - - return line; + } else { + _chain = new IniSource(loc, _handler, _commentChars, _config); + line = readLine(); + } } - private String readLineLocal() throws IOException - { - String line = readLineSkipComments(); + return line; + } - if (line == null) - { - close(); - } - else - { - line = handleInclude(line); - } + private String readLineLocal() throws IOException { + String line = readLineSkipComments(); - return line; + if (line == null) { + close(); + } else { + line = handleInclude(line); } - private String readLineSkipComments() throws IOException - { - String line; - StringBuilder comment = new StringBuilder(); - StringBuilder buff = new StringBuilder(); - - for (line = _reader.readLine(); line != null; line = _reader.readLine()) - { - line = line.trim(); - if (line.length() == 0) - { - handleComment(comment); - } - else if ((_commentChars.indexOf(line.charAt(0)) >= 0) && (buff.length() == 0)) - { - comment.append(line.substring(1)); - comment.append(_config.getLineSeparator()); - } - else - { - handleComment(comment); - if (!_config.isEscapeNewline() || ((countEndingEscapes(line) & 1) == 0)) - { - buff.append(line); - line = buff.toString(); - - break; - } - - buff.append(line.subSequence(0, line.length() - 1)); - } + return line; + } + + private String readLineSkipComments() throws IOException { + String line; + StringBuilder comment = new StringBuilder(); + StringBuilder buff = new StringBuilder(); + + for (line = _reader.readLine(); line != null; line = _reader.readLine()) { + line = line.trim(); + if (line.length() == 0) { + handleComment(comment); + } else if ((_commentChars.indexOf(line.charAt(0)) >= 0) && (buff.length() == 0)) { + comment.append(line.substring(1)); + comment.append(_config.getLineSeparator()); + } else { + handleComment(comment); + if (!_config.isEscapeNewline() || ((countEndingEscapes(line) & 1) == 0)) { + buff.append(line); + line = buff.toString(); + + break; } - // handle end comments - if ((line == null) && (comment.length() != 0)) - { - handleComment(comment); - } + buff.append(line.subSequence(0, line.length() - 1)); + } + } - return line; + // handle end comments + if ((line == null) && (comment.length() != 0)) { + handleComment(comment); } + + return line; + } } diff --git a/src/main/java/org/ini4j/spi/OptionsBuilder.java b/src/main/java/org/ini4j/spi/OptionsBuilder.java index 5dcb4d4..78374e3 100644 --- a/src/main/java/org/ini4j/spi/OptionsBuilder.java +++ b/src/main/java/org/ini4j/spi/OptionsBuilder.java @@ -18,106 +18,87 @@ import org.ini4j.Config; import org.ini4j.Options; -public class OptionsBuilder implements OptionsHandler -{ - private boolean _header; - private String _lastComment; - private Options _options; +public class OptionsBuilder implements OptionsHandler { + private boolean _header; + private String _lastComment; + private Options _options; - public static OptionsBuilder newInstance(Options opts) - { - OptionsBuilder instance = newInstance(); + public static OptionsBuilder newInstance(Options opts) { + OptionsBuilder instance = newInstance(); - instance.setOptions(opts); + instance.setOptions(opts); - return instance; + return instance; + } + + public void setOptions(Options value) { + _options = value; + } + + @Override + public void endOptions() { + + // comment only .opt file ... + if ((_lastComment != null) && _header) { + setHeaderComment(); } + } - public void setOptions(Options value) - { - _options = value; + @Override + public void handleComment(String comment) { + if ((_lastComment != null) && _header) { + setHeaderComment(); + _header = false; } - @Override public void endOptions() - { + _lastComment = comment; + } - // comment only .opt file ... - if ((_lastComment != null) && _header) - { - setHeaderComment(); - } + @Override + public void handleOption(String name, String value) { + if (getConfig().isMultiOption()) { + _options.add(name, value); + } else { + _options.put(name, value); } - @Override public void handleComment(String comment) - { - if ((_lastComment != null) && _header) - { - setHeaderComment(); - _header = false; - } + if (_lastComment != null) { + if (_header) { + setHeaderComment(); + } else { + putComment(name); + } - _lastComment = comment; + _lastComment = null; } - @Override public void handleOption(String name, String value) - { - if (getConfig().isMultiOption()) - { - _options.add(name, value); - } - else - { - _options.put(name, value); - } - - if (_lastComment != null) - { - if (_header) - { - setHeaderComment(); - } - else - { - putComment(name); - } - - _lastComment = null; - } - - _header = false; - } + _header = false; + } - @Override public void startOptions() - { - if (getConfig().isHeaderComment()) - { - _header = true; - } + @Override + public void startOptions() { + if (getConfig().isHeaderComment()) { + _header = true; } + } - protected static OptionsBuilder newInstance() - { - return ServiceFinder.findService(OptionsBuilder.class); - } + protected static OptionsBuilder newInstance() { + return ServiceFinder.findService(OptionsBuilder.class); + } - private Config getConfig() - { - return _options.getConfig(); - } + private Config getConfig() { + return _options.getConfig(); + } - private void setHeaderComment() - { - if (getConfig().isComment()) - { - _options.setComment(_lastComment); - } + private void setHeaderComment() { + if (getConfig().isComment()) { + _options.setComment(_lastComment); } + } - private void putComment(String key) - { - if (getConfig().isComment()) - { - _options.putComment(key, _lastComment); - } + private void putComment(String key) { + if (getConfig().isComment()) { + _options.putComment(key, _lastComment); } + } } diff --git a/src/main/java/org/ini4j/spi/OptionsFormatter.java b/src/main/java/org/ini4j/spi/OptionsFormatter.java index aa858ed..613a2e9 100644 --- a/src/main/java/org/ini4j/spi/OptionsFormatter.java +++ b/src/main/java/org/ini4j/spi/OptionsFormatter.java @@ -15,35 +15,29 @@ */ package org.ini4j.spi; -import org.ini4j.Config; - import java.io.PrintWriter; import java.io.Writer; +import org.ini4j.Config; -public class OptionsFormatter extends AbstractFormatter implements OptionsHandler -{ - public static OptionsFormatter newInstance(Writer out, Config config) - { - OptionsFormatter instance = newInstance(); +public class OptionsFormatter extends AbstractFormatter implements OptionsHandler { + public static OptionsFormatter newInstance(Writer out, Config config) { + OptionsFormatter instance = newInstance(); - instance.setOutput((out instanceof PrintWriter) ? (PrintWriter) out : new PrintWriter(out)); - instance.setConfig(config); + instance.setOutput((out instanceof PrintWriter) ? (PrintWriter) out : new PrintWriter(out)); + instance.setConfig(config); - return instance; - } + return instance; + } - public void endOptions() - { - getOutput().flush(); - } + public void endOptions() { + getOutput().flush(); + } - public void startOptions() - { - assert true; - } + public void startOptions() { + assert true; + } - private static OptionsFormatter newInstance() - { - return ServiceFinder.findService(OptionsFormatter.class); - } + private static OptionsFormatter newInstance() { + return ServiceFinder.findService(OptionsFormatter.class); + } } diff --git a/src/main/java/org/ini4j/spi/OptionsHandler.java b/src/main/java/org/ini4j/spi/OptionsHandler.java index 3987e5c..3f44af4 100644 --- a/src/main/java/org/ini4j/spi/OptionsHandler.java +++ b/src/main/java/org/ini4j/spi/OptionsHandler.java @@ -15,13 +15,14 @@ */ package org.ini4j.spi; -public interface OptionsHandler extends HandlerBase -{ - void endOptions(); +public interface OptionsHandler extends HandlerBase { + void endOptions(); - @Override void handleComment(String comment); + @Override + void handleComment(String comment); - @Override void handleOption(String optionName, String optionValue); + @Override + void handleOption(String optionName, String optionValue); - void startOptions(); + void startOptions(); } diff --git a/src/main/java/org/ini4j/spi/OptionsParser.java b/src/main/java/org/ini4j/spi/OptionsParser.java index 7a5fb0f..a366f60 100644 --- a/src/main/java/org/ini4j/spi/OptionsParser.java +++ b/src/main/java/org/ini4j/spi/OptionsParser.java @@ -15,62 +15,55 @@ */ package org.ini4j.spi; -import org.ini4j.Config; -import org.ini4j.InvalidFileFormatException; - import java.io.IOException; import java.io.InputStream; import java.io.Reader; - import java.net.URL; +import org.ini4j.Config; +import org.ini4j.InvalidFileFormatException; -public class OptionsParser extends AbstractParser -{ - private static final String COMMENTS = "!#"; - private static final String OPERATORS = ":="; - - public OptionsParser() - { - super(OPERATORS, COMMENTS); - } +public class OptionsParser extends AbstractParser { + private static final String COMMENTS = "!#"; + private static final String OPERATORS = ":="; - public static OptionsParser newInstance() - { - return ServiceFinder.findService(OptionsParser.class); - } + public OptionsParser() { + super(OPERATORS, COMMENTS); + } - public static OptionsParser newInstance(Config config) - { - OptionsParser instance = newInstance(); + public static OptionsParser newInstance() { + return ServiceFinder.findService(OptionsParser.class); + } - instance.setConfig(config); + public static OptionsParser newInstance(Config config) { + OptionsParser instance = newInstance(); - return instance; - } + instance.setConfig(config); - public void parse(InputStream input, OptionsHandler handler) throws IOException, InvalidFileFormatException - { - parse(newIniSource(input, handler), handler); - } + return instance; + } - public void parse(Reader input, OptionsHandler handler) throws IOException, InvalidFileFormatException - { - parse(newIniSource(input, handler), handler); - } + public void parse(InputStream input, OptionsHandler handler) + throws IOException, InvalidFileFormatException { + parse(newIniSource(input, handler), handler); + } - public void parse(URL input, OptionsHandler handler) throws IOException, InvalidFileFormatException - { - parse(newIniSource(input, handler), handler); - } + public void parse(Reader input, OptionsHandler handler) + throws IOException, InvalidFileFormatException { + parse(newIniSource(input, handler), handler); + } - private void parse(IniSource source, OptionsHandler handler) throws IOException, InvalidFileFormatException - { - handler.startOptions(); - for (String line = source.readLine(); line != null; line = source.readLine()) - { - parseOptionLine(line, handler, source.getLineNumber()); - } + public void parse(URL input, OptionsHandler handler) + throws IOException, InvalidFileFormatException { + parse(newIniSource(input, handler), handler); + } - handler.endOptions(); + private void parse(IniSource source, OptionsHandler handler) + throws IOException, InvalidFileFormatException { + handler.startOptions(); + for (String line = source.readLine(); line != null; line = source.readLine()) { + parseOptionLine(line, handler, source.getLineNumber()); } + + handler.endOptions(); + } } diff --git a/src/main/java/org/ini4j/spi/RegBuilder.java b/src/main/java/org/ini4j/spi/RegBuilder.java index 0684bf4..85a1f0d 100644 --- a/src/main/java/org/ini4j/spi/RegBuilder.java +++ b/src/main/java/org/ini4j/spi/RegBuilder.java @@ -18,56 +18,52 @@ import org.ini4j.Config; import org.ini4j.Profile; import org.ini4j.Reg; - import org.ini4j.Registry.Key; import org.ini4j.Registry.Type; -public class RegBuilder extends AbstractProfileBuilder -{ - private Reg _reg; - - public static RegBuilder newInstance(Reg reg) - { - RegBuilder instance = newInstance(); +public class RegBuilder extends AbstractProfileBuilder { + private Reg _reg; - instance.setReg(reg); + public static RegBuilder newInstance(Reg reg) { + RegBuilder instance = newInstance(); - return instance; - } + instance.setReg(reg); - public void setReg(Reg value) - { - _reg = value; - } + return instance; + } - @Override public void handleOption(String rawName, String rawValue) - { - String name = (rawName.charAt(0) == EscapeTool.DOUBLE_QUOTE) ? RegEscapeTool.getInstance().unquote(rawName) : rawName; - TypeValuesPair tv = RegEscapeTool.getInstance().decode(rawValue); + public void setReg(Reg value) { + _reg = value; + } - if (tv.getType() != Type.REG_SZ) - { - ((Key) getCurrentSection()).putType(name, tv.getType()); - } + @Override + public void handleOption(String rawName, String rawValue) { + String name = + (rawName.charAt(0) == EscapeTool.DOUBLE_QUOTE) + ? RegEscapeTool.getInstance().unquote(rawName) + : rawName; + TypeValuesPair tv = RegEscapeTool.getInstance().decode(rawValue); - for (String value : tv.getValues()) - { - super.handleOption(name, value); - } + if (tv.getType() != Type.REG_SZ) { + ((Key) getCurrentSection()).putType(name, tv.getType()); } - @Override Config getConfig() - { - return _reg.getConfig(); + for (String value : tv.getValues()) { + super.handleOption(name, value); } + } - @Override Profile getProfile() - { - return _reg; - } + @Override + Config getConfig() { + return _reg.getConfig(); + } - private static RegBuilder newInstance() - { - return ServiceFinder.findService(RegBuilder.class); - } + @Override + Profile getProfile() { + return _reg; + } + + private static RegBuilder newInstance() { + return ServiceFinder.findService(RegBuilder.class); + } } diff --git a/src/main/java/org/ini4j/spi/RegEscapeTool.java b/src/main/java/org/ini4j/spi/RegEscapeTool.java index ce8429f..4efdf6f 100644 --- a/src/main/java/org/ini4j/spi/RegEscapeTool.java +++ b/src/main/java/org/ini4j/spi/RegEscapeTool.java @@ -15,269 +15,218 @@ */ package org.ini4j.spi; -import org.ini4j.Registry; - -import org.ini4j.Registry.Type; - import java.io.UnsupportedEncodingException; - import java.nio.charset.Charset; - import java.util.Arrays; +import org.ini4j.Registry; +import org.ini4j.Registry.Type; -public class RegEscapeTool extends EscapeTool -{ - private static final RegEscapeTool INSTANCE = ServiceFinder.findService(RegEscapeTool.class); - private static final Charset HEX_CHARSET = Charset.forName("UTF-16LE"); - private static final int LOWER_DIGIT = 0x0f; - private static final int UPPER_DIGIT = 0xf0; - private static final int DIGIT_SIZE = 4; - - public static final RegEscapeTool getInstance() - { - return INSTANCE; +public class RegEscapeTool extends EscapeTool { + private static final RegEscapeTool INSTANCE = ServiceFinder.findService(RegEscapeTool.class); + private static final Charset HEX_CHARSET = Charset.forName("UTF-16LE"); + private static final int LOWER_DIGIT = 0x0f; + private static final int UPPER_DIGIT = 0xf0; + private static final int DIGIT_SIZE = 4; + + public static final RegEscapeTool getInstance() { + return INSTANCE; + } + + public TypeValuesPair decode(String raw) { + Type type = type(raw); + String value = + (type == Type.REG_SZ) ? unquote(raw) : raw.substring(type.toString().length() + 1); + String[] values; + + switch (type) { + case REG_EXPAND_SZ: + case REG_MULTI_SZ: + value = bytes2string(binary(value)); + break; + + case REG_DWORD: + value = String.valueOf(Long.parseLong(value, HEX_RADIX)); + break; + + case REG_SZ: + break; + + default: + break; } - public TypeValuesPair decode(String raw) - { - Type type = type(raw); - String value = (type == Type.REG_SZ) ? unquote(raw) : raw.substring(type.toString().length() + 1); - String[] values; - - switch (type) - { - - case REG_EXPAND_SZ: - case REG_MULTI_SZ: - value = bytes2string(binary(value)); - break; + if (type == Type.REG_MULTI_SZ) { + values = splitMulti(value); + } else { + values = new String[] {value}; + } - case REG_DWORD: - value = String.valueOf(Long.parseLong(value, HEX_RADIX)); - break; + return new TypeValuesPair(type, values); + } - case REG_SZ: - break; + public String encode(TypeValuesPair data) { + String ret = null; - default: - break; - } + if (data.getType() == Type.REG_SZ) { + ret = quote(data.getValues()[0]); + } else if (data.getValues()[0] != null) { + ret = encode(data.getType(), data.getValues()); + } - if (type == Type.REG_MULTI_SZ) - { - values = splitMulti(value); - } - else - { - values = new String[] { value }; - } + return ret; + } - return new TypeValuesPair(type, values); - } + byte[] binary(String value) { + byte[] bytes = new byte[value.length()]; + int idx = 0; + int shift = DIGIT_SIZE; - public String encode(TypeValuesPair data) - { - String ret = null; + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); - if (data.getType() == Type.REG_SZ) - { - ret = quote(data.getValues()[0]); - } - else if (data.getValues()[0] != null) - { - ret = encode(data.getType(), data.getValues()); - } + if (Character.isWhitespace(c)) { + continue; + } - return ret; - } + if (c == ',') { + idx++; + shift = DIGIT_SIZE; + } else { + int digit = Character.digit(c, HEX_RADIX); - byte[] binary(String value) - { - byte[] bytes = new byte[value.length()]; - int idx = 0; - int shift = DIGIT_SIZE; - - for (int i = 0; i < value.length(); i++) - { - char c = value.charAt(i); - - if (Character.isWhitespace(c)) - { - continue; - } - - if (c == ',') - { - idx++; - shift = DIGIT_SIZE; - } - else - { - int digit = Character.digit(c, HEX_RADIX); - - if (digit >= 0) - { - bytes[idx] |= digit << shift; - shift = 0; - } - } + if (digit >= 0) { + bytes[idx] |= digit << shift; + shift = 0; } - - return Arrays.copyOfRange(bytes, 0, idx + 1); + } } - String encode(Type type, String[] values) - { - StringBuilder buff = new StringBuilder(); + return Arrays.copyOfRange(bytes, 0, idx + 1); + } - buff.append(type.toString()); - buff.append(Type.SEPARATOR_CHAR); - switch (type) - { + String encode(Type type, String[] values) { + StringBuilder buff = new StringBuilder(); - case REG_EXPAND_SZ: - buff.append(hexadecimal(values[0])); - break; + buff.append(type.toString()); + buff.append(Type.SEPARATOR_CHAR); + switch (type) { + case REG_EXPAND_SZ: + buff.append(hexadecimal(values[0])); + break; - case REG_DWORD: - buff.append(String.format("%08x", Long.parseLong(values[0]))); - break; + case REG_DWORD: + buff.append(String.format("%08x", Long.parseLong(values[0]))); + break; - case REG_MULTI_SZ: - int n = values.length; + case REG_MULTI_SZ: + int n = values.length; - for (int i = 0; i < n; i++) - { - buff.append(hexadecimal(values[i])); - buff.append(','); - } - - buff.append("00,00"); - break; - - default: - buff.append(values[0]); - break; + for (int i = 0; i < n; i++) { + buff.append(hexadecimal(values[i])); + buff.append(','); } - return buff.toString(); + buff.append("00,00"); + break; + + default: + buff.append(values[0]); + break; } - String hexadecimal(String value) - { - StringBuilder buff = new StringBuilder(); + return buff.toString(); + } - if ((value != null) && (value.length() != 0)) - { - byte[] bytes = string2bytes(value); + String hexadecimal(String value) { + StringBuilder buff = new StringBuilder(); - for (int i = 0; i < bytes.length; i++) - { - buff.append(Character.forDigit((bytes[i] & UPPER_DIGIT) >> DIGIT_SIZE, HEX_RADIX)); - buff.append(Character.forDigit(bytes[i] & LOWER_DIGIT, HEX_RADIX)); - buff.append(','); - } + if ((value != null) && (value.length() != 0)) { + byte[] bytes = string2bytes(value); - buff.append("00,00"); - } + for (int i = 0; i < bytes.length; i++) { + buff.append(Character.forDigit((bytes[i] & UPPER_DIGIT) >> DIGIT_SIZE, HEX_RADIX)); + buff.append(Character.forDigit(bytes[i] & LOWER_DIGIT, HEX_RADIX)); + buff.append(','); + } - return buff.toString(); + buff.append("00,00"); } - Registry.Type type(String raw) - { - Registry.Type type; + return buff.toString(); + } - if (raw.charAt(0) == DOUBLE_QUOTE) - { - type = Registry.Type.REG_SZ; - } - else - { - int idx = raw.indexOf(Registry.TYPE_SEPARATOR); + Registry.Type type(String raw) { + Registry.Type type; - type = (idx < 0) ? Registry.Type.REG_SZ : Registry.Type.fromString(raw.substring(0, idx)); - } + if (raw.charAt(0) == DOUBLE_QUOTE) { + type = Registry.Type.REG_SZ; + } else { + int idx = raw.indexOf(Registry.TYPE_SEPARATOR); - return type; + type = (idx < 0) ? Registry.Type.REG_SZ : Registry.Type.fromString(raw.substring(0, idx)); } - // XXX Java 1.4 compatibility hack - private String bytes2string(byte[] bytes) - { - String str; - - try - { - str = new String(bytes, 0, bytes.length - 2, HEX_CHARSET); - } - catch (NoSuchMethodError x) - { - try - { - str = new String(bytes, 0, bytes.length, HEX_CHARSET.name()); - } - catch (UnsupportedEncodingException ex) - { - throw new IllegalStateException(ex); - } - } - - return str; + return type; + } + + // XXX Java 1.4 compatibility hack + private String bytes2string(byte[] bytes) { + String str; + + try { + str = new String(bytes, 0, bytes.length - 2, HEX_CHARSET); + } catch (NoSuchMethodError x) { + try { + str = new String(bytes, 0, bytes.length, HEX_CHARSET.name()); + } catch (UnsupportedEncodingException ex) { + throw new IllegalStateException(ex); + } } - private String[] splitMulti(String value) - { - int len = value.length(); - int start; - int end; - int n = 0; - - start = 0; - for (end = value.indexOf(0, start); end >= 0; end = value.indexOf(0, start)) - { - n++; - start = end + 1; - if (start >= len) - { - break; - } - } - - String[] values = new String[n]; - - start = 0; - for (int i = 0; i < n; i++) - { - end = value.indexOf(0, start); - values[i] = value.substring(start, end); - start = end + 1; - } - - return values; + return str; + } + + private String[] splitMulti(String value) { + int len = value.length(); + int start; + int end; + int n = 0; + + start = 0; + for (end = value.indexOf(0, start); end >= 0; end = value.indexOf(0, start)) { + n++; + start = end + 1; + if (start >= len) { + break; + } } - // XXX Java 1.4 compatibility hack - private byte[] string2bytes(String value) - { - byte[] bytes; + String[] values = new String[n]; - try - { - bytes = value.getBytes(HEX_CHARSET); - } - catch (NoSuchMethodError x) - { - try - { - bytes = value.getBytes(HEX_CHARSET.name()); - } - catch (UnsupportedEncodingException ex) - { - throw new IllegalStateException(ex); - } - } + start = 0; + for (int i = 0; i < n; i++) { + end = value.indexOf(0, start); + values[i] = value.substring(start, end); + start = end + 1; + } - return bytes; + return values; + } + + // XXX Java 1.4 compatibility hack + private byte[] string2bytes(String value) { + byte[] bytes; + + try { + bytes = value.getBytes(HEX_CHARSET); + } catch (NoSuchMethodError x) { + try { + bytes = value.getBytes(HEX_CHARSET.name()); + } catch (UnsupportedEncodingException ex) { + throw new IllegalStateException(ex); + } } + + return bytes; + } } diff --git a/src/main/java/org/ini4j/spi/ServiceFinder.java b/src/main/java/org/ini4j/spi/ServiceFinder.java index 9bd4b97..24bc389 100755 --- a/src/main/java/org/ini4j/spi/ServiceFinder.java +++ b/src/main/java/org/ini4j/spi/ServiceFinder.java @@ -23,139 +23,119 @@ * JDK JAR Services API alap� service keres� oszt�ly. * * @author Szkiba Iv�n - * @version $Name: $ + * @version $Name: $ */ -final class ServiceFinder -{ - private static final String SERVICES_PATH = "META-INF/services/"; - - private ServiceFinder() - { - } - - /** - * Service objektum keres�s �s p�ld�nyos�t�s - * - * a JDK JAR specifik�ci�ban defini�lt Services API-nak - * megfelel�en service oszt�ly keres�s, majd pedig p�ld�ny k�pz�s a context - * ClassLoader seg�ts�g�vel.

- * Az implement�l� oszt�ly n�v keres�se a serviceId nev� - * system property vizsg�lat�val kezd�dik. Amennyiben nincs ilyen - * property, �gy a keres�s a - * /META-INF/services/serviceId nev� file tartalm�val - * folytat�dik. Amennyiben nincs ilyen nev� file, �gy a param�terk�nt �tadott - * defaultService lesz az oszt�ly neve.

- * A fenti keres�st k�vet�en t�rt�nik a p�ld�ny k�pz�s. A visszat�r�si - * �rt�k mindig egy val�di objektum, l�v�n minden hiba exception-t gener�l. - * @param type - * @param clazz keresett oszt�ly/service neve - * @throws IllegalArgumentException keres�si vagy p�ld�nyos�t�si hiba eset�n - * @return a keresett oszt�ly implement�l� objektum - */ - static T findService(Class clazz) - { - try - { - - // ez a cast nem lenne szükséges, de úgy a ClassCastException csak a hívónál jön... - return clazz.cast(findServiceClass(clazz).getDeclaredConstructor().newInstance()); - } - catch (Exception x) - { - throw (IllegalArgumentException) new IllegalArgumentException("Provider " + clazz.getName() + " could not be instantiated: " + x) +final class ServiceFinder { + private static final String SERVICES_PATH = "META-INF/services/"; + + private ServiceFinder() {} + + /** + * Service objektum keres�s �s p�ld�nyos�t�s + * + *

a JDK JAR specifik�ci�ban defini�lt Services API-nak megfelel�en service oszt�ly + * keres�s, majd pedig p�ld�ny k�pz�s a context ClassLoader seg�ts�g�vel. + * + *

Az implement�l� oszt�ly n�v keres�se a serviceId nev� system property + * vizsg�lat�val kezd�dik. Amennyiben nincs ilyen property, �gy a keres�s a + * /META-INF/services/serviceId nev� file tartalm�val folytat�dik. Amennyiben nincs + * ilyen nev� file, �gy a param�terk�nt �tadott defaultService lesz az oszt�ly neve. + * + *

A fenti keres�st k�vet�en t�rt�nik a p�ld�ny k�pz�s. A visszat�r�si �rt�k mindig egy val�di + * objektum, l�v�n minden hiba exception-t gener�l. + * + * @param type + * @param clazz keresett oszt�ly/service neve + * @throws IllegalArgumentException keres�si vagy p�ld�nyos�t�si hiba eset�n + * @return a keresett oszt�ly implement�l� objektum + */ + static T findService(Class clazz) { + try { + + // ez a cast nem lenne szükséges, de úgy a ClassCastException csak a hívónál jön... + return clazz.cast(findServiceClass(clazz).getDeclaredConstructor().newInstance()); + } catch (Exception x) { + throw (IllegalArgumentException) + new IllegalArgumentException( + "Provider " + clazz.getName() + " could not be instantiated: " + x) .initCause(x); - } } - - @SuppressWarnings(Warnings.UNCHECKED) - static Class findServiceClass(Class clazz) throws IllegalArgumentException - { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - String serviceClassName = findServiceClassName(clazz.getName()); - Class ret = clazz; - - if (serviceClassName != null) - { - try - { - ret = (Class) ((classLoader == null) ? Class.forName(serviceClassName) : classLoader.loadClass(serviceClassName)); - } - catch (ClassNotFoundException x) - { - throw (IllegalArgumentException) new IllegalArgumentException("Provider " + serviceClassName + " not found").initCause(x); - } - } - - return ret; + } + + @SuppressWarnings(Warnings.UNCHECKED) + static Class findServiceClass(Class clazz) throws IllegalArgumentException { + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + String serviceClassName = findServiceClassName(clazz.getName()); + Class ret = clazz; + + if (serviceClassName != null) { + try { + ret = + (Class) + ((classLoader == null) + ? Class.forName(serviceClassName) + : classLoader.loadClass(serviceClassName)); + } catch (ClassNotFoundException x) { + throw (IllegalArgumentException) + new IllegalArgumentException("Provider " + serviceClassName + " not found") + .initCause(x); + } } - static String findServiceClassName(String serviceId) throws IllegalArgumentException - { - String serviceClassName = null; + return ret; + } - // Use the system property first - try - { - String systemProp = System.getProperty(serviceId); + static String findServiceClassName(String serviceId) throws IllegalArgumentException { + String serviceClassName = null; - if (systemProp != null) - { - serviceClassName = systemProp; - } - } - catch (SecurityException x) - { - assert true; - } + // Use the system property first + try { + String systemProp = System.getProperty(serviceId); - if (serviceClassName == null) - { - serviceClassName = loadLine(SERVICES_PATH + serviceId); - } + if (systemProp != null) { + serviceClassName = systemProp; + } + } catch (SecurityException x) { + assert true; + } - return serviceClassName; + if (serviceClassName == null) { + serviceClassName = loadLine(SERVICES_PATH + serviceId); } - private static String loadLine(String servicePath) - { - String ret = null; - - // try to find services in CLASSPATH - try - { - InputStream is = null; - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - - if (classLoader == null) - { - is = ClassLoader.getSystemResourceAsStream(servicePath); - } - else - { - is = classLoader.getResourceAsStream(servicePath); - } - - if (is != null) - { - BufferedReader rd = new BufferedReader(new InputStreamReader(is, "UTF-8")); - String line = rd.readLine(); - - rd.close(); - if (line != null) - { - line = line.trim(); - if (line.length() != 0) - { - ret = line.split("\\s|#")[0]; - } - } - } + return serviceClassName; + } + + private static String loadLine(String servicePath) { + String ret = null; + + // try to find services in CLASSPATH + try { + InputStream is = null; + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + + if (classLoader == null) { + is = ClassLoader.getSystemResourceAsStream(servicePath); + } else { + is = classLoader.getResourceAsStream(servicePath); + } + + if (is != null) { + BufferedReader rd = new BufferedReader(new InputStreamReader(is, "UTF-8")); + String line = rd.readLine(); + + rd.close(); + if (line != null) { + line = line.trim(); + if (line.length() != 0) { + ret = line.split("\\s|#")[0]; + } } - catch (Exception x) - { - assert true; - } - - return ret; + } + } catch (Exception x) { + assert true; } + + return ret; + } } diff --git a/src/main/java/org/ini4j/spi/TypeValuesPair.java b/src/main/java/org/ini4j/spi/TypeValuesPair.java index 2b1af21..fba517c 100644 --- a/src/main/java/org/ini4j/spi/TypeValuesPair.java +++ b/src/main/java/org/ini4j/spi/TypeValuesPair.java @@ -17,25 +17,21 @@ import org.ini4j.Registry.Type; -public class TypeValuesPair -{ - private final Type _type; - private final String[] _values; +public class TypeValuesPair { + private final Type _type; + private final String[] _values; - @SuppressWarnings("PMD.ArrayIsStoredDirectly") - public TypeValuesPair(Type type, String[] values) - { - _type = type; - _values = values; - } + @SuppressWarnings("PMD.ArrayIsStoredDirectly") + public TypeValuesPair(Type type, String[] values) { + _type = type; + _values = values; + } - public Type getType() - { - return _type; - } + public Type getType() { + return _type; + } - public String[] getValues() - { - return _values; - } + public String[] getValues() { + return _values; + } } diff --git a/src/main/java/org/ini4j/spi/UnicodeInputStreamReader.java b/src/main/java/org/ini4j/spi/UnicodeInputStreamReader.java index eeb5bd3..ebebac9 100644 --- a/src/main/java/org/ini4j/spi/UnicodeInputStreamReader.java +++ b/src/main/java/org/ini4j/spi/UnicodeInputStreamReader.java @@ -20,136 +20,113 @@ import java.io.InputStreamReader; import java.io.PushbackInputStream; import java.io.Reader; - import java.nio.charset.Charset; -class UnicodeInputStreamReader extends Reader -{ - private static final int BOM_SIZE = 4; - - private static enum Bom - { - UTF32BE("UTF-32BE", new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0xFE, (byte) 0xFF }), - UTF32LE("UTF-32LE", new byte[] { (byte) 0xFF, (byte) 0xFE, (byte) 0x00, (byte) 0x00 }), - UTF16BE("UTF-16BE", new byte[] { (byte) 0xFE, (byte) 0xFF }), - UTF16LE("UTF-16LE", new byte[] { (byte) 0xFF, (byte) 0xFE }), - UTF8("UTF-8", new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF }); - private final byte[] _bytes; - private Charset _charset; - - @SuppressWarnings("PMD.ArrayIsStoredDirectly") - private Bom(String charsetName, byte[] bytes) - { - try - { - _charset = Charset.forName(charsetName); - } - catch (Exception x) - { - _charset = null; - } - - _bytes = bytes; - } - - private static Bom find(byte[] data) - { - Bom ret = null; +class UnicodeInputStreamReader extends Reader { + private static final int BOM_SIZE = 4; + + private static enum Bom { + UTF32BE("UTF-32BE", new byte[] {(byte) 0x00, (byte) 0x00, (byte) 0xFE, (byte) 0xFF}), + UTF32LE("UTF-32LE", new byte[] {(byte) 0xFF, (byte) 0xFE, (byte) 0x00, (byte) 0x00}), + UTF16BE("UTF-16BE", new byte[] {(byte) 0xFE, (byte) 0xFF}), + UTF16LE("UTF-16LE", new byte[] {(byte) 0xFF, (byte) 0xFE}), + UTF8("UTF-8", new byte[] {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}); + private final byte[] _bytes; + private Charset _charset; + + @SuppressWarnings("PMD.ArrayIsStoredDirectly") + private Bom(String charsetName, byte[] bytes) { + try { + _charset = Charset.forName(charsetName); + } catch (Exception x) { + _charset = null; + } + + _bytes = bytes; + } - for (Bom bom : values()) - { - if (bom.supported() && bom.match(data)) - { - ret = bom; + private static Bom find(byte[] data) { + Bom ret = null; - break; - } - } + for (Bom bom : values()) { + if (bom.supported() && bom.match(data)) { + ret = bom; - return ret; + break; } + } - private boolean match(byte[] data) - { - boolean ok = true; + return ret; + } - for (int i = 0; i < _bytes.length; i++) - { - if (data[i] != _bytes[i]) - { - ok = false; + private boolean match(byte[] data) { + boolean ok = true; - break; - } - } + for (int i = 0; i < _bytes.length; i++) { + if (data[i] != _bytes[i]) { + ok = false; - return ok; + break; } + } - private boolean supported() - { - return _charset != null; - } + return ok; } - private final Charset _defaultEncoding; - private InputStreamReader _reader; - private final PushbackInputStream _stream; - - UnicodeInputStreamReader(InputStream in, Charset defaultEnc) - { - _stream = new PushbackInputStream(in, BOM_SIZE); - _defaultEncoding = defaultEnc; + private boolean supported() { + return _charset != null; } - - public void close() throws IOException - { - init(); - _reader.close(); + } + + private final Charset _defaultEncoding; + private InputStreamReader _reader; + private final PushbackInputStream _stream; + + UnicodeInputStreamReader(InputStream in, Charset defaultEnc) { + _stream = new PushbackInputStream(in, BOM_SIZE); + _defaultEncoding = defaultEnc; + } + + public void close() throws IOException { + init(); + _reader.close(); + } + + public int read(char[] cbuf, int off, int len) throws IOException { + init(); + + return _reader.read(cbuf, off, len); + } + + /** + * Read-ahead four bytes and check for BOM marks. Extra bytes are unread back to the stream, only + * BOM bytes are skipped. + */ + protected void init() throws IOException { + if (_reader != null) { + return; } - public int read(char[] cbuf, int off, int len) throws IOException - { - init(); + Charset encoding; + byte[] data = new byte[BOM_SIZE]; + int n; + int unread; - return _reader.read(cbuf, off, len); - } + n = _stream.read(data, 0, data.length); + Bom bom = Bom.find(data); - /** - * Read-ahead four bytes and check for BOM marks. Extra bytes are - * unread back to the stream, only BOM bytes are skipped. - */ - protected void init() throws IOException - { - if (_reader != null) - { - return; - } - - Charset encoding; - byte[] data = new byte[BOM_SIZE]; - int n; - int unread; - - n = _stream.read(data, 0, data.length); - Bom bom = Bom.find(data); - - if (bom == null) - { - encoding = _defaultEncoding; - unread = n; - } - else - { - encoding = bom._charset; - unread = data.length - bom._bytes.length; - } - - if (unread > 0) - { - _stream.unread(data, (n - unread), unread); - } + if (bom == null) { + encoding = _defaultEncoding; + unread = n; + } else { + encoding = bom._charset; + unread = data.length - bom._bytes.length; + } - _reader = new InputStreamReader(_stream, encoding); + if (unread > 0) { + _stream.unread(data, (n - unread), unread); } + + _reader = new InputStreamReader(_stream, encoding); + } } diff --git a/src/main/java/org/ini4j/spi/Warnings.java b/src/main/java/org/ini4j/spi/Warnings.java index 84de3d7..a085d10 100644 --- a/src/main/java/org/ini4j/spi/Warnings.java +++ b/src/main/java/org/ini4j/spi/Warnings.java @@ -15,12 +15,10 @@ */ package org.ini4j.spi; -public final class Warnings -{ - public static final String UNCHECKED = "unchecked"; +public final class Warnings { + public static final String UNCHECKED = "unchecked"; - private Warnings() - { - assert true; - } + private Warnings() { + assert true; + } } diff --git a/src/main/java/org/ini4j/spi/WinEscapeTool.java b/src/main/java/org/ini4j/spi/WinEscapeTool.java index c2e3abf..99e6a4c 100644 --- a/src/main/java/org/ini4j/spi/WinEscapeTool.java +++ b/src/main/java/org/ini4j/spi/WinEscapeTool.java @@ -15,54 +15,45 @@ */ package org.ini4j.spi; -public class WinEscapeTool extends EscapeTool -{ - private static final int ANSI_HEX_DIGITS = 2; - private static final int ANSI_OCTAL_DIGITS = 3; - private static final int OCTAL_RADIX = 8; - private static final WinEscapeTool INSTANCE = new WinEscapeTool(); +public class WinEscapeTool extends EscapeTool { + private static final int ANSI_HEX_DIGITS = 2; + private static final int ANSI_OCTAL_DIGITS = 3; + private static final int OCTAL_RADIX = 8; + private static final WinEscapeTool INSTANCE = new WinEscapeTool(); - public static WinEscapeTool getInstance() - { - return INSTANCE; - } - - @Override void escapeBinary(StringBuilder buff, char c) - { - buff.append("\\x"); - buff.append(HEX[(c >>> HEX_DIGIT_3_OFFSET) & HEX_DIGIT_MASK]); - buff.append(HEX[c & HEX_DIGIT_MASK]); - } + public static WinEscapeTool getInstance() { + return INSTANCE; + } - @Override int unescapeBinary(StringBuilder buff, char escapeType, String line, int index) - { - int ret = index; + @Override + void escapeBinary(StringBuilder buff, char c) { + buff.append("\\x"); + buff.append(HEX[(c >>> HEX_DIGIT_3_OFFSET) & HEX_DIGIT_MASK]); + buff.append(HEX[c & HEX_DIGIT_MASK]); + } - if (escapeType == 'x') - { - try - { - buff.append((char) Integer.parseInt(line.substring(index, index + ANSI_HEX_DIGITS), HEX_RADIX)); - ret = index + ANSI_HEX_DIGITS; - } - catch (Exception x) - { - throw new IllegalArgumentException("Malformed \\xHH encoding.", x); - } - } - else if (escapeType == 'o') - { - try - { - buff.append((char) Integer.parseInt(line.substring(index, index + ANSI_OCTAL_DIGITS), OCTAL_RADIX)); - ret = index + ANSI_OCTAL_DIGITS; - } - catch (Exception x) - { - throw new IllegalArgumentException("Malformed \\oOO encoding.", x); - } - } + @Override + int unescapeBinary(StringBuilder buff, char escapeType, String line, int index) { + int ret = index; - return ret; + if (escapeType == 'x') { + try { + buff.append( + (char) Integer.parseInt(line.substring(index, index + ANSI_HEX_DIGITS), HEX_RADIX)); + ret = index + ANSI_HEX_DIGITS; + } catch (Exception x) { + throw new IllegalArgumentException("Malformed \\xHH encoding.", x); + } + } else if (escapeType == 'o') { + try { + buff.append( + (char) Integer.parseInt(line.substring(index, index + ANSI_OCTAL_DIGITS), OCTAL_RADIX)); + ret = index + ANSI_OCTAL_DIGITS; + } catch (Exception x) { + throw new IllegalArgumentException("Malformed \\oOO encoding.", x); + } } + + return ret; + } } diff --git a/src/test/java/org/ini4j/BasicMultiMapTest.java b/src/test/java/org/ini4j/BasicMultiMapTest.java index 2bc1153..5fefef9 100644 --- a/src/test/java/org/ini4j/BasicMultiMapTest.java +++ b/src/test/java/org/ini4j/BasicMultiMapTest.java @@ -22,171 +22,164 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import org.junit.Before; -import org.junit.Test; - import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; +import org.junit.Before; +import org.junit.Test; -public class BasicMultiMapTest extends Ini4jCase -{ - private static final String KEY1 = "key1"; - private static final String KEY2 = "key2"; - private static final String KEY3 = "key3"; - private static final String VALUE1 = "value1"; - private static final String VALUE2 = "value2"; - private static final String VALUE3 = "value3"; - private static final String[] VALUES = { VALUE1, VALUE2, VALUE3 }; - private MultiMap _map; - - @Before @Override public void setUp() throws Exception - { - super.setUp(); - _map = new BasicMultiMap(); - } - - @Test public void testAdd() - { - _map.add(KEY1, VALUE1); - _map.add(KEY1, VALUE2); - _map.add(KEY1, VALUE3); - assertEquals(3, _map.length(KEY1)); - _map.add(KEY1, VALUE3, 0); - assertEquals(4, _map.length(KEY1)); - assertEquals(VALUE3, _map.get(KEY1, 0)); - assertEquals(VALUE3, _map.get(KEY1, 3)); - _map.clear(); - assertTrue(_map.isEmpty()); - } - - @Test public void testAll() - { - _map.putAll(KEY1, Arrays.asList(VALUES)); - assertEquals(VALUES.length, _map.length(KEY1)); - String[] values = _map.getAll(KEY1).toArray(new String[] {}); - - assertArrayEquals(VALUES, values); - } - - @Test public void testContainsValue() - { - _map.putAll(KEY1, Arrays.asList(VALUES)); - assertTrue(_map.containsValue(VALUE1)); - assertTrue(_map.containsValue(VALUE2)); - assertTrue(_map.containsValue(VALUE3)); - _map.clear(); - _map.put(KEY2, VALUE1); - assertFalse(_map.containsValue(VALUE3)); - } - - @Test public void testEntrySet() - { - _map.putAll(KEY1, Arrays.asList(VALUES)); - _map.put(KEY2, VALUE2); - _map.put(KEY3, VALUE3); - Set> set = _map.entrySet(); - - assertNotNull(set); - assertEquals(3, set.size()); - for (Entry e : set) - { - if (e.getKey().equals(KEY1)) - { - assertEquals(VALUES[2], e.getValue()); - e.setValue(VALUES[1]); - } - else if (e.getKey().equals(KEY2)) - { - assertEquals(VALUE2, e.getValue()); - e.setValue(VALUE3); - } - else if (e.getKey().equals(KEY3)) - { - assertEquals(VALUE3, e.getValue()); - e.setValue(VALUE2); - } - } - - assertEquals(VALUES[1], _map.get(KEY1)); - assertEquals(VALUES.length, _map.length(KEY1)); - assertEquals(VALUE3, _map.get(KEY2)); - assertEquals(VALUE2, _map.get(KEY3)); - } - - @Test public void testGetEmpty() - { - assertNull(_map.get(KEY1)); - assertNull(_map.get(KEY1, 1)); - } - - @Test public void testPut() - { - _map.put(KEY1, VALUE1); - _map.add(KEY1, VALUE2); - assertEquals(VALUE2, _map.get(KEY1, 1)); - _map.put(KEY1, VALUE3, 1); - assertEquals(VALUE3, _map.get(KEY1, 1)); - assertEquals(VALUE3, _map.get(KEY1)); - } - - @Test public void testPutAll() - { - _map.put(KEY1, VALUE1); - _map.put(KEY2, VALUE1); - _map.add(KEY2, VALUE2); - MultiMap other = new BasicMultiMap(); - - other.putAll(_map); - assertEquals(2, other.size()); - assertEquals(2, other.length(KEY2)); - assertEquals(1, other.length(KEY1)); - assertEquals(VALUE1, _map.get(KEY1)); - assertEquals(VALUE1, _map.get(KEY2, 0)); - assertEquals(VALUE2, _map.get(KEY2, 1)); - Map regular = new HashMap(_map); - - _map.clear(); - _map.putAll(regular); - assertEquals(regular.keySet(), _map.keySet()); - } - - @Test public void testRemove() - { - _map.add(KEY1, VALUE1); - _map.add(KEY2, VALUE1); - _map.add(KEY2, VALUE2); - _map.add(KEY3, VALUE1); - _map.add(KEY3, VALUE2); - _map.add(KEY3, VALUE3); - assertEquals(VALUE2, _map.get(KEY3, 1)); - _map.remove(KEY3, 1); - assertEquals(VALUE3, _map.get(KEY3, 1)); - _map.remove(KEY3, 1); - assertEquals(VALUE1, _map.get(KEY3)); - _map.remove(KEY3, 0); - assertEquals(0, _map.length(KEY3)); - assertFalse(_map.containsKey(KEY3)); - _map.remove(KEY2); - assertFalse(_map.containsKey(KEY2)); - _map.remove(KEY1); - assertFalse(_map.containsKey(KEY1)); - assertEquals(0, _map.size()); - assertTrue(_map.isEmpty()); - assertNull(_map.remove(KEY1)); - assertNull(_map.remove(KEY1, 1)); +public class BasicMultiMapTest extends Ini4jCase { + private static final String KEY1 = "key1"; + private static final String KEY2 = "key2"; + private static final String KEY3 = "key3"; + private static final String VALUE1 = "value1"; + private static final String VALUE2 = "value2"; + private static final String VALUE3 = "value3"; + private static final String[] VALUES = {VALUE1, VALUE2, VALUE3}; + private MultiMap _map; + + @Before + @Override + public void setUp() throws Exception { + super.setUp(); + _map = new BasicMultiMap(); + } + + @Test + public void testAdd() { + _map.add(KEY1, VALUE1); + _map.add(KEY1, VALUE2); + _map.add(KEY1, VALUE3); + assertEquals(3, _map.length(KEY1)); + _map.add(KEY1, VALUE3, 0); + assertEquals(4, _map.length(KEY1)); + assertEquals(VALUE3, _map.get(KEY1, 0)); + assertEquals(VALUE3, _map.get(KEY1, 3)); + _map.clear(); + assertTrue(_map.isEmpty()); + } + + @Test + public void testAll() { + _map.putAll(KEY1, Arrays.asList(VALUES)); + assertEquals(VALUES.length, _map.length(KEY1)); + String[] values = _map.getAll(KEY1).toArray(new String[] {}); + + assertArrayEquals(VALUES, values); + } + + @Test + public void testContainsValue() { + _map.putAll(KEY1, Arrays.asList(VALUES)); + assertTrue(_map.containsValue(VALUE1)); + assertTrue(_map.containsValue(VALUE2)); + assertTrue(_map.containsValue(VALUE3)); + _map.clear(); + _map.put(KEY2, VALUE1); + assertFalse(_map.containsValue(VALUE3)); + } + + @Test + public void testEntrySet() { + _map.putAll(KEY1, Arrays.asList(VALUES)); + _map.put(KEY2, VALUE2); + _map.put(KEY3, VALUE3); + Set> set = _map.entrySet(); + + assertNotNull(set); + assertEquals(3, set.size()); + for (Entry e : set) { + if (e.getKey().equals(KEY1)) { + assertEquals(VALUES[2], e.getValue()); + e.setValue(VALUES[1]); + } else if (e.getKey().equals(KEY2)) { + assertEquals(VALUE2, e.getValue()); + e.setValue(VALUE3); + } else if (e.getKey().equals(KEY3)) { + assertEquals(VALUE3, e.getValue()); + e.setValue(VALUE2); + } } - @Test public void testValues() - { - _map.put(KEY1, VALUE1); - _map.put(KEY2, VALUE2); - _map.add(KEY2, VALUE3); - String[] values = _map.values().toArray(new String[] {}); - - Arrays.sort(values); - assertArrayEquals(values, VALUES); - } + assertEquals(VALUES[1], _map.get(KEY1)); + assertEquals(VALUES.length, _map.length(KEY1)); + assertEquals(VALUE3, _map.get(KEY2)); + assertEquals(VALUE2, _map.get(KEY3)); + } + + @Test + public void testGetEmpty() { + assertNull(_map.get(KEY1)); + assertNull(_map.get(KEY1, 1)); + } + + @Test + public void testPut() { + _map.put(KEY1, VALUE1); + _map.add(KEY1, VALUE2); + assertEquals(VALUE2, _map.get(KEY1, 1)); + _map.put(KEY1, VALUE3, 1); + assertEquals(VALUE3, _map.get(KEY1, 1)); + assertEquals(VALUE3, _map.get(KEY1)); + } + + @Test + public void testPutAll() { + _map.put(KEY1, VALUE1); + _map.put(KEY2, VALUE1); + _map.add(KEY2, VALUE2); + MultiMap other = new BasicMultiMap(); + + other.putAll(_map); + assertEquals(2, other.size()); + assertEquals(2, other.length(KEY2)); + assertEquals(1, other.length(KEY1)); + assertEquals(VALUE1, _map.get(KEY1)); + assertEquals(VALUE1, _map.get(KEY2, 0)); + assertEquals(VALUE2, _map.get(KEY2, 1)); + Map regular = new HashMap(_map); + + _map.clear(); + _map.putAll(regular); + assertEquals(regular.keySet(), _map.keySet()); + } + + @Test + public void testRemove() { + _map.add(KEY1, VALUE1); + _map.add(KEY2, VALUE1); + _map.add(KEY2, VALUE2); + _map.add(KEY3, VALUE1); + _map.add(KEY3, VALUE2); + _map.add(KEY3, VALUE3); + assertEquals(VALUE2, _map.get(KEY3, 1)); + _map.remove(KEY3, 1); + assertEquals(VALUE3, _map.get(KEY3, 1)); + _map.remove(KEY3, 1); + assertEquals(VALUE1, _map.get(KEY3)); + _map.remove(KEY3, 0); + assertEquals(0, _map.length(KEY3)); + assertFalse(_map.containsKey(KEY3)); + _map.remove(KEY2); + assertFalse(_map.containsKey(KEY2)); + _map.remove(KEY1); + assertFalse(_map.containsKey(KEY1)); + assertEquals(0, _map.size()); + assertTrue(_map.isEmpty()); + assertNull(_map.remove(KEY1)); + assertNull(_map.remove(KEY1, 1)); + } + + @Test + public void testValues() { + _map.put(KEY1, VALUE1); + _map.put(KEY2, VALUE2); + _map.add(KEY2, VALUE3); + String[] values = _map.values().toArray(new String[] {}); + + Arrays.sort(values); + assertArrayEquals(values, VALUES); + } } diff --git a/src/test/java/org/ini4j/BasicOptionMapGate.java b/src/test/java/org/ini4j/BasicOptionMapGate.java index b5b0c3e..e66ddcf 100644 --- a/src/test/java/org/ini4j/BasicOptionMapGate.java +++ b/src/test/java/org/ini4j/BasicOptionMapGate.java @@ -17,17 +17,16 @@ import org.ini4j.spi.BeanAccess; -public class BasicOptionMapGate extends BasicOptionMap -{ - private static final long serialVersionUID = -479440334238558045L; +public class BasicOptionMapGate extends BasicOptionMap { + private static final long serialVersionUID = -479440334238558045L; - @Override public BeanAccess newBeanAccess() - { - return super.newBeanAccess(); - } + @Override + public BeanAccess newBeanAccess() { + return super.newBeanAccess(); + } - @Override public BeanAccess newBeanAccess(String prefix) - { - return super.newBeanAccess(prefix); - } + @Override + public BeanAccess newBeanAccess(String prefix) { + return super.newBeanAccess(prefix); + } } diff --git a/src/test/java/org/ini4j/BasicOptionMapTest.java b/src/test/java/org/ini4j/BasicOptionMapTest.java index 1376616..8b56aa7 100644 --- a/src/test/java/org/ini4j/BasicOptionMapTest.java +++ b/src/test/java/org/ini4j/BasicOptionMapTest.java @@ -15,367 +15,355 @@ */ package org.ini4j; -import org.ini4j.sample.Dwarf; -import org.ini4j.sample.DwarfBean; - -import org.ini4j.test.DwarfsData; -import org.ini4j.test.DwarfsData.DwarfData; -import org.ini4j.test.Helper; - import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import org.junit.Test; - import java.net.URI; +import org.ini4j.sample.Dwarf; +import org.ini4j.sample.DwarfBean; +import org.ini4j.test.DwarfsData; +import org.ini4j.test.DwarfsData.DwarfData; +import org.ini4j.test.Helper; +import org.junit.Test; -public class BasicOptionMapTest extends Ini4jCase -{ - private static final String FOO = "foo"; - private static BasicOptionMap _map; - - static - { - _map = new BasicOptionMap(); - _map.putAll(Helper.newDwarfsOpt()); - } - - @Test public void test_bug_2817403() throws Exception - { - OptionMap map = new BasicOptionMap(); - - map.add("player.name", "Joe"); - map.add("player.greeting", "Hi ${player.name}!"); - map.add("player.domain", "foo.bar"); - map.add("player.email", "${player.name}@${player.domain}"); - - // - assertEquals("Joe", map.fetch("player.name")); - assertEquals("Hi Joe!", map.fetch("player.greeting")); - assertEquals("foo.bar", map.fetch("player.domain")); - assertEquals("Joe@foo.bar", map.fetch("player.email")); - } - - @Test public void testAddPutNullAndString() - { - OptionMap map = new BasicOptionMap(); - Object o; - - // null - o = null; - map.add(Dwarf.PROP_AGE, o); - assertNull(map.get(Dwarf.PROP_AGE)); - map.put(Dwarf.PROP_AGE, new Integer(DwarfsData.doc.age)); - assertNotNull(map.get(Dwarf.PROP_AGE)); - map.add(Dwarf.PROP_AGE, o, 0); - assertNull(map.get(Dwarf.PROP_AGE, 0)); - map.put(Dwarf.PROP_AGE, new Integer(DwarfsData.doc.age), 0); - assertNotNull(map.get(Dwarf.PROP_AGE, 0)); - map.put(Dwarf.PROP_AGE, o, 0); - assertNull(map.get(Dwarf.PROP_AGE, 0)); - map.remove(Dwarf.PROP_AGE); - map.put(Dwarf.PROP_AGE, o); - assertNull(map.get(Dwarf.PROP_AGE)); - - // str - map.remove(Dwarf.PROP_AGE); - o = String.valueOf(DwarfsData.doc.age); - map.add(Dwarf.PROP_AGE, o); - assertEquals(o, map.get(Dwarf.PROP_AGE)); - map.remove(Dwarf.PROP_AGE); - map.put(Dwarf.PROP_AGE, o); - assertEquals(o, map.get(Dwarf.PROP_AGE)); - o = String.valueOf(DwarfsData.happy.age); - map.add(Dwarf.PROP_AGE, o, 0); - assertEquals(new Integer(DwarfsData.happy.age), (Integer) map.get(Dwarf.PROP_AGE, 0, int.class)); - o = String.valueOf(DwarfsData.doc.age); - map.put(Dwarf.PROP_AGE, o, 0); - assertEquals(DwarfsData.doc.age, (int) map.get(Dwarf.PROP_AGE, 0, int.class)); - } - - @Test public void testFetch() - { - OptionMap map = new BasicOptionMap(); - - Helper.addDwarf(map, DwarfsData.dopey, false); - Helper.addDwarf(map, DwarfsData.bashful); - Helper.addDwarf(map, DwarfsData.doc); - - // dopey - assertEquals(DwarfsData.dopey.weight, map.fetch(Dwarf.PROP_WEIGHT, double.class), Helper.DELTA); - map.add(Dwarf.PROP_HEIGHT, map.get(Dwarf.PROP_HEIGHT)); - assertEquals(DwarfsData.dopey.height, map.fetch(Dwarf.PROP_HEIGHT, 1, double.class), Helper.DELTA); - - // sneezy - map.clear(); - Helper.addDwarf(map, DwarfsData.happy); - Helper.addDwarf(map, DwarfsData.sneezy, false); - assertEquals(DwarfsData.sneezy.homePage, map.fetch(Dwarf.PROP_HOME_PAGE, URI.class)); - - // null - map = new BasicOptionMap(); - map.add(Dwarf.PROP_AGE, null); - assertNull(map.fetch(Dwarf.PROP_AGE, 0)); - } - - @Test public void testFetchAllException() - { - OptionMap map = new BasicOptionMap(); - - try - { - map.fetchAll(Dwarf.PROP_FORTUNE_NUMBER, String.class); - missing(IllegalArgumentException.class); - } - catch (IllegalArgumentException x) - { - // - } - } - - @Test public void testFromToAs() throws Exception - { - DwarfBean bean = new DwarfBean(); - - _map.to(bean); - Helper.assertEquals(DwarfsData.dopey, bean); - OptionMap map = new BasicOptionMap(); - - map.from(bean); - bean = new DwarfBean(); - map.to(bean); - Helper.assertEquals(DwarfsData.dopey, bean); - Dwarf proxy = map.as(Dwarf.class); - - Helper.assertEquals(DwarfsData.dopey, proxy); - map.clear(); - _map.to(proxy); - Helper.assertEquals(DwarfsData.dopey, proxy); - } - - @Test public void testFromToAsPrefixed() throws Exception - { - fromToAs(DwarfsData.bashful); - fromToAs(DwarfsData.doc); - fromToAs(DwarfsData.dopey); - fromToAs(DwarfsData.grumpy); - fromToAs(DwarfsData.happy); - fromToAs(DwarfsData.sleepy); - fromToAs(DwarfsData.sneezy); - } - - @Test public void testGet() - { - OptionMap map = new BasicOptionMap(); - - // bashful - Helper.addDwarf(map, DwarfsData.bashful, false); - assertEquals(DwarfsData.bashful.weight, map.get(Dwarf.PROP_WEIGHT, double.class), Helper.DELTA); - map.add(Dwarf.PROP_HEIGHT, map.get(Dwarf.PROP_HEIGHT)); - assertEquals(DwarfsData.bashful.height, map.get(Dwarf.PROP_HEIGHT, 1, double.class), Helper.DELTA); - assertEquals(DwarfsData.bashful.homePage, map.fetch(Dwarf.PROP_HOME_PAGE, URI.class)); - } - - @Test public void testGetAllException() - { - OptionMap map = new BasicOptionMap(); - - try - { - map.getAll(Dwarf.PROP_FORTUNE_NUMBER, String.class); - missing(IllegalArgumentException.class); - } - catch (IllegalArgumentException x) - { - // - } - } - - @Test public void testGetAndFetchDefaultValue() - { - OptionMap map = new BasicOptionMap(); - - Helper.addDwarf(map, DwarfsData.dopey, false); - Helper.addDwarf(map, DwarfsData.bashful); - Helper.addDwarf(map, DwarfsData.doc); - - // fetch with type - assertEquals(DwarfsData.dopey.weight, map.fetch(Dwarf.PROP_WEIGHT, double.class), Helper.DELTA); - assertEquals(DwarfsData.dopey.weight, map.fetch(Dwarf.PROP_WEIGHT, double.class, 1.2), Helper.DELTA); - map.remove(Dwarf.PROP_WEIGHT); - assertEquals(1.2, map.fetch(Dwarf.PROP_WEIGHT, double.class, 1.2), Helper.DELTA); - - // get with type - assertEquals(DwarfsData.dopey.age, (int) map.get(Dwarf.PROP_AGE, int.class)); - assertEquals(DwarfsData.dopey.age, (int) map.get(Dwarf.PROP_AGE, int.class, 11)); - map.remove(Dwarf.PROP_AGE); - assertEquals(11, (int) map.get(Dwarf.PROP_AGE, int.class, 11)); - - // get and fetch with strings - assertEquals(DwarfsData.dopey.homePage.toString(), map.fetch(Dwarf.PROP_HOME_PAGE, FOO)); - assertEquals(DwarfsData.dopey.homePage.toString(), map.get(Dwarf.PROP_HOME_PAGE, FOO)); - map.remove(Dwarf.PROP_HOME_PAGE); - assertEquals(FOO, map.fetch(Dwarf.PROP_HOME_PAGE, FOO)); - assertEquals(FOO, map.get(Dwarf.PROP_HOME_PAGE, FOO)); - } - - @Test public void testPropertyFirstUpper() - { - DwarfBean bean; - OptionMap map = new BasicOptionMap(true); - - map.from(DwarfsData.bashful); - assertTrue(map.containsKey("Age")); - assertTrue(map.containsKey("Height")); - assertTrue(map.containsKey("Weight")); - assertTrue(map.containsKey("HomePage")); - assertTrue(map.containsKey("HomeDir")); - bean = new DwarfBean(); - map.to(bean); - Helper.assertEquals(DwarfsData.bashful, bean); - Helper.assertEquals(DwarfsData.bashful, map.as(Dwarf.class)); +public class BasicOptionMapTest extends Ini4jCase { + private static final String FOO = "foo"; + private static BasicOptionMap _map; + + static { + _map = new BasicOptionMap(); + _map.putAll(Helper.newDwarfsOpt()); + } + + @Test + public void test_bug_2817403() throws Exception { + OptionMap map = new BasicOptionMap(); + + map.add("player.name", "Joe"); + map.add("player.greeting", "Hi ${player.name}!"); + map.add("player.domain", "foo.bar"); + map.add("player.email", "${player.name}@${player.domain}"); + + // + assertEquals("Joe", map.fetch("player.name")); + assertEquals("Hi Joe!", map.fetch("player.greeting")); + assertEquals("foo.bar", map.fetch("player.domain")); + assertEquals("Joe@foo.bar", map.fetch("player.email")); + } + + @Test + public void testAddPutNullAndString() { + OptionMap map = new BasicOptionMap(); + Object o; + + // null + o = null; + map.add(Dwarf.PROP_AGE, o); + assertNull(map.get(Dwarf.PROP_AGE)); + map.put(Dwarf.PROP_AGE, new Integer(DwarfsData.doc.age)); + assertNotNull(map.get(Dwarf.PROP_AGE)); + map.add(Dwarf.PROP_AGE, o, 0); + assertNull(map.get(Dwarf.PROP_AGE, 0)); + map.put(Dwarf.PROP_AGE, new Integer(DwarfsData.doc.age), 0); + assertNotNull(map.get(Dwarf.PROP_AGE, 0)); + map.put(Dwarf.PROP_AGE, o, 0); + assertNull(map.get(Dwarf.PROP_AGE, 0)); + map.remove(Dwarf.PROP_AGE); + map.put(Dwarf.PROP_AGE, o); + assertNull(map.get(Dwarf.PROP_AGE)); + + // str + map.remove(Dwarf.PROP_AGE); + o = String.valueOf(DwarfsData.doc.age); + map.add(Dwarf.PROP_AGE, o); + assertEquals(o, map.get(Dwarf.PROP_AGE)); + map.remove(Dwarf.PROP_AGE); + map.put(Dwarf.PROP_AGE, o); + assertEquals(o, map.get(Dwarf.PROP_AGE)); + o = String.valueOf(DwarfsData.happy.age); + map.add(Dwarf.PROP_AGE, o, 0); + assertEquals( + new Integer(DwarfsData.happy.age), (Integer) map.get(Dwarf.PROP_AGE, 0, int.class)); + o = String.valueOf(DwarfsData.doc.age); + map.put(Dwarf.PROP_AGE, o, 0); + assertEquals(DwarfsData.doc.age, (int) map.get(Dwarf.PROP_AGE, 0, int.class)); + } + + @Test + public void testFetch() { + OptionMap map = new BasicOptionMap(); + + Helper.addDwarf(map, DwarfsData.dopey, false); + Helper.addDwarf(map, DwarfsData.bashful); + Helper.addDwarf(map, DwarfsData.doc); + + // dopey + assertEquals(DwarfsData.dopey.weight, map.fetch(Dwarf.PROP_WEIGHT, double.class), Helper.DELTA); + map.add(Dwarf.PROP_HEIGHT, map.get(Dwarf.PROP_HEIGHT)); + assertEquals( + DwarfsData.dopey.height, map.fetch(Dwarf.PROP_HEIGHT, 1, double.class), Helper.DELTA); + + // sneezy + map.clear(); + Helper.addDwarf(map, DwarfsData.happy); + Helper.addDwarf(map, DwarfsData.sneezy, false); + assertEquals(DwarfsData.sneezy.homePage, map.fetch(Dwarf.PROP_HOME_PAGE, URI.class)); + + // null + map = new BasicOptionMap(); + map.add(Dwarf.PROP_AGE, null); + assertNull(map.fetch(Dwarf.PROP_AGE, 0)); + } + + @Test + public void testFetchAllException() { + OptionMap map = new BasicOptionMap(); + + try { + map.fetchAll(Dwarf.PROP_FORTUNE_NUMBER, String.class); + missing(IllegalArgumentException.class); + } catch (IllegalArgumentException x) { + // } - - @Test public void testPut() - { - OptionMap map = new BasicOptionMap(); - - map.add(Dwarf.PROP_AGE, new Integer(DwarfsData.sneezy.age)); - map.put(Dwarf.PROP_HEIGHT, new Double(DwarfsData.sneezy.height)); - map.add(Dwarf.PROP_HOME_DIR, DwarfsData.sneezy.homeDir); - map.add(Dwarf.PROP_WEIGHT, new Double(DwarfsData.sneezy.weight), 0); - map.put(Dwarf.PROP_HOME_PAGE, null); - map.put(Dwarf.PROP_HOME_PAGE, DwarfsData.sneezy.homePage); - map.add(Dwarf.PROP_FORTUNE_NUMBER, new Integer(DwarfsData.sneezy.fortuneNumber[1])); - map.add(Dwarf.PROP_FORTUNE_NUMBER, new Integer(DwarfsData.sneezy.fortuneNumber[2])); - map.add(Dwarf.PROP_FORTUNE_NUMBER, new Integer(0)); - map.put(Dwarf.PROP_FORTUNE_NUMBER, new Integer(DwarfsData.sneezy.fortuneNumber[3]), 2); - map.add(Dwarf.PROP_FORTUNE_NUMBER, new Integer(DwarfsData.sneezy.fortuneNumber[0]), 0); - Helper.assertEquals(DwarfsData.sneezy, map.as(Dwarf.class)); + } + + @Test + public void testFromToAs() throws Exception { + DwarfBean bean = new DwarfBean(); + + _map.to(bean); + Helper.assertEquals(DwarfsData.dopey, bean); + OptionMap map = new BasicOptionMap(); + + map.from(bean); + bean = new DwarfBean(); + map.to(bean); + Helper.assertEquals(DwarfsData.dopey, bean); + Dwarf proxy = map.as(Dwarf.class); + + Helper.assertEquals(DwarfsData.dopey, proxy); + map.clear(); + _map.to(proxy); + Helper.assertEquals(DwarfsData.dopey, proxy); + } + + @Test + public void testFromToAsPrefixed() throws Exception { + fromToAs(DwarfsData.bashful); + fromToAs(DwarfsData.doc); + fromToAs(DwarfsData.dopey); + fromToAs(DwarfsData.grumpy); + fromToAs(DwarfsData.happy); + fromToAs(DwarfsData.sleepy); + fromToAs(DwarfsData.sneezy); + } + + @Test + public void testGet() { + OptionMap map = new BasicOptionMap(); + + // bashful + Helper.addDwarf(map, DwarfsData.bashful, false); + assertEquals(DwarfsData.bashful.weight, map.get(Dwarf.PROP_WEIGHT, double.class), Helper.DELTA); + map.add(Dwarf.PROP_HEIGHT, map.get(Dwarf.PROP_HEIGHT)); + assertEquals( + DwarfsData.bashful.height, map.get(Dwarf.PROP_HEIGHT, 1, double.class), Helper.DELTA); + assertEquals(DwarfsData.bashful.homePage, map.fetch(Dwarf.PROP_HOME_PAGE, URI.class)); + } + + @Test + public void testGetAllException() { + OptionMap map = new BasicOptionMap(); + + try { + map.getAll(Dwarf.PROP_FORTUNE_NUMBER, String.class); + missing(IllegalArgumentException.class); + } catch (IllegalArgumentException x) { + // } - - @Test public void testPutAllException() - { - OptionMap map = new BasicOptionMap(); - - try - { - map.putAll(Dwarf.PROP_FORTUNE_NUMBER, new Integer(0)); - missing(IllegalArgumentException.class); - } - catch (IllegalArgumentException x) - { - // - } + } + + @Test + public void testGetAndFetchDefaultValue() { + OptionMap map = new BasicOptionMap(); + + Helper.addDwarf(map, DwarfsData.dopey, false); + Helper.addDwarf(map, DwarfsData.bashful); + Helper.addDwarf(map, DwarfsData.doc); + + // fetch with type + assertEquals(DwarfsData.dopey.weight, map.fetch(Dwarf.PROP_WEIGHT, double.class), Helper.DELTA); + assertEquals( + DwarfsData.dopey.weight, map.fetch(Dwarf.PROP_WEIGHT, double.class, 1.2), Helper.DELTA); + map.remove(Dwarf.PROP_WEIGHT); + assertEquals(1.2, map.fetch(Dwarf.PROP_WEIGHT, double.class, 1.2), Helper.DELTA); + + // get with type + assertEquals(DwarfsData.dopey.age, (int) map.get(Dwarf.PROP_AGE, int.class)); + assertEquals(DwarfsData.dopey.age, (int) map.get(Dwarf.PROP_AGE, int.class, 11)); + map.remove(Dwarf.PROP_AGE); + assertEquals(11, (int) map.get(Dwarf.PROP_AGE, int.class, 11)); + + // get and fetch with strings + assertEquals(DwarfsData.dopey.homePage.toString(), map.fetch(Dwarf.PROP_HOME_PAGE, FOO)); + assertEquals(DwarfsData.dopey.homePage.toString(), map.get(Dwarf.PROP_HOME_PAGE, FOO)); + map.remove(Dwarf.PROP_HOME_PAGE); + assertEquals(FOO, map.fetch(Dwarf.PROP_HOME_PAGE, FOO)); + assertEquals(FOO, map.get(Dwarf.PROP_HOME_PAGE, FOO)); + } + + @Test + public void testPropertyFirstUpper() { + DwarfBean bean; + OptionMap map = new BasicOptionMap(true); + + map.from(DwarfsData.bashful); + assertTrue(map.containsKey("Age")); + assertTrue(map.containsKey("Height")); + assertTrue(map.containsKey("Weight")); + assertTrue(map.containsKey("HomePage")); + assertTrue(map.containsKey("HomeDir")); + bean = new DwarfBean(); + map.to(bean); + Helper.assertEquals(DwarfsData.bashful, bean); + Helper.assertEquals(DwarfsData.bashful, map.as(Dwarf.class)); + } + + @Test + public void testPut() { + OptionMap map = new BasicOptionMap(); + + map.add(Dwarf.PROP_AGE, new Integer(DwarfsData.sneezy.age)); + map.put(Dwarf.PROP_HEIGHT, new Double(DwarfsData.sneezy.height)); + map.add(Dwarf.PROP_HOME_DIR, DwarfsData.sneezy.homeDir); + map.add(Dwarf.PROP_WEIGHT, new Double(DwarfsData.sneezy.weight), 0); + map.put(Dwarf.PROP_HOME_PAGE, null); + map.put(Dwarf.PROP_HOME_PAGE, DwarfsData.sneezy.homePage); + map.add(Dwarf.PROP_FORTUNE_NUMBER, new Integer(DwarfsData.sneezy.fortuneNumber[1])); + map.add(Dwarf.PROP_FORTUNE_NUMBER, new Integer(DwarfsData.sneezy.fortuneNumber[2])); + map.add(Dwarf.PROP_FORTUNE_NUMBER, new Integer(0)); + map.put(Dwarf.PROP_FORTUNE_NUMBER, new Integer(DwarfsData.sneezy.fortuneNumber[3]), 2); + map.add(Dwarf.PROP_FORTUNE_NUMBER, new Integer(DwarfsData.sneezy.fortuneNumber[0]), 0); + Helper.assertEquals(DwarfsData.sneezy, map.as(Dwarf.class)); + } + + @Test + public void testPutAllException() { + OptionMap map = new BasicOptionMap(); + + try { + map.putAll(Dwarf.PROP_FORTUNE_NUMBER, new Integer(0)); + missing(IllegalArgumentException.class); + } catch (IllegalArgumentException x) { + // } - - @Test public void testPutGetFetchAll() - { - OptionMap map = new BasicOptionMap(); - - map.putAll(Dwarf.PROP_FORTUNE_NUMBER, DwarfsData.sneezy.fortuneNumber); - assertEquals(DwarfsData.sneezy.fortuneNumber.length, map.length(Dwarf.PROP_FORTUNE_NUMBER)); - assertArrayEquals(DwarfsData.sneezy.fortuneNumber, map.getAll(Dwarf.PROP_FORTUNE_NUMBER, int[].class)); - assertArrayEquals(DwarfsData.sneezy.fortuneNumber, map.fetchAll(Dwarf.PROP_FORTUNE_NUMBER, int[].class)); - map.putAll(Dwarf.PROP_FORTUNE_NUMBER, (int[]) null); - assertEquals(0, map.length(Dwarf.PROP_FORTUNE_NUMBER)); - assertEquals(0, map.getAll(Dwarf.PROP_FORTUNE_NUMBER, int[].class).length); - assertEquals(0, map.fetchAll(Dwarf.PROP_FORTUNE_NUMBER, int[].class).length); + } + + @Test + public void testPutGetFetchAll() { + OptionMap map = new BasicOptionMap(); + + map.putAll(Dwarf.PROP_FORTUNE_NUMBER, DwarfsData.sneezy.fortuneNumber); + assertEquals(DwarfsData.sneezy.fortuneNumber.length, map.length(Dwarf.PROP_FORTUNE_NUMBER)); + assertArrayEquals( + DwarfsData.sneezy.fortuneNumber, map.getAll(Dwarf.PROP_FORTUNE_NUMBER, int[].class)); + assertArrayEquals( + DwarfsData.sneezy.fortuneNumber, map.fetchAll(Dwarf.PROP_FORTUNE_NUMBER, int[].class)); + map.putAll(Dwarf.PROP_FORTUNE_NUMBER, (int[]) null); + assertEquals(0, map.length(Dwarf.PROP_FORTUNE_NUMBER)); + assertEquals(0, map.getAll(Dwarf.PROP_FORTUNE_NUMBER, int[].class).length); + assertEquals(0, map.fetchAll(Dwarf.PROP_FORTUNE_NUMBER, int[].class).length); + } + + @Test + public void testResolve() throws Exception { + StringBuilder buffer; + String input; + + // simple value + input = "${height}"; + buffer = new StringBuilder(input); + + _map.resolve(buffer); + assertEquals("" + DwarfsData.dopey.getHeight(), buffer.toString()); + + // system property + input = "${@prop/user.home}"; + buffer = new StringBuilder(input); + + _map.resolve(buffer); + assertEquals(System.getProperty("user.home"), buffer.toString()); + + // system environment + input = "${@env/PATH}"; + buffer = new StringBuilder(input); + try { + _map.resolve(buffer); + assertEquals(System.getenv("PATH"), buffer.toString()); + } catch (Error e) { + // retroweaver + JDK 1.4 throws Error on getenv } - @Test public void testResolve() throws Exception - { - StringBuilder buffer; - String input; - - // simple value - input = "${height}"; - buffer = new StringBuilder(input); - - _map.resolve(buffer); - assertEquals("" + DwarfsData.dopey.getHeight(), buffer.toString()); + // unknown variable + input = "${no such name}"; + buffer = new StringBuilder(input); - // system property - input = "${@prop/user.home}"; - buffer = new StringBuilder(input); + _map.resolve(buffer); + assertEquals(input, buffer.toString()); - _map.resolve(buffer); - assertEquals(System.getProperty("user.home"), buffer.toString()); + // small input + input = "${"; + buffer = new StringBuilder(input); - // system environment - input = "${@env/PATH}"; - buffer = new StringBuilder(input); - try - { - _map.resolve(buffer); - assertEquals(System.getenv("PATH"), buffer.toString()); - } - catch (Error e) - { - // retroweaver + JDK 1.4 throws Error on getenv - } + _map.resolve(buffer); + assertEquals(input, buffer.toString()); - // unknown variable - input = "${no such name}"; - buffer = new StringBuilder(input); + // incorrect references + input = "${weight"; + buffer = new StringBuilder(input); - _map.resolve(buffer); - assertEquals(input, buffer.toString()); + _map.resolve(buffer); + assertEquals(input, buffer.toString()); - // small input - input = "${"; - buffer = new StringBuilder(input); + // empty references + input = "jim${}"; + buffer = new StringBuilder(input); - _map.resolve(buffer); - assertEquals(input, buffer.toString()); + _map.resolve(buffer); + assertEquals(input, buffer.toString()); - // incorrect references - input = "${weight"; - buffer = new StringBuilder(input); + // escaped references + input = "${weight}"; + buffer = new StringBuilder(input); - _map.resolve(buffer); - assertEquals(input, buffer.toString()); + _map.resolve(buffer); + assertEquals("" + DwarfsData.dopey.getWeight(), buffer.toString()); + input = "\\" + input; + buffer = new StringBuilder(input); - // empty references - input = "jim${}"; - buffer = new StringBuilder(input); + assertEquals(input, buffer.toString()); + } - _map.resolve(buffer); - assertEquals(input, buffer.toString()); + private void fromToAs(DwarfData dwarf) { + String prefix = dwarf.name + '.'; + DwarfBean bean = new DwarfBean(); - // escaped references - input = "${weight}"; - buffer = new StringBuilder(input); + _map.to(bean, prefix); + Helper.assertEquals(dwarf, bean); + OptionMap map = new BasicOptionMap(); - _map.resolve(buffer); - assertEquals("" + DwarfsData.dopey.getWeight(), buffer.toString()); - input = "\\" + input; - buffer = new StringBuilder(input); + map.from(bean, prefix); + bean = new DwarfBean(); + map.to(bean, prefix); + Helper.assertEquals(dwarf, bean); + Dwarf proxy = map.as(Dwarf.class, prefix); - assertEquals(input, buffer.toString()); - } - - private void fromToAs(DwarfData dwarf) - { - String prefix = dwarf.name + '.'; - DwarfBean bean = new DwarfBean(); - - _map.to(bean, prefix); - Helper.assertEquals(dwarf, bean); - OptionMap map = new BasicOptionMap(); - - map.from(bean, prefix); - bean = new DwarfBean(); - map.to(bean, prefix); - Helper.assertEquals(dwarf, bean); - Dwarf proxy = map.as(Dwarf.class, prefix); - - Helper.assertEquals(dwarf, proxy); - map.clear(); - _map.to(proxy, prefix); - Helper.assertEquals(dwarf, proxy); - } + Helper.assertEquals(dwarf, proxy); + map.clear(); + _map.to(proxy, prefix); + Helper.assertEquals(dwarf, proxy); + } } diff --git a/src/test/java/org/ini4j/BasicProfileSectionTest.java b/src/test/java/org/ini4j/BasicProfileSectionTest.java index c0fca44..c789355 100644 --- a/src/test/java/org/ini4j/BasicProfileSectionTest.java +++ b/src/test/java/org/ini4j/BasicProfileSectionTest.java @@ -15,80 +15,77 @@ */ package org.ini4j; -import org.ini4j.sample.Dwarf; -import org.ini4j.sample.Dwarfs; - -import org.ini4j.test.DwarfsData; -import org.ini4j.test.Helper; -import org.ini4j.test.TaleData; - import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; +import org.ini4j.sample.Dwarf; +import org.ini4j.sample.Dwarfs; +import org.ini4j.test.DwarfsData; +import org.ini4j.test.Helper; +import org.ini4j.test.TaleData; import org.junit.Test; -public class BasicProfileSectionTest extends Ini4jCase -{ - @Test public void testAddChild() throws Exception - { - Profile prof = Helper.newTaleIni(); - Profile.Section dwarfs = prof.get(TaleData.PROP_DWARFS); - Profile.Section doc = dwarfs.getChild(Dwarfs.PROP_DOC); - Profile.Section dopey2 = doc.addChild(Dwarfs.PROP_DOPEY); +public class BasicProfileSectionTest extends Ini4jCase { + @Test + public void testAddChild() throws Exception { + Profile prof = Helper.newTaleIni(); + Profile.Section dwarfs = prof.get(TaleData.PROP_DWARFS); + Profile.Section doc = dwarfs.getChild(Dwarfs.PROP_DOC); + Profile.Section dopey2 = doc.addChild(Dwarfs.PROP_DOPEY); - assertSame(doc, dopey2.getParent()); - assertSame(dopey2, dwarfs.lookup(Dwarfs.PROP_DOC, Dwarfs.PROP_DOPEY)); - assertSame(dopey2, dwarfs.lookup(Dwarfs.PROP_DOC + '/' + Dwarfs.PROP_DOPEY)); - assertEquals(1, doc.childrenNames().length); - doc.removeChild(Dwarfs.PROP_DOPEY); - assertEquals(0, doc.childrenNames().length); - assertNull(dwarfs.lookup(Dwarfs.PROP_DOC, Dwarfs.PROP_DOPEY)); - assertNull(dwarfs.lookup(Dwarfs.PROP_DOC + '/' + Dwarfs.PROP_DOPEY)); - } + assertSame(doc, dopey2.getParent()); + assertSame(dopey2, dwarfs.lookup(Dwarfs.PROP_DOC, Dwarfs.PROP_DOPEY)); + assertSame(dopey2, dwarfs.lookup(Dwarfs.PROP_DOC + '/' + Dwarfs.PROP_DOPEY)); + assertEquals(1, doc.childrenNames().length); + doc.removeChild(Dwarfs.PROP_DOPEY); + assertEquals(0, doc.childrenNames().length); + assertNull(dwarfs.lookup(Dwarfs.PROP_DOC, Dwarfs.PROP_DOPEY)); + assertNull(dwarfs.lookup(Dwarfs.PROP_DOC + '/' + Dwarfs.PROP_DOPEY)); + } - @Test public void testGetChild() throws Exception - { - Profile prof = Helper.newTaleIni(); - Profile.Section dwarfs = prof.get(TaleData.PROP_DWARFS); + @Test + public void testGetChild() throws Exception { + Profile prof = Helper.newTaleIni(); + Profile.Section dwarfs = prof.get(TaleData.PROP_DWARFS); - assertArrayEquals(DwarfsData.dwarfNames, dwarfs.childrenNames()); - assertSame(prof.get(TaleData.bashful.name), dwarfs.getChild(Dwarfs.PROP_BASHFUL)); - assertSame(prof.get(TaleData.doc.name), dwarfs.getChild(Dwarfs.PROP_DOC)); - assertSame(prof.get(TaleData.dopey.name), dwarfs.getChild(Dwarfs.PROP_DOPEY)); - assertSame(prof.get(TaleData.grumpy.name), dwarfs.getChild(Dwarfs.PROP_GRUMPY)); - assertSame(prof.get(TaleData.happy.name), dwarfs.getChild(Dwarfs.PROP_HAPPY)); - assertSame(prof.get(TaleData.sleepy.name), dwarfs.getChild(Dwarfs.PROP_SLEEPY)); - assertSame(prof.get(TaleData.sneezy.name), dwarfs.getChild(Dwarfs.PROP_SNEEZY)); - } + assertArrayEquals(DwarfsData.dwarfNames, dwarfs.childrenNames()); + assertSame(prof.get(TaleData.bashful.name), dwarfs.getChild(Dwarfs.PROP_BASHFUL)); + assertSame(prof.get(TaleData.doc.name), dwarfs.getChild(Dwarfs.PROP_DOC)); + assertSame(prof.get(TaleData.dopey.name), dwarfs.getChild(Dwarfs.PROP_DOPEY)); + assertSame(prof.get(TaleData.grumpy.name), dwarfs.getChild(Dwarfs.PROP_GRUMPY)); + assertSame(prof.get(TaleData.happy.name), dwarfs.getChild(Dwarfs.PROP_HAPPY)); + assertSame(prof.get(TaleData.sleepy.name), dwarfs.getChild(Dwarfs.PROP_SLEEPY)); + assertSame(prof.get(TaleData.sneezy.name), dwarfs.getChild(Dwarfs.PROP_SNEEZY)); + } - @Test public void testGetParent() throws Exception - { - Profile prof = Helper.newTaleIni(); - Profile.Section dwarfs = prof.get(TaleData.PROP_DWARFS); + @Test + public void testGetParent() throws Exception { + Profile prof = Helper.newTaleIni(); + Profile.Section dwarfs = prof.get(TaleData.PROP_DWARFS); - assertNull(dwarfs.getParent()); - assertSame(dwarfs, prof.get(TaleData.bashful.name).getParent()); - assertSame(dwarfs, prof.get(TaleData.doc.name).getParent()); - assertSame(dwarfs, prof.get(TaleData.dopey.name).getParent()); - assertSame(dwarfs, prof.get(TaleData.grumpy.name).getParent()); - assertSame(dwarfs, prof.get(TaleData.happy.name).getParent()); - assertSame(dwarfs, prof.get(TaleData.sleepy.name).getParent()); - assertSame(dwarfs, prof.get(TaleData.sneezy.name).getParent()); - } + assertNull(dwarfs.getParent()); + assertSame(dwarfs, prof.get(TaleData.bashful.name).getParent()); + assertSame(dwarfs, prof.get(TaleData.doc.name).getParent()); + assertSame(dwarfs, prof.get(TaleData.dopey.name).getParent()); + assertSame(dwarfs, prof.get(TaleData.grumpy.name).getParent()); + assertSame(dwarfs, prof.get(TaleData.happy.name).getParent()); + assertSame(dwarfs, prof.get(TaleData.sleepy.name).getParent()); + assertSame(dwarfs, prof.get(TaleData.sneezy.name).getParent()); + } - @Test public void testLoad() throws Exception - { - Profile prof = Helper.loadTaleIni(); - Profile.Section dwarfs = prof.get(TaleData.PROP_DWARFS); + @Test + public void testLoad() throws Exception { + Profile prof = Helper.loadTaleIni(); + Profile.Section dwarfs = prof.get(TaleData.PROP_DWARFS); - Helper.assertEquals(DwarfsData.bashful, dwarfs.getChild(Dwarfs.PROP_BASHFUL).as(Dwarf.class)); - Helper.assertEquals(DwarfsData.doc, dwarfs.getChild(Dwarfs.PROP_DOC).as(Dwarf.class)); - Helper.assertEquals(DwarfsData.dopey, dwarfs.getChild(Dwarfs.PROP_DOPEY).as(Dwarf.class)); - Helper.assertEquals(DwarfsData.grumpy, dwarfs.getChild(Dwarfs.PROP_GRUMPY).as(Dwarf.class)); - Helper.assertEquals(DwarfsData.happy, dwarfs.getChild(Dwarfs.PROP_HAPPY).as(Dwarf.class)); - Helper.assertEquals(DwarfsData.sleepy, dwarfs.getChild(Dwarfs.PROP_SLEEPY).as(Dwarf.class)); - Helper.assertEquals(DwarfsData.sneezy, dwarfs.getChild(Dwarfs.PROP_SNEEZY).as(Dwarf.class)); - } + Helper.assertEquals(DwarfsData.bashful, dwarfs.getChild(Dwarfs.PROP_BASHFUL).as(Dwarf.class)); + Helper.assertEquals(DwarfsData.doc, dwarfs.getChild(Dwarfs.PROP_DOC).as(Dwarf.class)); + Helper.assertEquals(DwarfsData.dopey, dwarfs.getChild(Dwarfs.PROP_DOPEY).as(Dwarf.class)); + Helper.assertEquals(DwarfsData.grumpy, dwarfs.getChild(Dwarfs.PROP_GRUMPY).as(Dwarf.class)); + Helper.assertEquals(DwarfsData.happy, dwarfs.getChild(Dwarfs.PROP_HAPPY).as(Dwarf.class)); + Helper.assertEquals(DwarfsData.sleepy, dwarfs.getChild(Dwarfs.PROP_SLEEPY).as(Dwarf.class)); + Helper.assertEquals(DwarfsData.sneezy, dwarfs.getChild(Dwarfs.PROP_SNEEZY).as(Dwarf.class)); + } } diff --git a/src/test/java/org/ini4j/BasicProfileTest.java b/src/test/java/org/ini4j/BasicProfileTest.java index e67b0b3..d0c367a 100644 --- a/src/test/java/org/ini4j/BasicProfileTest.java +++ b/src/test/java/org/ini4j/BasicProfileTest.java @@ -15,435 +15,432 @@ */ package org.ini4j; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.net.URI; import org.ini4j.sample.Dwarf; import org.ini4j.sample.DwarfBean; import org.ini4j.sample.Dwarfs; - import org.ini4j.test.DwarfsData; import org.ini4j.test.DwarfsData.DwarfData; import org.ini4j.test.Helper; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - import org.junit.Test; -import java.net.URI; - -public class BasicProfileTest extends Ini4jCase -{ - private static final String SECTION = "section"; - private static final String NUMBER = "number"; - private static final String SINGLE = "single"; - private static final String SOLO = "solo"; - private static final String LOCATION = "location"; - private static final String LOCATION_1 = "http://www.ini4j.org"; - private static final String LOCATION_2 = "http://ini4j.org"; - - /* - * thanx to Gary Pampara for bug report - */ - @Test public void test_bug_2817403() throws Exception - { - BasicProfile prof = new BasicProfile(); - Profile.Section sec = prof.add("section"); - - sec.add("player.name", "Joe"); - sec.add("player.greeting", "Hi ${player.name}!"); - sec.add("player.domain", "foo.bar"); - sec.add("player.email", "${player.name}@${player.domain}"); - - // - assertEquals("Joe", sec.fetch("player.name")); - assertEquals("Hi Joe!", sec.fetch("player.greeting")); - assertEquals("foo.bar", sec.fetch("player.domain")); - assertEquals("Joe@foo.bar", sec.fetch("player.email")); - - // - sec = prof.add("other"); - sec.add("option", "${section/player.name}"); - assertEquals("Joe", sec.fetch("option")); - sec.put("option", "${section/player.email}"); - assertEquals("Joe@foo.bar", sec.fetch("option")); - sec.put("option2", "${option} ${section/player.name} ${section/player.domain}"); - assertEquals("Joe@foo.bar Joe foo.bar", sec.fetch("option2")); - } - - @Test public void testAddPut() - { - Profile prof = new BasicProfile(); - - prof.add(SECTION, Dwarf.PROP_AGE, DwarfsData.sneezy.age); - prof.put(SECTION, Dwarf.PROP_HEIGHT, DwarfsData.sneezy.height); - prof.add(SECTION, Dwarf.PROP_HOME_DIR, DwarfsData.sneezy.homeDir); - prof.add(SECTION, Dwarf.PROP_WEIGHT, DwarfsData.sneezy.weight); - prof.put(SECTION, Dwarf.PROP_HOME_PAGE, null); - prof.put(SECTION, Dwarf.PROP_HOME_PAGE, DwarfsData.sneezy.homePage); - prof.add(SECTION, Dwarf.PROP_FORTUNE_NUMBER, DwarfsData.sneezy.fortuneNumber[0]); - prof.add(SECTION, Dwarf.PROP_FORTUNE_NUMBER, DwarfsData.sneezy.fortuneNumber[1]); - prof.add(SECTION, Dwarf.PROP_FORTUNE_NUMBER, DwarfsData.sneezy.fortuneNumber[2]); - prof.add(SECTION, Dwarf.PROP_FORTUNE_NUMBER, DwarfsData.sneezy.fortuneNumber[3]); - Helper.assertEquals(DwarfsData.sneezy, prof.get(SECTION).as(Dwarf.class)); - assertNotNull(prof.removeOption(SECTION, Dwarf.PROP_FORTUNE_NUMBER)); - assertEquals(0, prof.get(SECTION).length(Dwarf.PROP_FORTUNE_NUMBER)); - assertNotNull(prof.remove(SECTION)); - assertNull(prof.removeOption(SECTION, Dwarf.PROP_FORTUNE_NUMBER)); - } - - @Test public void testFirstUpper() - { - BasicProfile prof = new BasicProfile(true, true); - DwarfsRW dwarfs = prof.as(DwarfsRW.class); - - dwarfs.setBashful(DwarfsData.bashful); - assertTrue(prof.containsKey("Bashful")); - assertNotNull(dwarfs.getBashful()); - } - - @Test public void testFromToAs() throws Exception - { - BasicProfile prof = new BasicProfile(); - - Helper.addDwarfs(prof); - fromToAs(prof, DwarfsData.bashful); - fromToAs(prof, DwarfsData.doc); - fromToAs(prof, DwarfsData.dopey); - fromToAs(prof, DwarfsData.grumpy); - fromToAs(prof, DwarfsData.happy); - fromToAs(prof, DwarfsData.sleepy); - fromToAs(prof, DwarfsData.sneezy); - - // - DwarfsRW dwarfs = prof.as(DwarfsRW.class); - - Helper.assertEquals(DwarfsData.bashful, dwarfs.getBashful()); - Helper.assertEquals(DwarfsData.doc, dwarfs.getDoc()); - Helper.assertEquals(DwarfsData.dopey, dwarfs.getDopey()); - Helper.assertEquals(DwarfsData.grumpy, dwarfs.getGrumpy()); - Helper.assertEquals(DwarfsData.happy, dwarfs.getHappy()); - Helper.assertEquals(DwarfsData.sleepy, dwarfs.getSleepy()); - Helper.assertEquals(DwarfsData.sneezy, dwarfs.getSneezy()); - - // - prof.remove(Dwarfs.PROP_BASHFUL); - assertNull(prof.get(Dwarfs.PROP_BASHFUL)); - assertEquals(0, prof.length(Dwarfs.PROP_BASHFUL)); - assertNull(dwarfs.getBashful()); - dwarfs.setBashful(DwarfsData.dopey); - Helper.assertEquals(DwarfsData.dopey, dwarfs.getBashful()); - } - - @Test public void testIniGetFetch() - { - Profile prof = new BasicProfile(); - Profile.Section sec = Helper.addDwarf(prof, DwarfsData.dopey); - - Helper.addDwarf(prof, DwarfsData.bashful); - Helper.addDwarf(prof, DwarfsData.doc); - assertEquals(sec.get(Dwarf.PROP_AGE), prof.get(Dwarfs.PROP_DOPEY, Dwarf.PROP_AGE)); - assertEquals(DwarfsData.dopey.age, (int) prof.get(Dwarfs.PROP_DOPEY, Dwarf.PROP_AGE, int.class)); - assertEquals(sec.get(Dwarf.PROP_WEIGHT), prof.get(Dwarfs.PROP_DOPEY, Dwarf.PROP_WEIGHT)); - assertEquals(DwarfsData.dopey.weight, prof.fetch(Dwarfs.PROP_DOPEY, Dwarf.PROP_WEIGHT, double.class), Helper.DELTA); - assertEquals(sec.fetch(Dwarf.PROP_HEIGHT), prof.fetch(Dwarfs.PROP_DOPEY, Dwarf.PROP_HEIGHT)); - assertEquals(DwarfsData.dopey.weight, prof.fetch(Dwarfs.PROP_DOPEY, Dwarf.PROP_WEIGHT, double.class), Helper.DELTA); - assertEquals(sec.fetch(Dwarf.PROP_HOME_PAGE), prof.fetch(Dwarfs.PROP_DOPEY, Dwarf.PROP_HOME_PAGE)); - assertEquals(DwarfsData.dopey.homePage, prof.fetch(Dwarfs.PROP_DOPEY, Dwarf.PROP_HOME_PAGE, URI.class)); - - // nulls - assertNull(prof.get(SECTION, Dwarf.PROP_AGE)); - assertEquals(0, (int) prof.get(SECTION, Dwarf.PROP_AGE, int.class)); - assertNull(prof.get(SECTION, Dwarf.PROP_WEIGHT)); - assertEquals(0.0, prof.fetch(SECTION, Dwarf.PROP_WEIGHT, double.class), Helper.DELTA); - assertNull(prof.fetch(SECTION, Dwarf.PROP_HEIGHT)); - assertEquals(0.0, prof.fetch(SECTION, Dwarf.PROP_WEIGHT, double.class), Helper.DELTA); - assertNull(prof.fetch(SECTION, Dwarf.PROP_HOME_PAGE)); - assertNull(prof.fetch(SECTION, Dwarf.PROP_HOME_PAGE, URI.class)); - } - - @Test public void testOptionArray() throws Exception - { - BasicProfile prof = new BasicProfile(); - Profile.Section sec = prof.add(SECTION); - - sec.add(NUMBER, 1); - sec.add(LOCATION, LOCATION_1); - sec.add(NUMBER, 2); - sec.add(LOCATION, LOCATION_2); - Section s = prof.get(SECTION).as(Section.class); - - assertNotNull(s); - assertEquals(2, s.getNumber().length); - assertEquals(1, s.getNumber()[0]); - assertEquals(2, s.getNumber()[1]); - assertEquals(2, s.getLocation().length); - assertEquals(new URI(LOCATION_1), s.getLocation()[0]); - assertNull(s.getMissing()); - int[] numbers = new int[] { 1, 2, 3, 4, 5 }; - - s.setNumber(numbers); - assertEquals(5, sec.length(NUMBER)); - } - - @Test public void testResolve() throws Exception - { - BasicProfile prof = new BasicProfile(); - - Helper.addDwarf(prof, DwarfsData.happy); - Profile.Section doc = Helper.addDwarf(prof, DwarfsData.doc); - StringBuilder buffer; - String input; - - // other sections's value - input = "${happy/weight}"; - buffer = new StringBuilder(input); - - prof.resolve(buffer, doc); - assertEquals(String.valueOf(DwarfsData.happy.weight), buffer.toString()); - - // same sections's value - input = "${height}"; - buffer = new StringBuilder(input); - - prof.resolve(buffer, doc); - assertEquals(String.valueOf(DwarfsData.doc.height), buffer.toString()); - - // system property - input = "${@prop/user.home}"; - buffer = new StringBuilder(input); - - prof.resolve(buffer, doc); - assertEquals(System.getProperty("user.home"), buffer.toString()); - - // system environment - input = "${@env/PATH}"; - buffer = new StringBuilder(input); - try - { - prof.resolve(buffer, doc); - assertEquals(System.getenv("PATH"), buffer.toString()); - } - catch (Error e) - { - // retroweaver + JDK 1.4 throws Error on getenv - } - - // unknown variable - input = "${no such name}"; - buffer = new StringBuilder(input); - - prof.resolve(buffer, doc); - assertEquals(input, buffer.toString()); - - // unknown section's unknown variable - input = "${no such section/no such name}"; - buffer = new StringBuilder(input); - - prof.resolve(buffer, doc); - assertEquals(input, buffer.toString()); - - // other section's unknown variable - input = "${happy/no such name}"; - buffer = new StringBuilder(input); - - prof.resolve(buffer, doc); - assertEquals(input, buffer.toString()); - - // small input - input = "${"; - buffer = new StringBuilder(input); - - prof.resolve(buffer, doc); - assertEquals(input, buffer.toString()); - - // incorrect references - input = "${doc/weight"; - buffer = new StringBuilder(input); - - prof.resolve(buffer, doc); - assertEquals(input, buffer.toString()); - - // empty references - input = "jim${}"; - buffer = new StringBuilder(input); - - prof.resolve(buffer, doc); - assertEquals(input, buffer.toString()); - - // escaped references - input = "${happy/weight}"; - buffer = new StringBuilder(input); - - prof.resolve(buffer, doc); - assertEquals("" + DwarfsData.happy.weight, buffer.toString()); - input = "\\" + input; - buffer = new StringBuilder(input); - - prof.resolve(buffer, doc); - assertEquals(input, buffer.toString()); +public class BasicProfileTest extends Ini4jCase { + private static final String SECTION = "section"; + private static final String NUMBER = "number"; + private static final String SINGLE = "single"; + private static final String SOLO = "solo"; + private static final String LOCATION = "location"; + private static final String LOCATION_1 = "http://www.ini4j.org"; + private static final String LOCATION_2 = "http://ini4j.org"; + + /* + * thanx to Gary Pampara for bug report + */ + @Test + public void test_bug_2817403() throws Exception { + BasicProfile prof = new BasicProfile(); + Profile.Section sec = prof.add("section"); + + sec.add("player.name", "Joe"); + sec.add("player.greeting", "Hi ${player.name}!"); + sec.add("player.domain", "foo.bar"); + sec.add("player.email", "${player.name}@${player.domain}"); + + // + assertEquals("Joe", sec.fetch("player.name")); + assertEquals("Hi Joe!", sec.fetch("player.greeting")); + assertEquals("foo.bar", sec.fetch("player.domain")); + assertEquals("Joe@foo.bar", sec.fetch("player.email")); + + // + sec = prof.add("other"); + sec.add("option", "${section/player.name}"); + assertEquals("Joe", sec.fetch("option")); + sec.put("option", "${section/player.email}"); + assertEquals("Joe@foo.bar", sec.fetch("option")); + sec.put("option2", "${option} ${section/player.name} ${section/player.domain}"); + assertEquals("Joe@foo.bar Joe foo.bar", sec.fetch("option2")); + } + + @Test + public void testAddPut() { + Profile prof = new BasicProfile(); + + prof.add(SECTION, Dwarf.PROP_AGE, DwarfsData.sneezy.age); + prof.put(SECTION, Dwarf.PROP_HEIGHT, DwarfsData.sneezy.height); + prof.add(SECTION, Dwarf.PROP_HOME_DIR, DwarfsData.sneezy.homeDir); + prof.add(SECTION, Dwarf.PROP_WEIGHT, DwarfsData.sneezy.weight); + prof.put(SECTION, Dwarf.PROP_HOME_PAGE, null); + prof.put(SECTION, Dwarf.PROP_HOME_PAGE, DwarfsData.sneezy.homePage); + prof.add(SECTION, Dwarf.PROP_FORTUNE_NUMBER, DwarfsData.sneezy.fortuneNumber[0]); + prof.add(SECTION, Dwarf.PROP_FORTUNE_NUMBER, DwarfsData.sneezy.fortuneNumber[1]); + prof.add(SECTION, Dwarf.PROP_FORTUNE_NUMBER, DwarfsData.sneezy.fortuneNumber[2]); + prof.add(SECTION, Dwarf.PROP_FORTUNE_NUMBER, DwarfsData.sneezy.fortuneNumber[3]); + Helper.assertEquals(DwarfsData.sneezy, prof.get(SECTION).as(Dwarf.class)); + assertNotNull(prof.removeOption(SECTION, Dwarf.PROP_FORTUNE_NUMBER)); + assertEquals(0, prof.get(SECTION).length(Dwarf.PROP_FORTUNE_NUMBER)); + assertNotNull(prof.remove(SECTION)); + assertNull(prof.removeOption(SECTION, Dwarf.PROP_FORTUNE_NUMBER)); + } + + @Test + public void testFirstUpper() { + BasicProfile prof = new BasicProfile(true, true); + DwarfsRW dwarfs = prof.as(DwarfsRW.class); + + dwarfs.setBashful(DwarfsData.bashful); + assertTrue(prof.containsKey("Bashful")); + assertNotNull(dwarfs.getBashful()); + } + + @Test + public void testFromToAs() throws Exception { + BasicProfile prof = new BasicProfile(); + + Helper.addDwarfs(prof); + fromToAs(prof, DwarfsData.bashful); + fromToAs(prof, DwarfsData.doc); + fromToAs(prof, DwarfsData.dopey); + fromToAs(prof, DwarfsData.grumpy); + fromToAs(prof, DwarfsData.happy); + fromToAs(prof, DwarfsData.sleepy); + fromToAs(prof, DwarfsData.sneezy); + + // + DwarfsRW dwarfs = prof.as(DwarfsRW.class); + + Helper.assertEquals(DwarfsData.bashful, dwarfs.getBashful()); + Helper.assertEquals(DwarfsData.doc, dwarfs.getDoc()); + Helper.assertEquals(DwarfsData.dopey, dwarfs.getDopey()); + Helper.assertEquals(DwarfsData.grumpy, dwarfs.getGrumpy()); + Helper.assertEquals(DwarfsData.happy, dwarfs.getHappy()); + Helper.assertEquals(DwarfsData.sleepy, dwarfs.getSleepy()); + Helper.assertEquals(DwarfsData.sneezy, dwarfs.getSneezy()); + + // + prof.remove(Dwarfs.PROP_BASHFUL); + assertNull(prof.get(Dwarfs.PROP_BASHFUL)); + assertEquals(0, prof.length(Dwarfs.PROP_BASHFUL)); + assertNull(dwarfs.getBashful()); + dwarfs.setBashful(DwarfsData.dopey); + Helper.assertEquals(DwarfsData.dopey, dwarfs.getBashful()); + } + + @Test + public void testIniGetFetch() { + Profile prof = new BasicProfile(); + Profile.Section sec = Helper.addDwarf(prof, DwarfsData.dopey); + + Helper.addDwarf(prof, DwarfsData.bashful); + Helper.addDwarf(prof, DwarfsData.doc); + assertEquals(sec.get(Dwarf.PROP_AGE), prof.get(Dwarfs.PROP_DOPEY, Dwarf.PROP_AGE)); + assertEquals( + DwarfsData.dopey.age, (int) prof.get(Dwarfs.PROP_DOPEY, Dwarf.PROP_AGE, int.class)); + assertEquals(sec.get(Dwarf.PROP_WEIGHT), prof.get(Dwarfs.PROP_DOPEY, Dwarf.PROP_WEIGHT)); + assertEquals( + DwarfsData.dopey.weight, + prof.fetch(Dwarfs.PROP_DOPEY, Dwarf.PROP_WEIGHT, double.class), + Helper.DELTA); + assertEquals(sec.fetch(Dwarf.PROP_HEIGHT), prof.fetch(Dwarfs.PROP_DOPEY, Dwarf.PROP_HEIGHT)); + assertEquals( + DwarfsData.dopey.weight, + prof.fetch(Dwarfs.PROP_DOPEY, Dwarf.PROP_WEIGHT, double.class), + Helper.DELTA); + assertEquals( + sec.fetch(Dwarf.PROP_HOME_PAGE), prof.fetch(Dwarfs.PROP_DOPEY, Dwarf.PROP_HOME_PAGE)); + assertEquals( + DwarfsData.dopey.homePage, prof.fetch(Dwarfs.PROP_DOPEY, Dwarf.PROP_HOME_PAGE, URI.class)); + + // nulls + assertNull(prof.get(SECTION, Dwarf.PROP_AGE)); + assertEquals(0, (int) prof.get(SECTION, Dwarf.PROP_AGE, int.class)); + assertNull(prof.get(SECTION, Dwarf.PROP_WEIGHT)); + assertEquals(0.0, prof.fetch(SECTION, Dwarf.PROP_WEIGHT, double.class), Helper.DELTA); + assertNull(prof.fetch(SECTION, Dwarf.PROP_HEIGHT)); + assertEquals(0.0, prof.fetch(SECTION, Dwarf.PROP_WEIGHT, double.class), Helper.DELTA); + assertNull(prof.fetch(SECTION, Dwarf.PROP_HOME_PAGE)); + assertNull(prof.fetch(SECTION, Dwarf.PROP_HOME_PAGE, URI.class)); + } + + @Test + public void testOptionArray() throws Exception { + BasicProfile prof = new BasicProfile(); + Profile.Section sec = prof.add(SECTION); + + sec.add(NUMBER, 1); + sec.add(LOCATION, LOCATION_1); + sec.add(NUMBER, 2); + sec.add(LOCATION, LOCATION_2); + Section s = prof.get(SECTION).as(Section.class); + + assertNotNull(s); + assertEquals(2, s.getNumber().length); + assertEquals(1, s.getNumber()[0]); + assertEquals(2, s.getNumber()[1]); + assertEquals(2, s.getLocation().length); + assertEquals(new URI(LOCATION_1), s.getLocation()[0]); + assertNull(s.getMissing()); + int[] numbers = new int[] {1, 2, 3, 4, 5}; + + s.setNumber(numbers); + assertEquals(5, sec.length(NUMBER)); + } + + @Test + public void testResolve() throws Exception { + BasicProfile prof = new BasicProfile(); + + Helper.addDwarf(prof, DwarfsData.happy); + Profile.Section doc = Helper.addDwarf(prof, DwarfsData.doc); + StringBuilder buffer; + String input; + + // other sections's value + input = "${happy/weight}"; + buffer = new StringBuilder(input); + + prof.resolve(buffer, doc); + assertEquals(String.valueOf(DwarfsData.happy.weight), buffer.toString()); + + // same sections's value + input = "${height}"; + buffer = new StringBuilder(input); + + prof.resolve(buffer, doc); + assertEquals(String.valueOf(DwarfsData.doc.height), buffer.toString()); + + // system property + input = "${@prop/user.home}"; + buffer = new StringBuilder(input); + + prof.resolve(buffer, doc); + assertEquals(System.getProperty("user.home"), buffer.toString()); + + // system environment + input = "${@env/PATH}"; + buffer = new StringBuilder(input); + try { + prof.resolve(buffer, doc); + assertEquals(System.getenv("PATH"), buffer.toString()); + } catch (Error e) { + // retroweaver + JDK 1.4 throws Error on getenv } - @Test public void testResolveArray() throws Exception - { - StringBuilder buffer; - BasicProfile prof = new BasicProfile(); - - prof.add(SECTION).add(NUMBER, 1); - prof.add(SECTION).add(NUMBER, 2); - Profile.Section sec = prof.get(SECTION); - - // - buffer = new StringBuilder("${section[0]/number}"); - prof.resolve(buffer, sec); - assertEquals("1", buffer.toString()); - buffer = new StringBuilder("${section[1]/number}"); - prof.resolve(buffer, sec); - assertEquals("2", buffer.toString()); - buffer = new StringBuilder("${section[0]/number}-${section[1]/number}"); - prof.resolve(buffer, sec); - assertEquals("1-2", buffer.toString()); - - // - prof.clear(); - sec = prof.add(SECTION); - sec.add(NUMBER, 1); - sec.add(NUMBER, 2); - sec = prof.get(SECTION); - assertEquals(2, sec.length(NUMBER)); - buffer = new StringBuilder("${number}"); - prof.resolve(buffer, sec); - assertEquals("2", buffer.toString()); - buffer = new StringBuilder("${number[0]}-${section/number[1]}-${section[0]/number}"); - prof.resolve(buffer, sec); - assertEquals("1-2-2", buffer.toString()); + // unknown variable + input = "${no such name}"; + buffer = new StringBuilder(input); + + prof.resolve(buffer, doc); + assertEquals(input, buffer.toString()); + + // unknown section's unknown variable + input = "${no such section/no such name}"; + buffer = new StringBuilder(input); + + prof.resolve(buffer, doc); + assertEquals(input, buffer.toString()); + + // other section's unknown variable + input = "${happy/no such name}"; + buffer = new StringBuilder(input); + + prof.resolve(buffer, doc); + assertEquals(input, buffer.toString()); + + // small input + input = "${"; + buffer = new StringBuilder(input); + + prof.resolve(buffer, doc); + assertEquals(input, buffer.toString()); + + // incorrect references + input = "${doc/weight"; + buffer = new StringBuilder(input); + + prof.resolve(buffer, doc); + assertEquals(input, buffer.toString()); + + // empty references + input = "jim${}"; + buffer = new StringBuilder(input); + + prof.resolve(buffer, doc); + assertEquals(input, buffer.toString()); + + // escaped references + input = "${happy/weight}"; + buffer = new StringBuilder(input); + + prof.resolve(buffer, doc); + assertEquals("" + DwarfsData.happy.weight, buffer.toString()); + input = "\\" + input; + buffer = new StringBuilder(input); + + prof.resolve(buffer, doc); + assertEquals(input, buffer.toString()); + } + + @Test + public void testResolveArray() throws Exception { + StringBuilder buffer; + BasicProfile prof = new BasicProfile(); + + prof.add(SECTION).add(NUMBER, 1); + prof.add(SECTION).add(NUMBER, 2); + Profile.Section sec = prof.get(SECTION); + + // + buffer = new StringBuilder("${section[0]/number}"); + prof.resolve(buffer, sec); + assertEquals("1", buffer.toString()); + buffer = new StringBuilder("${section[1]/number}"); + prof.resolve(buffer, sec); + assertEquals("2", buffer.toString()); + buffer = new StringBuilder("${section[0]/number}-${section[1]/number}"); + prof.resolve(buffer, sec); + assertEquals("1-2", buffer.toString()); + + // + prof.clear(); + sec = prof.add(SECTION); + sec.add(NUMBER, 1); + sec.add(NUMBER, 2); + sec = prof.get(SECTION); + assertEquals(2, sec.length(NUMBER)); + buffer = new StringBuilder("${number}"); + prof.resolve(buffer, sec); + assertEquals("2", buffer.toString()); + buffer = new StringBuilder("${number[0]}-${section/number[1]}-${section[0]/number}"); + prof.resolve(buffer, sec); + assertEquals("1-2-2", buffer.toString()); + } + + @Test + public void testSectionArray() throws Exception { + BasicProfile prof = new BasicProfile(); + + prof.add(SECTION).add(NUMBER, 1); + prof.add(SECTION).add(NUMBER, 2); + prof.add(SINGLE).add(NUMBER, 3); + Global g = prof.as(Global.class); + + assertNotNull(g); + assertEquals(2, g.getSection().length); + assertEquals(1, g.getSingle().length); + assertNull(g.getMissing()); + assertTrue(g.hasSection()); + } + + @Test + public void testSetter() { + BasicProfile prof = new BasicProfile(); + Global g = prof.as(Global.class); + Section s1 = new SectionBean(); + Section s2 = new SectionBean(); + Section[] all = new Section[] {s1, s2}; + + g.setSection(all); + assertEquals(2, prof.length("section")); + assertNull(g.getSolo()); + g.setSolo(s1); + assertNotNull(g.getSolo()); + g.setSolo(null); + assertEquals(0, prof.length("solo")); + } + + private void fromToAs(BasicProfile prof, DwarfData dwarf) { + Profile.Section sec = prof.get(dwarf.name); + Profile.Section dup = new BasicProfileSection(prof, SECTION); + DwarfBean bean = new DwarfBean(); + + sec.to(bean); + Helper.assertEquals(dwarf, bean); + dup.from(bean); + bean = new DwarfBean(); + dup.to(bean); + Helper.assertEquals(dwarf, bean); + Dwarf proxy = dup.as(Dwarf.class); + + Helper.assertEquals(dwarf, proxy); + dup.clear(); + sec.to(proxy); + Helper.assertEquals(dwarf, proxy); + prof.remove(dup); + } + + public static interface DwarfsRW extends Dwarfs { + void setBashful(Dwarf value); + } + + public static interface Global { + Section[] getMissing(); + + Section[] getSection(); + + void setSection(Section[] value); + + Section[] getSingle(); + + Section getSolo(); + + void setSolo(Section value); + + boolean hasSection(); + } + + public static interface Section { + URI[] getLocation(); + + void setLocation(URI[] value); + + String[] getMissing(); + + void setMissing(String[] value); + + int[] getNumber(); + + void setNumber(int[] value); + } + + public static class SectionBean implements Section { + private URI[] _location; + private String[] _missing; + private int[] _number; + + @Override + public URI[] getLocation() { + return _location; } - @Test public void testSectionArray() throws Exception - { - BasicProfile prof = new BasicProfile(); - - prof.add(SECTION).add(NUMBER, 1); - prof.add(SECTION).add(NUMBER, 2); - prof.add(SINGLE).add(NUMBER, 3); - Global g = prof.as(Global.class); - - assertNotNull(g); - assertEquals(2, g.getSection().length); - assertEquals(1, g.getSingle().length); - assertNull(g.getMissing()); - assertTrue(g.hasSection()); + @Override + public void setLocation(URI[] value) { + _location = value; } - @Test public void testSetter() - { - BasicProfile prof = new BasicProfile(); - Global g = prof.as(Global.class); - Section s1 = new SectionBean(); - Section s2 = new SectionBean(); - Section[] all = new Section[] { s1, s2 }; - - g.setSection(all); - assertEquals(2, prof.length("section")); - assertNull(g.getSolo()); - g.setSolo(s1); - assertNotNull(g.getSolo()); - g.setSolo(null); - assertEquals(0, prof.length("solo")); + @Override + public String[] getMissing() { + return _missing; } - private void fromToAs(BasicProfile prof, DwarfData dwarf) - { - Profile.Section sec = prof.get(dwarf.name); - Profile.Section dup = new BasicProfileSection(prof, SECTION); - DwarfBean bean = new DwarfBean(); - - sec.to(bean); - Helper.assertEquals(dwarf, bean); - dup.from(bean); - bean = new DwarfBean(); - dup.to(bean); - Helper.assertEquals(dwarf, bean); - Dwarf proxy = dup.as(Dwarf.class); - - Helper.assertEquals(dwarf, proxy); - dup.clear(); - sec.to(proxy); - Helper.assertEquals(dwarf, proxy); - prof.remove(dup); + @Override + public void setMissing(String[] value) { + _missing = value; } - public static interface DwarfsRW extends Dwarfs - { - void setBashful(Dwarf value); - } - - public static interface Global - { - Section[] getMissing(); - - Section[] getSection(); - - void setSection(Section[] value); - - Section[] getSingle(); - - Section getSolo(); - - void setSolo(Section value); - - boolean hasSection(); - } - - public static interface Section - { - URI[] getLocation(); - - void setLocation(URI[] value); - - String[] getMissing(); - - void setMissing(String[] value); - - int[] getNumber(); - - void setNumber(int[] value); + @Override + public int[] getNumber() { + return _number; } - public static class SectionBean implements Section - { - private URI[] _location; - private String[] _missing; - private int[] _number; - - @Override public URI[] getLocation() - { - return _location; - } - - @Override public void setLocation(URI[] value) - { - _location = value; - } - - @Override public String[] getMissing() - { - return _missing; - } - - @Override public void setMissing(String[] value) - { - _missing = value; - } - - @Override public int[] getNumber() - { - return _number; - } - - @Override public void setNumber(int[] value) - { - _number = value; - } + @Override + public void setNumber(int[] value) { + _number = value; } + } } diff --git a/src/test/java/org/ini4j/BasicRegistryKeyTest.java b/src/test/java/org/ini4j/BasicRegistryKeyTest.java index d2c09ac..f4b3fc9 100644 --- a/src/test/java/org/ini4j/BasicRegistryKeyTest.java +++ b/src/test/java/org/ini4j/BasicRegistryKeyTest.java @@ -15,38 +15,36 @@ */ package org.ini4j; -import org.ini4j.Registry.Type; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; +import org.ini4j.Registry.Type; import org.junit.Test; -public class BasicRegistryKeyTest extends Ini4jCase -{ - private static final String KEY = "key"; - private static final String DUMMY = "dummy"; - private static final String OPTION = "option"; +public class BasicRegistryKeyTest extends Ini4jCase { + private static final String KEY = "key"; + private static final String DUMMY = "dummy"; + private static final String OPTION = "option"; - @Test public void testWrapped() throws Exception - { - BasicRegistry reg = new BasicRegistry(); - Registry.Key parent = reg.add(KEY); - Registry.Key child = parent.addChild(DUMMY); + @Test + public void testWrapped() throws Exception { + BasicRegistry reg = new BasicRegistry(); + Registry.Key parent = reg.add(KEY); + Registry.Key child = parent.addChild(DUMMY); - assertSame(parent, child.getParent()); - assertSame(child, parent.getChild(DUMMY)); - Registry.Key kid = child.addChild(KEY); + assertSame(parent, child.getParent()); + assertSame(child, parent.getChild(DUMMY)); + Registry.Key kid = child.addChild(KEY); - assertSame(kid, parent.lookup(DUMMY, KEY)); - parent.put(OPTION, DUMMY); - parent.putType(OPTION, Type.REG_BINARY); - assertEquals(Type.REG_BINARY, parent.getType(OPTION)); - parent.removeType(OPTION); - assertNull(parent.getType(OPTION)); - parent.putType(OPTION, Type.REG_BINARY); - parent.remove(OPTION); - assertNull(parent.getType(OPTION)); - } + assertSame(kid, parent.lookup(DUMMY, KEY)); + parent.put(OPTION, DUMMY); + parent.putType(OPTION, Type.REG_BINARY); + assertEquals(Type.REG_BINARY, parent.getType(OPTION)); + parent.removeType(OPTION); + assertNull(parent.getType(OPTION)); + parent.putType(OPTION, Type.REG_BINARY); + parent.remove(OPTION); + assertNull(parent.getType(OPTION)); + } } diff --git a/src/test/java/org/ini4j/BasicRegistryTest.java b/src/test/java/org/ini4j/BasicRegistryTest.java index cd0f7a6..53595d1 100644 --- a/src/test/java/org/ini4j/BasicRegistryTest.java +++ b/src/test/java/org/ini4j/BasicRegistryTest.java @@ -22,38 +22,37 @@ import org.junit.Test; -public class BasicRegistryTest extends Ini4jCase -{ - private static final String KEY = "key"; - private static final String DUMMY = "dummy"; - private static final String VERSION = "Windows Registry Editor Version 5.00"; - - @Test public void testVersion() - { - BasicRegistry reg = new BasicRegistry(); - - assertEquals(VERSION, reg.getVersion()); - reg.setVersion(DUMMY); - assertEquals(DUMMY, reg.getVersion()); - } - - @Test public void testWrapped() throws Exception - { - BasicRegistry reg = new BasicRegistry(); - Registry.Key key1 = reg.add(KEY); - Registry.Key key2 = reg.add(KEY); - - assertNotNull(key1); - assertNotNull(key2); - assertTrue(reg.get(KEY) instanceof Registry.Key); - assertTrue(reg.get(KEY, 1) instanceof Registry.Key); - Registry.Key key3 = new BasicRegistryKey(reg, KEY); - - assertSame(key1, reg.put(KEY, key3, 0)); - assertSame(key2, reg.put(KEY, key3)); - assertSame(key3, reg.remove(KEY, 1)); - assertSame(key3, reg.remove(KEY)); - key1 = reg.add(KEY); - assertSame(key1, reg.remove(key1)); - } +public class BasicRegistryTest extends Ini4jCase { + private static final String KEY = "key"; + private static final String DUMMY = "dummy"; + private static final String VERSION = "Windows Registry Editor Version 5.00"; + + @Test + public void testVersion() { + BasicRegistry reg = new BasicRegistry(); + + assertEquals(VERSION, reg.getVersion()); + reg.setVersion(DUMMY); + assertEquals(DUMMY, reg.getVersion()); + } + + @Test + public void testWrapped() throws Exception { + BasicRegistry reg = new BasicRegistry(); + Registry.Key key1 = reg.add(KEY); + Registry.Key key2 = reg.add(KEY); + + assertNotNull(key1); + assertNotNull(key2); + assertTrue(reg.get(KEY) instanceof Registry.Key); + assertTrue(reg.get(KEY, 1) instanceof Registry.Key); + Registry.Key key3 = new BasicRegistryKey(reg, KEY); + + assertSame(key1, reg.put(KEY, key3, 0)); + assertSame(key2, reg.put(KEY, key3)); + assertSame(key3, reg.remove(KEY, 1)); + assertSame(key3, reg.remove(KEY)); + key1 = reg.add(KEY); + assertSame(key1, reg.remove(key1)); + } } diff --git a/src/test/java/org/ini4j/CommonMultiMapTest.java b/src/test/java/org/ini4j/CommonMultiMapTest.java index bf7a6da..73fbb7c 100644 --- a/src/test/java/org/ini4j/CommonMultiMapTest.java +++ b/src/test/java/org/ini4j/CommonMultiMapTest.java @@ -19,95 +19,93 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import org.junit.Test; - import java.util.HashMap; import java.util.Map; +import org.junit.Test; -public class CommonMultiMapTest extends Ini4jCase -{ - private static final String KEY = "key"; - private static final String VALUE = "value"; - private static final String COMMENT = "comment"; - - @Test public void testClearAndRemove() throws Exception - { - CommonMultiMap map = new CommonMultiMap(); - - assertNull(map.removeComment(KEY)); - - // - map.put(KEY, VALUE); - map.clear(); - assertTrue(map.isEmpty()); - - // - map.put(KEY, VALUE); - map.remove(KEY); - assertNull(map.getComment(KEY)); - - // - map.put(KEY, VALUE); - map.remove(KEY, 0); - assertNull(map.getComment(KEY)); - - // - map.add(KEY, VALUE); - map.add(KEY, VALUE); - map.putComment(KEY, COMMENT); - map.remove(KEY, 0); - assertEquals(COMMENT, map.getComment(KEY)); - - // - map.put(KEY, VALUE); - map.putComment(KEY, COMMENT); - assertEquals(COMMENT, map.getComment(KEY)); - map.clear(); - assertNull(map.getComment(KEY)); - - // - map.put(KEY, VALUE); - map.putComment(KEY, COMMENT); - map.remove(KEY); - assertNull(map.getComment(KEY)); - - // - map.put(KEY, VALUE); - map.putComment(KEY, COMMENT); - assertEquals(COMMENT, map.removeComment(KEY)); - assertNull(map.getComment(KEY)); - - // - map.put(KEY, VALUE); - map.putComment(KEY, COMMENT); - map.remove(KEY, 0); - assertNull(map.getComment(KEY)); - } - - @Test public void testPutAll() throws Exception - { - CommonMultiMap map = new CommonMultiMap(); - CommonMultiMap copy = new CommonMultiMap(); - - map.put(KEY, VALUE); - map.putComment(KEY, COMMENT); - copy.putAll(map); - assertEquals(COMMENT, copy.getComment(KEY)); - Map simple = new HashMap(); - - simple.put(KEY, VALUE); - copy.clear(); - assertTrue(copy.isEmpty()); - copy.putAll(simple); - assertNull(copy.getComment(KEY)); - assertEquals(VALUE, copy.get(KEY)); - - // - map = new CommonMultiMap(); - map.put(KEY, VALUE); - copy.clear(); - copy.putAll(map); - assertEquals(VALUE, copy.get(KEY)); - assertNull(copy.getComment(KEY)); - } +public class CommonMultiMapTest extends Ini4jCase { + private static final String KEY = "key"; + private static final String VALUE = "value"; + private static final String COMMENT = "comment"; + + @Test + public void testClearAndRemove() throws Exception { + CommonMultiMap map = new CommonMultiMap(); + + assertNull(map.removeComment(KEY)); + + // + map.put(KEY, VALUE); + map.clear(); + assertTrue(map.isEmpty()); + + // + map.put(KEY, VALUE); + map.remove(KEY); + assertNull(map.getComment(KEY)); + + // + map.put(KEY, VALUE); + map.remove(KEY, 0); + assertNull(map.getComment(KEY)); + + // + map.add(KEY, VALUE); + map.add(KEY, VALUE); + map.putComment(KEY, COMMENT); + map.remove(KEY, 0); + assertEquals(COMMENT, map.getComment(KEY)); + + // + map.put(KEY, VALUE); + map.putComment(KEY, COMMENT); + assertEquals(COMMENT, map.getComment(KEY)); + map.clear(); + assertNull(map.getComment(KEY)); + + // + map.put(KEY, VALUE); + map.putComment(KEY, COMMENT); + map.remove(KEY); + assertNull(map.getComment(KEY)); + + // + map.put(KEY, VALUE); + map.putComment(KEY, COMMENT); + assertEquals(COMMENT, map.removeComment(KEY)); + assertNull(map.getComment(KEY)); + + // + map.put(KEY, VALUE); + map.putComment(KEY, COMMENT); + map.remove(KEY, 0); + assertNull(map.getComment(KEY)); + } + + @Test + public void testPutAll() throws Exception { + CommonMultiMap map = new CommonMultiMap(); + CommonMultiMap copy = new CommonMultiMap(); + + map.put(KEY, VALUE); + map.putComment(KEY, COMMENT); + copy.putAll(map); + assertEquals(COMMENT, copy.getComment(KEY)); + Map simple = new HashMap(); + + simple.put(KEY, VALUE); + copy.clear(); + assertTrue(copy.isEmpty()); + copy.putAll(simple); + assertNull(copy.getComment(KEY)); + assertEquals(VALUE, copy.get(KEY)); + + // + map = new CommonMultiMap(); + map.put(KEY, VALUE); + copy.clear(); + copy.putAll(map); + assertEquals(VALUE, copy.get(KEY)); + assertNull(copy.getComment(KEY)); + } } diff --git a/src/test/java/org/ini4j/ConfigParserTest.java b/src/test/java/org/ini4j/ConfigParserTest.java index a0e080c..adb52df 100644 --- a/src/test/java/org/ini4j/ConfigParserTest.java +++ b/src/test/java/org/ini4j/ConfigParserTest.java @@ -15,14 +15,6 @@ */ package org.ini4j; -import org.ini4j.sample.Dwarf; -import org.ini4j.sample.Dwarfs; - -import org.ini4j.test.DwarfsData; -import org.ini4j.test.Helper; - -import org.junit.After; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; @@ -30,9 +22,6 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import org.junit.Before; -import org.junit.Test; - import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; @@ -41,450 +30,407 @@ import java.io.FileWriter; import java.io.IOException; import java.io.StringReader; - import java.util.HashMap; import java.util.List; import java.util.Map; +import org.ini4j.sample.Dwarf; +import org.ini4j.sample.Dwarfs; +import org.ini4j.test.DwarfsData; +import org.ini4j.test.Helper; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; -public class ConfigParserTest extends Ini4jCase -{ - private static final String SECTION = "section"; - private static final String OPTION = "option"; - private static final String DWARFS_PATH = "org/ini4j/addon/dwarfs-py.ini"; - private static final String BAD = "[bashful\nage=3"; - private static final String TEST_DATA_PATH = "src/test/resources"; - private static final String TEST_WORK_PATH = "target"; - private static final String MISSING = "missing"; - private static final String MISSING_REF = "%(missing)"; - private static final String DUMMY = "dummy"; - protected ConfigParser instance; - - @Before @Override public void setUp() throws Exception - { - super.setUp(); - instance = new ConfigParser(); - } - - @After @Override public void tearDown() - { - } - - @Test public void testAddHasRemove() throws Exception - { - assertFalse(instance.hasSection(SECTION)); - assertFalse(instance.hasOption(SECTION, OPTION)); - assertFalse(instance.getIni().containsKey(SECTION)); - instance.addSection(SECTION); - assertTrue(instance.hasSection(SECTION)); - instance.set(SECTION, OPTION, "dummy"); - assertTrue(instance.hasOption(SECTION, OPTION)); - assertTrue(instance.getIni().get(SECTION).containsKey(OPTION)); - instance.removeOption(SECTION, OPTION); - assertFalse(instance.hasOption(SECTION, OPTION)); - instance.removeSection(SECTION); - assertFalse(instance.hasSection(SECTION)); - } - - @Test public void testAddSectionDuplicate() throws Exception - { - instance.addSection(SECTION); - try - { - instance.addSection(SECTION); - missing(ConfigParser.DuplicateSectionException.class); - } - catch (ConfigParser.DuplicateSectionException x) - { - // - } - } - - @Test public void testAddSectionIllegal() throws Exception - { - try - { - instance.addSection(ConfigParser.PyIni.DEFAULT_SECTION_NAME); - missing(IllegalArgumentException.class); - } - catch (IllegalArgumentException x) - { - // - } - } - - @Test public void testDefaults() throws Exception - { - Map defs = new HashMap(); - - instance = new ConfigParser(defs); - - assertSame(defs, instance.defaults()); - } - - @Test public void testDwarfs() throws Exception - { - readDwarfs(); - checkEquals(DwarfsData.bashful, Dwarfs.PROP_BASHFUL); - checkEquals(DwarfsData.doc, Dwarfs.PROP_DOC); - checkEquals(DwarfsData.dopey, Dwarfs.PROP_DOPEY); - checkEquals(DwarfsData.happy, Dwarfs.PROP_HAPPY); - checkEquals(DwarfsData.grumpy, Dwarfs.PROP_GRUMPY); - checkEquals(DwarfsData.sleepy, Dwarfs.PROP_SLEEPY); - checkEquals(DwarfsData.sneezy, Dwarfs.PROP_SNEEZY); - } - - @Test public void testGet() throws Exception - { - Ini.Section section = instance.getIni().add(SECTION); - - section.put(OPTION, "on"); - assertTrue(instance.getBoolean(SECTION, OPTION)); - section.put(OPTION, "1"); - assertTrue(instance.getBoolean(SECTION, OPTION)); - section.put(OPTION, "true"); - assertTrue(instance.getBoolean(SECTION, OPTION)); - section.put(OPTION, "yes"); - assertTrue(instance.getBoolean(SECTION, OPTION)); - section.put(OPTION, "TruE"); - assertTrue(instance.getBoolean(SECTION, OPTION)); - - // - section.put(OPTION, "off"); - assertFalse(instance.getBoolean(SECTION, OPTION)); - section.put(OPTION, "0"); - assertFalse(instance.getBoolean(SECTION, OPTION)); - section.put(OPTION, "no"); - assertFalse(instance.getBoolean(SECTION, OPTION)); - section.put(OPTION, "false"); - assertFalse(instance.getBoolean(SECTION, OPTION)); - section.put(OPTION, "FalsE"); - assertFalse(instance.getBoolean(SECTION, OPTION)); - - // ints - section.put(OPTION, "12"); - assertEquals(12, instance.getInt(SECTION, OPTION)); - assertEquals(12L, instance.getLong(SECTION, OPTION)); - section.put(OPTION, "1.2"); - assertEquals(1.2f, instance.getFloat(SECTION, OPTION), Helper.DELTA); - assertEquals(1.2, instance.getDouble(SECTION, OPTION), Helper.DELTA); - } - - @Test public void testGetBooleanException() throws Exception - { - Ini.Section section = instance.getIni().add(SECTION); - - section.put(OPTION, "joe"); - try - { - instance.getBoolean(SECTION, OPTION); - missing(IllegalArgumentException.class); - } - catch (IllegalArgumentException x) - { - // - } - } - - @Test public void testGetMissinOptionException() throws Exception - { - instance.addSection(SECTION); - instance.set(SECTION, OPTION, MISSING_REF); - try - { - instance.get(SECTION, OPTION); - missing(ConfigParser.InterpolationMissingOptionException.class); - } - catch (ConfigParser.InterpolationMissingOptionException x) - { - // - } - } - - @Test public void testGetNoOption() throws Exception - { - instance.getIni().add(SECTION); - try - { - instance.get(SECTION, OPTION); - missing(ConfigParser.NoOptionException.class); - } - catch (ConfigParser.NoOptionException x) - { - // - } - } - - @Test public void testGetNoSection() throws Exception - { - try - { - instance.get(SECTION, OPTION); - missing(ConfigParser.NoSectionException.class); - } - catch (ConfigParser.NoSectionException x) - { - // - } +public class ConfigParserTest extends Ini4jCase { + private static final String SECTION = "section"; + private static final String OPTION = "option"; + private static final String DWARFS_PATH = "org/ini4j/addon/dwarfs-py.ini"; + private static final String BAD = "[bashful\nage=3"; + private static final String TEST_DATA_PATH = "src/test/resources"; + private static final String TEST_WORK_PATH = "target"; + private static final String MISSING = "missing"; + private static final String MISSING_REF = "%(missing)"; + private static final String DUMMY = "dummy"; + protected ConfigParser instance; + + @Before + @Override + public void setUp() throws Exception { + super.setUp(); + instance = new ConfigParser(); + } + + @After + @Override + public void tearDown() {} + + @Test + public void testAddHasRemove() throws Exception { + assertFalse(instance.hasSection(SECTION)); + assertFalse(instance.hasOption(SECTION, OPTION)); + assertFalse(instance.getIni().containsKey(SECTION)); + instance.addSection(SECTION); + assertTrue(instance.hasSection(SECTION)); + instance.set(SECTION, OPTION, "dummy"); + assertTrue(instance.hasOption(SECTION, OPTION)); + assertTrue(instance.getIni().get(SECTION).containsKey(OPTION)); + instance.removeOption(SECTION, OPTION); + assertFalse(instance.hasOption(SECTION, OPTION)); + instance.removeSection(SECTION); + assertFalse(instance.hasSection(SECTION)); + } + + @Test + public void testAddSectionDuplicate() throws Exception { + instance.addSection(SECTION); + try { + instance.addSection(SECTION); + missing(ConfigParser.DuplicateSectionException.class); + } catch (ConfigParser.DuplicateSectionException x) { + // } - - @Test - @SuppressWarnings("empty-statement") - public void testGetVars() throws Exception - { - Map vars = new HashMap(); - - instance = new ConfigParser(vars); - - instance.addSection(SECTION); - instance.set(SECTION, OPTION, MISSING_REF); - assertEquals(MISSING_REF, instance.get(SECTION, OPTION, true)); - requireMissingOptionException(SECTION, OPTION); - vars.put(MISSING, DUMMY); - assertEquals(DUMMY, instance.get(SECTION, OPTION)); - vars.remove(MISSING); - requireMissingOptionException(SECTION, OPTION); - instance.getIni().add(ConfigParser.PyIni.DEFAULT_SECTION_NAME); - ((ConfigParser.PyIni) instance.getIni()).getDefaultSection().put(MISSING, DUMMY); - assertEquals(DUMMY, instance.get(SECTION, OPTION)); - ((ConfigParser.PyIni) instance.getIni()).getDefaultSection().remove(MISSING); - requireMissingOptionException(SECTION, OPTION); - instance = new ConfigParser(); - instance.addSection(SECTION); - instance.set(SECTION, OPTION, MISSING_REF); - vars.put(MISSING, DUMMY); - assertEquals(DUMMY, instance.get(SECTION, OPTION, false, vars)); + } + + @Test + public void testAddSectionIllegal() throws Exception { + try { + instance.addSection(ConfigParser.PyIni.DEFAULT_SECTION_NAME); + missing(IllegalArgumentException.class); + } catch (IllegalArgumentException x) { + // } - - @Test public void testItems() throws Exception - { - Ini ini = new Ini(); - - ini.add(SECTION).from(DwarfsData.dopey); - Ini.Section section = ini.get(SECTION); - Ini.Section dopey = ini.add(Dwarfs.PROP_DOPEY); - - for (String key : section.keySet()) - { - dopey.put(key.toLowerCase(), section.get(key)); - } - - readDwarfs(); - List> items = instance.items(Dwarfs.PROP_DOPEY); - - assertEquals(5, items.size()); - assertEquals(6, dopey.size()); - for (Map.Entry entry : items) - { - assertEquals(dopey.get(entry.getKey()), entry.getValue()); - } - - // raw - dopey = instance.getIni().get(Dwarfs.PROP_DOPEY); - items = instance.items(Dwarfs.PROP_DOPEY, true); - - assertEquals(5, items.size()); - assertEquals("%(_weight)", dopey.get(Dwarf.PROP_WEIGHT)); - assertEquals("%(_height)", dopey.get(Dwarf.PROP_HEIGHT)); + } + + @Test + public void testDefaults() throws Exception { + Map defs = new HashMap(); + + instance = new ConfigParser(defs); + + assertSame(defs, instance.defaults()); + } + + @Test + public void testDwarfs() throws Exception { + readDwarfs(); + checkEquals(DwarfsData.bashful, Dwarfs.PROP_BASHFUL); + checkEquals(DwarfsData.doc, Dwarfs.PROP_DOC); + checkEquals(DwarfsData.dopey, Dwarfs.PROP_DOPEY); + checkEquals(DwarfsData.happy, Dwarfs.PROP_HAPPY); + checkEquals(DwarfsData.grumpy, Dwarfs.PROP_GRUMPY); + checkEquals(DwarfsData.sleepy, Dwarfs.PROP_SLEEPY); + checkEquals(DwarfsData.sneezy, Dwarfs.PROP_SNEEZY); + } + + @Test + public void testGet() throws Exception { + Ini.Section section = instance.getIni().add(SECTION); + + section.put(OPTION, "on"); + assertTrue(instance.getBoolean(SECTION, OPTION)); + section.put(OPTION, "1"); + assertTrue(instance.getBoolean(SECTION, OPTION)); + section.put(OPTION, "true"); + assertTrue(instance.getBoolean(SECTION, OPTION)); + section.put(OPTION, "yes"); + assertTrue(instance.getBoolean(SECTION, OPTION)); + section.put(OPTION, "TruE"); + assertTrue(instance.getBoolean(SECTION, OPTION)); + + // + section.put(OPTION, "off"); + assertFalse(instance.getBoolean(SECTION, OPTION)); + section.put(OPTION, "0"); + assertFalse(instance.getBoolean(SECTION, OPTION)); + section.put(OPTION, "no"); + assertFalse(instance.getBoolean(SECTION, OPTION)); + section.put(OPTION, "false"); + assertFalse(instance.getBoolean(SECTION, OPTION)); + section.put(OPTION, "FalsE"); + assertFalse(instance.getBoolean(SECTION, OPTION)); + + // ints + section.put(OPTION, "12"); + assertEquals(12, instance.getInt(SECTION, OPTION)); + assertEquals(12L, instance.getLong(SECTION, OPTION)); + section.put(OPTION, "1.2"); + assertEquals(1.2f, instance.getFloat(SECTION, OPTION), Helper.DELTA); + assertEquals(1.2, instance.getDouble(SECTION, OPTION), Helper.DELTA); + } + + @Test + public void testGetBooleanException() throws Exception { + Ini.Section section = instance.getIni().add(SECTION); + + section.put(OPTION, "joe"); + try { + instance.getBoolean(SECTION, OPTION); + missing(IllegalArgumentException.class); + } catch (IllegalArgumentException x) { + // } - - @Test public void testOptions() throws Exception - { - instance.addSection(SECTION); - assertEquals(0, instance.options(SECTION).size()); - for (int i = 0; i < 10; i++) - { - instance.set(SECTION, OPTION + i, DUMMY); - } - - assertEquals(10, instance.options(SECTION).size()); + } + + @Test + public void testGetMissinOptionException() throws Exception { + instance.addSection(SECTION); + instance.set(SECTION, OPTION, MISSING_REF); + try { + instance.get(SECTION, OPTION); + missing(ConfigParser.InterpolationMissingOptionException.class); + } catch (ConfigParser.InterpolationMissingOptionException x) { + // } - - @Test public void testRead() throws Exception - { - File file = newTestFile(DWARFS_PATH); - - assertTrue(file.exists()); - instance.read(file.getCanonicalPath()); - instance.read(file); - instance.read(new FileReader(file)); - instance.read(new FileInputStream(file)); - instance.read(file.toURI().toURL()); + } + + @Test + public void testGetNoOption() throws Exception { + instance.getIni().add(SECTION); + try { + instance.get(SECTION, OPTION); + missing(ConfigParser.NoOptionException.class); + } catch (ConfigParser.NoOptionException x) { + // } - - @Test public void testReadFileException() throws Exception - { - try - { - instance.read(badFile()); - missing(ConfigParser.ParsingException.class); - } - catch (ConfigParser.ParsingException x) - { - // - } + } + + @Test + public void testGetNoSection() throws Exception { + try { + instance.get(SECTION, OPTION); + missing(ConfigParser.NoSectionException.class); + } catch (ConfigParser.NoSectionException x) { + // } - - @Test public void testReadReaderException() throws Exception - { - try - { - instance.read(new StringReader(BAD)); - missing(ConfigParser.ParsingException.class); - } - catch (ConfigParser.ParsingException x) - { - // - } + } + + @Test + @SuppressWarnings("empty-statement") + public void testGetVars() throws Exception { + Map vars = new HashMap(); + + instance = new ConfigParser(vars); + + instance.addSection(SECTION); + instance.set(SECTION, OPTION, MISSING_REF); + assertEquals(MISSING_REF, instance.get(SECTION, OPTION, true)); + requireMissingOptionException(SECTION, OPTION); + vars.put(MISSING, DUMMY); + assertEquals(DUMMY, instance.get(SECTION, OPTION)); + vars.remove(MISSING); + requireMissingOptionException(SECTION, OPTION); + instance.getIni().add(ConfigParser.PyIni.DEFAULT_SECTION_NAME); + ((ConfigParser.PyIni) instance.getIni()).getDefaultSection().put(MISSING, DUMMY); + assertEquals(DUMMY, instance.get(SECTION, OPTION)); + ((ConfigParser.PyIni) instance.getIni()).getDefaultSection().remove(MISSING); + requireMissingOptionException(SECTION, OPTION); + instance = new ConfigParser(); + instance.addSection(SECTION); + instance.set(SECTION, OPTION, MISSING_REF); + vars.put(MISSING, DUMMY); + assertEquals(DUMMY, instance.get(SECTION, OPTION, false, vars)); + } + + @Test + public void testItems() throws Exception { + Ini ini = new Ini(); + + ini.add(SECTION).from(DwarfsData.dopey); + Ini.Section section = ini.get(SECTION); + Ini.Section dopey = ini.add(Dwarfs.PROP_DOPEY); + + for (String key : section.keySet()) { + dopey.put(key.toLowerCase(), section.get(key)); } - @Test public void testReadStreamException() throws Exception - { - try - { - instance.read(new ByteArrayInputStream(BAD.getBytes())); - missing(ConfigParser.ParsingException.class); - } - catch (ConfigParser.ParsingException x) - { - // - } - } + readDwarfs(); + List> items = instance.items(Dwarfs.PROP_DOPEY); - @Test public void testReadURLException() throws Exception - { - try - { - instance.read(badFile().toURI().toURL()); - missing(ConfigParser.ParsingException.class); - } - catch (ConfigParser.ParsingException x) - { - // - } + assertEquals(5, items.size()); + assertEquals(6, dopey.size()); + for (Map.Entry entry : items) { + assertEquals(dopey.get(entry.getKey()), entry.getValue()); } - @Test public void testSections() throws Exception - { - instance.addSection(SECTION); - assertEquals(1, instance.sections().size()); - for (int i = 0; i < 10; i++) - { - instance.addSection(SECTION + i); - } - - assertEquals(11, instance.sections().size()); + // raw + dopey = instance.getIni().get(Dwarfs.PROP_DOPEY); + items = instance.items(Dwarfs.PROP_DOPEY, true); + + assertEquals(5, items.size()); + assertEquals("%(_weight)", dopey.get(Dwarf.PROP_WEIGHT)); + assertEquals("%(_height)", dopey.get(Dwarf.PROP_HEIGHT)); + } + + @Test + public void testOptions() throws Exception { + instance.addSection(SECTION); + assertEquals(0, instance.options(SECTION).size()); + for (int i = 0; i < 10; i++) { + instance.set(SECTION, OPTION + i, DUMMY); } - @Test public void testSet() throws Exception - { - instance.addSection(SECTION); - instance.set(SECTION, OPTION, "dummy"); - assertEquals("dummy", instance.getIni().get(SECTION).get(OPTION)); - assertTrue(instance.hasOption(SECTION, OPTION)); - instance.set(SECTION, OPTION, null); - assertFalse(instance.hasOption(SECTION, OPTION)); + assertEquals(10, instance.options(SECTION).size()); + } + + @Test + public void testRead() throws Exception { + File file = newTestFile(DWARFS_PATH); + + assertTrue(file.exists()); + instance.read(file.getCanonicalPath()); + instance.read(file); + instance.read(new FileReader(file)); + instance.read(new FileInputStream(file)); + instance.read(file.toURI().toURL()); + } + + @Test + public void testReadFileException() throws Exception { + try { + instance.read(badFile()); + missing(ConfigParser.ParsingException.class); + } catch (ConfigParser.ParsingException x) { + // } - - @Test public void testSetNoSection() throws Exception - { - try - { - instance.set(SECTION, OPTION, "dummy"); - missing(ConfigParser.NoSectionException.class); - } - catch (ConfigParser.NoSectionException x) - { - // - } + } + + @Test + public void testReadReaderException() throws Exception { + try { + instance.read(new StringReader(BAD)); + missing(ConfigParser.ParsingException.class); + } catch (ConfigParser.ParsingException x) { + // } - - @Test public void testWrite() throws Exception - { - File input = newTestFile(DWARFS_PATH); - File output = new File(TEST_WORK_PATH, input.getName()); - - instance.read(input); - instance.write(output); - checkWrite(output); - instance.write(new FileWriter(output)); - checkWrite(output); - instance.write(new FileOutputStream(output)); - checkWrite(output); + } + + @Test + public void testReadStreamException() throws Exception { + try { + instance.read(new ByteArrayInputStream(BAD.getBytes())); + missing(ConfigParser.ParsingException.class); + } catch (ConfigParser.ParsingException x) { + // } - - protected void checkEquals(Dwarf expected, String sectionName) throws Exception - { - assertEquals("" + expected.getAge(), instance.get(sectionName, Dwarf.PROP_AGE)); - assertEquals("" + expected.getHeight(), instance.get(sectionName, Dwarf.PROP_HEIGHT)); - assertEquals("" + expected.getWeight(), instance.get(sectionName, Dwarf.PROP_WEIGHT)); - assertEquals("" + expected.getHomePage(), instance.get(sectionName, Dwarf.PROP_HOME_PAGE.toLowerCase())); - assertEquals("" + expected.getHomeDir(), instance.get(sectionName, Dwarf.PROP_HOME_DIR.toLowerCase())); + } + + @Test + public void testReadURLException() throws Exception { + try { + instance.read(badFile().toURI().toURL()); + missing(ConfigParser.ParsingException.class); + } catch (ConfigParser.ParsingException x) { + // } - - protected File newTestFile(String path) - { - return new File(TEST_DATA_PATH, path); + } + + @Test + public void testSections() throws Exception { + instance.addSection(SECTION); + assertEquals(1, instance.sections().size()); + for (int i = 0; i < 10; i++) { + instance.addSection(SECTION + i); } - protected void readDwarfs() throws Exception - { - instance.read(newTestFile(DWARFS_PATH)); + assertEquals(11, instance.sections().size()); + } + + @Test + public void testSet() throws Exception { + instance.addSection(SECTION); + instance.set(SECTION, OPTION, "dummy"); + assertEquals("dummy", instance.getIni().get(SECTION).get(OPTION)); + assertTrue(instance.hasOption(SECTION, OPTION)); + instance.set(SECTION, OPTION, null); + assertFalse(instance.hasOption(SECTION, OPTION)); + } + + @Test + public void testSetNoSection() throws Exception { + try { + instance.set(SECTION, OPTION, "dummy"); + missing(ConfigParser.NoSectionException.class); + } catch (ConfigParser.NoSectionException x) { + // } - - private File badFile() throws IOException - { - File f = File.createTempFile("test", "ini"); - - f.deleteOnExit(); - FileWriter w = new FileWriter(f); - - w.write(BAD, 0, BAD.length()); - w.close(); - - return f; + } + + @Test + public void testWrite() throws Exception { + File input = newTestFile(DWARFS_PATH); + File output = new File(TEST_WORK_PATH, input.getName()); + + instance.read(input); + instance.write(output); + checkWrite(output); + instance.write(new FileWriter(output)); + checkWrite(output); + instance.write(new FileOutputStream(output)); + checkWrite(output); + } + + protected void checkEquals(Dwarf expected, String sectionName) throws Exception { + assertEquals("" + expected.getAge(), instance.get(sectionName, Dwarf.PROP_AGE)); + assertEquals("" + expected.getHeight(), instance.get(sectionName, Dwarf.PROP_HEIGHT)); + assertEquals("" + expected.getWeight(), instance.get(sectionName, Dwarf.PROP_WEIGHT)); + assertEquals( + "" + expected.getHomePage(), instance.get(sectionName, Dwarf.PROP_HOME_PAGE.toLowerCase())); + assertEquals( + "" + expected.getHomeDir(), instance.get(sectionName, Dwarf.PROP_HOME_DIR.toLowerCase())); + } + + protected File newTestFile(String path) { + return new File(TEST_DATA_PATH, path); + } + + protected void readDwarfs() throws Exception { + instance.read(newTestFile(DWARFS_PATH)); + } + + private File badFile() throws IOException { + File f = File.createTempFile("test", "ini"); + + f.deleteOnExit(); + FileWriter w = new FileWriter(f); + + w.write(BAD, 0, BAD.length()); + w.close(); + + return f; + } + + private void checkEquals(Map a, Map b) throws Exception { + if (a == null) { + assertNull(b); + } else { + assertEquals(a.size(), b.size()); + for (String key : a.keySet()) { + assertEquals(a.get(key), b.get(key)); + } } - - private void checkEquals(Map a, Map b) throws Exception - { - if (a == null) - { - assertNull(b); - } - else - { - assertEquals(a.size(), b.size()); - for (String key : a.keySet()) - { - assertEquals(a.get(key), b.get(key)); - } - } - } - - private void checkWrite(File file) throws Exception - { - ConfigParser saved = new ConfigParser(instance.defaults()); - - saved.read(file); - checkEquals(((ConfigParser.PyIni) instance.getIni()).getDefaultSection(), - ((ConfigParser.PyIni) saved.getIni()).getDefaultSection()); - assertEquals(instance.sections().size(), saved.sections().size()); - for (String sectionName : instance.sections()) - { - checkEquals(instance.getIni().get(sectionName), saved.getIni().get(sectionName)); - } + } + + private void checkWrite(File file) throws Exception { + ConfigParser saved = new ConfigParser(instance.defaults()); + + saved.read(file); + checkEquals( + ((ConfigParser.PyIni) instance.getIni()).getDefaultSection(), + ((ConfigParser.PyIni) saved.getIni()).getDefaultSection()); + assertEquals(instance.sections().size(), saved.sections().size()); + for (String sectionName : instance.sections()) { + checkEquals(instance.getIni().get(sectionName), saved.getIni().get(sectionName)); } - - @SuppressWarnings("empty-statement") - private void requireMissingOptionException(String sectionName, String optionName) throws Exception - { - try - { - instance.get(sectionName, optionName); - fail(); - } - catch (ConfigParser.InterpolationMissingOptionException x) - { - ; - } + } + + @SuppressWarnings("empty-statement") + private void requireMissingOptionException(String sectionName, String optionName) + throws Exception { + try { + instance.get(sectionName, optionName); + fail(); + } catch (ConfigParser.InterpolationMissingOptionException x) { + ; } + } } diff --git a/src/test/java/org/ini4j/ConfigTest.java b/src/test/java/org/ini4j/ConfigTest.java index bf4a8a8..b5f18cb 100644 --- a/src/test/java/org/ini4j/ConfigTest.java +++ b/src/test/java/org/ini4j/ConfigTest.java @@ -15,152 +15,143 @@ */ package org.ini4j; +import java.nio.charset.Charset; import org.junit.Assert; import org.junit.Test; -import java.nio.charset.Charset; - -public class ConfigTest extends Ini4jCase -{ - @Test public void testDefaults() - { - Config def = newDefaultConfig(); - - assertEquals(def, new Config()); - assertEquals(def, Config.getGlobal()); - assertEquals(def, Config.getGlobal().clone()); - } - - @Test public void testSystemProperties() - { - Config exp = newInverseConfig(); - - setBoolean(Config.PROP_EMPTY_OPTION, exp.isEmptyOption()); - setBoolean(Config.PROP_EMPTY_SECTION, exp.isEmptySection()); - setBoolean(Config.PROP_GLOBAL_SECTION, exp.isGlobalSection()); - setString(Config.PROP_GLOBAL_SECTION_NAME, exp.getGlobalSectionName()); - setBoolean(Config.PROP_INCLUDE, exp.isInclude()); - setBoolean(Config.PROP_LOWER_CASE_OPTION, exp.isLowerCaseOption()); - setBoolean(Config.PROP_LOWER_CASE_SECTION, exp.isLowerCaseSection()); - setBoolean(Config.PROP_MULTI_OPTION, exp.isMultiOption()); - setBoolean(Config.PROP_MULTI_SECTION, exp.isMultiSection()); - setBoolean(Config.PROP_STRICT_OPERATOR, exp.isStrictOperator()); - setBoolean(Config.PROP_UNNAMED_SECTION, exp.isUnnamedSection()); - setBoolean(Config.PROP_ESCAPE, exp.isEscape()); - setBoolean(Config.PROP_ESCAPE_KEY_ONLY, exp.isEscapeKeyOnly()); - setBoolean(Config.PROP_ESCAPE_NEWLINE, exp.isEscapeNewline()); - setChar(Config.PROP_PATH_SEPARATOR, exp.getPathSeparator()); - setBoolean(Config.PROP_TREE, exp.isTree()); - setBoolean(Config.PROP_PROPERTY_FIRST_UPPER, exp.isPropertyFirstUpper()); - setString(Config.PROP_LINE_SEPARATOR, exp.getLineSeparator()); - setCharset(Config.PROP_FILE_ENCODING, exp.getFileEncoding()); - setBoolean(Config.PROP_COMMENT, exp.isComment()); - setBoolean(Config.PROP_HEADER_COMMENT, exp.isHeaderComment()); - Config cfg = new Config(); - - assertEquals(exp, cfg); - } - - private void setBoolean(String prop, boolean value) - { - System.setProperty(Config.KEY_PREFIX + prop, String.valueOf(value)); - } - - private void setChar(String prop, char value) - { - System.setProperty(Config.KEY_PREFIX + prop, String.valueOf(value)); - } - - private void setCharset(String prop, Charset value) - { - System.setProperty(Config.KEY_PREFIX + prop, String.valueOf(value)); - } - - private void setString(String prop, String value) - { - System.setProperty(Config.KEY_PREFIX + prop, value); - } - - private void assertEquals(Config exp, Config act) - { - Assert.assertEquals(exp.isEmptyOption(), act.isEmptyOption()); - Assert.assertEquals(exp.isEmptySection(), act.isEmptySection()); - Assert.assertEquals(exp.isEscape(), act.isEscape()); - Assert.assertEquals(exp.isEscapeKeyOnly(), act.isEscapeKeyOnly()); - Assert.assertEquals(exp.isEscapeNewline(), act.isEscapeNewline()); - Assert.assertEquals(exp.isGlobalSection(), act.isGlobalSection()); - Assert.assertEquals(exp.isInclude(), act.isInclude()); - Assert.assertEquals(exp.isLowerCaseOption(), act.isLowerCaseOption()); - Assert.assertEquals(exp.isLowerCaseSection(), act.isLowerCaseSection()); - Assert.assertEquals(exp.isMultiOption(), act.isMultiOption()); - Assert.assertEquals(exp.isMultiSection(), act.isMultiSection()); - Assert.assertEquals(exp.isStrictOperator(), act.isStrictOperator()); - Assert.assertEquals(exp.isUnnamedSection(), act.isUnnamedSection()); - Assert.assertEquals(exp.getGlobalSectionName(), act.getGlobalSectionName()); - Assert.assertEquals(exp.getPathSeparator(), act.getPathSeparator()); - Assert.assertEquals(exp.isTree(), act.isTree()); - Assert.assertEquals(exp.isPropertyFirstUpper(), act.isPropertyFirstUpper()); - Assert.assertEquals(exp.getLineSeparator(), act.getLineSeparator()); - Assert.assertEquals(exp.getFileEncoding(), act.getFileEncoding()); - Assert.assertEquals(exp.isComment(), act.isComment()); - Assert.assertEquals(exp.isHeaderComment(), act.isHeaderComment()); - } - - private Config newDefaultConfig() - { - Config cfg = new Config(); - - cfg.setEmptyOption(false); - cfg.setEmptySection(false); - cfg.setEscape(true); - cfg.setEscapeKeyOnly(false); - cfg.setEscapeNewline(true); - cfg.setGlobalSection(false); - cfg.setGlobalSectionName("?"); - cfg.setInclude(false); - cfg.setLowerCaseOption(false); - cfg.setLowerCaseSection(false); - cfg.setMultiSection(false); - cfg.setMultiOption(true); - cfg.setStrictOperator(false); - cfg.setUnnamedSection(false); - cfg.setPathSeparator('/'); - cfg.setTree(true); - cfg.setPropertyFirstUpper(false); - cfg.setLineSeparator(System.getProperty("line.separator")); - cfg.setFileEncoding(Charset.forName("UTF-8")); - cfg.setComment(true); - cfg.setHeaderComment(true); - - return cfg; - } - - private Config newInverseConfig() - { - Config cfg = newDefaultConfig(); - - cfg.setEmptyOption(!cfg.isEmptyOption()); - cfg.setEmptySection(!cfg.isEmptySection()); - cfg.setEscape(!cfg.isEscape()); - cfg.setEscapeKeyOnly(!cfg.isEscapeKeyOnly()); - cfg.setEscapeNewline(!cfg.isEscapeNewline()); - cfg.setGlobalSection(!cfg.isGlobalSection()); - cfg.setGlobalSectionName("+"); - cfg.setInclude(!cfg.isInclude()); - cfg.setLowerCaseOption(!cfg.isLowerCaseOption()); - cfg.setLowerCaseSection(!cfg.isLowerCaseSection()); - cfg.setMultiSection(!cfg.isMultiSection()); - cfg.setMultiOption(!cfg.isMultiOption()); - cfg.setStrictOperator(!cfg.isStrictOperator()); - cfg.setUnnamedSection(!cfg.isUnnamedSection()); - cfg.setPathSeparator('?'); - cfg.setTree(!cfg.isTree()); - cfg.setPropertyFirstUpper(!cfg.isPropertyFirstUpper()); - cfg.setComment(!cfg.isComment()); - cfg.setHeaderComment(!cfg.isHeaderComment()); - - //cfg.setLineSeparator("\t"); - //cfg.setFileEncoding(Charset.forName("ASCII")); - return cfg; - } +public class ConfigTest extends Ini4jCase { + @Test + public void testDefaults() { + Config def = newDefaultConfig(); + + assertEquals(def, new Config()); + assertEquals(def, Config.getGlobal()); + assertEquals(def, Config.getGlobal().clone()); + } + + @Test + public void testSystemProperties() { + Config exp = newInverseConfig(); + + setBoolean(Config.PROP_EMPTY_OPTION, exp.isEmptyOption()); + setBoolean(Config.PROP_EMPTY_SECTION, exp.isEmptySection()); + setBoolean(Config.PROP_GLOBAL_SECTION, exp.isGlobalSection()); + setString(Config.PROP_GLOBAL_SECTION_NAME, exp.getGlobalSectionName()); + setBoolean(Config.PROP_INCLUDE, exp.isInclude()); + setBoolean(Config.PROP_LOWER_CASE_OPTION, exp.isLowerCaseOption()); + setBoolean(Config.PROP_LOWER_CASE_SECTION, exp.isLowerCaseSection()); + setBoolean(Config.PROP_MULTI_OPTION, exp.isMultiOption()); + setBoolean(Config.PROP_MULTI_SECTION, exp.isMultiSection()); + setBoolean(Config.PROP_STRICT_OPERATOR, exp.isStrictOperator()); + setBoolean(Config.PROP_UNNAMED_SECTION, exp.isUnnamedSection()); + setBoolean(Config.PROP_ESCAPE, exp.isEscape()); + setBoolean(Config.PROP_ESCAPE_KEY_ONLY, exp.isEscapeKeyOnly()); + setBoolean(Config.PROP_ESCAPE_NEWLINE, exp.isEscapeNewline()); + setChar(Config.PROP_PATH_SEPARATOR, exp.getPathSeparator()); + setBoolean(Config.PROP_TREE, exp.isTree()); + setBoolean(Config.PROP_PROPERTY_FIRST_UPPER, exp.isPropertyFirstUpper()); + setString(Config.PROP_LINE_SEPARATOR, exp.getLineSeparator()); + setCharset(Config.PROP_FILE_ENCODING, exp.getFileEncoding()); + setBoolean(Config.PROP_COMMENT, exp.isComment()); + setBoolean(Config.PROP_HEADER_COMMENT, exp.isHeaderComment()); + Config cfg = new Config(); + + assertEquals(exp, cfg); + } + + private void setBoolean(String prop, boolean value) { + System.setProperty(Config.KEY_PREFIX + prop, String.valueOf(value)); + } + + private void setChar(String prop, char value) { + System.setProperty(Config.KEY_PREFIX + prop, String.valueOf(value)); + } + + private void setCharset(String prop, Charset value) { + System.setProperty(Config.KEY_PREFIX + prop, String.valueOf(value)); + } + + private void setString(String prop, String value) { + System.setProperty(Config.KEY_PREFIX + prop, value); + } + + private void assertEquals(Config exp, Config act) { + Assert.assertEquals(exp.isEmptyOption(), act.isEmptyOption()); + Assert.assertEquals(exp.isEmptySection(), act.isEmptySection()); + Assert.assertEquals(exp.isEscape(), act.isEscape()); + Assert.assertEquals(exp.isEscapeKeyOnly(), act.isEscapeKeyOnly()); + Assert.assertEquals(exp.isEscapeNewline(), act.isEscapeNewline()); + Assert.assertEquals(exp.isGlobalSection(), act.isGlobalSection()); + Assert.assertEquals(exp.isInclude(), act.isInclude()); + Assert.assertEquals(exp.isLowerCaseOption(), act.isLowerCaseOption()); + Assert.assertEquals(exp.isLowerCaseSection(), act.isLowerCaseSection()); + Assert.assertEquals(exp.isMultiOption(), act.isMultiOption()); + Assert.assertEquals(exp.isMultiSection(), act.isMultiSection()); + Assert.assertEquals(exp.isStrictOperator(), act.isStrictOperator()); + Assert.assertEquals(exp.isUnnamedSection(), act.isUnnamedSection()); + Assert.assertEquals(exp.getGlobalSectionName(), act.getGlobalSectionName()); + Assert.assertEquals(exp.getPathSeparator(), act.getPathSeparator()); + Assert.assertEquals(exp.isTree(), act.isTree()); + Assert.assertEquals(exp.isPropertyFirstUpper(), act.isPropertyFirstUpper()); + Assert.assertEquals(exp.getLineSeparator(), act.getLineSeparator()); + Assert.assertEquals(exp.getFileEncoding(), act.getFileEncoding()); + Assert.assertEquals(exp.isComment(), act.isComment()); + Assert.assertEquals(exp.isHeaderComment(), act.isHeaderComment()); + } + + private Config newDefaultConfig() { + Config cfg = new Config(); + + cfg.setEmptyOption(false); + cfg.setEmptySection(false); + cfg.setEscape(true); + cfg.setEscapeKeyOnly(false); + cfg.setEscapeNewline(true); + cfg.setGlobalSection(false); + cfg.setGlobalSectionName("?"); + cfg.setInclude(false); + cfg.setLowerCaseOption(false); + cfg.setLowerCaseSection(false); + cfg.setMultiSection(false); + cfg.setMultiOption(true); + cfg.setStrictOperator(false); + cfg.setUnnamedSection(false); + cfg.setPathSeparator('/'); + cfg.setTree(true); + cfg.setPropertyFirstUpper(false); + cfg.setLineSeparator(System.getProperty("line.separator")); + cfg.setFileEncoding(Charset.forName("UTF-8")); + cfg.setComment(true); + cfg.setHeaderComment(true); + + return cfg; + } + + private Config newInverseConfig() { + Config cfg = newDefaultConfig(); + + cfg.setEmptyOption(!cfg.isEmptyOption()); + cfg.setEmptySection(!cfg.isEmptySection()); + cfg.setEscape(!cfg.isEscape()); + cfg.setEscapeKeyOnly(!cfg.isEscapeKeyOnly()); + cfg.setEscapeNewline(!cfg.isEscapeNewline()); + cfg.setGlobalSection(!cfg.isGlobalSection()); + cfg.setGlobalSectionName("+"); + cfg.setInclude(!cfg.isInclude()); + cfg.setLowerCaseOption(!cfg.isLowerCaseOption()); + cfg.setLowerCaseSection(!cfg.isLowerCaseSection()); + cfg.setMultiSection(!cfg.isMultiSection()); + cfg.setMultiOption(!cfg.isMultiOption()); + cfg.setStrictOperator(!cfg.isStrictOperator()); + cfg.setUnnamedSection(!cfg.isUnnamedSection()); + cfg.setPathSeparator('?'); + cfg.setTree(!cfg.isTree()); + cfg.setPropertyFirstUpper(!cfg.isPropertyFirstUpper()); + cfg.setComment(!cfg.isComment()); + cfg.setHeaderComment(!cfg.isHeaderComment()); + + // cfg.setLineSeparator("\t"); + // cfg.setFileEncoding(Charset.forName("ASCII")); + return cfg; + } } diff --git a/src/test/java/org/ini4j/Ini4jCase.java b/src/test/java/org/ini4j/Ini4jCase.java index 6558b37..6a08a21 100644 --- a/src/test/java/org/ini4j/Ini4jCase.java +++ b/src/test/java/org/ini4j/Ini4jCase.java @@ -16,19 +16,18 @@ package org.ini4j; import junit.framework.TestCase; -import org.junit.Before; import org.ini4j.test.Helper; +import org.junit.Before; -public class Ini4jCase extends TestCase -{ - @Override @Before public void setUp() throws Exception - { - super.setUp(); - Helper.resetConfig(); - } +public class Ini4jCase extends TestCase { + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + Helper.resetConfig(); + } - protected void missing(Class clazz) - { - fail("Missing exception: " + clazz.getName()); - } + protected void missing(Class clazz) { + fail("Missing exception: " + clazz.getName()); + } } diff --git a/src/test/java/org/ini4j/IniPreferencesFactoryTest.java b/src/test/java/org/ini4j/IniPreferencesFactoryTest.java index e6a3384..57e253c 100755 --- a/src/test/java/org/ini4j/IniPreferencesFactoryTest.java +++ b/src/test/java/org/ini4j/IniPreferencesFactoryTest.java @@ -15,90 +15,79 @@ */ package org.ini4j; -import org.ini4j.test.Helper; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; -import org.junit.Test; - import java.util.prefs.Preferences; +import org.ini4j.test.Helper; +import org.junit.Test; -public class IniPreferencesFactoryTest extends Ini4jCase -{ - private static final String DUMMY = "dummy"; +public class IniPreferencesFactoryTest extends Ini4jCase { + private static final String DUMMY = "dummy"; - @Test public void testGetIniLocation() throws Exception - { - IniPreferencesFactory factory = new IniPreferencesFactory(); + @Test + public void testGetIniLocation() throws Exception { + IniPreferencesFactory factory = new IniPreferencesFactory(); - System.setProperty(DUMMY, DUMMY); - assertEquals(DUMMY, factory.getIniLocation(DUMMY)); - System.getProperties().remove(DUMMY); - assertNull(factory.getIniLocation(DUMMY)); - } + System.setProperty(DUMMY, DUMMY); + assertEquals(DUMMY, factory.getIniLocation(DUMMY)); + System.getProperties().remove(DUMMY); + assertNull(factory.getIniLocation(DUMMY)); + } - @SuppressWarnings("empty-statement") - @Test public void testGetResourceAsStream() throws Exception - { - IniPreferencesFactory factory = new IniPreferencesFactory(); + @SuppressWarnings("empty-statement") + @Test + public void testGetResourceAsStream() throws Exception { + IniPreferencesFactory factory = new IniPreferencesFactory(); - // class path - assertNotNull(factory.getResourceAsStream(Helper.DWARFS_INI)); + // class path + assertNotNull(factory.getResourceAsStream(Helper.DWARFS_INI)); - // url - String location = Helper.getResourceURL(Helper.DWARFS_INI).toString(); + // url + String location = Helper.getResourceURL(Helper.DWARFS_INI).toString(); - assertNotNull(factory.getResourceAsStream(location)); + assertNotNull(factory.getResourceAsStream(location)); - // invalid url should throw IllegalArgumentException - try - { - factory.getResourceAsStream("http://"); - fail(); - } - catch (IllegalArgumentException x) - { - ; - } + // invalid url should throw IllegalArgumentException + try { + factory.getResourceAsStream("http://"); + fail(); + } catch (IllegalArgumentException x) { + ; } - - @Test public void testNewIniPreferences() - { - System.setProperty(DUMMY, DUMMY); - try - { - new IniPreferencesFactory().newIniPreferences(DUMMY); - missing(IllegalArgumentException.class); - } - catch (IllegalArgumentException x) - { - // - } - finally - { - System.getProperties().remove(DUMMY); - } + } + + @Test + public void testNewIniPreferences() { + System.setProperty(DUMMY, DUMMY); + try { + new IniPreferencesFactory().newIniPreferences(DUMMY); + missing(IllegalArgumentException.class); + } catch (IllegalArgumentException x) { + // + } finally { + System.getProperties().remove(DUMMY); } + } - @Test public void testSystemRoot() throws Exception - { - Preferences prefs = Preferences.systemRoot(); + @Test + public void testSystemRoot() throws Exception { + Preferences prefs = Preferences.systemRoot(); - assertNotNull(prefs); - assertEquals(IniPreferences.class, prefs.getClass()); - assertSame(prefs, Preferences.systemRoot()); - } + assertNotNull(prefs); + assertEquals(IniPreferences.class, prefs.getClass()); + assertSame(prefs, Preferences.systemRoot()); + } - @Test public void testUserRoot() throws Exception - { - Preferences prefs = Preferences.userRoot(); + @Test + public void testUserRoot() throws Exception { + Preferences prefs = Preferences.userRoot(); - assertNotNull(prefs); - assertEquals(IniPreferences.class, prefs.getClass()); - assertSame(prefs, Preferences.userRoot()); - } + assertNotNull(prefs); + assertEquals(IniPreferences.class, prefs.getClass()); + assertSame(prefs, Preferences.userRoot()); + } } diff --git a/src/test/java/org/ini4j/IniPreferencesTest.java b/src/test/java/org/ini4j/IniPreferencesTest.java index 4d2f3fe..a996c77 100755 --- a/src/test/java/org/ini4j/IniPreferencesTest.java +++ b/src/test/java/org/ini4j/IniPreferencesTest.java @@ -15,217 +15,192 @@ */ package org.ini4j; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; + +import java.util.prefs.Preferences; import org.ini4j.sample.Dwarf; import org.ini4j.sample.Dwarfs; - import org.ini4j.spi.BeanAccess; import org.ini4j.spi.BeanTool; - import org.ini4j.test.DwarfsData; import org.ini4j.test.Helper; import org.ini4j.test.TaleData; +import org.junit.Test; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; +public class IniPreferencesTest extends Ini4jCase { + private static final String DUMMY = "dummy"; + + @Test + public void testConstructor() throws Exception { + Ini ini = Helper.newDwarfsIni(); + IniPreferences prefs = new IniPreferences(ini); + + assertSame(ini, prefs.getIni()); + Helper.assertEquals(DwarfsData.dwarfs, ini.as(Dwarfs.class)); + prefs = new IniPreferences(Helper.getResourceStream(Helper.DWARFS_INI)); + Helper.assertEquals(DwarfsData.doc, newDwarf(prefs.node(Dwarfs.PROP_DOC))); + prefs = new IniPreferences(Helper.getResourceReader(Helper.DWARFS_INI)); + Helper.assertEquals(DwarfsData.happy, newDwarf(prefs.node(Dwarfs.PROP_HAPPY))); + prefs = new IniPreferences(Helper.getResourceURL(Helper.DWARFS_INI)); + Helper.assertEquals(DwarfsData.sleepy, newDwarf(prefs.node(Dwarfs.PROP_SLEEPY))); + } + + @Test + public void testMisc() throws Exception { + Ini ini = new Ini(); + IniPreferences prefs = new IniPreferences(ini); + + // do nothing, but doesn't throw exception + prefs.sync(); + prefs.flush(); + + // node & key count + assertEquals(0, prefs.keysSpi().length); + assertEquals(0, prefs.childrenNamesSpi().length); + + // childNode for new and for existing section + assertNotNull(prefs.node(Dwarfs.PROP_DOC)); + assertEquals(1, prefs.childrenNamesSpi().length); + ini.add(Dwarfs.PROP_HAPPY); + assertNotNull(prefs.node(Dwarfs.PROP_HAPPY)); + assertEquals(2, prefs.childrenNamesSpi().length); + + // SectionPreferences + IniPreferences.SectionPreferences sec = + (IniPreferences.SectionPreferences) prefs.node(Dwarfs.PROP_DOC); + + assertEquals(0, sec.childrenNamesSpi().length); + + // do nothing, but doesn't throw exception + sec.sync(); + sec.syncSpi(); + sec.flush(); + sec.flushSpi(); + + // empty + assertEquals(0, sec.keysSpi().length); + + // add one key + sec.put(Dwarf.PROP_AGE, "87"); + sec.flush(); + assertEquals("87", sec.getSpi(Dwarf.PROP_AGE)); + + // has one key + assertEquals(1, sec.keysSpi().length); + + // remove key + sec.remove(Dwarf.PROP_AGE); + sec.flush(); + + // has 0 key + assertEquals(0, sec.keysSpi().length); + sec.removeNode(); + prefs.flush(); + assertNull(ini.get(Dwarfs.PROP_DOC)); + } + + @Test + public void testTaleTree() throws Exception { + Ini ini = Helper.newTaleIni(); + IniPreferences prefs = new IniPreferences(ini); + Preferences dwarfs = prefs.node(TaleData.PROP_DWARFS); + + Helper.assertEquals(DwarfsData.doc, newDwarf(dwarfs.node(Dwarfs.PROP_DOC))); + assertArrayEquals(DwarfsData.dwarfNames, dwarfs.childrenNames()); + assertEquals(1, prefs.childrenNames().length); + } + + @Test + public void testTree() throws Exception { + Ini ini = new Ini(); + IniPreferences prefs = new IniPreferences(ini); + IniPreferences.SectionPreferences sec = + (IniPreferences.SectionPreferences) prefs.node(Dwarfs.PROP_DOC); + Preferences child = sec.node(DUMMY); + + assertNotNull(child); + assertNotNull(sec.node(DUMMY)); + assertNotNull(ini.get(Dwarfs.PROP_DOC).getChild(DUMMY)); + assertEquals(1, prefs.childrenNames().length); + } + + @SuppressWarnings("empty-statement") + @Test + public void testUnsupported() throws Exception { + Ini ini = new Ini(); + IniPreferences prefs = new IniPreferences(ini); + + try { + prefs.getSpi(DUMMY); + fail(); + } catch (UnsupportedOperationException x) { + ; + } -import org.junit.Test; + try { + prefs.putSpi(DUMMY, DUMMY); + fail(); + } catch (UnsupportedOperationException x) { + ; + } -import java.util.prefs.Preferences; + try { + prefs.removeNodeSpi(); + fail(); + } catch (UnsupportedOperationException x) { + ; + } + + try { + prefs.removeSpi(DUMMY); + fail(); + } catch (UnsupportedOperationException x) { + ; + } + } -public class IniPreferencesTest extends Ini4jCase -{ - private static final String DUMMY = "dummy"; - - @Test public void testConstructor() throws Exception - { - Ini ini = Helper.newDwarfsIni(); - IniPreferences prefs = new IniPreferences(ini); - - assertSame(ini, prefs.getIni()); - Helper.assertEquals(DwarfsData.dwarfs, ini.as(Dwarfs.class)); - prefs = new IniPreferences(Helper.getResourceStream(Helper.DWARFS_INI)); - Helper.assertEquals(DwarfsData.doc, newDwarf(prefs.node(Dwarfs.PROP_DOC))); - prefs = new IniPreferences(Helper.getResourceReader(Helper.DWARFS_INI)); - Helper.assertEquals(DwarfsData.happy, newDwarf(prefs.node(Dwarfs.PROP_HAPPY))); - prefs = new IniPreferences(Helper.getResourceURL(Helper.DWARFS_INI)); - Helper.assertEquals(DwarfsData.sleepy, newDwarf(prefs.node(Dwarfs.PROP_SLEEPY))); + private Dwarf newDwarf(Preferences node) { + return BeanTool.getInstance().proxy(Dwarf.class, new Access(node)); + } + + public static class Access implements BeanAccess { + private final Preferences _node; + + public Access(Preferences node) { + _node = node; } - @Test public void testMisc() throws Exception - { - Ini ini = new Ini(); - IniPreferences prefs = new IniPreferences(ini); - - // do nothing, but doesn't throw exception - prefs.sync(); - prefs.flush(); - - // node & key count - assertEquals(0, prefs.keysSpi().length); - assertEquals(0, prefs.childrenNamesSpi().length); - - // childNode for new and for existing section - assertNotNull(prefs.node(Dwarfs.PROP_DOC)); - assertEquals(1, prefs.childrenNamesSpi().length); - ini.add(Dwarfs.PROP_HAPPY); - assertNotNull(prefs.node(Dwarfs.PROP_HAPPY)); - assertEquals(2, prefs.childrenNamesSpi().length); - - // SectionPreferences - IniPreferences.SectionPreferences sec = (IniPreferences.SectionPreferences) prefs.node(Dwarfs.PROP_DOC); - - assertEquals(0, sec.childrenNamesSpi().length); - - // do nothing, but doesn't throw exception - sec.sync(); - sec.syncSpi(); - sec.flush(); - sec.flushSpi(); - - // empty - assertEquals(0, sec.keysSpi().length); - - // add one key - sec.put(Dwarf.PROP_AGE, "87"); - sec.flush(); - assertEquals("87", sec.getSpi(Dwarf.PROP_AGE)); - - // has one key - assertEquals(1, sec.keysSpi().length); - - // remove key - sec.remove(Dwarf.PROP_AGE); - sec.flush(); - - // has 0 key - assertEquals(0, sec.keysSpi().length); - sec.removeNode(); - prefs.flush(); - assertNull(ini.get(Dwarfs.PROP_DOC)); + public void propAdd(String propertyName, String value) { + throw new UnsupportedOperationException("Not supported yet."); } - @Test public void testTaleTree() throws Exception - { - Ini ini = Helper.newTaleIni(); - IniPreferences prefs = new IniPreferences(ini); - Preferences dwarfs = prefs.node(TaleData.PROP_DWARFS); + public String propDel(String propertyName) { + throw new UnsupportedOperationException("Not supported yet."); + } - Helper.assertEquals(DwarfsData.doc, newDwarf(dwarfs.node(Dwarfs.PROP_DOC))); - assertArrayEquals(DwarfsData.dwarfNames, dwarfs.childrenNames()); - assertEquals(1, prefs.childrenNames().length); + public String propGet(String propertyName) { + return _node.get(propertyName, null); } - @Test public void testTree() throws Exception - { - Ini ini = new Ini(); - IniPreferences prefs = new IniPreferences(ini); - IniPreferences.SectionPreferences sec = (IniPreferences.SectionPreferences) prefs.node(Dwarfs.PROP_DOC); - Preferences child = sec.node(DUMMY); - - assertNotNull(child); - assertNotNull(sec.node(DUMMY)); - assertNotNull(ini.get(Dwarfs.PROP_DOC).getChild(DUMMY)); - assertEquals(1, prefs.childrenNames().length); + public String propGet(String propertyName, int index) { + return (index == 0) ? propGet(propertyName) : null; } - @SuppressWarnings("empty-statement") - @Test public void testUnsupported() throws Exception - { - Ini ini = new Ini(); - IniPreferences prefs = new IniPreferences(ini); - - try - { - prefs.getSpi(DUMMY); - fail(); - } - catch (UnsupportedOperationException x) - { - ; - } - - try - { - prefs.putSpi(DUMMY, DUMMY); - fail(); - } - catch (UnsupportedOperationException x) - { - ; - } - - try - { - prefs.removeNodeSpi(); - fail(); - } - catch (UnsupportedOperationException x) - { - ; - } - - try - { - prefs.removeSpi(DUMMY); - fail(); - } - catch (UnsupportedOperationException x) - { - ; - } + public int propLength(String propertyName) { + return (propGet(propertyName) == null) ? 0 : 1; } - private Dwarf newDwarf(Preferences node) - { - return BeanTool.getInstance().proxy(Dwarf.class, new Access(node)); + public String propSet(String propertyName, String value) { + throw new UnsupportedOperationException("Not supported yet."); } - public static class Access implements BeanAccess - { - private final Preferences _node; - - public Access(Preferences node) - { - _node = node; - } - - public void propAdd(String propertyName, String value) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - public String propDel(String propertyName) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - public String propGet(String propertyName) - { - return _node.get(propertyName, null); - } - - public String propGet(String propertyName, int index) - { - return (index == 0) ? propGet(propertyName) : null; - } - - public int propLength(String propertyName) - { - return (propGet(propertyName) == null) ? 0 : 1; - } - - public String propSet(String propertyName, String value) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - public String propSet(String propertyName, String value, int index) - { - throw new UnsupportedOperationException("Not supported yet."); - } + public String propSet(String propertyName, String value, int index) { + throw new UnsupportedOperationException("Not supported yet."); } + } } diff --git a/src/test/java/org/ini4j/IniTest.java b/src/test/java/org/ini4j/IniTest.java index 49554ce..6ab9aaa 100755 --- a/src/test/java/org/ini4j/IniTest.java +++ b/src/test/java/org/ini4j/IniTest.java @@ -15,15 +15,8 @@ */ package org.ini4j; -import org.ini4j.sample.Dwarfs; - -import org.ini4j.test.DwarfsData; -import org.ini4j.test.Helper; - import static org.junit.Assert.assertEquals; -import org.junit.Test; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -32,215 +25,217 @@ import java.io.OutputStreamWriter; import java.io.StringReader; import java.io.StringWriter; +import org.ini4j.sample.Dwarfs; +import org.ini4j.test.DwarfsData; +import org.ini4j.test.Helper; +import org.junit.Test; -public class IniTest extends Ini4jCase -{ - private static final String COMMENT_ONLY = "# first line\n# second line\n"; - private static final String COMMENT_ONLY_VALUE = " first line\n second line"; - private static final String INI_ONE_HEADER = COMMENT_ONLY + "\n\n[section]\nkey=value\n"; - private static final String COMMENTED_OPTION = COMMENT_ONLY + "\n\n[section]\n;comment\nkey=value\n"; - private static final String MULTI = "[section]\noption=value\noption=value2\n[section]\noption=value3\noption=value4\noption=value5\n"; - - @Test public void testCommentedOption() throws Exception - { - Ini ini = new Ini(new StringReader(COMMENTED_OPTION)); - - assertEquals("comment", ini.get("section").getComment("key")); - } - - @Test public void testCommentOnly() throws Exception - { - Ini ini = new Ini(new StringReader(COMMENT_ONLY)); - - assertEquals(COMMENT_ONLY_VALUE, ini.getComment()); - } - - @Test public void testLoad() throws Exception - { - Ini ini; - - ini = new Ini(Helper.getResourceURL(Helper.DWARFS_INI)); - Helper.assertEquals(DwarfsData.dwarfs, ini.as(Dwarfs.class)); - ini = new Ini(Helper.getResourceStream(Helper.DWARFS_INI)); - Helper.assertEquals(DwarfsData.dwarfs, ini.as(Dwarfs.class)); - ini = new Ini(Helper.getResourceReader(Helper.DWARFS_INI)); - Helper.assertEquals(DwarfsData.dwarfs, ini.as(Dwarfs.class)); - ini = new Ini(Helper.getSourceFile(Helper.DWARFS_INI)); - Helper.assertEquals(DwarfsData.dwarfs, ini.as(Dwarfs.class)); - ini = new Ini(); - ini.setFile(Helper.getSourceFile(Helper.DWARFS_INI)); - ini.load(); - Helper.assertEquals(DwarfsData.dwarfs, ini.as(Dwarfs.class)); +public class IniTest extends Ini4jCase { + private static final String COMMENT_ONLY = "# first line\n# second line\n"; + private static final String COMMENT_ONLY_VALUE = " first line\n second line"; + private static final String INI_ONE_HEADER = COMMENT_ONLY + "\n\n[section]\nkey=value\n"; + private static final String COMMENTED_OPTION = + COMMENT_ONLY + "\n\n[section]\n;comment\nkey=value\n"; + private static final String MULTI = + "[section]\n" + + "option=value\n" + + "option=value2\n" + + "[section]\n" + + "option=value3\n" + + "option=value4\n" + + "option=value5\n"; + + @Test + public void testCommentedOption() throws Exception { + Ini ini = new Ini(new StringReader(COMMENTED_OPTION)); + + assertEquals("comment", ini.get("section").getComment("key")); + } + + @Test + public void testCommentOnly() throws Exception { + Ini ini = new Ini(new StringReader(COMMENT_ONLY)); + + assertEquals(COMMENT_ONLY_VALUE, ini.getComment()); + } + + @Test + public void testLoad() throws Exception { + Ini ini; + + ini = new Ini(Helper.getResourceURL(Helper.DWARFS_INI)); + Helper.assertEquals(DwarfsData.dwarfs, ini.as(Dwarfs.class)); + ini = new Ini(Helper.getResourceStream(Helper.DWARFS_INI)); + Helper.assertEquals(DwarfsData.dwarfs, ini.as(Dwarfs.class)); + ini = new Ini(Helper.getResourceReader(Helper.DWARFS_INI)); + Helper.assertEquals(DwarfsData.dwarfs, ini.as(Dwarfs.class)); + ini = new Ini(Helper.getSourceFile(Helper.DWARFS_INI)); + Helper.assertEquals(DwarfsData.dwarfs, ini.as(Dwarfs.class)); + ini = new Ini(); + ini.setFile(Helper.getSourceFile(Helper.DWARFS_INI)); + ini.load(); + Helper.assertEquals(DwarfsData.dwarfs, ini.as(Dwarfs.class)); + } + + @Test + public void testLoadException() throws Exception { + Ini ini = new Ini(); + + try { + ini.load(); + missing(FileNotFoundException.class); + } catch (FileNotFoundException x) { + // } - - @Test public void testLoadException() throws Exception - { - Ini ini = new Ini(); - - try - { - ini.load(); - missing(FileNotFoundException.class); - } - catch (FileNotFoundException x) - { - // - } + } + + @Test + public void testMulti() throws Exception { + Ini ini = new Ini(new StringReader(MULTI)); + Ini.Section sec; + + assertEquals(1, ini.length("section")); + assertEquals(5, ini.get("section", 0).length("option")); + ini.clear(); + Config cfg = new Config(); + + cfg.setMultiSection(true); + ini.setConfig(cfg); + ini.load(new StringReader(MULTI)); + assertEquals(2, ini.get("section", 0).length("option")); + assertEquals(3, ini.get("section", 1).length("option")); + + // + StringWriter writer = new StringWriter(); + + cfg.setMultiOption(false); + ini.store(writer); + ini.clear(); + cfg.setMultiOption(true); + ini.load(new StringReader(writer.toString())); + assertEquals(1, ini.get("section", 0).length("option")); + assertEquals(1, ini.get("section", 1).length("option")); + assertEquals("value2", ini.get("section", 0).get("option")); + assertEquals("value5", ini.get("section", 1).get("option")); + + // + ini.clear(); + cfg.setMultiOption(false); + ini.load(new StringReader(MULTI)); + assertEquals(1, ini.get("section", 0).length("option")); + assertEquals(1, ini.get("section", 1).length("option")); + } + + @Test + public void testOneHeaderOnly() throws Exception { + Ini ini = new Ini(new StringReader(INI_ONE_HEADER)); + + assertEquals(COMMENT_ONLY_VALUE, ini.getComment()); + } + + @Test + public void testStore() throws Exception { + Ini ini = Helper.newDwarfsIni(); + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + + ini.store(buffer); + Ini dup = new Ini(); + + dup.load(new ByteArrayInputStream(buffer.toByteArray())); + Helper.assertEquals(DwarfsData.dwarfs, dup.as(Dwarfs.class)); + buffer = new ByteArrayOutputStream(); + ini.store(new OutputStreamWriter(buffer)); + dup = new Ini(); + dup.load(new InputStreamReader(new ByteArrayInputStream(buffer.toByteArray()))); + Helper.assertEquals(DwarfsData.dwarfs, dup.as(Dwarfs.class)); + + // + File file = File.createTempFile("test", ".ini"); + + file.deleteOnExit(); + ini.setFile(file); + assertEquals(file, ini.getFile()); + ini.store(); + dup = new Ini(); + dup.setFile(file); + dup.load(); + Helper.assertEquals(DwarfsData.dwarfs, dup.as(Dwarfs.class)); + file.delete(); + } + + @Test + public void testStoreException() throws Exception { + Ini ini = new Ini(); + + try { + ini.store(); + missing(FileNotFoundException.class); + } catch (FileNotFoundException x) { + // } + } - @Test public void testMulti() throws Exception - { - Ini ini = new Ini(new StringReader(MULTI)); - Ini.Section sec; - - assertEquals(1, ini.length("section")); - assertEquals(5, ini.get("section", 0).length("option")); - ini.clear(); - Config cfg = new Config(); - - cfg.setMultiSection(true); - ini.setConfig(cfg); - ini.load(new StringReader(MULTI)); - assertEquals(2, ini.get("section", 0).length("option")); - assertEquals(3, ini.get("section", 1).length("option")); - - // - StringWriter writer = new StringWriter(); - - cfg.setMultiOption(false); - ini.store(writer); - ini.clear(); - cfg.setMultiOption(true); - ini.load(new StringReader(writer.toString())); - assertEquals(1, ini.get("section", 0).length("option")); - assertEquals(1, ini.get("section", 1).length("option")); - assertEquals("value2", ini.get("section", 0).get("option")); - assertEquals("value5", ini.get("section", 1).get("option")); - - // - ini.clear(); - cfg.setMultiOption(false); - ini.load(new StringReader(MULTI)); - assertEquals(1, ini.get("section", 0).length("option")); - assertEquals(1, ini.get("section", 1).length("option")); - } + @Test + public void testWithComment() throws Exception { + Ini ini = new Ini(); - @Test public void testOneHeaderOnly() throws Exception - { - Ini ini = new Ini(new StringReader(INI_ONE_HEADER)); - - assertEquals(COMMENT_ONLY_VALUE, ini.getComment()); + ini.load(Helper.getResourceStream(Helper.DWARFS_INI)); + assertNotNull(ini.getComment()); + for (Ini.Section sec : ini.values()) { + assertNotNull(ini.getComment(sec.getName())); } - - @Test public void testStore() throws Exception - { - Ini ini = Helper.newDwarfsIni(); - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - - ini.store(buffer); - Ini dup = new Ini(); - - dup.load(new ByteArrayInputStream(buffer.toByteArray())); - Helper.assertEquals(DwarfsData.dwarfs, dup.as(Dwarfs.class)); - buffer = new ByteArrayOutputStream(); - ini.store(new OutputStreamWriter(buffer)); - dup = new Ini(); - dup.load(new InputStreamReader(new ByteArrayInputStream(buffer.toByteArray()))); - Helper.assertEquals(DwarfsData.dwarfs, dup.as(Dwarfs.class)); - - // - File file = File.createTempFile("test", ".ini"); - - file.deleteOnExit(); - ini.setFile(file); - assertEquals(file, ini.getFile()); - ini.store(); - dup = new Ini(); - dup.setFile(file); - dup.load(); - Helper.assertEquals(DwarfsData.dwarfs, dup.as(Dwarfs.class)); - file.delete(); + } + + @Test + public void testWithoutComment() throws Exception { + Ini ini = new Ini(); + Config cfg = new Config(); + + cfg.setComment(false); + ini.setConfig(cfg); + ini.load(Helper.getResourceStream(Helper.DWARFS_INI)); + assertNull(ini.getComment()); + for (Ini.Section sec : ini.values()) { + assertNull(ini.getComment(sec.getName())); } - @Test public void testStoreException() throws Exception - { - Ini ini = new Ini(); - - try - { - ini.store(); - missing(FileNotFoundException.class); - } - catch (FileNotFoundException x) - { - // - } + ini = new Ini(); + ini.setConfig(cfg); + ini.setComment("comment"); + Ini.Section sec = ini.add("section"); + + sec.add("option", "value"); + ini.putComment("section", "section-comment"); + StringWriter writer = new StringWriter(); + + ini.store(writer); + assertEquals("[section]\noption = value\n\n", writer.toString()); + } + + @Test + public void testWithoutHeaderComment() throws Exception { + Ini ini = new Ini(); + Config cfg = new Config(); + + cfg.setHeaderComment(false); + cfg.setComment(true); + ini.setConfig(cfg); + ini.load(Helper.getResourceStream(Helper.DWARFS_INI)); + assertNull(ini.getComment()); + for (Ini.Section sec : ini.values()) { + assertNotNull(ini.getComment(sec.getName())); } - @Test public void testWithComment() throws Exception - { - Ini ini = new Ini(); - - ini.load(Helper.getResourceStream(Helper.DWARFS_INI)); - assertNotNull(ini.getComment()); - for (Ini.Section sec : ini.values()) - { - assertNotNull(ini.getComment(sec.getName())); - } - } + ini = new Ini(); + ini.setConfig(cfg); + ini.setComment("comment"); + Ini.Section sec = ini.add("section"); - @Test public void testWithoutComment() throws Exception - { - Ini ini = new Ini(); - Config cfg = new Config(); - - cfg.setComment(false); - ini.setConfig(cfg); - ini.load(Helper.getResourceStream(Helper.DWARFS_INI)); - assertNull(ini.getComment()); - for (Ini.Section sec : ini.values()) - { - assertNull(ini.getComment(sec.getName())); - } - - ini = new Ini(); - ini.setConfig(cfg); - ini.setComment("comment"); - Ini.Section sec = ini.add("section"); - - sec.add("option", "value"); - ini.putComment("section", "section-comment"); - StringWriter writer = new StringWriter(); - - ini.store(writer); - assertEquals("[section]\noption = value\n\n", writer.toString()); - } + sec.add("option", "value"); + ini.putComment("section", "section-comment"); + StringWriter writer = new StringWriter(); - @Test public void testWithoutHeaderComment() throws Exception - { - Ini ini = new Ini(); - Config cfg = new Config(); - - cfg.setHeaderComment(false); - cfg.setComment(true); - ini.setConfig(cfg); - ini.load(Helper.getResourceStream(Helper.DWARFS_INI)); - assertNull(ini.getComment()); - for (Ini.Section sec : ini.values()) - { - assertNotNull(ini.getComment(sec.getName())); - } - - ini = new Ini(); - ini.setConfig(cfg); - ini.setComment("comment"); - Ini.Section sec = ini.add("section"); - - sec.add("option", "value"); - ini.putComment("section", "section-comment"); - StringWriter writer = new StringWriter(); - - ini.store(writer); - assertEquals("#section-comment\n[section]\noption = value\n\n", writer.toString()); - } + ini.store(writer); + assertEquals("#section-comment\n[section]\noption = value\n\n", writer.toString()); + } } diff --git a/src/test/java/org/ini4j/OptionsTest.java b/src/test/java/org/ini4j/OptionsTest.java index 85e429b..e28df25 100644 --- a/src/test/java/org/ini4j/OptionsTest.java +++ b/src/test/java/org/ini4j/OptionsTest.java @@ -15,11 +15,6 @@ */ package org.ini4j; -import org.ini4j.sample.Dwarf; - -import org.ini4j.test.DwarfsData; -import org.ini4j.test.Helper; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; @@ -27,8 +22,6 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import org.junit.Test; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -36,212 +29,203 @@ import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.StringReader; +import org.ini4j.sample.Dwarf; +import org.ini4j.test.DwarfsData; +import org.ini4j.test.Helper; +import org.junit.Test; -public class OptionsTest extends Ini4jCase -{ - private static final String[] _badOptions = { "=value\n", "\\u000d\\u000d=value\n" }; - private static final String COMMENT_ONLY = "# first line\n# second line\n"; - private static final String COMMENT_ONLY_VALUE = " first line\n second line"; - private static final String OPTIONS_ONE_HEADER = COMMENT_ONLY + "\n\nkey=value\n"; - private static final String MULTI = "option=value\noption=value2\noption=value3\noption=value4\noption=value5\n"; - - @Test public void testCommentOnly() throws Exception - { - Options opt = new Options(new StringReader(COMMENT_ONLY)); - - assertEquals(COMMENT_ONLY_VALUE, opt.getComment()); - } - - @Test public void testConfig() - { - Options opts = new Options(); - Config conf = opts.getConfig(); - - assertTrue(conf.isEmptyOption()); - assertTrue(conf.isEscape()); - assertFalse(conf.isInclude()); - assertTrue(conf.isMultiOption()); - conf = new Config(); - opts.setConfig(conf); - assertSame(conf, opts.getConfig()); - } - - @Test public void testDwarfs() throws Exception - { - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - Options happy = new Options(); - - happy.from(DwarfsData.happy); - happy.store(buffer); - Options dup = new Options(new ByteArrayInputStream(buffer.toByteArray())); - - Helper.assertEquals(DwarfsData.happy, dup.as(Dwarf.class)); - buffer = new ByteArrayOutputStream(); - happy.store(new OutputStreamWriter(buffer)); - dup = new Options(new ByteArrayInputStream(buffer.toByteArray())); - Helper.assertEquals(DwarfsData.happy, dup.as(Dwarf.class)); - File file = File.createTempFile("test", ".opt"); - - file.deleteOnExit(); - happy.setFile(file); - happy.store(); - dup = new Options(); - dup.setFile(file); - assertEquals(file, dup.getFile()); - dup.load(); - Helper.assertEquals(DwarfsData.happy, dup.as(Dwarf.class)); - file.delete(); - } - - @Test public void testLoad() throws Exception - { - Options o1 = new Options(Helper.getResourceURL(Helper.DWARFS_OPT)); - Options o2 = new Options(Helper.getResourceURL(Helper.DWARFS_OPT).openStream()); - Options o3 = new Options(new InputStreamReader(Helper.getResourceURL(Helper.DWARFS_OPT).openStream())); - Options o4 = new Options(Helper.getResourceURL(Helper.DWARFS_OPT)); - Options o5 = new Options(Helper.getSourceFile(Helper.DWARFS_OPT)); - Options o6 = new Options(); - - o6.setFile(Helper.getSourceFile(Helper.DWARFS_OPT)); - o6.load(); - Helper.assertEquals(DwarfsData.dopey, o1.as(Dwarf.class)); - Helper.assertEquals(DwarfsData.dopey, o2.as(Dwarf.class)); - Helper.assertEquals(DwarfsData.dopey, o3.as(Dwarf.class)); - Helper.assertEquals(DwarfsData.dopey, o4.as(Dwarf.class)); - Helper.assertEquals(DwarfsData.dopey, o5.as(Dwarf.class)); - Helper.assertEquals(DwarfsData.dopey, o6.as(Dwarf.class)); - } - - @Test public void testLoadException() throws Exception - { - Options opt = new Options(); - - try - { - opt.load(); - missing(FileNotFoundException.class); - } - catch (FileNotFoundException x) - { - // - } - } - - @Test public void testLowerCase() throws Exception - { - Config cfg = new Config(); - Options opts = new Options(); - - cfg.setLowerCaseOption(true); - opts.setConfig(cfg); - opts.load(new StringReader("OptIon=value\n")); - assertTrue(opts.containsKey("option")); - } - - @Test public void testMultiOption() throws Exception - { - Options opts = new Options(new StringReader(MULTI)); - - assertEquals(5, opts.length("option")); - opts.clear(); - Config cfg = new Config(); - - cfg.setMultiOption(false); - opts.setConfig(cfg); - opts.load(new StringReader(MULTI)); - assertEquals(1, opts.length("option")); - } - - @Test public void testNoEmptyOption() throws Exception - { - Config cfg = new Config(); - Options opts = new Options(); - - opts.setConfig(cfg); - try - { - opts.load(new StringReader("foo\n")); - missing(InvalidFileFormatException.class); - } - catch (InvalidFileFormatException x) - { - // - } - - cfg.setEmptyOption(true); - opts.load(new StringReader("dummy\n")); - assertTrue(opts.containsKey("dummy")); - assertNull(opts.get("dummy")); - } - - @Test public void testOneHeaderOnly() throws Exception - { - Options opt = new Options(new StringReader(OPTIONS_ONE_HEADER)); - - assertEquals(COMMENT_ONLY_VALUE, opt.getComment()); - } - - @Test - @SuppressWarnings("empty-statement") - public void testParseError() throws Exception - { - for (String s : _badOptions) - { - try - { - new Options(new ByteArrayInputStream(s.getBytes())); - fail("expected InvalidIniFormatException: " + s); - } - catch (InvalidFileFormatException x) - { - ; - } - } - } - - @Test public void testStoreException() throws Exception - { - Options opt = new Options(); - - try - { - opt.store(); - missing(FileNotFoundException.class); - } - catch (FileNotFoundException x) - { - // - } +public class OptionsTest extends Ini4jCase { + private static final String[] _badOptions = {"=value\n", "\\u000d\\u000d=value\n"}; + private static final String COMMENT_ONLY = "# first line\n# second line\n"; + private static final String COMMENT_ONLY_VALUE = " first line\n second line"; + private static final String OPTIONS_ONE_HEADER = COMMENT_ONLY + "\n\nkey=value\n"; + private static final String MULTI = + "option=value\noption=value2\noption=value3\noption=value4\noption=value5\n"; + + @Test + public void testCommentOnly() throws Exception { + Options opt = new Options(new StringReader(COMMENT_ONLY)); + + assertEquals(COMMENT_ONLY_VALUE, opt.getComment()); + } + + @Test + public void testConfig() { + Options opts = new Options(); + Config conf = opts.getConfig(); + + assertTrue(conf.isEmptyOption()); + assertTrue(conf.isEscape()); + assertFalse(conf.isInclude()); + assertTrue(conf.isMultiOption()); + conf = new Config(); + opts.setConfig(conf); + assertSame(conf, opts.getConfig()); + } + + @Test + public void testDwarfs() throws Exception { + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + Options happy = new Options(); + + happy.from(DwarfsData.happy); + happy.store(buffer); + Options dup = new Options(new ByteArrayInputStream(buffer.toByteArray())); + + Helper.assertEquals(DwarfsData.happy, dup.as(Dwarf.class)); + buffer = new ByteArrayOutputStream(); + happy.store(new OutputStreamWriter(buffer)); + dup = new Options(new ByteArrayInputStream(buffer.toByteArray())); + Helper.assertEquals(DwarfsData.happy, dup.as(Dwarf.class)); + File file = File.createTempFile("test", ".opt"); + + file.deleteOnExit(); + happy.setFile(file); + happy.store(); + dup = new Options(); + dup.setFile(file); + assertEquals(file, dup.getFile()); + dup.load(); + Helper.assertEquals(DwarfsData.happy, dup.as(Dwarf.class)); + file.delete(); + } + + @Test + public void testLoad() throws Exception { + Options o1 = new Options(Helper.getResourceURL(Helper.DWARFS_OPT)); + Options o2 = new Options(Helper.getResourceURL(Helper.DWARFS_OPT).openStream()); + Options o3 = + new Options(new InputStreamReader(Helper.getResourceURL(Helper.DWARFS_OPT).openStream())); + Options o4 = new Options(Helper.getResourceURL(Helper.DWARFS_OPT)); + Options o5 = new Options(Helper.getSourceFile(Helper.DWARFS_OPT)); + Options o6 = new Options(); + + o6.setFile(Helper.getSourceFile(Helper.DWARFS_OPT)); + o6.load(); + Helper.assertEquals(DwarfsData.dopey, o1.as(Dwarf.class)); + Helper.assertEquals(DwarfsData.dopey, o2.as(Dwarf.class)); + Helper.assertEquals(DwarfsData.dopey, o3.as(Dwarf.class)); + Helper.assertEquals(DwarfsData.dopey, o4.as(Dwarf.class)); + Helper.assertEquals(DwarfsData.dopey, o5.as(Dwarf.class)); + Helper.assertEquals(DwarfsData.dopey, o6.as(Dwarf.class)); + } + + @Test + public void testLoadException() throws Exception { + Options opt = new Options(); + + try { + opt.load(); + missing(FileNotFoundException.class); + } catch (FileNotFoundException x) { + // } - - @Test public void testWithComment() throws Exception - { - Options opts = new Options(); - - opts.load(Helper.getResourceStream(Helper.DWARFS_OPT)); - assertNotNull(opts.getComment()); + } + + @Test + public void testLowerCase() throws Exception { + Config cfg = new Config(); + Options opts = new Options(); + + cfg.setLowerCaseOption(true); + opts.setConfig(cfg); + opts.load(new StringReader("OptIon=value\n")); + assertTrue(opts.containsKey("option")); + } + + @Test + public void testMultiOption() throws Exception { + Options opts = new Options(new StringReader(MULTI)); + + assertEquals(5, opts.length("option")); + opts.clear(); + Config cfg = new Config(); + + cfg.setMultiOption(false); + opts.setConfig(cfg); + opts.load(new StringReader(MULTI)); + assertEquals(1, opts.length("option")); + } + + @Test + public void testNoEmptyOption() throws Exception { + Config cfg = new Config(); + Options opts = new Options(); + + opts.setConfig(cfg); + try { + opts.load(new StringReader("foo\n")); + missing(InvalidFileFormatException.class); + } catch (InvalidFileFormatException x) { + // } - @Test public void testWithoutComment() throws Exception - { - Options opts = new Options(); - Config cfg = new Config(); - - cfg.setComment(false); - opts.setConfig(cfg); - opts.load(Helper.getResourceStream(Helper.DWARFS_OPT)); - assertNull(opts.getComment()); + cfg.setEmptyOption(true); + opts.load(new StringReader("dummy\n")); + assertTrue(opts.containsKey("dummy")); + assertNull(opts.get("dummy")); + } + + @Test + public void testOneHeaderOnly() throws Exception { + Options opt = new Options(new StringReader(OPTIONS_ONE_HEADER)); + + assertEquals(COMMENT_ONLY_VALUE, opt.getComment()); + } + + @Test + @SuppressWarnings("empty-statement") + public void testParseError() throws Exception { + for (String s : _badOptions) { + try { + new Options(new ByteArrayInputStream(s.getBytes())); + fail("expected InvalidIniFormatException: " + s); + } catch (InvalidFileFormatException x) { + ; + } } + } - @Test public void testWithoutHeaderComment() throws Exception - { - Options opts = new Options(); - Config cfg = new Config(); + @Test + public void testStoreException() throws Exception { + Options opt = new Options(); - cfg.setComment(true); - cfg.setHeaderComment(false); - opts.setConfig(cfg); - opts.load(Helper.getResourceStream(Helper.DWARFS_OPT)); - assertNull(opts.getComment()); + try { + opt.store(); + missing(FileNotFoundException.class); + } catch (FileNotFoundException x) { + // } + } + + @Test + public void testWithComment() throws Exception { + Options opts = new Options(); + + opts.load(Helper.getResourceStream(Helper.DWARFS_OPT)); + assertNotNull(opts.getComment()); + } + + @Test + public void testWithoutComment() throws Exception { + Options opts = new Options(); + Config cfg = new Config(); + + cfg.setComment(false); + opts.setConfig(cfg); + opts.load(Helper.getResourceStream(Helper.DWARFS_OPT)); + assertNull(opts.getComment()); + } + + @Test + public void testWithoutHeaderComment() throws Exception { + Options opts = new Options(); + Config cfg = new Config(); + + cfg.setComment(true); + cfg.setHeaderComment(false); + opts.setConfig(cfg); + opts.load(Helper.getResourceStream(Helper.DWARFS_OPT)); + assertNull(opts.getComment()); + } } diff --git a/src/test/java/org/ini4j/RegTest.java b/src/test/java/org/ini4j/RegTest.java index 3b7d19b..1bd9c87 100644 --- a/src/test/java/org/ini4j/RegTest.java +++ b/src/test/java/org/ini4j/RegTest.java @@ -15,18 +15,11 @@ */ package org.ini4j; -import org.ini4j.sample.Dwarfs; - -import org.ini4j.test.DwarfsData; -import org.ini4j.test.Helper; - import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; -import org.junit.Test; - import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; @@ -36,257 +29,222 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringReader; +import org.ini4j.sample.Dwarfs; +import org.ini4j.test.DwarfsData; +import org.ini4j.test.Helper; +import org.junit.Test; -public class RegTest extends Ini4jCase -{ - private static final String DWARFS_PATH = Helper.DWARFS_REG_PATH + "\\dwarfs\\"; - - @Test public void proba() throws Exception - { - } - - @Test public void testDwarfs() throws Exception - { - Reg reg = Helper.loadDwarfsReg(); - Dwarfs dwarfs = reg.as(Dwarfs.class, DWARFS_PATH); - - assertNotNull(dwarfs); - Helper.assertEquals(DwarfsData.dwarfs, dwarfs); - } - - @Test public void testInvalidFileFormatException() throws Exception - { - try - { - new Reg(Helper.getResourceReader(Helper.DWARFS_INI)); - missing(InvalidFileFormatException.class); - } - catch (InvalidFileFormatException x) - { - // - } - } - - @Test public void testIsWindwos() - { - assertEquals(isWindows(), Reg.isWindows()); - } - - @Test public void testLoad() throws Exception - { - Reg r1 = new Reg(new InputStreamReader(Helper.getResourceStream(Helper.DWARFS_REG), "UnicodeLittle")); - Reg r2 = new Reg(Helper.getResourceStream(Helper.DWARFS_REG)); - Reg r3 = new Reg(Helper.getResourceURL(Helper.DWARFS_REG)); - File f = Helper.getSourceFile(Helper.DWARFS_REG); - Reg r4 = new Reg(f); - Reg r5 = new Reg(); - - r5.setFile(f); - r5.load(); - Helper.assertEquals(DwarfsData.dwarfs, r1.as(Dwarfs.class, DWARFS_PATH)); - Helper.assertEquals(DwarfsData.dwarfs, r2.as(Dwarfs.class, DWARFS_PATH)); - Helper.assertEquals(DwarfsData.dwarfs, r3.as(Dwarfs.class, DWARFS_PATH)); - Helper.assertEquals(DwarfsData.dwarfs, r4.as(Dwarfs.class, DWARFS_PATH)); - Helper.assertEquals(DwarfsData.dwarfs, r5.as(Dwarfs.class, DWARFS_PATH)); - assertSame(f, r4.getFile()); - } - - @Test public void testLoadFileNotFoundException() throws Exception - { - Reg reg = new Reg(); - - try - { - reg.load(); - missing(FileNotFoundException.class); - } - catch (FileNotFoundException x) - { - // - } - } - - @Test public void testLoadSave() throws Exception - { - Reg reg = new Reg(Helper.getResourceURL(Helper.TEST_REG)); - - checkLoadSave(Helper.TEST_REG, reg); - } +public class RegTest extends Ini4jCase { + private static final String DWARFS_PATH = Helper.DWARFS_REG_PATH + "\\dwarfs\\"; + + @Test + public void proba() throws Exception {} + + @Test + public void testDwarfs() throws Exception { + Reg reg = Helper.loadDwarfsReg(); + Dwarfs dwarfs = reg.as(Dwarfs.class, DWARFS_PATH); + + assertNotNull(dwarfs); + Helper.assertEquals(DwarfsData.dwarfs, dwarfs); + } + + @Test + public void testInvalidFileFormatException() throws Exception { + try { + new Reg(Helper.getResourceReader(Helper.DWARFS_INI)); + missing(InvalidFileFormatException.class); + } catch (InvalidFileFormatException x) { + // + } + } + + @Test + public void testIsWindwos() { + assertEquals(isWindows(), Reg.isWindows()); + } + + @Test + public void testLoad() throws Exception { + Reg r1 = + new Reg( + new InputStreamReader(Helper.getResourceStream(Helper.DWARFS_REG), "UnicodeLittle")); + Reg r2 = new Reg(Helper.getResourceStream(Helper.DWARFS_REG)); + Reg r3 = new Reg(Helper.getResourceURL(Helper.DWARFS_REG)); + File f = Helper.getSourceFile(Helper.DWARFS_REG); + Reg r4 = new Reg(f); + Reg r5 = new Reg(); + + r5.setFile(f); + r5.load(); + Helper.assertEquals(DwarfsData.dwarfs, r1.as(Dwarfs.class, DWARFS_PATH)); + Helper.assertEquals(DwarfsData.dwarfs, r2.as(Dwarfs.class, DWARFS_PATH)); + Helper.assertEquals(DwarfsData.dwarfs, r3.as(Dwarfs.class, DWARFS_PATH)); + Helper.assertEquals(DwarfsData.dwarfs, r4.as(Dwarfs.class, DWARFS_PATH)); + Helper.assertEquals(DwarfsData.dwarfs, r5.as(Dwarfs.class, DWARFS_PATH)); + assertSame(f, r4.getFile()); + } + + @Test + public void testLoadFileNotFoundException() throws Exception { + Reg reg = new Reg(); + + try { + reg.load(); + missing(FileNotFoundException.class); + } catch (FileNotFoundException x) { + // + } + } + + @Test + public void testLoadSave() throws Exception { + Reg reg = new Reg(Helper.getResourceURL(Helper.TEST_REG)); + + checkLoadSave(Helper.TEST_REG, reg); + } + + @Test + public void testMissingVersion() throws Exception { + try { + new Reg(new StringReader("\r\n\r\n[section]\r\n\"option\"=\"value\"")); + missing(InvalidFileFormatException.class); + } catch (InvalidFileFormatException x) { + // + } + } + + @Test + public void testNonWindwosExec() throws Exception { + if (isSkip(isWindows(), "testNonWindwosExec")) { + return; + } + + Reg reg = new Reg(); + + reg.exec(new String[] {"/bin/true"}); + try { + reg.exec(new String[] {"/bin/ls", "no such file"}); + fail("IOException expected"); + } catch (IOException x) { + assert true; + } + } + + @Test + public void testReadException() throws Exception { + if (!isWindows()) { + try { + new Reg(Reg.Hive.HKEY_CURRENT_USER.toString()); + fail("missing UnsupportedOperationException"); + } catch (UnsupportedOperationException x) { + assert true; + } + } else { + try { + new Reg("no such key"); + fail("missing IOException"); + } catch (IOException x) { + assert true; + } + } + } + + @Test + public void testReadWrite() throws Exception { + if (isSkip(!isWindows(), "testReadWrite")) { + return; + } + + Reg reg = Helper.loadDwarfsReg(); + + reg.write(); + Reg dup = new Reg(Helper.DWARFS_REG_PATH); + + Helper.assertEquals(reg.get(Helper.DWARFS_REG_PATH), dup.get(Helper.DWARFS_REG_PATH)); + Dwarfs dwarfs = dup.as(Dwarfs.class, DWARFS_PATH); + + assertNotNull(dwarfs); + Helper.assertEquals(DwarfsData.dwarfs, dwarfs); + } + + @Test + public void testStore() throws Exception { + Reg reg = Helper.loadDwarfsReg(); + File tmp = File.createTempFile(Reg.TMP_PREFIX, Reg.DEFAULT_SUFFIX); - @Test public void testMissingVersion() throws Exception - { - try - { - new Reg(new StringReader("\r\n\r\n[section]\r\n\"option\"=\"value\"")); - missing(InvalidFileFormatException.class); - } - catch (InvalidFileFormatException x) - { - // - } - } + tmp.deleteOnExit(); + reg.setFile(tmp); + reg.store(); + reg = new Reg(tmp); + Helper.assertEquals(DwarfsData.dwarfs, reg.as(Dwarfs.class, DWARFS_PATH)); + tmp.delete(); + } - @Test public void testNonWindwosExec() throws Exception - { - if (isSkip(isWindows(), "testNonWindwosExec")) - { - return; - } - - Reg reg = new Reg(); - - reg.exec(new String[] { "/bin/true" }); - try - { - reg.exec(new String[] { "/bin/ls", "no such file" }); - fail("IOException expected"); - } - catch (IOException x) - { - assert true; - } + @Test + public void testStoreFileNotFoundException() throws Exception { + try { + new Reg().store(); + missing(FileNotFoundException.class); + } catch (FileNotFoundException x) { + // } + } - @Test public void testReadException() throws Exception - { - if (!isWindows()) - { - try - { - new Reg(Reg.Hive.HKEY_CURRENT_USER.toString()); - fail("missing UnsupportedOperationException"); - } - catch (UnsupportedOperationException x) - { - assert true; - } - } - else - { - try - { - new Reg("no such key"); - fail("missing IOException"); - } - catch (IOException x) - { - assert true; - } - } + @Test + public void testUnsupportedOperatingSystem() throws Exception { + if (isSkip(isWindows(), "testUnsupportedOperatingSystem")) { + return; } - @Test public void testReadWrite() throws Exception - { - if (isSkip(!isWindows(), "testReadWrite")) - { - return; - } + Reg reg = new Reg(); - Reg reg = Helper.loadDwarfsReg(); - - reg.write(); - Reg dup = new Reg(Helper.DWARFS_REG_PATH); - - Helper.assertEquals(reg.get(Helper.DWARFS_REG_PATH), dup.get(Helper.DWARFS_REG_PATH)); - Dwarfs dwarfs = dup.as(Dwarfs.class, DWARFS_PATH); - - assertNotNull(dwarfs); - Helper.assertEquals(DwarfsData.dwarfs, dwarfs); + try { + reg.read(Helper.DWARFS_REG_PATH); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException x) { + assert true; } - @Test public void testStore() throws Exception - { - Reg reg = Helper.loadDwarfsReg(); - File tmp = File.createTempFile(Reg.TMP_PREFIX, Reg.DEFAULT_SUFFIX); - - tmp.deleteOnExit(); - reg.setFile(tmp); - reg.store(); - reg = new Reg(tmp); - Helper.assertEquals(DwarfsData.dwarfs, reg.as(Dwarfs.class, DWARFS_PATH)); - tmp.delete(); + try { + reg.write(); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException x) { + assert true; } + } - @Test public void testStoreFileNotFoundException() throws Exception - { - try - { - new Reg().store(); - missing(FileNotFoundException.class); - } - catch (FileNotFoundException x) - { - // - } + private boolean isSkip(boolean flag, String testName) { + if (!flag) { + System.out.println("Skipping " + getClass().getName() + '#' + testName); } - @Test public void testUnsupportedOperatingSystem() throws Exception - { - if (isSkip(isWindows(), "testUnsupportedOperatingSystem")) - { - return; - } - - Reg reg = new Reg(); - - try - { - reg.read(Helper.DWARFS_REG_PATH); - fail("UnsupportedOperationException expected"); - } - catch (UnsupportedOperationException x) - { - assert true; - } - - try - { - reg.write(); - fail("UnsupportedOperationException expected"); - } - catch (UnsupportedOperationException x) - { - assert true; - } - } + return flag; + } - private boolean isSkip(boolean flag, String testName) - { - if (!flag) - { - System.out.println("Skipping " + getClass().getName() + '#' + testName); - } + private boolean isWindows() { + String family = System.getProperty("os.family"); - return flag; - } + return (family != null) && family.equals("windows"); + } - private boolean isWindows() - { - String family = System.getProperty("os.family"); + private void checkLoadSave(String path, Reg reg) throws Exception { + File tmp = File.createTempFile(Reg.TMP_PREFIX, Reg.DEFAULT_SUFFIX); - return (family != null) && family.equals("windows"); - } + tmp.deleteOnExit(); + reg.store(new FileOutputStream(tmp)); + assertArrayEquals(read(Helper.getResourceStream(path)), read(new FileInputStream(tmp))); + } - private void checkLoadSave(String path, Reg reg) throws Exception - { - File tmp = File.createTempFile(Reg.TMP_PREFIX, Reg.DEFAULT_SUFFIX); + private byte[] read(InputStream input) throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buff = new byte[81912]; + int n; - tmp.deleteOnExit(); - reg.store(new FileOutputStream(tmp)); - assertArrayEquals(read(Helper.getResourceStream(path)), read(new FileInputStream(tmp))); + while ((n = input.read(buff)) >= 0) { + out.write(buff, 0, n); } - private byte[] read(InputStream input) throws Exception - { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - byte[] buff = new byte[81912]; - int n; - - while ((n = input.read(buff)) >= 0) - { - out.write(buff, 0, n); - } - - return out.toByteArray(); - } + return out.toByteArray(); + } } diff --git a/src/test/java/org/ini4j/WiniTest.java b/src/test/java/org/ini4j/WiniTest.java index daa0342..a8e482b 100644 --- a/src/test/java/org/ini4j/WiniTest.java +++ b/src/test/java/org/ini4j/WiniTest.java @@ -15,118 +15,108 @@ */ package org.ini4j; -import org.ini4j.spi.WinEscapeToolTest; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import org.junit.Test; - import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.Reader; - import java.net.URL; +import org.ini4j.spi.WinEscapeToolTest; +import org.junit.Test; -public class WiniTest extends Ini4jCase -{ - @Test public void testConstructors() throws Exception - { - File f = File.createTempFile("wini", "test"); - - f.deleteOnExit(); - assertTrue(new WiniHelper(new FileInputStream(f)).isOK()); - assertTrue(new WiniHelper(new FileReader(f)).isOK()); - assertTrue(new WiniHelper(f).isOK()); - assertTrue(new WiniHelper(f.toURI().toURL()).isOK()); +public class WiniTest extends Ini4jCase { + @Test + public void testConstructors() throws Exception { + File f = File.createTempFile("wini", "test"); + + f.deleteOnExit(); + assertTrue(new WiniHelper(new FileInputStream(f)).isOK()); + assertTrue(new WiniHelper(new FileReader(f)).isOK()); + assertTrue(new WiniHelper(f).isOK()); + assertTrue(new WiniHelper(f.toURI().toURL()).isOK()); + } + + @Test + public void testDefaults() { + Wini wini = new Wini(); + Config cfg = wini.getConfig(); + + assertTrue(cfg.isGlobalSection()); + assertTrue(cfg.isEmptyOption()); + assertFalse(cfg.isMultiOption()); + assertFalse(cfg.isEscape()); + } + + @Test + public void testEscape() { + Wini instance = new Wini(); + + assertEquals(WinEscapeToolTest.ESCAPE1, instance.escape(WinEscapeToolTest.VALUE1)); + assertEquals(WinEscapeToolTest.ESCAPE2, instance.escape(WinEscapeToolTest.VALUE2)); + assertEquals(WinEscapeToolTest.ESCAPE3, instance.escape(WinEscapeToolTest.VALUE3)); + assertEquals(WinEscapeToolTest.ESCAPE4, instance.escape(WinEscapeToolTest.VALUE4)); + assertEquals(WinEscapeToolTest.ESCAPE5, instance.escape(WinEscapeToolTest.VALUE5)); + } + + @Test + public void testUnescape() throws Exception { + Wini instance = new Wini(); + + assertEquals(WinEscapeToolTest.VALUE1, instance.unescape(WinEscapeToolTest.ESCAPE1)); + assertEquals(WinEscapeToolTest.VALUE2, instance.unescape(WinEscapeToolTest.ESCAPE2)); + assertEquals(WinEscapeToolTest.VALUE3, instance.unescape(WinEscapeToolTest.ESCAPE3)); + assertEquals(WinEscapeToolTest.VALUE4, instance.unescape(WinEscapeToolTest.ESCAPE4)); + assertEquals(WinEscapeToolTest.VALUE5, instance.unescape(WinEscapeToolTest.ESCAPE5)); + assertEquals("=", instance.unescape("\\=")); + assertEquals("xAx", instance.unescape("x\\o101x")); + } + + private static class WiniHelper extends Wini { + private boolean _ok; + + public WiniHelper(Reader input) throws IOException, InvalidFileFormatException { + super(input); } - @Test public void testDefaults() - { - Wini wini = new Wini(); - Config cfg = wini.getConfig(); + public WiniHelper(InputStream input) throws IOException, InvalidFileFormatException { + super(input); + } + + public WiniHelper(URL input) throws IOException, InvalidFileFormatException { + super(input); + } - assertTrue(cfg.isGlobalSection()); - assertTrue(cfg.isEmptyOption()); - assertFalse(cfg.isMultiOption()); - assertFalse(cfg.isEscape()); + public WiniHelper(File input) throws IOException, InvalidFileFormatException { + super(input); } - @Test public void testEscape() - { - Wini instance = new Wini(); + public boolean isOK() { + return _ok; + } + + @Override + public void load(InputStream input) throws IOException, InvalidFileFormatException { + _ok = true; + } - assertEquals(WinEscapeToolTest.ESCAPE1, instance.escape(WinEscapeToolTest.VALUE1)); - assertEquals(WinEscapeToolTest.ESCAPE2, instance.escape(WinEscapeToolTest.VALUE2)); - assertEquals(WinEscapeToolTest.ESCAPE3, instance.escape(WinEscapeToolTest.VALUE3)); - assertEquals(WinEscapeToolTest.ESCAPE4, instance.escape(WinEscapeToolTest.VALUE4)); - assertEquals(WinEscapeToolTest.ESCAPE5, instance.escape(WinEscapeToolTest.VALUE5)); + @Override + public void load(Reader input) throws IOException, InvalidFileFormatException { + _ok = true; } - @Test public void testUnescape() throws Exception - { - Wini instance = new Wini(); - - assertEquals(WinEscapeToolTest.VALUE1, instance.unescape(WinEscapeToolTest.ESCAPE1)); - assertEquals(WinEscapeToolTest.VALUE2, instance.unescape(WinEscapeToolTest.ESCAPE2)); - assertEquals(WinEscapeToolTest.VALUE3, instance.unescape(WinEscapeToolTest.ESCAPE3)); - assertEquals(WinEscapeToolTest.VALUE4, instance.unescape(WinEscapeToolTest.ESCAPE4)); - assertEquals(WinEscapeToolTest.VALUE5, instance.unescape(WinEscapeToolTest.ESCAPE5)); - assertEquals("=", instance.unescape("\\=")); - assertEquals("xAx", instance.unescape("x\\o101x")); + @Override + public void load(File input) throws IOException, InvalidFileFormatException { + _ok = true; } - private static class WiniHelper extends Wini - { - private boolean _ok; - - public WiniHelper(Reader input) throws IOException, InvalidFileFormatException - { - super(input); - } - - public WiniHelper(InputStream input) throws IOException, InvalidFileFormatException - { - super(input); - } - - public WiniHelper(URL input) throws IOException, InvalidFileFormatException - { - super(input); - } - - public WiniHelper(File input) throws IOException, InvalidFileFormatException - { - super(input); - } - - public boolean isOK() - { - return _ok; - } - - @Override public void load(InputStream input) throws IOException, InvalidFileFormatException - { - _ok = true; - } - - @Override public void load(Reader input) throws IOException, InvalidFileFormatException - { - _ok = true; - } - - @Override public void load(File input) throws IOException, InvalidFileFormatException - { - _ok = true; - } - - @Override public void load(URL input) throws IOException, InvalidFileFormatException - { - _ok = true; - } + @Override + public void load(URL input) throws IOException, InvalidFileFormatException { + _ok = true; } + } } diff --git a/src/test/java/org/ini4j/demo/Demo.java b/src/test/java/org/ini4j/demo/Demo.java index 016d022..d7becd4 100644 --- a/src/test/java/org/ini4j/demo/Demo.java +++ b/src/test/java/org/ini4j/demo/Demo.java @@ -16,17 +16,12 @@ package org.ini4j.demo; import bsh.util.JConsole; - -import org.ini4j.demo.DemoModel.Mode; - import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; - import java.io.IOException; - import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; @@ -37,226 +32,195 @@ import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; +import org.ini4j.demo.DemoModel.Mode; -public class Demo -{ - private enum Command - { - MODE_INI, - MODE_REG, - MODE_OPTIONS, - LOAD_TEST_DATA, - PARSE_DATA, - CLEAR_DATA - } - - private JConsole _console; - private final Container _container; - private JTextArea _dataTextArea; - private JTextArea _helpTextArea; - private DemoModel _model; - private JTextArea _tipTextArea; - private ActionListener _actionListener = new ActionListener() - { - public void actionPerformed(ActionEvent event) - { - Command cmd = Command.valueOf(event.getActionCommand()); - - switch (cmd) - { - - case MODE_INI: - doMode(Mode.INI); - break; - - case MODE_REG: - doMode(Mode.REG); - break; - - case MODE_OPTIONS: - doMode(Mode.OPTIONS); - break; - - case LOAD_TEST_DATA: - doLoad(); - break; - - case PARSE_DATA: - doParse(); - break; - - case CLEAR_DATA: - doClear(); - break; - } - } - }; - - public Demo(Container container) - { - _container = container; - } - - public void init() - { - _container.setBackground(Color.WHITE); - _container.setLayout(new BoxLayout(_container, BoxLayout.PAGE_AXIS)); - initInputPane(); - initButtonsPane(); - initOutputPane(); - - // - new Thread(_model).start(); - doMode(Mode.INI); - } - - private void addButton(JPanel panel, String label, Command command) - { - JButton button = new JButton(); - - button.setText(label); - button.setActionCommand(command.name()); - button.addActionListener(_actionListener); - panel.add(button); - } - - private void addModeButton(ButtonGroup group, JPanel panel, Mode mode) - { - String label = mode.name().charAt(0) + mode.name().toLowerCase().substring(1); - JRadioButton button = new JRadioButton(label); - - button.setActionCommand("MODE_" + mode.name()); - button.setSelected(mode == Mode.INI); - panel.add(button); - button.addActionListener(_actionListener); - group.add(button); - } - - private void doClear() - { - try - { - _dataTextArea.setText(""); - _model.clear(); - } - catch (Exception x) - { - exceptionThrown(x); - } - } - - private void doLoad() - { - try - { - _dataTextArea.setText(_model.load()); - _console.println("Test data loaded"); - } - catch (Exception x) - { - exceptionThrown(x); +public class Demo { + private enum Command { + MODE_INI, + MODE_REG, + MODE_OPTIONS, + LOAD_TEST_DATA, + PARSE_DATA, + CLEAR_DATA + } + + private JConsole _console; + private final Container _container; + private JTextArea _dataTextArea; + private JTextArea _helpTextArea; + private DemoModel _model; + private JTextArea _tipTextArea; + private ActionListener _actionListener = + new ActionListener() { + public void actionPerformed(ActionEvent event) { + Command cmd = Command.valueOf(event.getActionCommand()); + + switch (cmd) { + case MODE_INI: + doMode(Mode.INI); + break; + + case MODE_REG: + doMode(Mode.REG); + break; + + case MODE_OPTIONS: + doMode(Mode.OPTIONS); + break; + + case LOAD_TEST_DATA: + doLoad(); + break; + + case PARSE_DATA: + doParse(); + break; + + case CLEAR_DATA: + doClear(); + break; + } } + }; + + public Demo(Container container) { + _container = container; + } + + public void init() { + _container.setBackground(Color.WHITE); + _container.setLayout(new BoxLayout(_container, BoxLayout.PAGE_AXIS)); + initInputPane(); + initButtonsPane(); + initOutputPane(); + + // + new Thread(_model).start(); + doMode(Mode.INI); + } + + private void addButton(JPanel panel, String label, Command command) { + JButton button = new JButton(); + + button.setText(label); + button.setActionCommand(command.name()); + button.addActionListener(_actionListener); + panel.add(button); + } + + private void addModeButton(ButtonGroup group, JPanel panel, Mode mode) { + String label = mode.name().charAt(0) + mode.name().toLowerCase().substring(1); + JRadioButton button = new JRadioButton(label); + + button.setActionCommand("MODE_" + mode.name()); + button.setSelected(mode == Mode.INI); + panel.add(button); + button.addActionListener(_actionListener); + group.add(button); + } + + private void doClear() { + try { + _dataTextArea.setText(""); + _model.clear(); + } catch (Exception x) { + exceptionThrown(x); } - - private void doMode(Mode mode) - { - _model.setMode(mode); - try - { - _tipTextArea.setText(_model.tip()); - } - catch (Exception x) - { - exceptionThrown(x); - } + } + + private void doLoad() { + try { + _dataTextArea.setText(_model.load()); + _console.println("Test data loaded"); + } catch (Exception x) { + exceptionThrown(x); } - - private void doParse() - { - try - { - _model.parse(_dataTextArea.getText()); - _console.println("Parse ready"); - } - catch (Exception x) - { - exceptionThrown(x); - } + } + + private void doMode(Mode mode) { + _model.setMode(mode); + try { + _tipTextArea.setText(_model.tip()); + } catch (Exception x) { + exceptionThrown(x); } - - private void exceptionThrown(Exception exception) - { - _console.error(exception); - _console.error("\n"); - exception.printStackTrace(); + } + + private void doParse() { + try { + _model.parse(_dataTextArea.getText()); + _console.println("Parse ready"); + } catch (Exception x) { + exceptionThrown(x); } - - private void initButtonsPane() - { - JPanel buttons = new JPanel(); - - buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS)); - buttons.setBackground(Color.WHITE); - buttons.add(new JLabel("Mode: ")); - ButtonGroup group = new ButtonGroup(); - - addModeButton(group, buttons, Mode.INI); - addModeButton(group, buttons, Mode.REG); - addModeButton(group, buttons, Mode.OPTIONS); - buttons.add(Box.createHorizontalGlue()); - addButton(buttons, " C L E A R ", Command.CLEAR_DATA); - addButton(buttons, " L O A D ", Command.LOAD_TEST_DATA); - addButton(buttons, " P A R S E ", Command.PARSE_DATA); - _container.add(buttons); - } - - private void initInputPane() - { - JTabbedPane inputPane = new JTabbedPane(JTabbedPane.TOP); - - inputPane.setPreferredSize(new Dimension(Short.MAX_VALUE, Short.MAX_VALUE)); - inputPane.setBackground(Color.WHITE); - _dataTextArea = new JTextArea(); - JScrollPane sp = new JScrollPane(_dataTextArea); - - inputPane.addTab("data", sp); - _tipTextArea = new JTextArea(); - _tipTextArea.setEditable(false); - sp = new JScrollPane(_tipTextArea); - inputPane.addTab("tip", sp); - _helpTextArea = new JTextArea(); - _helpTextArea.setEditable(false); - sp = new JScrollPane(_helpTextArea); - inputPane.addTab("help", sp); -// - _container.add(inputPane); + } + + private void exceptionThrown(Exception exception) { + _console.error(exception); + _console.error("\n"); + exception.printStackTrace(); + } + + private void initButtonsPane() { + JPanel buttons = new JPanel(); + + buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS)); + buttons.setBackground(Color.WHITE); + buttons.add(new JLabel("Mode: ")); + ButtonGroup group = new ButtonGroup(); + + addModeButton(group, buttons, Mode.INI); + addModeButton(group, buttons, Mode.REG); + addModeButton(group, buttons, Mode.OPTIONS); + buttons.add(Box.createHorizontalGlue()); + addButton(buttons, " C L E A R ", Command.CLEAR_DATA); + addButton(buttons, " L O A D ", Command.LOAD_TEST_DATA); + addButton(buttons, " P A R S E ", Command.PARSE_DATA); + _container.add(buttons); + } + + private void initInputPane() { + JTabbedPane inputPane = new JTabbedPane(JTabbedPane.TOP); + + inputPane.setPreferredSize(new Dimension(Short.MAX_VALUE, Short.MAX_VALUE)); + inputPane.setBackground(Color.WHITE); + _dataTextArea = new JTextArea(); + JScrollPane sp = new JScrollPane(_dataTextArea); + + inputPane.addTab("data", sp); + _tipTextArea = new JTextArea(); + _tipTextArea.setEditable(false); + sp = new JScrollPane(_tipTextArea); + inputPane.addTab("tip", sp); + _helpTextArea = new JTextArea(); + _helpTextArea.setEditable(false); + sp = new JScrollPane(_helpTextArea); + inputPane.addTab("help", sp); + // + _container.add(inputPane); + } + + private void initOutputPane() { + JTabbedPane output = new JTabbedPane(JTabbedPane.BOTTOM); + JConsole console = new JConsole(); + + console.setBackground(Color.WHITE); + _model = new DemoModel(console); + _console = new JConsole(); + + output.addTab("Console", _console); + output.setBackground(Color.WHITE); + output.setPreferredSize(new Dimension(Short.MAX_VALUE, Short.MAX_VALUE)); + output.addTab("Interpreter", console); + try { + + // + _helpTextArea.setText(_model.help()); + } catch (IOException x) { + exceptionThrown(x); } - private void initOutputPane() - { - JTabbedPane output = new JTabbedPane(JTabbedPane.BOTTOM); - JConsole console = new JConsole(); - - console.setBackground(Color.WHITE); - _model = new DemoModel(console); - _console = new JConsole(); - - output.addTab("Console", _console); - output.setBackground(Color.WHITE); - output.setPreferredSize(new Dimension(Short.MAX_VALUE, Short.MAX_VALUE)); - output.addTab("Interpreter", console); - try - { - - // - _helpTextArea.setText(_model.help()); - } - catch (IOException x) - { - exceptionThrown(x); - } - - // - _container.add(output); - } + // + _container.add(output); + } } diff --git a/src/test/java/org/ini4j/demo/DemoApplet.java b/src/test/java/org/ini4j/demo/DemoApplet.java index 9ef4e9c..ef23021 100644 --- a/src/test/java/org/ini4j/demo/DemoApplet.java +++ b/src/test/java/org/ini4j/demo/DemoApplet.java @@ -18,26 +18,21 @@ import javax.swing.JApplet; import javax.swing.UIManager; -public class DemoApplet extends JApplet -{ - private static final long serialVersionUID = -7269388726751989763L; +public class DemoApplet extends JApplet { + private static final long serialVersionUID = -7269388726751989763L; - public DemoApplet() - { - try - { - UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); - } - catch (Exception x) - { - x.printStackTrace(); - } + public DemoApplet() { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } catch (Exception x) { + x.printStackTrace(); } + } - @Override public void init() - { - Demo demo = new Demo(getContentPane()); + @Override + public void init() { + Demo demo = new Demo(getContentPane()); - demo.init(); - } + demo.init(); + } } diff --git a/src/test/java/org/ini4j/demo/DemoMain.java b/src/test/java/org/ini4j/demo/DemoMain.java index aa811ea..8f09006 100644 --- a/src/test/java/org/ini4j/demo/DemoMain.java +++ b/src/test/java/org/ini4j/demo/DemoMain.java @@ -16,38 +16,32 @@ package org.ini4j.demo; import java.awt.Dimension; - import javax.swing.JFrame; import javax.swing.SwingUtilities; import javax.swing.UIManager; -public class DemoMain implements Runnable -{ - private Demo _demo; - - public static void main(String[] args) - { - try - { - UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); - } - catch (Exception x) - { - x.printStackTrace(); - } +public class DemoMain implements Runnable { + private Demo _demo; - SwingUtilities.invokeLater(new DemoMain()); + public static void main(String[] args) { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } catch (Exception x) { + x.printStackTrace(); } - @Override public void run() - { - JFrame frame = new JFrame("TopLevelDemo"); + SwingUtilities.invokeLater(new DemoMain()); + } - frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - frame.setPreferredSize(new Dimension(800, 600)); - _demo = new Demo(frame.getContentPane()); - _demo.init(); - frame.pack(); - frame.setVisible(true); - } + @Override + public void run() { + JFrame frame = new JFrame("TopLevelDemo"); + + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setPreferredSize(new Dimension(800, 600)); + _demo = new Demo(frame.getContentPane()); + _demo.init(); + frame.pack(); + frame.setVisible(true); + } } diff --git a/src/test/java/org/ini4j/demo/DemoModel.java b/src/test/java/org/ini4j/demo/DemoModel.java index e462eda..7299e87 100644 --- a/src/test/java/org/ini4j/demo/DemoModel.java +++ b/src/test/java/org/ini4j/demo/DemoModel.java @@ -19,128 +19,110 @@ import bsh.EvalError; import bsh.Interpreter; import bsh.NameSpace; - -import org.ini4j.Config; -import org.ini4j.Ini; -import org.ini4j.Options; -import org.ini4j.Persistable; -import org.ini4j.Reg; - import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; +import org.ini4j.Config; +import org.ini4j.Ini; +import org.ini4j.Options; +import org.ini4j.Persistable; +import org.ini4j.Reg; -public class DemoModel implements Runnable -{ - public static enum Mode - { - INI, - REG, - OPTIONS; - } - - private Persistable _data; - private Interpreter _interpreter; - private Mode _mode = Mode.INI; - - public DemoModel(ConsoleInterface console) - { - _interpreter = new Interpreter(console); - NameSpace namespace = _interpreter.getNameSpace(); - - namespace.importPackage("org.ini4j.spi"); - namespace.importPackage("org.ini4j"); - namespace.importPackage("org.ini4j.sample"); - } - - public Object getData() - { - return _data; - } - - public Mode getMode() - { - return _mode; - } - - public void setMode(Mode mode) - { - _mode = mode; - } - - public void clear() throws EvalError - { - _interpreter.unset("data"); - } - - public String help() throws IOException - { - return readResource("help.txt"); - } - - public String load() throws IOException - { - return readResource(_mode.name().toLowerCase() + "-data.txt"); - } - - public void parse(String text) throws IOException, EvalError - { - Persistable data = newData(); - - data.load(new StringReader(text)); - _interpreter.set("data", data); - _data = data; - } - - @Override public void run() - { - _interpreter.setExitOnEOF(false); - _interpreter.run(); - } - - public String tip() throws IOException - { - return readResource(_mode.name().toLowerCase() + "-tip.txt"); +public class DemoModel implements Runnable { + public static enum Mode { + INI, + REG, + OPTIONS; + } + + private Persistable _data; + private Interpreter _interpreter; + private Mode _mode = Mode.INI; + + public DemoModel(ConsoleInterface console) { + _interpreter = new Interpreter(console); + NameSpace namespace = _interpreter.getNameSpace(); + + namespace.importPackage("org.ini4j.spi"); + namespace.importPackage("org.ini4j"); + namespace.importPackage("org.ini4j.sample"); + } + + public Object getData() { + return _data; + } + + public Mode getMode() { + return _mode; + } + + public void setMode(Mode mode) { + _mode = mode; + } + + public void clear() throws EvalError { + _interpreter.unset("data"); + } + + public String help() throws IOException { + return readResource("help.txt"); + } + + public String load() throws IOException { + return readResource(_mode.name().toLowerCase() + "-data.txt"); + } + + public void parse(String text) throws IOException, EvalError { + Persistable data = newData(); + + data.load(new StringReader(text)); + _interpreter.set("data", data); + _data = data; + } + + @Override + public void run() { + _interpreter.setExitOnEOF(false); + _interpreter.run(); + } + + public String tip() throws IOException { + return readResource(_mode.name().toLowerCase() + "-tip.txt"); + } + + private Persistable newData() { + Persistable ret = null; + + switch (_mode) { + case INI: + ret = new Ini(); + break; + + case REG: + ret = new Reg(); + break; + + case OPTIONS: + ret = new Options(); + break; } - private Persistable newData() - { - Persistable ret = null; - - switch (_mode) - { + return ret; + } - case INI: - ret = new Ini(); - break; + private String readResource(String path) throws IOException { + InputStream in = getClass().getResourceAsStream(path); + Reader reader = new InputStreamReader(in, Config.DEFAULT_FILE_ENCODING); + StringBuilder str = new StringBuilder(); + char[] buff = new char[8192]; + int n; - case REG: - ret = new Reg(); - break; - - case OPTIONS: - ret = new Options(); - break; - } - - return ret; + while ((n = reader.read(buff)) >= 0) { + str.append(buff, 0, n); } - private String readResource(String path) throws IOException - { - InputStream in = getClass().getResourceAsStream(path); - Reader reader = new InputStreamReader(in, Config.DEFAULT_FILE_ENCODING); - StringBuilder str = new StringBuilder(); - char[] buff = new char[8192]; - int n; - - while ((n = reader.read(buff)) >= 0) - { - str.append(buff, 0, n); - } - - return str.toString(); - } + return str.toString(); + } } diff --git a/src/test/java/org/ini4j/sample/BeanEventSample.java b/src/test/java/org/ini4j/sample/BeanEventSample.java index 78cd5c2..9bb1bd6 100755 --- a/src/test/java/org/ini4j/sample/BeanEventSample.java +++ b/src/test/java/org/ini4j/sample/BeanEventSample.java @@ -15,50 +15,46 @@ */ package org.ini4j.sample; -// -//| -//| --------------- -//| BeanEventSample -//| -//|BeanEventSample -//| -//| A sample that demonstrates the handling of the bound bean properties. -//| -//| This sample program expect the .ini file as a command line argument. -//| If there is no such argument, it use the {{{dwarfs.ini.html}dwarfs.ini}} file. -//| -//| Source code for bean: {{{Dwarf.java.html}Dwarf}}, -//| -// -//{ -import org.ini4j.Ini; - +// +// | +// | --------------- +// | BeanEventSample +// | +// |BeanEventSample +// | +// | A sample that demonstrates the handling of the bound bean properties. +// | +// | This sample program expect the .ini file as a command line argument. +// | If there is no such argument, it use the {{{dwarfs.ini.html}dwarfs.ini}} file. +// | +// | Source code for bean: {{{Dwarf.java.html}Dwarf}}, +// | +// +// { import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; - import java.io.FileInputStream; +import org.ini4j.Ini; -public class BeanEventSample -{ - public static final String FILENAME = "dwarfs.ini"; +public class BeanEventSample { + public static final String FILENAME = "dwarfs.ini"; - public static void main(String[] args) throws Exception - { - String filename = (args.length > 0) ? args[0] : FILENAME; - Ini ini = new Ini(new FileInputStream(filename)); - Dwarf sneezy = ini.get("sneezy").as(Dwarf.class); + public static void main(String[] args) throws Exception { + String filename = (args.length > 0) ? args[0] : FILENAME; + Ini ini = new Ini(new FileInputStream(filename)); + Dwarf sneezy = ini.get("sneezy").as(Dwarf.class); - sneezy.addPropertyChangeListener("age", new PropertyChangeListener() - { - public void propertyChange(PropertyChangeEvent event) - { - System.out.println("property " + event.getPropertyName() + " change"); - System.out.println(event.getOldValue() + " -> " + event.getNewValue()); - } - }); - System.out.println("Sneezy's age: " + sneezy.getAge()); - sneezy.setAge(44); - System.out.println("Sneezy's age: " + sneezy.getAge()); - } + sneezy.addPropertyChangeListener( + "age", + new PropertyChangeListener() { + public void propertyChange(PropertyChangeEvent event) { + System.out.println("property " + event.getPropertyName() + " change"); + System.out.println(event.getOldValue() + " -> " + event.getNewValue()); + } + }); + System.out.println("Sneezy's age: " + sneezy.getAge()); + sneezy.setAge(44); + System.out.println("Sneezy's age: " + sneezy.getAge()); + } } -//} +// } diff --git a/src/test/java/org/ini4j/sample/BeanSample.java b/src/test/java/org/ini4j/sample/BeanSample.java index 33f069b..403e7c7 100755 --- a/src/test/java/org/ini4j/sample/BeanSample.java +++ b/src/test/java/org/ini4j/sample/BeanSample.java @@ -15,41 +15,38 @@ */ package org.ini4j.sample; -// -//| -//| ---------- -//| BeanSample -//| -//|BeanSample -//| -//| Accessing the whole .ini file as Java Beans-style beans. -//| -//| This sample program expect the .ini file as a command line argument. -//| If there is no such argument, it use the {{{dwarfs.ini.html}dwarfs.ini}} file. -//| -//| Source code for beans: {{{Dwarf.java.html}Dwarf}}, -//| {{{Dwarfs.java.html}Dwarfs}} -//| -// -//{ -import org.ini4j.Ini; - +// +// | +// | ---------- +// | BeanSample +// | +// |BeanSample +// | +// | Accessing the whole .ini file as Java Beans-style beans. +// | +// | This sample program expect the .ini file as a command line argument. +// | If there is no such argument, it use the {{{dwarfs.ini.html}dwarfs.ini}} file. +// | +// | Source code for beans: {{{Dwarf.java.html}Dwarf}}, +// | {{{Dwarfs.java.html}Dwarfs}} +// | +// +// { import java.io.FileInputStream; +import org.ini4j.Ini; -public class BeanSample -{ - public static final String FILENAME = "dwarfs.ini"; +public class BeanSample { + public static final String FILENAME = "dwarfs.ini"; - public static void main(String[] args) throws Exception - { - String filename = (args.length > 0) ? args[0] : FILENAME; - Dwarfs dwarfs = new Ini(new FileInputStream(filename)).as(Dwarfs.class); - Dwarf happy = dwarfs.getHappy(); - Dwarf doc = dwarfs.getDoc(); + public static void main(String[] args) throws Exception { + String filename = (args.length > 0) ? args[0] : FILENAME; + Dwarfs dwarfs = new Ini(new FileInputStream(filename)).as(Dwarfs.class); + Dwarf happy = dwarfs.getHappy(); + Dwarf doc = dwarfs.getDoc(); - System.out.println("Happy's age: " + happy.getAge()); - doc.setAge(44); - System.out.println("Doc's age: " + doc.getAge()); - } + System.out.println("Happy's age: " + happy.getAge()); + doc.setAge(44); + System.out.println("Doc's age: " + doc.getAge()); + } } -//} +// } diff --git a/src/test/java/org/ini4j/sample/DumpSample.java b/src/test/java/org/ini4j/sample/DumpSample.java index 3ef4caf..cdf40f6 100755 --- a/src/test/java/org/ini4j/sample/DumpSample.java +++ b/src/test/java/org/ini4j/sample/DumpSample.java @@ -15,43 +15,38 @@ */ package org.ini4j.sample; -// -//| -//| ---------- -//| DumpSample -//| -//|DumpSample -//| -//| Writing the .ini file received as input to the stand output. -//| -//| This sample program expect the .ini file as a command line argument. -//| If there is no such argument, it use the {{{dwarfs.ini.html}dwarfs.ini}} file. -//| -// -//{ -import org.ini4j.Ini; - +// +// | +// | ---------- +// | DumpSample +// | +// |DumpSample +// | +// | Writing the .ini file received as input to the stand output. +// | +// | This sample program expect the .ini file as a command line argument. +// | If there is no such argument, it use the {{{dwarfs.ini.html}dwarfs.ini}} file. +// | +// +// { import java.io.FileReader; +import org.ini4j.Ini; -public class DumpSample -{ - public static final String FILENAME = "dwarfs.ini"; +public class DumpSample { + public static final String FILENAME = "dwarfs.ini"; - public static void main(String[] args) throws Exception - { - String filename = (args.length > 0) ? args[0] : FILENAME; - Ini ini = new Ini(new FileReader(filename)); + public static void main(String[] args) throws Exception { + String filename = (args.length > 0) ? args[0] : FILENAME; + Ini ini = new Ini(new FileReader(filename)); - for (Ini.Section section : ini.values()) - { - System.out.println("[" + section.getName() + "]"); - for (String option : section.keySet()) - { - System.out.println(option + " = " + section.fetch(option)); - } + for (Ini.Section section : ini.values()) { + System.out.println("[" + section.getName() + "]"); + for (String option : section.keySet()) { + System.out.println(option + " = " + section.fetch(option)); + } - System.out.println(); - } + System.out.println(); } + } } -//} +// } diff --git a/src/test/java/org/ini4j/sample/Dwarf.java b/src/test/java/org/ini4j/sample/Dwarf.java index 5ea1e2f..1799cc1 100644 --- a/src/test/java/org/ini4j/sample/Dwarf.java +++ b/src/test/java/org/ini4j/sample/Dwarf.java @@ -18,72 +18,70 @@ import java.beans.PropertyChangeListener; import java.beans.PropertyVetoException; import java.beans.VetoableChangeListener; - import java.net.URI; -// -//| -//| --------------- -//| Dwarf interface -//| -//|Dwarf interface -//| -//| This is a very simple bean interface with a few getter and setter. Some of -//| the properties are java primitive types. The <<>> property has a -//| complex type (java.net.URI). It is not a problem for \[ini4j\] to do the -//| required type conversion automatically between java.lang.String and the tpye -//| of the given property. The <<>> property is indexed, just to -//| show you may use indexed properties as well. -//| -// -//{ -public interface Dwarf -{ - String PROP_AGE = "age"; - String PROP_FORTUNE_NUMBER = "fortuneNumber"; - String PROP_HEIGHT = "height"; - String PROP_HOME_DIR = "homeDir"; - String PROP_HOME_PAGE = "homePage"; - String PROP_WEIGHT = "weight"; +// +// | +// | --------------- +// | Dwarf interface +// | +// |Dwarf interface +// | +// | This is a very simple bean interface with a few getter and setter. Some of +// | the properties are java primitive types. The <<>> property has a +// | complex type (java.net.URI). It is not a problem for \[ini4j\] to do the +// | required type conversion automatically between java.lang.String and the tpye +// | of the given property. The <<>> property is indexed, just to +// | show you may use indexed properties as well. +// | +// +// { +public interface Dwarf { + String PROP_AGE = "age"; + String PROP_FORTUNE_NUMBER = "fortuneNumber"; + String PROP_HEIGHT = "height"; + String PROP_HOME_DIR = "homeDir"; + String PROP_HOME_PAGE = "homePage"; + String PROP_WEIGHT = "weight"; - int getAge(); + int getAge(); - void setAge(int age); + void setAge(int age); - int[] getFortuneNumber(); + int[] getFortuneNumber(); - void setFortuneNumber(int[] value); + void setFortuneNumber(int[] value); - double getHeight(); + double getHeight(); - void setHeight(double height) throws PropertyVetoException; + void setHeight(double height) throws PropertyVetoException; - String getHomeDir(); + String getHomeDir(); - void setHomeDir(String dir); + void setHomeDir(String dir); - URI getHomePage(); + URI getHomePage(); - void setHomePage(URI location); + void setHomePage(URI location); - double getWeight(); + double getWeight(); - void setWeight(double weight); + void setWeight(double weight); - void addPropertyChangeListener(String property, PropertyChangeListener listener); + void addPropertyChangeListener(String property, PropertyChangeListener listener); - void addVetoableChangeListener(String property, VetoableChangeListener listener); + void addVetoableChangeListener(String property, VetoableChangeListener listener); - boolean hasAge(); + boolean hasAge(); - boolean hasHeight(); + boolean hasHeight(); - boolean hasHomePage(); + boolean hasHomePage(); - boolean hasWeight(); + boolean hasWeight(); - void removePropertyChangeListener(String property, PropertyChangeListener listener); + void removePropertyChangeListener(String property, PropertyChangeListener listener); - void removeVetoableChangeListener(String property, VetoableChangeListener listener); + void removeVetoableChangeListener(String property, VetoableChangeListener listener); } -//} +// } diff --git a/src/test/java/org/ini4j/sample/DwarfBean.java b/src/test/java/org/ini4j/sample/DwarfBean.java index c63191e..648193f 100644 --- a/src/test/java/org/ini4j/sample/DwarfBean.java +++ b/src/test/java/org/ini4j/sample/DwarfBean.java @@ -20,154 +20,151 @@ import java.beans.PropertyVetoException; import java.beans.VetoableChangeListener; import java.beans.VetoableChangeSupport; - import java.net.URI; -// -//| -//| --------------- -//| DwarfBean class -//| -//|DwarfBean class -//| -// -//{ -public class DwarfBean implements Dwarf -{ - private int _age; - private int[] _fortuneNumber; - private double _height; - private String _homeDir; - private URI _homePage; - private final PropertyChangeSupport _pcSupport; - private final VetoableChangeSupport _vcSupport; - private double _weight; - - public DwarfBean() - { - _pcSupport = new PropertyChangeSupport(this); - _vcSupport = new VetoableChangeSupport(this); - } - - @Override public int getAge() - { - return _age; - } - - @Override public void setAge(int value) - { - int old = _age; - - _age = value; - - _pcSupport.firePropertyChange(PROP_AGE, old, value); - } - - @Override public int[] getFortuneNumber() - { - return _fortuneNumber; - } - - @Override public void setFortuneNumber(int[] value) - { - _fortuneNumber = value; - } - - @Override public double getHeight() - { - return _height; - } - - @Override public void setHeight(double value) throws PropertyVetoException - { - _vcSupport.fireVetoableChange(PROP_HEIGHT, _height, value); - double old = _height; - - _height = value; - - _pcSupport.firePropertyChange(PROP_HEIGHT, old, value); - } - - @Override public String getHomeDir() - { - return _homeDir; - } - - @Override public void setHomeDir(String value) - { - String old = _homeDir; - - _homeDir = value; - - _pcSupport.firePropertyChange(PROP_HOME_DIR, old, value); - } - - @Override public URI getHomePage() - { - return _homePage; - } - - @Override public void setHomePage(URI value) - { - URI old = _homePage; - - _homePage = value; - - _pcSupport.firePropertyChange(PROP_HOME_PAGE, old, value); - } - - @Override public double getWeight() - { - return _weight; - } - - @Override public void setWeight(double value) - { - double old = _weight; - - _weight = value; - - _pcSupport.firePropertyChange(PROP_WEIGHT, old, value); - } - - @Override public void addPropertyChangeListener(String property, PropertyChangeListener listener) - { - _pcSupport.addPropertyChangeListener(property, listener); - } - - @Override public void addVetoableChangeListener(String property, VetoableChangeListener listener) - { - _vcSupport.addVetoableChangeListener(property, listener); - } - - @Override public boolean hasAge() - { - return _age != 0; - } - - @Override public boolean hasHeight() - { - return _height != 0.0; - } - - @Override public boolean hasHomePage() - { - return _homePage != null; - } +// +// | +// | --------------- +// | DwarfBean class +// | +// |DwarfBean class +// | +// +// { +public class DwarfBean implements Dwarf { + private int _age; + private int[] _fortuneNumber; + private double _height; + private String _homeDir; + private URI _homePage; + private final PropertyChangeSupport _pcSupport; + private final VetoableChangeSupport _vcSupport; + private double _weight; + + public DwarfBean() { + _pcSupport = new PropertyChangeSupport(this); + _vcSupport = new VetoableChangeSupport(this); + } + + @Override + public int getAge() { + return _age; + } + + @Override + public void setAge(int value) { + int old = _age; + + _age = value; + + _pcSupport.firePropertyChange(PROP_AGE, old, value); + } + + @Override + public int[] getFortuneNumber() { + return _fortuneNumber; + } + + @Override + public void setFortuneNumber(int[] value) { + _fortuneNumber = value; + } + + @Override + public double getHeight() { + return _height; + } + + @Override + public void setHeight(double value) throws PropertyVetoException { + _vcSupport.fireVetoableChange(PROP_HEIGHT, _height, value); + double old = _height; + + _height = value; + + _pcSupport.firePropertyChange(PROP_HEIGHT, old, value); + } + + @Override + public String getHomeDir() { + return _homeDir; + } + + @Override + public void setHomeDir(String value) { + String old = _homeDir; + + _homeDir = value; + + _pcSupport.firePropertyChange(PROP_HOME_DIR, old, value); + } + + @Override + public URI getHomePage() { + return _homePage; + } + + @Override + public void setHomePage(URI value) { + URI old = _homePage; + + _homePage = value; + + _pcSupport.firePropertyChange(PROP_HOME_PAGE, old, value); + } + + @Override + public double getWeight() { + return _weight; + } + + @Override + public void setWeight(double value) { + double old = _weight; + + _weight = value; + + _pcSupport.firePropertyChange(PROP_WEIGHT, old, value); + } + + @Override + public void addPropertyChangeListener(String property, PropertyChangeListener listener) { + _pcSupport.addPropertyChangeListener(property, listener); + } + + @Override + public void addVetoableChangeListener(String property, VetoableChangeListener listener) { + _vcSupport.addVetoableChangeListener(property, listener); + } + + @Override + public boolean hasAge() { + return _age != 0; + } + + @Override + public boolean hasHeight() { + return _height != 0.0; + } + + @Override + public boolean hasHomePage() { + return _homePage != null; + } - @Override public boolean hasWeight() - { - return _weight != 0.0; - } + @Override + public boolean hasWeight() { + return _weight != 0.0; + } - @Override public void removePropertyChangeListener(String property, PropertyChangeListener listener) - { - _pcSupport.removePropertyChangeListener(property, listener); - } - - @Override public void removeVetoableChangeListener(String property, VetoableChangeListener listener) - { - _vcSupport.removeVetoableChangeListener(property, listener); - } + @Override + public void removePropertyChangeListener(String property, PropertyChangeListener listener) { + _pcSupport.removePropertyChangeListener(property, listener); + } + + @Override + public void removeVetoableChangeListener(String property, VetoableChangeListener listener) { + _vcSupport.removeVetoableChangeListener(property, listener); + } } -//} +// } diff --git a/src/test/java/org/ini4j/sample/Dwarfs.java b/src/test/java/org/ini4j/sample/Dwarfs.java index b9f2cc7..13f9358 100644 --- a/src/test/java/org/ini4j/sample/Dwarfs.java +++ b/src/test/java/org/ini4j/sample/Dwarfs.java @@ -15,37 +15,36 @@ */ package org.ini4j.sample; -// -//| -//| --------------- -//| Dwarfs interface -//| -//|Dwarfs interface -//| -// -//{ -public interface Dwarfs -{ - String PROP_BASHFUL = "bashful"; - String PROP_DOC = "doc"; - String PROP_DOPEY = "dopey"; - String PROP_GRUMPY = "grumpy"; - String PROP_HAPPY = "happy"; - String PROP_SLEEPY = "sleepy"; - String PROP_SNEEZY = "sneezy"; - - Dwarf getBashful(); - - Dwarf getDoc(); - - Dwarf getDopey(); - - Dwarf getGrumpy(); - - Dwarf getHappy(); - - Dwarf getSleepy(); - - Dwarf getSneezy(); +// +// | +// | --------------- +// | Dwarfs interface +// | +// |Dwarfs interface +// | +// +// { +public interface Dwarfs { + String PROP_BASHFUL = "bashful"; + String PROP_DOC = "doc"; + String PROP_DOPEY = "dopey"; + String PROP_GRUMPY = "grumpy"; + String PROP_HAPPY = "happy"; + String PROP_SLEEPY = "sleepy"; + String PROP_SNEEZY = "sneezy"; + + Dwarf getBashful(); + + Dwarf getDoc(); + + Dwarf getDopey(); + + Dwarf getGrumpy(); + + Dwarf getHappy(); + + Dwarf getSleepy(); + + Dwarf getSneezy(); } -//} +// } diff --git a/src/test/java/org/ini4j/sample/DwarfsBean.java b/src/test/java/org/ini4j/sample/DwarfsBean.java index 2543ab5..9634609 100644 --- a/src/test/java/org/ini4j/sample/DwarfsBean.java +++ b/src/test/java/org/ini4j/sample/DwarfsBean.java @@ -15,93 +15,85 @@ */ package org.ini4j.sample; -// -//| -//| ---------------- -//| DwarfsBean class -//| -//|DwarfsBean class -//| -// -//{ -public class DwarfsBean implements Dwarfs -{ - private Dwarf _bashful; - private Dwarf _doc; - private Dwarf _dopey; - private Dwarf _grumpy; - private Dwarf _happy; - private Dwarf _sleepy; - private Dwarf _sneezy; +// +// | +// | ---------------- +// | DwarfsBean class +// | +// |DwarfsBean class +// | +// +// { +public class DwarfsBean implements Dwarfs { + private Dwarf _bashful; + private Dwarf _doc; + private Dwarf _dopey; + private Dwarf _grumpy; + private Dwarf _happy; + private Dwarf _sleepy; + private Dwarf _sneezy; - @Override public Dwarf getBashful() - { - return _bashful; - } + @Override + public Dwarf getBashful() { + return _bashful; + } - public void setBashful(Dwarf value) - { - _bashful = value; - } + public void setBashful(Dwarf value) { + _bashful = value; + } - @Override public Dwarf getDoc() - { - return _doc; - } + @Override + public Dwarf getDoc() { + return _doc; + } - public void setDoc(Dwarf value) - { - _doc = value; - } + public void setDoc(Dwarf value) { + _doc = value; + } - @Override public Dwarf getDopey() - { - return _dopey; - } + @Override + public Dwarf getDopey() { + return _dopey; + } - public void setDopey(Dwarf value) - { - _dopey = value; - } + public void setDopey(Dwarf value) { + _dopey = value; + } - @Override public Dwarf getGrumpy() - { - return _grumpy; - } + @Override + public Dwarf getGrumpy() { + return _grumpy; + } - public void setGrumpy(Dwarf value) - { - _grumpy = value; - } + public void setGrumpy(Dwarf value) { + _grumpy = value; + } - @Override public Dwarf getHappy() - { - return _happy; - } + @Override + public Dwarf getHappy() { + return _happy; + } - public void setHappy(Dwarf value) - { - _happy = value; - } + public void setHappy(Dwarf value) { + _happy = value; + } - @Override public Dwarf getSleepy() - { - return _sleepy; - } + @Override + public Dwarf getSleepy() { + return _sleepy; + } - public void setSleepy(Dwarf value) - { - _sleepy = value; - } + public void setSleepy(Dwarf value) { + _sleepy = value; + } - @Override public Dwarf getSneezy() - { - return _sneezy; - } + @Override + public Dwarf getSneezy() { + return _sneezy; + } - public void setSneezy(Dwarf value) - { - _sneezy = value; - } + public void setSneezy(Dwarf value) { + _sneezy = value; + } } -//} +// } diff --git a/src/test/java/org/ini4j/sample/FromSample.java b/src/test/java/org/ini4j/sample/FromSample.java index 5a80f35..37aee77 100644 --- a/src/test/java/org/ini4j/sample/FromSample.java +++ b/src/test/java/org/ini4j/sample/FromSample.java @@ -15,40 +15,37 @@ */ package org.ini4j.sample; -// -//| -//| ---------- -//| FromSample -//| -//|FromSample -//| -//| Marshall Java Beans to Ini.Section. -//| -//| This sample program expect the .ini file as a command line argument. -//| If there is no such argument, it use the {{{dwarfs.ini.html}dwarfs.ini}} file. -//| -//| Source code for beans: {{{Dwarf.java.html}Dwarf}}, -//| {{{DwarfBean.java.html}DwarfBean}} -//| -// -//{ -import org.ini4j.Ini; - +// +// | +// | ---------- +// | FromSample +// | +// |FromSample +// | +// | Marshall Java Beans to Ini.Section. +// | +// | This sample program expect the .ini file as a command line argument. +// | If there is no such argument, it use the {{{dwarfs.ini.html}dwarfs.ini}} file. +// | +// | Source code for beans: {{{Dwarf.java.html}Dwarf}}, +// | {{{DwarfBean.java.html}DwarfBean}} +// | +// +// { import java.net.URI; +import org.ini4j.Ini; -public class FromSample -{ - public static void main(String[] args) throws Exception - { - Ini ini = new Ini(); - DwarfBean doc = new DwarfBean(); +public class FromSample { + public static void main(String[] args) throws Exception { + Ini ini = new Ini(); + DwarfBean doc = new DwarfBean(); - doc.setAge(123); - doc.setHeight(111); - doc.setWeight(22.1); - doc.setHomePage(new URI("http://foo.bar")); - ini.add("doc").from(doc); - ini.store(System.out); - } + doc.setAge(123); + doc.setHeight(111); + doc.setWeight(22.1); + doc.setHomePage(new URI("http://foo.bar")); + ini.add("doc").from(doc); + ini.store(System.out); + } } -//} +// } diff --git a/src/test/java/org/ini4j/sample/IniSample.java b/src/test/java/org/ini4j/sample/IniSample.java index 378ec00..f5ea862 100755 --- a/src/test/java/org/ini4j/sample/IniSample.java +++ b/src/test/java/org/ini4j/sample/IniSample.java @@ -15,38 +15,35 @@ */ package org.ini4j.sample; -// -//| -//| --------- -//| IniSample -//| -//|IniSample -//| -//| The [ini4j] library has a simple API: the .ini file is a map of sections, while the section is a map of options. -//| Due to the Java 1.5 generics these are type safe maps. -//| -//| This sample program expect the .ini file as a command line argument. -//| If there is no such argument, it use the {{{dwarfs.ini.html}dwarfs.ini}} file. -//| -// -//{ -import org.ini4j.Ini; - +// +// | +// | --------- +// | IniSample +// | +// |IniSample +// | +// | The [ini4j] library has a simple API: the .ini file is a map of sections, while the section is +// a map of options. +// | Due to the Java 1.5 generics these are type safe maps. +// | +// | This sample program expect the .ini file as a command line argument. +// | If there is no such argument, it use the {{{dwarfs.ini.html}dwarfs.ini}} file. +// | +// +// { import java.io.FileReader; +import org.ini4j.Ini; -public class IniSample -{ - public static final String FILENAME = "dwarfs.ini"; +public class IniSample { + public static final String FILENAME = "dwarfs.ini"; - public static void main(String[] args) throws Exception - { - String filename = (args.length > 0) ? args[0] : FILENAME; - Ini ini = new Ini(new FileReader(filename)); + public static void main(String[] args) throws Exception { + String filename = (args.length > 0) ? args[0] : FILENAME; + Ini ini = new Ini(new FileReader(filename)); - for (String key : ini.get("sleepy").keySet()) - { - System.out.println("sleepy/" + key + " = " + ini.get("sleepy").fetch(key)); - } + for (String key : ini.get("sleepy").keySet()) { + System.out.println("sleepy/" + key + " = " + ini.get("sleepy").fetch(key)); } + } } -//} +// } diff --git a/src/test/java/org/ini4j/sample/ListenerSample.java b/src/test/java/org/ini4j/sample/ListenerSample.java index 7c7b864..a404e2c 100755 --- a/src/test/java/org/ini4j/sample/ListenerSample.java +++ b/src/test/java/org/ini4j/sample/ListenerSample.java @@ -15,62 +15,54 @@ */ package org.ini4j.sample; -// -//| -//| -------------- -//| ListenerSample -//| -//|ListenerSample -//| -//| This advanced sample presents the event-controlled usage. The \[ini4j\] -//| library fully supports the events defined in Preferences API. -//| -//| This sample program expect the .ini file as a command line argument. -//| If there is no such argument, it use the {{{dwarfs.ini.html}dwarfs.ini}} file. -//| -// -//{ -import org.ini4j.IniPreferences; - +// +// | +// | -------------- +// | ListenerSample +// | +// |ListenerSample +// | +// | This advanced sample presents the event-controlled usage. The \[ini4j\] +// | library fully supports the events defined in Preferences API. +// | +// | This sample program expect the .ini file as a command line argument. +// | If there is no such argument, it use the {{{dwarfs.ini.html}dwarfs.ini}} file. +// | +// +// { import java.io.FileInputStream; - import java.util.prefs.*; +import org.ini4j.IniPreferences; -public class ListenerSample -{ - public static final String FILENAME = "dwarfs.ini"; +public class ListenerSample { + public static final String FILENAME = "dwarfs.ini"; - public static void main(String[] args) throws Exception - { - String filename = (args.length > 0) ? args[0] : FILENAME; - Preferences prefs = new IniPreferences(new FileInputStream(filename)); - Listener listener = new Listener(); + public static void main(String[] args) throws Exception { + String filename = (args.length > 0) ? args[0] : FILENAME; + Preferences prefs = new IniPreferences(new FileInputStream(filename)); + Listener listener = new Listener(); - prefs.addNodeChangeListener(listener); - Preferences jerry = prefs.node("jerry"); + prefs.addNodeChangeListener(listener); + Preferences jerry = prefs.node("jerry"); - jerry.addPreferenceChangeListener(listener); - jerry.put("color", "blue"); - jerry.put("color", "gray"); - jerry.putInt("age", 2); - } + jerry.addPreferenceChangeListener(listener); + jerry.put("color", "blue"); + jerry.put("color", "gray"); + jerry.putInt("age", 2); + } - static class Listener implements NodeChangeListener, PreferenceChangeListener - { - public void childAdded(NodeChangeEvent event) - { - System.out.println("node added: " + event.getChild().name()); - } + static class Listener implements NodeChangeListener, PreferenceChangeListener { + public void childAdded(NodeChangeEvent event) { + System.out.println("node added: " + event.getChild().name()); + } - public void childRemoved(NodeChangeEvent event) - { - System.out.println("node removed: " + event.getChild().name()); - } + public void childRemoved(NodeChangeEvent event) { + System.out.println("node removed: " + event.getChild().name()); + } - public void preferenceChange(PreferenceChangeEvent event) - { - System.out.println("preference changed: " + event.getKey() + " = " + event.getNewValue()); - } + public void preferenceChange(PreferenceChangeEvent event) { + System.out.println("preference changed: " + event.getKey() + " = " + event.getNewValue()); } + } } -//} +// } diff --git a/src/test/java/org/ini4j/sample/NoImportSample.java b/src/test/java/org/ini4j/sample/NoImportSample.java index 400edea..03f425f 100755 --- a/src/test/java/org/ini4j/sample/NoImportSample.java +++ b/src/test/java/org/ini4j/sample/NoImportSample.java @@ -15,41 +15,38 @@ */ package org.ini4j.sample; -// -//| -//| -------------- -//| NoImportSample -//| -//|NoImportSample -//| -//| Using [ini4j] without class level dependency (no Java imports). You may use -//| \[ini4j\] library as full Preferences implementation for user and system -//| root. -//| -//| This sample program expect the .ini file as a command line argument. -//| If there is no such argument, it use the {{{dwarfs.ini.html}dwarfs.ini}} file. -//| -// -//{ +// +// | +// | -------------- +// | NoImportSample +// | +// |NoImportSample +// | +// | Using [ini4j] without class level dependency (no Java imports). You may use +// | \[ini4j\] library as full Preferences implementation for user and system +// | root. +// | +// | This sample program expect the .ini file as a command line argument. +// | If there is no such argument, it use the {{{dwarfs.ini.html}dwarfs.ini}} file. +// | +// +// { import java.util.prefs.Preferences; -public class NoImportSample -{ +public class NoImportSample { - static - { - System.setProperty("java.util.prefs.PreferencesFactory", "org.ini4j.IniPreferencesFactory"); + static { + System.setProperty("java.util.prefs.PreferencesFactory", "org.ini4j.IniPreferencesFactory"); - // you should set file:///... like URL as property value to work - System.setProperty("org.ini4j.prefs.user", "org/ini4j/sample/dwarfs.ini"); - } + // you should set file:///... like URL as property value to work + System.setProperty("org.ini4j.prefs.user", "org/ini4j/sample/dwarfs.ini"); + } - public static void main(String[] args) throws Exception - { - Preferences prefs = Preferences.userRoot(); + public static void main(String[] args) throws Exception { + Preferences prefs = Preferences.userRoot(); - System.out.println("grumpy/homePage: " + prefs.node("grumpy").get("homePage", null)); - System.out.println(prefs.getClass()); - } + System.out.println("grumpy/homePage: " + prefs.node("grumpy").get("homePage", null)); + System.out.println(prefs.getClass()); + } } -//} +// } diff --git a/src/test/java/org/ini4j/sample/PyReadSample.java b/src/test/java/org/ini4j/sample/PyReadSample.java index e98f878..b6c9b35 100644 --- a/src/test/java/org/ini4j/sample/PyReadSample.java +++ b/src/test/java/org/ini4j/sample/PyReadSample.java @@ -15,38 +15,35 @@ */ package org.ini4j.sample; -// -//| -//| ---------------------------------- -//| Using Python like ConfigParser API -//| -//|Using Python like ConfigParser API -//| -//| For Python programmers the simlest API to use is ConfigParser. -//| This sample presents accessing .ini files as Python ConfigParser objects. -//| -//| This sample program expect the .ini file as a command line argument. -//| If there is no such argument, it use the {{{dwarfs-py.ini.html}dwarfs-py.ini}} -//| file. -//| -// -//{ +// +// | +// | ---------------------------------- +// | Using Python like ConfigParser API +// | +// |Using Python like ConfigParser API +// | +// | For Python programmers the simlest API to use is ConfigParser. +// | This sample presents accessing .ini files as Python ConfigParser objects. +// | +// | This sample program expect the .ini file as a command line argument. +// | If there is no such argument, it use the {{{dwarfs-py.ini.html}dwarfs-py.ini}} +// | file. +// | +// +// { import org.ini4j.ConfigParser; -public class PyReadSample -{ - public static final String FILENAME = "dwarfs-py.ini"; +public class PyReadSample { + public static final String FILENAME = "dwarfs-py.ini"; - public static void main(String[] args) throws Exception - { - String filename = (args.length > 0) ? args[0] : FILENAME; - ConfigParser config = new ConfigParser(); + public static void main(String[] args) throws Exception { + String filename = (args.length > 0) ? args[0] : FILENAME; + ConfigParser config = new ConfigParser(); - config.read(filename); - for (String key : config.options("sleepy")) - { - System.out.println("sleepy/" + key + " = " + config.get("sleepy", key)); - } + config.read(filename); + for (String key : config.options("sleepy")) { + System.out.println("sleepy/" + key + " = " + config.get("sleepy", key)); } + } } -//} +// } diff --git a/src/test/java/org/ini4j/sample/ReadPrimitiveSample.java b/src/test/java/org/ini4j/sample/ReadPrimitiveSample.java index 5910b4a..8193c6c 100755 --- a/src/test/java/org/ini4j/sample/ReadPrimitiveSample.java +++ b/src/test/java/org/ini4j/sample/ReadPrimitiveSample.java @@ -15,41 +15,37 @@ */ package org.ini4j.sample; -// -//| -//| ------------------- -//| ReadPrimitiveSample -//| -//|ReadPrimitiveSample -//| -//| Reading some Java primitive type values. -//| -//| This sample program expect the .ini file as a command line argument. -//| If there is no such argument, it use the {{{dwarfs.ini.html}dwarfs.ini}} file. -//| -//{ -// -import org.ini4j.Ini; -import org.ini4j.IniPreferences; - +// +// | +// | ------------------- +// | ReadPrimitiveSample +// | +// |ReadPrimitiveSample +// | +// | Reading some Java primitive type values. +// | +// | This sample program expect the .ini file as a command line argument. +// | If there is no such argument, it use the {{{dwarfs.ini.html}dwarfs.ini}} file. +// | +// { +// import java.io.File; - import java.util.prefs.Preferences; +import org.ini4j.Ini; +import org.ini4j.IniPreferences; -public class ReadPrimitiveSample -{ - public static final String FILENAME = "dwarfs.ini"; +public class ReadPrimitiveSample { + public static final String FILENAME = "dwarfs.ini"; - public static void main(String[] args) throws Exception - { - String filename = (args.length > 0) ? args[0] : FILENAME; - Preferences prefs = new IniPreferences(new Ini(new File(filename))); - Preferences dopey = prefs.node("dopey"); - int age = dopey.getInt("age", 0); - float weight = dopey.getFloat("weight", 0); + public static void main(String[] args) throws Exception { + String filename = (args.length > 0) ? args[0] : FILENAME; + Preferences prefs = new IniPreferences(new Ini(new File(filename))); + Preferences dopey = prefs.node("dopey"); + int age = dopey.getInt("age", 0); + float weight = dopey.getFloat("weight", 0); - System.out.println("dopey/age: " + age); - System.out.println("dopey/weight: " + weight); - } + System.out.println("dopey/age: " + age); + System.out.println("dopey/weight: " + weight); + } } -//} +// } diff --git a/src/test/java/org/ini4j/sample/ReadStringSample.java b/src/test/java/org/ini4j/sample/ReadStringSample.java index cbd945b..ab77c56 100755 --- a/src/test/java/org/ini4j/sample/ReadStringSample.java +++ b/src/test/java/org/ini4j/sample/ReadStringSample.java @@ -15,37 +15,33 @@ */ package org.ini4j.sample; -// -//| -//| ---------------- -//| ReadStringSample -//| -//|ReadStringSample -//| -//| This sample presents accessing String type values. -//| -//| This sample program expect the .ini file as a command line argument. -//| If there is no such argument, it use the {{{dwarfs.ini.html}dwarfs.ini}} file. -//| -// -//{ -import org.ini4j.Ini; -import org.ini4j.IniPreferences; - +// +// | +// | ---------------- +// | ReadStringSample +// | +// |ReadStringSample +// | +// | This sample presents accessing String type values. +// | +// | This sample program expect the .ini file as a command line argument. +// | If there is no such argument, it use the {{{dwarfs.ini.html}dwarfs.ini}} file. +// | +// +// { import java.io.File; - import java.util.prefs.Preferences; +import org.ini4j.Ini; +import org.ini4j.IniPreferences; -public class ReadStringSample -{ - public static final String FILENAME = "dwarfs.ini"; +public class ReadStringSample { + public static final String FILENAME = "dwarfs.ini"; - public static void main(String[] args) throws Exception - { - String filename = (args.length > 0) ? args[0] : FILENAME; - Preferences prefs = new IniPreferences(new Ini(new File(filename))); + public static void main(String[] args) throws Exception { + String filename = (args.length > 0) ? args[0] : FILENAME; + Preferences prefs = new IniPreferences(new Ini(new File(filename))); - System.out.println("grumpy/homePage: " + prefs.node("grumpy").get("homePage", null)); - } + System.out.println("grumpy/homePage: " + prefs.node("grumpy").get("homePage", null)); + } } -//} +// } diff --git a/src/test/java/org/ini4j/sample/StreamSample.java b/src/test/java/org/ini4j/sample/StreamSample.java index 2f774eb..b0c69da 100755 --- a/src/test/java/org/ini4j/sample/StreamSample.java +++ b/src/test/java/org/ini4j/sample/StreamSample.java @@ -15,41 +15,36 @@ */ package org.ini4j.sample; -// -//| -//| ------------ -//| StreamSample -//| -//|StreamSample -//| -//| This sample demonstrates that the Preferences API may be used without a -//| filesystem access. In this case, naturally, there's no way of saving the -//| altered settings, they may only be accessed in the memory. -//| -//| This sample program expect the .ini file as a command line argument. -//| If there is no such argument, it use the {{{dwarfs.ini.html}dwarfs.ini}} file. -//| -// -//{ -import org.ini4j.IniPreferences; - +// +// | +// | ------------ +// | StreamSample +// | +// |StreamSample +// | +// | This sample demonstrates that the Preferences API may be used without a +// | filesystem access. In this case, naturally, there's no way of saving the +// | altered settings, they may only be accessed in the memory. +// | +// | This sample program expect the .ini file as a command line argument. +// | If there is no such argument, it use the {{{dwarfs.ini.html}dwarfs.ini}} file. +// | +// +// { import java.io.FileInputStream; - import java.util.prefs.Preferences; +import org.ini4j.IniPreferences; -public class StreamSample -{ - public static final String FILENAME = "dwarfs.ini"; +public class StreamSample { + public static final String FILENAME = "dwarfs.ini"; - public static void main(String[] args) throws Exception - { - String filename = (args.length > 0) ? args[0] : FILENAME; - Preferences prefs = new IniPreferences(new FileInputStream(filename)); + public static void main(String[] args) throws Exception { + String filename = (args.length > 0) ? args[0] : FILENAME; + Preferences prefs = new IniPreferences(new FileInputStream(filename)); - for (String key : prefs.node("sleepy").keys()) - { - System.out.println("sleepy/" + key + " = " + prefs.node("sleepy").get(key, null)); - } + for (String key : prefs.node("sleepy").keys()) { + System.out.println("sleepy/" + key + " = " + prefs.node("sleepy").get(key, null)); } + } } -//} +// } diff --git a/src/test/java/org/ini4j/sample/ToSample.java b/src/test/java/org/ini4j/sample/ToSample.java index 726496a..b86378e 100644 --- a/src/test/java/org/ini4j/sample/ToSample.java +++ b/src/test/java/org/ini4j/sample/ToSample.java @@ -15,40 +15,37 @@ */ package org.ini4j.sample; -// -//| -//| -------- -//| ToSample -//| -//|ToSample -//| -//| Unmarshall Java Beans from Ini.Section. -//| -//| This sample program expect the .ini file as a command line argument. -//| If there is no such argument, it use the {{{dwarfs.ini.html}dwarfs.ini}} file. -//| -//| Source code for beans: {{{Dwarf.java.html}Dwarf}}, -//| {{{DwarfBean.java.html}DwarfBean}} -//| -// -//{ -import org.ini4j.Ini; - +// +// | +// | -------- +// | ToSample +// | +// |ToSample +// | +// | Unmarshall Java Beans from Ini.Section. +// | +// | This sample program expect the .ini file as a command line argument. +// | If there is no such argument, it use the {{{dwarfs.ini.html}dwarfs.ini}} file. +// | +// | Source code for beans: {{{Dwarf.java.html}Dwarf}}, +// | {{{DwarfBean.java.html}DwarfBean}} +// | +// +// { import java.io.FileInputStream; +import org.ini4j.Ini; -public class ToSample -{ - public static final String FILENAME = "dwarfs.ini"; +public class ToSample { + public static final String FILENAME = "dwarfs.ini"; - public static void main(String[] args) throws Exception - { - String filename = (args.length > 0) ? args[0] : FILENAME; - Ini ini = new Ini(new FileInputStream(filename)); - DwarfBean happy = new DwarfBean(); + public static void main(String[] args) throws Exception { + String filename = (args.length > 0) ? args[0] : FILENAME; + Ini ini = new Ini(new FileInputStream(filename)); + DwarfBean happy = new DwarfBean(); - ini.get("happy").to(happy); - System.out.println("Happy's age: " + happy.getAge()); - System.out.println("Happy's homePage: " + happy.getHomePage()); - } + ini.get("happy").to(happy); + System.out.println("Happy's age: " + happy.getAge()); + System.out.println("Happy's homePage: " + happy.getHomePage()); + } } -//} +// } diff --git a/src/test/java/org/ini4j/sample/package-info.java b/src/test/java/org/ini4j/sample/package-info.java index f171d78..74a7124 100644 --- a/src/test/java/org/ini4j/sample/package-info.java +++ b/src/test/java/org/ini4j/sample/package-info.java @@ -14,14 +14,14 @@ * limitations under the License. */ package org.ini4j.sample; -//| -//| ------- -//| Samples -//| -//|Samples -//| -//| The simple (but useful) samples you can find here illustrate the usage of [ini4j]. -//| These are small, independent programs that may be translates and run. -//| The build process of [ini4j] guarantees compilability and runability, since no -//| distribution may be created without compiling and running these programs. -//| +// | +// | ------- +// | Samples +// | +// |Samples +// | +// | The simple (but useful) samples you can find here illustrate the usage of [ini4j]. +// | These are small, independent programs that may be translates and run. +// | The build process of [ini4j] guarantees compilability and runability, since no +// | distribution may be created without compiling and running these programs. +// | diff --git a/src/test/java/org/ini4j/spi/AbstractBeanInvocationHandlerTest.java b/src/test/java/org/ini4j/spi/AbstractBeanInvocationHandlerTest.java index d627ea4..99fd91e 100755 --- a/src/test/java/org/ini4j/spi/AbstractBeanInvocationHandlerTest.java +++ b/src/test/java/org/ini4j/spi/AbstractBeanInvocationHandlerTest.java @@ -15,12 +15,6 @@ */ package org.ini4j.spi; -import org.ini4j.Ini4jCase; - -import org.ini4j.sample.Dwarf; - -import org.ini4j.test.Helper; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -29,245 +23,234 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import org.junit.Test; - import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyVetoException; import java.beans.VetoableChangeListener; - import java.lang.reflect.Proxy; - import java.util.HashMap; import java.util.Map; +import org.ini4j.Ini4jCase; +import org.ini4j.sample.Dwarf; +import org.ini4j.test.Helper; +import org.junit.Test; -public class AbstractBeanInvocationHandlerTest extends Ini4jCase -{ - private static final String PROP_AGE = Dwarf.PROP_AGE; - private static final String PROP_HEIGHT = Dwarf.PROP_HEIGHT; - - @Test public void testGetProperty() throws Exception - { - Map map = new HashMap(); - MapBeanHandler handler = new MapBeanHandler(map); - Integer i = new Integer(23); - - map.put(PROP_AGE, "23"); - assertEquals(i, (Integer) handler.getProperty(PROP_AGE, Integer.class)); - assertTrue(handler.hasProperty(PROP_AGE)); - assertFalse(handler.hasProperty(null)); - map.put(PROP_AGE, "?."); - assertEquals(null, handler.getProperty(PROP_AGE, Integer.class)); - assertEquals("?.", (String) handler.getProperty(PROP_AGE, String.class)); - handler = new MapBeanHandler(map) - { - @Override protected boolean hasPropertySpi(String property) - { - throw new UnsupportedOperationException(); - } +public class AbstractBeanInvocationHandlerTest extends Ini4jCase { + private static final String PROP_AGE = Dwarf.PROP_AGE; + private static final String PROP_HEIGHT = Dwarf.PROP_HEIGHT; + + @Test + public void testGetProperty() throws Exception { + Map map = new HashMap(); + MapBeanHandler handler = new MapBeanHandler(map); + Integer i = new Integer(23); + + map.put(PROP_AGE, "23"); + assertEquals(i, (Integer) handler.getProperty(PROP_AGE, Integer.class)); + assertTrue(handler.hasProperty(PROP_AGE)); + assertFalse(handler.hasProperty(null)); + map.put(PROP_AGE, "?."); + assertEquals(null, handler.getProperty(PROP_AGE, Integer.class)); + assertEquals("?.", (String) handler.getProperty(PROP_AGE, String.class)); + handler = + new MapBeanHandler(map) { + @Override + protected boolean hasPropertySpi(String property) { + throw new UnsupportedOperationException(); + } }; - assertFalse(handler.hasProperty(PROP_AGE)); - } - - @Test public void testGetSetHas() throws Exception - { - Dwarf dwarf = MapBeanHandler.newBean(Dwarf.class); - - assertFalse(dwarf.hasAge()); - dwarf.setAge(23); - assertEquals(23, dwarf.getAge()); - assertNull(dwarf.getHomeDir()); - dwarf.setHomeDir("dummy"); - } - - @Test public void testMisc() throws Exception - { - Map map = new HashMap(); - MapBeanHandler handler = new MapBeanHandler(map); - Dummy dummy = (Dummy) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { Dummy.class }, handler); - - assertNull(handler.getProxy()); - - // non existend method calls - dummy.dummy(); - dummy.addDummy(); - dummy.removeDummy(); - - // boolean invoke - map.put("dummy", "true"); - assertTrue(dummy.isDummy()); - assertSame(dummy, handler.getProxy()); - - // subclass should call fire methods any time - // so null support reference should be not a problem - handler.firePropertyChange(PROP_AGE, Integer.valueOf(1), Integer.valueOf(2)); - handler.fireVetoableChange(PROP_AGE, Integer.valueOf(1), Integer.valueOf(2)); + assertFalse(handler.hasProperty(PROP_AGE)); + } + + @Test + public void testGetSetHas() throws Exception { + Dwarf dwarf = MapBeanHandler.newBean(Dwarf.class); + + assertFalse(dwarf.hasAge()); + dwarf.setAge(23); + assertEquals(23, dwarf.getAge()); + assertNull(dwarf.getHomeDir()); + dwarf.setHomeDir("dummy"); + } + + @Test + public void testMisc() throws Exception { + Map map = new HashMap(); + MapBeanHandler handler = new MapBeanHandler(map); + Dummy dummy = + (Dummy) + Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] {Dummy.class}, handler); + + assertNull(handler.getProxy()); + + // non existend method calls + dummy.dummy(); + dummy.addDummy(); + dummy.removeDummy(); + + // boolean invoke + map.put("dummy", "true"); + assertTrue(dummy.isDummy()); + assertSame(dummy, handler.getProxy()); + + // subclass should call fire methods any time + // so null support reference should be not a problem + handler.firePropertyChange(PROP_AGE, Integer.valueOf(1), Integer.valueOf(2)); + handler.fireVetoableChange(PROP_AGE, Integer.valueOf(1), Integer.valueOf(2)); + } + + @Test + public void testPropertyChangeListener() throws Exception { + class Listener implements PropertyChangeListener { + int _counter; + String _property; + PropertyChangeEvent _event; + + Listener(String property) { + _property = property; + } + + @Override + public void propertyChange(PropertyChangeEvent event) { + if (_property.equals(event.getPropertyName())) { + _counter++; + _event = event; + } + } } - @Test public void testPropertyChangeListener() throws Exception - { - class Listener implements PropertyChangeListener - { - int _counter; - String _property; - PropertyChangeEvent _event; - - Listener(String property) - { - _property = property; - } - - @Override public void propertyChange(PropertyChangeEvent event) - { - if (_property.equals(event.getPropertyName())) - { - _counter++; - _event = event; - } - } + Dwarf d = MapBeanHandler.newBean(Dwarf.class); + Listener l = new Listener(PROP_AGE); + + // test add and remove: invalid state should be OK + d.removePropertyChangeListener(PROP_AGE, l); + d.addPropertyChangeListener(PROP_AGE, l); + d.addPropertyChangeListener(PROP_AGE, l); + d.removePropertyChangeListener(PROP_AGE, l); + d.removePropertyChangeListener(PROP_AGE, l); + + // check listener call + d.setAge(23); + d.addPropertyChangeListener(PROP_AGE, l); + d.setAge(45); + assertNotNull(l._event); + assertEquals(23, ((Integer) l._event.getOldValue()).intValue()); + assertEquals(45, ((Integer) l._event.getNewValue()).intValue()); + + // check listener call again + d.setAge(2); + d.setWeight(23.4); + assertEquals(2, l._counter); + d.removePropertyChangeListener(PROP_AGE, l); + + // should not run listener + d.setAge(44); + assertEquals(2, l._counter); + + // test remove listener> invalid state should be OK + d.removePropertyChangeListener(PROP_AGE, l); + } + + @Test + public void testSetProperty() throws Exception { + Map map = new HashMap(); + MapBeanHandler handler = new MapBeanHandler(map); + + // very special case: set string property to non stirng value implies string conversion + handler.setProperty(PROP_AGE, new Integer(23), String.class); + assertEquals("23", handler.getProperty(PROP_AGE, String.class)); + } + + @Test + public void testVetoableChangeListener() throws Exception { + class HeightCheck implements VetoableChangeListener { + @Override + public void vetoableChange(PropertyChangeEvent event) throws PropertyVetoException { + if (PROP_HEIGHT.equals(event.getPropertyName())) { + if (((Double) event.getNewValue()) < 0.0) { + throw new PropertyVetoException("invalid value", event); + } } - - Dwarf d = MapBeanHandler.newBean(Dwarf.class); - Listener l = new Listener(PROP_AGE); - - // test add and remove: invalid state should be OK - d.removePropertyChangeListener(PROP_AGE, l); - d.addPropertyChangeListener(PROP_AGE, l); - d.addPropertyChangeListener(PROP_AGE, l); - d.removePropertyChangeListener(PROP_AGE, l); - d.removePropertyChangeListener(PROP_AGE, l); - - // check listener call - d.setAge(23); - d.addPropertyChangeListener(PROP_AGE, l); - d.setAge(45); - assertNotNull(l._event); - assertEquals(23, ((Integer) l._event.getOldValue()).intValue()); - assertEquals(45, ((Integer) l._event.getNewValue()).intValue()); - - // check listener call again - d.setAge(2); - d.setWeight(23.4); - assertEquals(2, l._counter); - d.removePropertyChangeListener(PROP_AGE, l); - - // should not run listener - d.setAge(44); - assertEquals(2, l._counter); - - // test remove listener> invalid state should be OK - d.removePropertyChangeListener(PROP_AGE, l); + } } - @Test public void testSetProperty() throws Exception - { - Map map = new HashMap(); - MapBeanHandler handler = new MapBeanHandler(map); - - // very special case: set string property to non stirng value implies string conversion - handler.setProperty(PROP_AGE, new Integer(23), String.class); - assertEquals("23", handler.getProperty(PROP_AGE, String.class)); + Dwarf d = MapBeanHandler.newBean(Dwarf.class); + HeightCheck l = new HeightCheck(); + + // test add and remove: invalid state should be OK + d.removeVetoableChangeListener(PROP_HEIGHT, l); + d.addVetoableChangeListener(PROP_HEIGHT, l); + d.addVetoableChangeListener(PROP_HEIGHT, l); + d.removeVetoableChangeListener(PROP_HEIGHT, l); + d.removeVetoableChangeListener(PROP_HEIGHT, l); + + // set invalid value without lsitener + d.setHeight(-2.0); + d.setHeight(33.0); + d.addVetoableChangeListener(PROP_HEIGHT, l); + + // set invalid value with listener + try { + d.setHeight(-3.4); + fail(); + } catch (PropertyVetoException x) { + assertEquals(33.0, d.getHeight(), Helper.DELTA); } - @Test public void testVetoableChangeListener() throws Exception - { - class HeightCheck implements VetoableChangeListener - { - @Override public void vetoableChange(PropertyChangeEvent event) throws PropertyVetoException - { - if (PROP_HEIGHT.equals(event.getPropertyName())) - { - if (((Double) event.getNewValue()) < 0.0) - { - throw new PropertyVetoException("invalid value", event); - } - } - } - } + // set valid value + d.setHeight(44.0); + assertEquals(44.0, d.getHeight(), Helper.DELTA); + d.removeVetoableChangeListener(PROP_HEIGHT, l); - Dwarf d = MapBeanHandler.newBean(Dwarf.class); - HeightCheck l = new HeightCheck(); - - // test add and remove: invalid state should be OK - d.removeVetoableChangeListener(PROP_HEIGHT, l); - d.addVetoableChangeListener(PROP_HEIGHT, l); - d.addVetoableChangeListener(PROP_HEIGHT, l); - d.removeVetoableChangeListener(PROP_HEIGHT, l); - d.removeVetoableChangeListener(PROP_HEIGHT, l); - - // set invalid value without lsitener - d.setHeight(-2.0); - d.setHeight(33.0); - d.addVetoableChangeListener(PROP_HEIGHT, l); - - // set invalid value with listener - try - { - d.setHeight(-3.4); - fail(); - } - catch (PropertyVetoException x) - { - assertEquals(33.0, d.getHeight(), Helper.DELTA); - } + // set invalid value without lsitener + d.setHeight(-4.0); + assertEquals(-4.0, d.getHeight(), Helper.DELTA); - // set valid value - d.setHeight(44.0); - assertEquals(44.0, d.getHeight(), Helper.DELTA); - d.removeVetoableChangeListener(PROP_HEIGHT, l); + // test remove: invalid state should be OK + d.removeVetoableChangeListener(PROP_HEIGHT, l); + } - // set invalid value without lsitener - d.setHeight(-4.0); - assertEquals(-4.0, d.getHeight(), Helper.DELTA); + static interface Dummy { + boolean isDummy(); - // test remove: invalid state should be OK - d.removeVetoableChangeListener(PROP_HEIGHT, l); - } + void addDummy(); - static interface Dummy - { - boolean isDummy(); + void dummy(); - void addDummy(); + void removeDummy(); + } - void dummy(); + static class MapBeanHandler extends AbstractBeanInvocationHandler { + private Map _map; - void removeDummy(); + MapBeanHandler(Map map) { + super(); + _map = map; } - static class MapBeanHandler extends AbstractBeanInvocationHandler - { - private Map _map; - - MapBeanHandler(Map map) - { - super(); - _map = map; - } - - protected static T newBean(Class clazz) - { - return newBean(clazz, new HashMap()); - } + protected static T newBean(Class clazz) { + return newBean(clazz, new HashMap()); + } - protected static T newBean(Class clazz, Map map) - { - return clazz.cast(Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, new MapBeanHandler(map))); - } + protected static T newBean(Class clazz, Map map) { + return clazz.cast( + Proxy.newProxyInstance( + clazz.getClassLoader(), new Class[] {clazz}, new MapBeanHandler(map))); + } - @Override protected Object getPropertySpi(String property, Class clazz) - { - return _map.get(property); - } + @Override + protected Object getPropertySpi(String property, Class clazz) { + return _map.get(property); + } - @Override protected void setPropertySpi(String property, Object value, Class clazz) - { - _map.put(property, value.toString()); - } + @Override + protected void setPropertySpi(String property, Object value, Class clazz) { + _map.put(property, value.toString()); + } - @Override protected boolean hasPropertySpi(String property) - { - return _map.containsKey(property); - } + @Override + protected boolean hasPropertySpi(String property) { + return _map.containsKey(property); } + } } diff --git a/src/test/java/org/ini4j/spi/BeanToolTest.java b/src/test/java/org/ini4j/spi/BeanToolTest.java index aeb24ae..0012f8e 100644 --- a/src/test/java/org/ini4j/spi/BeanToolTest.java +++ b/src/test/java/org/ini4j/spi/BeanToolTest.java @@ -15,15 +15,6 @@ */ package org.ini4j.spi; -import org.ini4j.BasicOptionMapGate; -import org.ini4j.Ini4jCase; - -import org.ini4j.sample.Dwarf; -import org.ini4j.sample.DwarfBean; - -import org.ini4j.test.DwarfsData; -import org.ini4j.test.Helper; - import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -32,230 +23,213 @@ import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; -import org.junit.Before; -import org.junit.Test; - import java.io.File; import java.io.IOException; - import java.net.URI; import java.net.URL; - import java.util.TimeZone; +import org.ini4j.BasicOptionMapGate; +import org.ini4j.Ini4jCase; +import org.ini4j.sample.Dwarf; +import org.ini4j.sample.DwarfBean; +import org.ini4j.test.DwarfsData; +import org.ini4j.test.Helper; +import org.junit.Before; +import org.junit.Test; -public class BeanToolTest extends Ini4jCase -{ - protected BeanTool instance; - - @Before @Override public void setUp() throws Exception - { - super.setUp(); - instance = BeanTool.getInstance(); - } - - @Test public void testInject() throws Exception - { - testInject(null); - testInject("dummy"); - } - - @Test public void testInjectIllegalArgument1() throws Exception - { - TestMap map = new TestMap(); - - try - { - instance.inject(map.newBeanAccess(), new BadBean()); - missing(IllegalArgumentException.class); - } - catch (IllegalArgumentException x) - { - // - } - } - - @Test public void testInjectIllegalArgument2() throws Exception - { - TestMap map = new TestMap(); - - map.put("name", "bad"); - try - { - instance.inject(new BadBean(), map.newBeanAccess()); - missing(IllegalArgumentException.class); - } - catch (IllegalArgumentException x) - { - // - } - } - - @SuppressWarnings("empty-statement") - @Test public void testParse() throws Exception - { - String input = "6"; - int value = 6; - - assertEquals(value, instance.parse(input, byte.class).byteValue()); - assertEquals(value, instance.parse(input, short.class).shortValue()); - assertEquals(value, instance.parse(input, int.class).intValue()); - assertEquals(value, instance.parse(input, long.class).longValue()); - assertEquals((float) value, instance.parse(input, float.class).floatValue(), Helper.DELTA); - assertEquals((double) value, instance.parse(input, double.class).doubleValue(), Helper.DELTA); - assertFalse(instance.parse(input, boolean.class)); - assertEquals('6', instance.parse(input, char.class).charValue()); - - // parse null mean zero - assertEquals(0, instance.parse(null, byte.class).byteValue()); - - // parse to null class mean exception - try - { - instance.parse(input, null); - fail(); - } - catch (IllegalArgumentException x) - { - ; - } - - // invalid primitive value mean exception - try - { - instance.parse("?", int.class); - fail(); - } - catch (IllegalArgumentException x) - { - ; - } - - // standard, but not primitive types - assertSame(input, instance.parse(input, String.class)); - assertEquals(new Character('6'), instance.parse(input, Character.class)); - assertEquals(new Byte(input), instance.parse(input, Byte.class)); - - // special values - input = "http://www.ini4j.org"; - assertEquals(new URL(input), instance.parse(input, URL.class)); - assertEquals(new URI(input), instance.parse(input, URI.class)); - assertEquals(new File(input), instance.parse(input, File.class)); - input = "Europe/Budapest"; - assertEquals(input, instance.parse(input, TimeZone.class).getID()); - input = "java.lang.String"; - assertEquals(String.class, instance.parse(input, Class.class)); - - // invalid value should throw IllegalArgumentException - try - { - instance.parse("", URL.class); - } - catch (IllegalArgumentException x) - { - ; - } +public class BeanToolTest extends Ini4jCase { + protected BeanTool instance; + + @Before + @Override + public void setUp() throws Exception { + super.setUp(); + instance = BeanTool.getInstance(); + } + + @Test + public void testInject() throws Exception { + testInject(null); + testInject("dummy"); + } + + @Test + public void testInjectIllegalArgument1() throws Exception { + TestMap map = new TestMap(); + + try { + instance.inject(map.newBeanAccess(), new BadBean()); + missing(IllegalArgumentException.class); + } catch (IllegalArgumentException x) { + // } - - @Test public void testSetGet() throws Exception - { - TestMap map = new TestMap(); - Dwarf proxy = instance.proxy(Dwarf.class, map.newBeanAccess()); - - assertNull(proxy.getHomeDir()); - assertFalse(proxy.hasHomePage()); - assertNull(proxy.getFortuneNumber()); - proxy.setAge(DwarfsData.sneezy.age); - proxy.setHeight(DwarfsData.sneezy.height); - proxy.setWeight(DwarfsData.sneezy.weight); - proxy.setHomePage(DwarfsData.sneezy.homePage); - proxy.setHomeDir(DwarfsData.sneezy.homeDir); - proxy.setFortuneNumber(DwarfsData.sneezy.fortuneNumber); - Helper.assertEquals(DwarfsData.sneezy, proxy); - assertArrayEquals(DwarfsData.sneezy.fortuneNumber, proxy.getFortuneNumber()); + } + + @Test + public void testInjectIllegalArgument2() throws Exception { + TestMap map = new TestMap(); + + map.put("name", "bad"); + try { + instance.inject(new BadBean(), map.newBeanAccess()); + missing(IllegalArgumentException.class); + } catch (IllegalArgumentException x) { + // } - - @Test public void testSingleton() throws Exception - { - assertEquals(BeanTool.class, BeanTool.getInstance().getClass()); + } + + @SuppressWarnings("empty-statement") + @Test + public void testParse() throws Exception { + String input = "6"; + int value = 6; + + assertEquals(value, instance.parse(input, byte.class).byteValue()); + assertEquals(value, instance.parse(input, short.class).shortValue()); + assertEquals(value, instance.parse(input, int.class).intValue()); + assertEquals(value, instance.parse(input, long.class).longValue()); + assertEquals((float) value, instance.parse(input, float.class).floatValue(), Helper.DELTA); + assertEquals((double) value, instance.parse(input, double.class).doubleValue(), Helper.DELTA); + assertFalse(instance.parse(input, boolean.class)); + assertEquals('6', instance.parse(input, char.class).charValue()); + + // parse null mean zero + assertEquals(0, instance.parse(null, byte.class).byteValue()); + + // parse to null class mean exception + try { + instance.parse(input, null); + fail(); + } catch (IllegalArgumentException x) { + ; } - @Test public void testZero() throws Exception - { - assertEquals(null, instance.zero(Object.class)); - assertEquals(0, instance.zero(byte.class).byteValue()); - assertEquals(0, instance.zero(short.class).shortValue()); - assertEquals(0, instance.zero(int.class).intValue()); - assertEquals(0, instance.zero(long.class).longValue()); - assertEquals(0.0f, instance.zero(float.class).floatValue(), Helper.DELTA); - assertEquals(0.0, instance.zero(double.class).doubleValue(), Helper.DELTA); - assertNotNull((instance.zero(boolean.class))); - assertFalse(instance.zero(boolean.class)); - assertEquals('\0', instance.zero(char.class).charValue()); + // invalid primitive value mean exception + try { + instance.parse("?", int.class); + fail(); + } catch (IllegalArgumentException x) { + ; } - protected void testInject(String prefix) throws Exception - { - String p = (prefix == null) ? "" : prefix; - Dwarf bean = new DwarfBean(); - - bean.setAge(23); - bean.setHeight(5.3); - URI uri = new URI("http://www.ini4j.org"); - - bean.setHomePage(uri); - String dir = "/home/happy"; - - bean.setHomeDir(dir); - bean.setFortuneNumber(new int[] { 1, 2, 3 }); - TestMap map = new TestMap(); - - instance.inject(map.newBeanAccess(prefix), bean); - assertEquals(6, map.size()); - assertEquals("23", map.get(p + Dwarf.PROP_AGE)); - assertEquals("5.3", map.get(p + Dwarf.PROP_HEIGHT)); - assertEquals(uri.toString(), map.get(p + Dwarf.PROP_HOME_PAGE)); - assertEquals(dir, map.get(p + Dwarf.PROP_HOME_DIR)); - assertEquals(3, map.length(p + Dwarf.PROP_FORTUNE_NUMBER)); - assertEquals("1", map.get(p + Dwarf.PROP_FORTUNE_NUMBER, 0)); - assertEquals("2", map.get(p + Dwarf.PROP_FORTUNE_NUMBER, 1)); - assertEquals("3", map.get(p + Dwarf.PROP_FORTUNE_NUMBER, 2)); - bean.setAge(0); - bean.setHeight(0); - bean.setHomePage(null); - instance.inject(bean, map.newBeanAccess(prefix)); - assertEquals(23, bean.getAge()); - assertEquals(5.3, bean.getHeight(), Helper.DELTA); - assertEquals(uri, bean.getHomePage()); - assertEquals(dir, bean.getHomeDir()); - assertArrayEquals(new int[] { 1, 2, 3 }, bean.getFortuneNumber()); - - // - // bean interface - // - Dwarf proxy = instance.proxy(Dwarf.class, map.newBeanAccess(prefix)); - - assertEquals(23, proxy.getAge()); - assertEquals(5.3, proxy.getHeight(), Helper.DELTA); - assertEquals(uri, proxy.getHomePage()); - assertEquals(dir, proxy.getHomeDir()); - assertArrayEquals(new int[] { 1, 2, 3 }, proxy.getFortuneNumber()); + // standard, but not primitive types + assertSame(input, instance.parse(input, String.class)); + assertEquals(new Character('6'), instance.parse(input, Character.class)); + assertEquals(new Byte(input), instance.parse(input, Byte.class)); + + // special values + input = "http://www.ini4j.org"; + assertEquals(new URL(input), instance.parse(input, URL.class)); + assertEquals(new URI(input), instance.parse(input, URI.class)); + assertEquals(new File(input), instance.parse(input, File.class)); + input = "Europe/Budapest"; + assertEquals(input, instance.parse(input, TimeZone.class).getID()); + input = "java.lang.String"; + assertEquals(String.class, instance.parse(input, Class.class)); + + // invalid value should throw IllegalArgumentException + try { + instance.parse("", URL.class); + } catch (IllegalArgumentException x) { + ; } - - static class TestMap extends BasicOptionMapGate - { - private static final long serialVersionUID = 4818386732025655044L; + } + + @Test + public void testSetGet() throws Exception { + TestMap map = new TestMap(); + Dwarf proxy = instance.proxy(Dwarf.class, map.newBeanAccess()); + + assertNull(proxy.getHomeDir()); + assertFalse(proxy.hasHomePage()); + assertNull(proxy.getFortuneNumber()); + proxy.setAge(DwarfsData.sneezy.age); + proxy.setHeight(DwarfsData.sneezy.height); + proxy.setWeight(DwarfsData.sneezy.weight); + proxy.setHomePage(DwarfsData.sneezy.homePage); + proxy.setHomeDir(DwarfsData.sneezy.homeDir); + proxy.setFortuneNumber(DwarfsData.sneezy.fortuneNumber); + Helper.assertEquals(DwarfsData.sneezy, proxy); + assertArrayEquals(DwarfsData.sneezy.fortuneNumber, proxy.getFortuneNumber()); + } + + @Test + public void testSingleton() throws Exception { + assertEquals(BeanTool.class, BeanTool.getInstance().getClass()); + } + + @Test + public void testZero() throws Exception { + assertEquals(null, instance.zero(Object.class)); + assertEquals(0, instance.zero(byte.class).byteValue()); + assertEquals(0, instance.zero(short.class).shortValue()); + assertEquals(0, instance.zero(int.class).intValue()); + assertEquals(0, instance.zero(long.class).longValue()); + assertEquals(0.0f, instance.zero(float.class).floatValue(), Helper.DELTA); + assertEquals(0.0, instance.zero(double.class).doubleValue(), Helper.DELTA); + assertNotNull((instance.zero(boolean.class))); + assertFalse(instance.zero(boolean.class)); + assertEquals('\0', instance.zero(char.class).charValue()); + } + + protected void testInject(String prefix) throws Exception { + String p = (prefix == null) ? "" : prefix; + Dwarf bean = new DwarfBean(); + + bean.setAge(23); + bean.setHeight(5.3); + URI uri = new URI("http://www.ini4j.org"); + + bean.setHomePage(uri); + String dir = "/home/happy"; + + bean.setHomeDir(dir); + bean.setFortuneNumber(new int[] {1, 2, 3}); + TestMap map = new TestMap(); + + instance.inject(map.newBeanAccess(prefix), bean); + assertEquals(6, map.size()); + assertEquals("23", map.get(p + Dwarf.PROP_AGE)); + assertEquals("5.3", map.get(p + Dwarf.PROP_HEIGHT)); + assertEquals(uri.toString(), map.get(p + Dwarf.PROP_HOME_PAGE)); + assertEquals(dir, map.get(p + Dwarf.PROP_HOME_DIR)); + assertEquals(3, map.length(p + Dwarf.PROP_FORTUNE_NUMBER)); + assertEquals("1", map.get(p + Dwarf.PROP_FORTUNE_NUMBER, 0)); + assertEquals("2", map.get(p + Dwarf.PROP_FORTUNE_NUMBER, 1)); + assertEquals("3", map.get(p + Dwarf.PROP_FORTUNE_NUMBER, 2)); + bean.setAge(0); + bean.setHeight(0); + bean.setHomePage(null); + instance.inject(bean, map.newBeanAccess(prefix)); + assertEquals(23, bean.getAge()); + assertEquals(5.3, bean.getHeight(), Helper.DELTA); + assertEquals(uri, bean.getHomePage()); + assertEquals(dir, bean.getHomeDir()); + assertArrayEquals(new int[] {1, 2, 3}, bean.getFortuneNumber()); + + // + // bean interface + // + Dwarf proxy = instance.proxy(Dwarf.class, map.newBeanAccess(prefix)); + + assertEquals(23, proxy.getAge()); + assertEquals(5.3, proxy.getHeight(), Helper.DELTA); + assertEquals(uri, proxy.getHomePage()); + assertEquals(dir, proxy.getHomeDir()); + assertArrayEquals(new int[] {1, 2, 3}, proxy.getFortuneNumber()); + } + + static class TestMap extends BasicOptionMapGate { + private static final long serialVersionUID = 4818386732025655044L; + } + + private static class BadBean { + public String getName() throws IOException { + throw new IOException(); } - private static class BadBean - { - public String getName() throws IOException - { - throw new IOException(); - } - - public void setName(String value) throws IOException - { - throw new IOException(); - } + public void setName(String value) throws IOException { + throw new IOException(); } + } } diff --git a/src/test/java/org/ini4j/spi/EscapeToolTest.java b/src/test/java/org/ini4j/spi/EscapeToolTest.java index bd219e1..7e2c3aa 100755 --- a/src/test/java/org/ini4j/spi/EscapeToolTest.java +++ b/src/test/java/org/ini4j/spi/EscapeToolTest.java @@ -15,80 +15,76 @@ */ package org.ini4j.spi; -import org.ini4j.Ini4jCase; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; +import org.ini4j.Ini4jCase; import org.junit.Before; import org.junit.Test; -public class EscapeToolTest extends Ini4jCase -{ - private static final String VALUE1 = "simple"; - private static final String ESCAPE1 = "simple"; - private static final String VALUE2 = "Iv\ufffdn"; - private static final String ESCAPE2 = "Iv\\ufffdn"; - private static final String VALUE3 = "1\t2\n3\f4\b5\r6"; - private static final String ESCAPE3 = "1\\t2\\n3\\f4\\b5\\r6"; - private static final String VALUE4 = "Iv\u0017n"; - private static final String ESCAPE4 = "Iv\\u0017n"; - private static final String INVALID_UNICODE = "\\u98x"; - private static final String UNQUOTED1 = "simple"; - private static final String QUOTED1 = "\"simple\""; - private static final String UNQUOTED2 = "no\\csak\""; - private static final String QUOTED2 = "\"no\\\\csak\\\"\""; - private static final String UNQUOTED3 = ""; - private static final String QUOTED3 = ""; - protected EscapeTool instance; +public class EscapeToolTest extends Ini4jCase { + private static final String VALUE1 = "simple"; + private static final String ESCAPE1 = "simple"; + private static final String VALUE2 = "Iv\ufffdn"; + private static final String ESCAPE2 = "Iv\\ufffdn"; + private static final String VALUE3 = "1\t2\n3\f4\b5\r6"; + private static final String ESCAPE3 = "1\\t2\\n3\\f4\\b5\\r6"; + private static final String VALUE4 = "Iv\u0017n"; + private static final String ESCAPE4 = "Iv\\u0017n"; + private static final String INVALID_UNICODE = "\\u98x"; + private static final String UNQUOTED1 = "simple"; + private static final String QUOTED1 = "\"simple\""; + private static final String UNQUOTED2 = "no\\csak\""; + private static final String QUOTED2 = "\"no\\\\csak\\\"\""; + private static final String UNQUOTED3 = ""; + private static final String QUOTED3 = ""; + protected EscapeTool instance; - @Before @Override public void setUp() throws Exception - { - super.setUp(); - instance = EscapeTool.getInstance(); - } + @Before + @Override + public void setUp() throws Exception { + super.setUp(); + instance = EscapeTool.getInstance(); + } - @Test public void testEscape() throws Exception - { - assertEquals(ESCAPE1, instance.escape(VALUE1)); - assertEquals(ESCAPE2, instance.escape(VALUE2)); - assertEquals(ESCAPE3, instance.escape(VALUE3)); - assertEquals(ESCAPE4, instance.escape(VALUE4)); - } + @Test + public void testEscape() throws Exception { + assertEquals(ESCAPE1, instance.escape(VALUE1)); + assertEquals(ESCAPE2, instance.escape(VALUE2)); + assertEquals(ESCAPE3, instance.escape(VALUE3)); + assertEquals(ESCAPE4, instance.escape(VALUE4)); + } - @Test public void testInvalidUnicode() - { - try - { - instance.unescape(INVALID_UNICODE); - missing(IllegalArgumentException.class); - } - catch (IllegalArgumentException x) - { - // - } + @Test + public void testInvalidUnicode() { + try { + instance.unescape(INVALID_UNICODE); + missing(IllegalArgumentException.class); + } catch (IllegalArgumentException x) { + // } + } - @Test public void testQuote() throws Exception - { - assertEquals(QUOTED1, instance.quote(UNQUOTED1)); - assertEquals(QUOTED2, instance.quote(UNQUOTED2)); - assertEquals(QUOTED3, instance.quote(UNQUOTED3)); - assertNull(instance.quote(null)); - } + @Test + public void testQuote() throws Exception { + assertEquals(QUOTED1, instance.quote(UNQUOTED1)); + assertEquals(QUOTED2, instance.quote(UNQUOTED2)); + assertEquals(QUOTED3, instance.quote(UNQUOTED3)); + assertNull(instance.quote(null)); + } - @Test public void testSingleton() throws Exception - { - assertEquals(EscapeTool.class, EscapeTool.getInstance().getClass()); - } + @Test + public void testSingleton() throws Exception { + assertEquals(EscapeTool.class, EscapeTool.getInstance().getClass()); + } - @SuppressWarnings("empty-statement") - @Test public void testUnescape() throws Exception - { - assertEquals(VALUE1, instance.unescape(ESCAPE1)); - assertEquals(VALUE2, instance.unescape(ESCAPE2)); - assertEquals(VALUE3, instance.unescape(ESCAPE3)); - assertEquals(VALUE4, instance.unescape(ESCAPE4)); - assertEquals("=", instance.unescape("\\=")); - } + @SuppressWarnings("empty-statement") + @Test + public void testUnescape() throws Exception { + assertEquals(VALUE1, instance.unescape(ESCAPE1)); + assertEquals(VALUE2, instance.unescape(ESCAPE2)); + assertEquals(VALUE3, instance.unescape(ESCAPE3)); + assertEquals(VALUE4, instance.unescape(ESCAPE4)); + assertEquals("=", instance.unescape("\\=")); + } } diff --git a/src/test/java/org/ini4j/spi/IniFormatterTest.java b/src/test/java/org/ini4j/spi/IniFormatterTest.java index bfdaa06..7606aad 100644 --- a/src/test/java/org/ini4j/spi/IniFormatterTest.java +++ b/src/test/java/org/ini4j/spi/IniFormatterTest.java @@ -15,218 +15,211 @@ */ package org.ini4j.spi; -import org.easymock.EasyMock; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import java.io.PrintWriter; +import java.io.StringReader; +import java.io.StringWriter; +import org.easymock.EasyMock; import org.ini4j.Config; import org.ini4j.Ini; import org.ini4j.Ini4jCase; - import org.ini4j.sample.Dwarf; import org.ini4j.sample.Dwarfs; - import org.ini4j.test.DwarfsData; import org.ini4j.test.Helper; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; - import org.junit.Test; -import java.io.PrintWriter; -import java.io.StringReader; -import java.io.StringWriter; - -public class IniFormatterTest extends Ini4jCase -{ - private static final String NL = System.getProperty("line.separator"); - private static final String DUMMY = "dummy"; - - @Test public void testFormat() throws Exception - { - Ini ini = Helper.newDwarfsIni(); - IniHandler handler = EasyMock.createMock(IniHandler.class); - Dwarf dwarf; - - handler.startIni(); - handler.handleComment(Helper.HEADER_COMMENT); - handler.handleComment(" " + Dwarfs.PROP_BASHFUL); - dwarf = DwarfsData.bashful; - handler.startSection(Dwarfs.PROP_BASHFUL); - handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); - handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); - handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.endSection(); - handler.handleComment(" " + Dwarfs.PROP_DOC); - dwarf = DwarfsData.doc; - handler.startSection(Dwarfs.PROP_DOC); - handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); - handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); - handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.endSection(); - handler.handleComment(" " + Dwarfs.PROP_DOPEY); - dwarf = DwarfsData.dopey; - handler.startSection(Dwarfs.PROP_DOPEY); - handler.handleOption(Dwarf.PROP_WEIGHT, DwarfsData.INI_DOPEY_WEIGHT); - handler.handleOption(Dwarf.PROP_HEIGHT, DwarfsData.INI_DOPEY_HEIGHT); - handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[0])); - handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[1])); - handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[2])); - handler.endSection(); - handler.handleComment(" " + Dwarfs.PROP_GRUMPY); - dwarf = DwarfsData.grumpy; - handler.startSection(Dwarfs.PROP_GRUMPY); - handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); - handler.handleOption(Dwarf.PROP_HEIGHT, DwarfsData.INI_GRUMPY_HEIGHT); - handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.endSection(); - handler.handleComment(" " + Dwarfs.PROP_HAPPY); - dwarf = DwarfsData.happy; - handler.startSection(Dwarfs.PROP_HAPPY); - handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); - handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); - handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.endSection(); - handler.handleComment(" " + Dwarfs.PROP_SLEEPY); - dwarf = DwarfsData.sleepy; - handler.startSection(Dwarfs.PROP_SLEEPY); - handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); - handler.handleOption(Dwarf.PROP_HEIGHT, DwarfsData.INI_SLEEPY_HEIGHT); - handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[0])); - handler.endSection(); - handler.handleComment(" " + Dwarfs.PROP_SNEEZY); - dwarf = DwarfsData.sneezy; - handler.startSection(Dwarfs.PROP_SNEEZY); - handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); - handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); - handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(Dwarf.PROP_HOME_PAGE, DwarfsData.INI_SNEEZY_HOME_PAGE); - handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[0])); - handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[1])); - handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[2])); - handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[3])); - handler.endSection(); - handler.endIni(); - EasyMock.replay(handler); - verify(ini, handler); - } - - @Test public void testNewInstance() throws Exception - { - StringWriter stringWriter; - PrintWriter printWriter; - Config cfg = new Config(); - IniFormatter instance; - - stringWriter = new StringWriter(); - instance = IniFormatter.newInstance(stringWriter, cfg); - - instance.getOutput().print(DUMMY); - instance.getOutput().flush(); - assertEquals(DUMMY, stringWriter.toString()); - assertSame(cfg, instance.getConfig()); - - // - stringWriter = new StringWriter(); - instance = IniFormatter.newInstance(stringWriter, cfg); - - instance.getOutput().print(DUMMY); - instance.getOutput().flush(); - assertEquals(DUMMY, stringWriter.toString()); - - // - printWriter = new PrintWriter(stringWriter); - instance = IniFormatter.newInstance(printWriter, cfg); - - assertSame(printWriter, instance.getOutput()); - } - - @Test public void testWithEmptyOption() throws Exception - { - Config cfg = new Config(); - - cfg.setEmptyOption(true); - Ini ini = new Ini(); - Ini.Section sec = ini.add(Dwarfs.PROP_BASHFUL); - - sec.put(Dwarf.PROP_FORTUNE_NUMBER, null); - ini.setConfig(cfg); - IniHandler handler = EasyMock.createMock(IniHandler.class); - - handler.startIni(); - handler.startSection(Dwarfs.PROP_BASHFUL); - handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, ""); - handler.endSection(); - handler.endIni(); - EasyMock.replay(handler); - verify(ini, handler); - } - - @Test public void testWithoutConfig() throws Exception - { - Ini ini = new Ini(); - Ini.Section sec = ini.add(Dwarfs.PROP_BASHFUL); - - sec.put(Dwarf.PROP_FORTUNE_NUMBER, null); - IniHandler handler = EasyMock.createMock(IniHandler.class); - - handler.startIni(); - handler.startSection(Dwarfs.PROP_BASHFUL); - handler.endSection(); - handler.endIni(); - EasyMock.replay(handler); - verify(ini, handler); - } - - @Test public void testWithStrictOperator() throws Exception - { - Config cfg = new Config(); - - cfg.setStrictOperator(true); - Ini ini = new Ini(); - Ini.Section sec = ini.add(Dwarfs.PROP_BASHFUL); - - sec.put(Dwarf.PROP_AGE, DwarfsData.bashful.age); - ini.setConfig(cfg); - StringWriter writer = new StringWriter(); - - ini.store(writer); - StringBuilder exp = new StringBuilder(); - - exp.append(IniParser.SECTION_BEGIN); - exp.append(Dwarfs.PROP_BASHFUL); - exp.append(IniParser.SECTION_END); - exp.append(NL); - exp.append(Dwarf.PROP_AGE); - exp.append('='); - exp.append(DwarfsData.bashful.age); - exp.append(NL); - exp.append(NL); - assertEquals(exp.toString(), writer.toString()); - } - - private void verify(Ini ini, IniHandler mock) throws Exception - { - StringWriter writer = new StringWriter(); - - ini.store(writer); - IniParser parser = new IniParser(); - - parser.parse(new StringReader(writer.toString()), mock); - EasyMock.verify(mock); - } +public class IniFormatterTest extends Ini4jCase { + private static final String NL = System.getProperty("line.separator"); + private static final String DUMMY = "dummy"; + + @Test + public void testFormat() throws Exception { + Ini ini = Helper.newDwarfsIni(); + IniHandler handler = EasyMock.createMock(IniHandler.class); + Dwarf dwarf; + + handler.startIni(); + handler.handleComment(Helper.HEADER_COMMENT); + handler.handleComment(" " + Dwarfs.PROP_BASHFUL); + dwarf = DwarfsData.bashful; + handler.startSection(Dwarfs.PROP_BASHFUL); + handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); + handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); + handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.endSection(); + handler.handleComment(" " + Dwarfs.PROP_DOC); + dwarf = DwarfsData.doc; + handler.startSection(Dwarfs.PROP_DOC); + handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); + handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); + handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.endSection(); + handler.handleComment(" " + Dwarfs.PROP_DOPEY); + dwarf = DwarfsData.dopey; + handler.startSection(Dwarfs.PROP_DOPEY); + handler.handleOption(Dwarf.PROP_WEIGHT, DwarfsData.INI_DOPEY_WEIGHT); + handler.handleOption(Dwarf.PROP_HEIGHT, DwarfsData.INI_DOPEY_HEIGHT); + handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[0])); + handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[1])); + handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[2])); + handler.endSection(); + handler.handleComment(" " + Dwarfs.PROP_GRUMPY); + dwarf = DwarfsData.grumpy; + handler.startSection(Dwarfs.PROP_GRUMPY); + handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); + handler.handleOption(Dwarf.PROP_HEIGHT, DwarfsData.INI_GRUMPY_HEIGHT); + handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.endSection(); + handler.handleComment(" " + Dwarfs.PROP_HAPPY); + dwarf = DwarfsData.happy; + handler.startSection(Dwarfs.PROP_HAPPY); + handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); + handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); + handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.endSection(); + handler.handleComment(" " + Dwarfs.PROP_SLEEPY); + dwarf = DwarfsData.sleepy; + handler.startSection(Dwarfs.PROP_SLEEPY); + handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); + handler.handleOption(Dwarf.PROP_HEIGHT, DwarfsData.INI_SLEEPY_HEIGHT); + handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[0])); + handler.endSection(); + handler.handleComment(" " + Dwarfs.PROP_SNEEZY); + dwarf = DwarfsData.sneezy; + handler.startSection(Dwarfs.PROP_SNEEZY); + handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); + handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); + handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(Dwarf.PROP_HOME_PAGE, DwarfsData.INI_SNEEZY_HOME_PAGE); + handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[0])); + handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[1])); + handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[2])); + handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[3])); + handler.endSection(); + handler.endIni(); + EasyMock.replay(handler); + verify(ini, handler); + } + + @Test + public void testNewInstance() throws Exception { + StringWriter stringWriter; + PrintWriter printWriter; + Config cfg = new Config(); + IniFormatter instance; + + stringWriter = new StringWriter(); + instance = IniFormatter.newInstance(stringWriter, cfg); + + instance.getOutput().print(DUMMY); + instance.getOutput().flush(); + assertEquals(DUMMY, stringWriter.toString()); + assertSame(cfg, instance.getConfig()); + + // + stringWriter = new StringWriter(); + instance = IniFormatter.newInstance(stringWriter, cfg); + + instance.getOutput().print(DUMMY); + instance.getOutput().flush(); + assertEquals(DUMMY, stringWriter.toString()); + + // + printWriter = new PrintWriter(stringWriter); + instance = IniFormatter.newInstance(printWriter, cfg); + + assertSame(printWriter, instance.getOutput()); + } + + @Test + public void testWithEmptyOption() throws Exception { + Config cfg = new Config(); + + cfg.setEmptyOption(true); + Ini ini = new Ini(); + Ini.Section sec = ini.add(Dwarfs.PROP_BASHFUL); + + sec.put(Dwarf.PROP_FORTUNE_NUMBER, null); + ini.setConfig(cfg); + IniHandler handler = EasyMock.createMock(IniHandler.class); + + handler.startIni(); + handler.startSection(Dwarfs.PROP_BASHFUL); + handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, ""); + handler.endSection(); + handler.endIni(); + EasyMock.replay(handler); + verify(ini, handler); + } + + @Test + public void testWithoutConfig() throws Exception { + Ini ini = new Ini(); + Ini.Section sec = ini.add(Dwarfs.PROP_BASHFUL); + + sec.put(Dwarf.PROP_FORTUNE_NUMBER, null); + IniHandler handler = EasyMock.createMock(IniHandler.class); + + handler.startIni(); + handler.startSection(Dwarfs.PROP_BASHFUL); + handler.endSection(); + handler.endIni(); + EasyMock.replay(handler); + verify(ini, handler); + } + + @Test + public void testWithStrictOperator() throws Exception { + Config cfg = new Config(); + + cfg.setStrictOperator(true); + Ini ini = new Ini(); + Ini.Section sec = ini.add(Dwarfs.PROP_BASHFUL); + + sec.put(Dwarf.PROP_AGE, DwarfsData.bashful.age); + ini.setConfig(cfg); + StringWriter writer = new StringWriter(); + + ini.store(writer); + StringBuilder exp = new StringBuilder(); + + exp.append(IniParser.SECTION_BEGIN); + exp.append(Dwarfs.PROP_BASHFUL); + exp.append(IniParser.SECTION_END); + exp.append(NL); + exp.append(Dwarf.PROP_AGE); + exp.append('='); + exp.append(DwarfsData.bashful.age); + exp.append(NL); + exp.append(NL); + assertEquals(exp.toString(), writer.toString()); + } + + private void verify(Ini ini, IniHandler mock) throws Exception { + StringWriter writer = new StringWriter(); + + ini.store(writer); + IniParser parser = new IniParser(); + + parser.parse(new StringReader(writer.toString()), mock); + EasyMock.verify(mock); + } } diff --git a/src/test/java/org/ini4j/spi/IniParserTest.java b/src/test/java/org/ini4j/spi/IniParserTest.java index 4281a13..20f2e3d 100755 --- a/src/test/java/org/ini4j/spi/IniParserTest.java +++ b/src/test/java/org/ini4j/spi/IniParserTest.java @@ -15,258 +15,254 @@ */ package org.ini4j.spi; -import org.easymock.EasyMock; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; +import java.io.ByteArrayInputStream; +import java.io.StringReader; +import org.easymock.EasyMock; import org.ini4j.Config; import org.ini4j.Ini4jCase; import org.ini4j.InvalidFileFormatException; - import org.ini4j.sample.Dwarf; import org.ini4j.sample.Dwarfs; - import org.ini4j.test.DwarfsData; import org.ini4j.test.Helper; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; - import org.junit.Test; -import java.io.ByteArrayInputStream; -import java.io.StringReader; - -public class IniParserTest extends Ini4jCase -{ - private static final String[] BAD = { "[section\noption=value\n", "[]\noption=value", "section\noption=value", "[section]\noption\n", "[section]\n=value\n", "[section]\n\\u000d\\u000d=value\n" }; - private static final String CFG_LOWER = "[SectioN]\n\nOptioN=ValuE\n"; - private static final String CFG_UNNAMED = "[]\noption=value\n"; - private static final String CFG_EMPTY_OPTION = "[section]\noption\n"; - private static final String CFG_GLOBAL = "option=value\n"; - private static final String[] CFG_EXTRA = { CFG_EMPTY_OPTION, CFG_UNNAMED, CFG_GLOBAL }; - private static final String ANONYMOUS = "?"; - private static final String EMPTY = ""; - private static final String SECTION = "section"; - private static final String OPTION = "option"; - private static final String VALUE = "value"; +public class IniParserTest extends Ini4jCase { + private static final String[] BAD = { + "[section\noption=value\n", + "[]\noption=value", + "section\noption=value", + "[section]\noption\n", + "[section]\n=value\n", + "[section]\n\\u000d\\u000d=value\n" + }; + private static final String CFG_LOWER = "[SectioN]\n\nOptioN=ValuE\n"; + private static final String CFG_UNNAMED = "[]\noption=value\n"; + private static final String CFG_EMPTY_OPTION = "[section]\noption\n"; + private static final String CFG_GLOBAL = "option=value\n"; + private static final String[] CFG_EXTRA = {CFG_EMPTY_OPTION, CFG_UNNAMED, CFG_GLOBAL}; + private static final String ANONYMOUS = "?"; + private static final String EMPTY = ""; + private static final String SECTION = "section"; + private static final String OPTION = "option"; + private static final String VALUE = "value"; - @Test public void testEmpty() throws Exception - { - IniParser parser = new IniParser(); - IniHandler handler = EasyMock.createMock(IniHandler.class); + @Test + public void testEmpty() throws Exception { + IniParser parser = new IniParser(); + IniHandler handler = EasyMock.createMock(IniHandler.class); - handler.startIni(); - handler.endIni(); - EasyMock.replay(handler); - parser.parse(new StringReader(EMPTY), handler); - EasyMock.verify(handler); - } + handler.startIni(); + handler.endIni(); + EasyMock.replay(handler); + parser.parse(new StringReader(EMPTY), handler); + EasyMock.verify(handler); + } - @Test public void testEmptyOption() throws Exception - { - IniParser parser = new IniParser(); - IniHandler handler = EasyMock.createMock(IniHandler.class); + @Test + public void testEmptyOption() throws Exception { + IniParser parser = new IniParser(); + IniHandler handler = EasyMock.createMock(IniHandler.class); - handler.startIni(); - handler.startSection(SECTION); - handler.handleOption(OPTION, null); - handler.endSection(); - handler.endIni(); - EasyMock.replay(handler); - Config cfg = new Config(); + handler.startIni(); + handler.startSection(SECTION); + handler.handleOption(OPTION, null); + handler.endSection(); + handler.endIni(); + EasyMock.replay(handler); + Config cfg = new Config(); - cfg.setEmptyOption(true); - parser.setConfig(cfg); - parser.parse(new StringReader(CFG_EMPTY_OPTION), handler); - EasyMock.verify(handler); - } + cfg.setEmptyOption(true); + parser.setConfig(cfg); + parser.parse(new StringReader(CFG_EMPTY_OPTION), handler); + EasyMock.verify(handler); + } - @Test public void testGlobalSection() throws Exception - { - IniParser parser = new IniParser(); - IniHandler handler = EasyMock.createMock(IniHandler.class); + @Test + public void testGlobalSection() throws Exception { + IniParser parser = new IniParser(); + IniHandler handler = EasyMock.createMock(IniHandler.class); - handler.startIni(); - handler.startSection(ANONYMOUS); - handler.handleOption(OPTION, VALUE); - handler.endSection(); - handler.endIni(); - EasyMock.replay(handler); - Config cfg = new Config(); + handler.startIni(); + handler.startSection(ANONYMOUS); + handler.handleOption(OPTION, VALUE); + handler.endSection(); + handler.endIni(); + EasyMock.replay(handler); + Config cfg = new Config(); - cfg.setGlobalSection(true); - parser.setConfig(cfg); - parser.parse(new StringReader(CFG_GLOBAL), handler); - EasyMock.verify(handler); - } + cfg.setGlobalSection(true); + parser.setConfig(cfg); + parser.parse(new StringReader(CFG_GLOBAL), handler); + EasyMock.verify(handler); + } - @Test public void testLower() throws Exception - { - IniParser parser = new IniParser(); - IniHandler handler = EasyMock.createMock(IniHandler.class); + @Test + public void testLower() throws Exception { + IniParser parser = new IniParser(); + IniHandler handler = EasyMock.createMock(IniHandler.class); - handler.startIni(); - handler.startSection(SECTION); - handler.handleOption(OPTION, "ValuE"); - handler.endSection(); - handler.endIni(); - EasyMock.replay(handler); - Config cfg = new Config(); + handler.startIni(); + handler.startSection(SECTION); + handler.handleOption(OPTION, "ValuE"); + handler.endSection(); + handler.endIni(); + EasyMock.replay(handler); + Config cfg = new Config(); - cfg.setLowerCaseOption(true); - cfg.setLowerCaseSection(true); - parser.setConfig(cfg); - parser.parse(new StringReader(CFG_LOWER), handler); - EasyMock.verify(handler); - } + cfg.setLowerCaseOption(true); + cfg.setLowerCaseSection(true); + parser.setConfig(cfg); + parser.parse(new StringReader(CFG_LOWER), handler); + EasyMock.verify(handler); + } - @Test public void testNewInstance() throws Exception - { - Config cfg = new Config(); - IniParser parser = IniParser.newInstance(); + @Test + public void testNewInstance() throws Exception { + Config cfg = new Config(); + IniParser parser = IniParser.newInstance(); - assertEquals(IniParser.class, parser.getClass()); - parser = IniParser.newInstance(cfg); - assertEquals(IniParser.class, parser.getClass()); - assertSame(cfg, parser.getConfig()); - } + assertEquals(IniParser.class, parser.getClass()); + parser = IniParser.newInstance(cfg); + assertEquals(IniParser.class, parser.getClass()); + assertSame(cfg, parser.getConfig()); + } - @Test public void testParse() throws Exception - { - IniParser parser = new IniParser(); - IniHandler handler = EasyMock.createMock(IniHandler.class); - Dwarf dwarf; + @Test + public void testParse() throws Exception { + IniParser parser = new IniParser(); + IniHandler handler = EasyMock.createMock(IniHandler.class); + Dwarf dwarf; - handler.startIni(); - handler.handleComment(Helper.HEADER_COMMENT); - handler.handleComment((String) EasyMock.anyObject()); - handler.handleComment(" " + Dwarfs.PROP_BASHFUL); - dwarf = DwarfsData.bashful; - handler.startSection(Dwarfs.PROP_BASHFUL); - handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); - handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); - handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.endSection(); - handler.handleComment(" " + Dwarfs.PROP_DOC); - dwarf = DwarfsData.doc; - handler.startSection(Dwarfs.PROP_DOC); - handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); - handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); - handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.endSection(); - handler.handleComment(" " + Dwarfs.PROP_DOPEY); - dwarf = DwarfsData.dopey; - handler.startSection(Dwarfs.PROP_DOPEY); - handler.handleOption(Dwarf.PROP_WEIGHT, DwarfsData.INI_DOPEY_WEIGHT); - handler.handleOption(Dwarf.PROP_HEIGHT, DwarfsData.INI_DOPEY_HEIGHT); - handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[0])); - handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[1])); - handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[2])); - handler.endSection(); - handler.handleComment(" " + Dwarfs.PROP_GRUMPY); - dwarf = DwarfsData.grumpy; - handler.startSection(Dwarfs.PROP_GRUMPY); - handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); - handler.handleOption(Dwarf.PROP_HEIGHT, DwarfsData.INI_GRUMPY_HEIGHT); - handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.endSection(); - handler.handleComment(" " + Dwarfs.PROP_HAPPY); - dwarf = DwarfsData.happy; - handler.startSection(Dwarfs.PROP_HAPPY); - handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); - handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); - handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(EasyMock.eq(Dwarf.PROP_HOME_PAGE), (String) EasyMock.anyObject()); - handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.endSection(); - handler.handleComment(" " + Dwarfs.PROP_SLEEPY); - dwarf = DwarfsData.sleepy; - handler.startSection(Dwarfs.PROP_SLEEPY); - handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); - handler.handleOption(Dwarf.PROP_HEIGHT, DwarfsData.INI_SLEEPY_HEIGHT); - handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[0])); - handler.endSection(); - handler.handleComment(" " + Dwarfs.PROP_SNEEZY); - dwarf = DwarfsData.sneezy; - handler.startSection(Dwarfs.PROP_SNEEZY); - handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); - handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); - handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(Dwarf.PROP_HOME_PAGE, DwarfsData.INI_SNEEZY_HOME_PAGE); - handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[0])); - handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[1])); - handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[2])); - handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[3])); - handler.endSection(); - handler.handleComment(" " + Dwarfs.PROP_HAPPY + " again"); - dwarf = DwarfsData.happy; - handler.startSection(Dwarfs.PROP_HAPPY); - handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleComment("}"); - handler.endSection(); - handler.endIni(); + handler.startIni(); + handler.handleComment(Helper.HEADER_COMMENT); + handler.handleComment((String) EasyMock.anyObject()); + handler.handleComment(" " + Dwarfs.PROP_BASHFUL); + dwarf = DwarfsData.bashful; + handler.startSection(Dwarfs.PROP_BASHFUL); + handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); + handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); + handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.endSection(); + handler.handleComment(" " + Dwarfs.PROP_DOC); + dwarf = DwarfsData.doc; + handler.startSection(Dwarfs.PROP_DOC); + handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); + handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); + handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.endSection(); + handler.handleComment(" " + Dwarfs.PROP_DOPEY); + dwarf = DwarfsData.dopey; + handler.startSection(Dwarfs.PROP_DOPEY); + handler.handleOption(Dwarf.PROP_WEIGHT, DwarfsData.INI_DOPEY_WEIGHT); + handler.handleOption(Dwarf.PROP_HEIGHT, DwarfsData.INI_DOPEY_HEIGHT); + handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[0])); + handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[1])); + handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[2])); + handler.endSection(); + handler.handleComment(" " + Dwarfs.PROP_GRUMPY); + dwarf = DwarfsData.grumpy; + handler.startSection(Dwarfs.PROP_GRUMPY); + handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); + handler.handleOption(Dwarf.PROP_HEIGHT, DwarfsData.INI_GRUMPY_HEIGHT); + handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.endSection(); + handler.handleComment(" " + Dwarfs.PROP_HAPPY); + dwarf = DwarfsData.happy; + handler.startSection(Dwarfs.PROP_HAPPY); + handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); + handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); + handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(EasyMock.eq(Dwarf.PROP_HOME_PAGE), (String) EasyMock.anyObject()); + handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.endSection(); + handler.handleComment(" " + Dwarfs.PROP_SLEEPY); + dwarf = DwarfsData.sleepy; + handler.startSection(Dwarfs.PROP_SLEEPY); + handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); + handler.handleOption(Dwarf.PROP_HEIGHT, DwarfsData.INI_SLEEPY_HEIGHT); + handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[0])); + handler.endSection(); + handler.handleComment(" " + Dwarfs.PROP_SNEEZY); + dwarf = DwarfsData.sneezy; + handler.startSection(Dwarfs.PROP_SNEEZY); + handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); + handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); + handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(Dwarf.PROP_HOME_PAGE, DwarfsData.INI_SNEEZY_HOME_PAGE); + handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[0])); + handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[1])); + handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[2])); + handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[3])); + handler.endSection(); + handler.handleComment(" " + Dwarfs.PROP_HAPPY + " again"); + dwarf = DwarfsData.happy; + handler.startSection(Dwarfs.PROP_HAPPY); + handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleComment("}"); + handler.endSection(); + handler.endIni(); - // - EasyMock.replay(handler); - parser.parse(Helper.getResourceURL(Helper.DWARFS_INI), handler); - EasyMock.verify(handler); - } + // + EasyMock.replay(handler); + parser.parse(Helper.getResourceURL(Helper.DWARFS_INI), handler); + EasyMock.verify(handler); + } - @Test public void testParseExceptions() throws Exception - { - assertBad(BAD); - assertBad(CFG_EXTRA); - } + @Test + public void testParseExceptions() throws Exception { + assertBad(BAD); + assertBad(CFG_EXTRA); + } - @Test public void testUnnamedSection() throws Exception - { - IniParser parser = new IniParser(); - IniHandler handler = EasyMock.createMock(IniHandler.class); + @Test + public void testUnnamedSection() throws Exception { + IniParser parser = new IniParser(); + IniHandler handler = EasyMock.createMock(IniHandler.class); - handler.startIni(); - handler.startSection(EMPTY); - handler.handleOption(OPTION, VALUE); - handler.endSection(); - handler.endIni(); - EasyMock.replay(handler); - Config cfg = new Config(); + handler.startIni(); + handler.startSection(EMPTY); + handler.handleOption(OPTION, VALUE); + handler.endSection(); + handler.endIni(); + EasyMock.replay(handler); + Config cfg = new Config(); - cfg.setUnnamedSection(true); - parser.setConfig(cfg); - parser.parse(new StringReader(CFG_UNNAMED), handler); - EasyMock.verify(handler); - } + cfg.setUnnamedSection(true); + parser.setConfig(cfg); + parser.parse(new StringReader(CFG_UNNAMED), handler); + EasyMock.verify(handler); + } - @SuppressWarnings("empty-statement") - private void assertBad(String[] values) throws Exception - { - IniParser parser = new IniParser(); - IniHandler handler = EasyMock.createNiceMock(IniHandler.class); + @SuppressWarnings("empty-statement") + private void assertBad(String[] values) throws Exception { + IniParser parser = new IniParser(); + IniHandler handler = EasyMock.createNiceMock(IniHandler.class); - for (String s : values) - { - try - { - parser.parse(new ByteArrayInputStream(s.getBytes()), handler); - fail("expected InvalidIniFormatException: " + s); - } - catch (InvalidFileFormatException x) - { - ; - } - } + for (String s : values) { + try { + parser.parse(new ByteArrayInputStream(s.getBytes()), handler); + fail("expected InvalidIniFormatException: " + s); + } catch (InvalidFileFormatException x) { + ; + } } + } } diff --git a/src/test/java/org/ini4j/spi/IniSourceTest.java b/src/test/java/org/ini4j/spi/IniSourceTest.java index c7b3980..2313af0 100644 --- a/src/test/java/org/ini4j/spi/IniSourceTest.java +++ b/src/test/java/org/ini4j/spi/IniSourceTest.java @@ -15,122 +15,117 @@ */ package org.ini4j.spi; -import org.easymock.EasyMock; - -import org.ini4j.Config; -import org.ini4j.Ini4jCase; - -import org.ini4j.test.Helper; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -import org.junit.Test; - import java.io.ByteArrayInputStream; import java.io.InputStream; +import org.easymock.EasyMock; +import org.ini4j.Config; +import org.ini4j.Ini4jCase; +import org.ini4j.test.Helper; +import org.junit.Test; -public class IniSourceTest extends Ini4jCase -{ - private static final String COMMENTS = ";#"; - private static final String NESTED_TXT = "nested.txt"; - private static final String NESTED = ":" + NESTED_TXT; - private static final String NESTED_PATH = "org/ini4j/spi/" + NESTED_TXT; - private static final String INCLUDE = ":include.txt"; - private static final String PART1 = ":part1.txt"; - private static final String PART2 = ":part2.txt"; - private static final String OUTER = ":outer"; - - @Test public void testWithInclude() throws Exception - { - HandlerBase handler = EasyMock.createMock(HandlerBase.class); - - handler.handleComment("-1" + OUTER); - handler.handleComment("-1" + NESTED); - handler.handleComment("-2" + NESTED); - handler.handleComment("-1" + INCLUDE); - handler.handleComment("-2" + INCLUDE); - handler.handleComment("-1" + PART1); - handler.handleComment("-2" + PART1); - handler.handleComment("-3" + INCLUDE); - handler.handleComment("-4" + INCLUDE); - handler.handleComment("-5" + INCLUDE); - handler.handleComment("-6" + INCLUDE); - handler.handleComment("-1" + PART2); - handler.handleComment("-2" + PART2); - handler.handleComment("-7" + INCLUDE); - handler.handleComment("-8" + INCLUDE); - handler.handleComment("-3" + NESTED); - handler.handleComment("-4" + NESTED); - handler.handleComment("-2" + OUTER); - EasyMock.replay(handler); - StringBuilder outer = new StringBuilder(); - - outer.append(";-1" + OUTER + '\n'); - outer.append("1" + OUTER + '\n'); - outer.append('<'); - outer.append(Helper.getResourceURL(NESTED_PATH).toExternalForm()); - outer.append(">\n"); - outer.append("2" + OUTER + '\n'); - outer.append(";-2" + OUTER + '\n'); - InputStream in = new ByteArrayInputStream(outer.toString().getBytes()); - Config cfg = new Config(); - - cfg.setInclude(true); - IniSource src = new IniSource(in, handler, COMMENTS, cfg); - - assertEquals("1" + OUTER, src.readLine()); - assertEquals(2, src.getLineNumber()); - assertEquals("1" + NESTED, src.readLine()); - assertEquals(2, src.getLineNumber()); - assertEquals("1" + INCLUDE, src.readLine()); - assertEquals(2, src.getLineNumber()); - assertEquals("1" + PART1, src.readLine()); - assertEquals(2, src.getLineNumber()); - assertEquals("2" + PART1, src.readLine()); - assertEquals(4, src.getLineNumber()); - assertEquals("3" + PART1 + "\\\\", src.readLine()); - assertEquals(5, src.getLineNumber()); - assertEquals("4:\\\\part1.txt", src.readLine()); - assertEquals(7, src.getLineNumber()); - assertEquals("5" + PART1 + "\\\\\\\\", src.readLine()); - assertEquals(8, src.getLineNumber()); - assertEquals("6" + PART1 + ";", src.readLine()); - assertEquals(10, src.getLineNumber()); - assertEquals("2" + INCLUDE, src.readLine()); - assertEquals(6, src.getLineNumber()); - assertEquals("3" + INCLUDE, src.readLine()); - assertEquals(10, src.getLineNumber()); - assertEquals("1" + PART2, src.readLine()); - assertEquals(3, src.getLineNumber()); - assertEquals("4" + INCLUDE, src.readLine()); - assertEquals(14, src.getLineNumber()); - assertEquals("2" + NESTED, src.readLine()); - assertEquals(6, src.getLineNumber()); - assertEquals("2" + OUTER, src.readLine()); - assertEquals(4, src.getLineNumber()); - assertNull(src.readLine()); - EasyMock.verify(handler); - } - - @Test public void testWithoutInclude() throws Exception - { - HandlerBase handler = EasyMock.createMock(HandlerBase.class); - - handler.handleComment("-1" + NESTED); - handler.handleComment("-2" + NESTED); - handler.handleComment("-3" + NESTED); - handler.handleComment("-4" + NESTED); - EasyMock.replay(handler); - Config cfg = new Config(); - - cfg.setInclude(false); - IniSource src = new IniSource(Helper.getResourceURL(NESTED_PATH), handler, COMMENTS, cfg); - - assertEquals("1" + NESTED, src.readLine()); - assertEquals("", src.readLine()); - assertEquals("2" + NESTED, src.readLine()); - assertNull(src.readLine()); - EasyMock.verify(handler); - } +public class IniSourceTest extends Ini4jCase { + private static final String COMMENTS = ";#"; + private static final String NESTED_TXT = "nested.txt"; + private static final String NESTED = ":" + NESTED_TXT; + private static final String NESTED_PATH = "org/ini4j/spi/" + NESTED_TXT; + private static final String INCLUDE = ":include.txt"; + private static final String PART1 = ":part1.txt"; + private static final String PART2 = ":part2.txt"; + private static final String OUTER = ":outer"; + + @Test + public void testWithInclude() throws Exception { + HandlerBase handler = EasyMock.createMock(HandlerBase.class); + + handler.handleComment("-1" + OUTER); + handler.handleComment("-1" + NESTED); + handler.handleComment("-2" + NESTED); + handler.handleComment("-1" + INCLUDE); + handler.handleComment("-2" + INCLUDE); + handler.handleComment("-1" + PART1); + handler.handleComment("-2" + PART1); + handler.handleComment("-3" + INCLUDE); + handler.handleComment("-4" + INCLUDE); + handler.handleComment("-5" + INCLUDE); + handler.handleComment("-6" + INCLUDE); + handler.handleComment("-1" + PART2); + handler.handleComment("-2" + PART2); + handler.handleComment("-7" + INCLUDE); + handler.handleComment("-8" + INCLUDE); + handler.handleComment("-3" + NESTED); + handler.handleComment("-4" + NESTED); + handler.handleComment("-2" + OUTER); + EasyMock.replay(handler); + StringBuilder outer = new StringBuilder(); + + outer.append(";-1" + OUTER + '\n'); + outer.append("1" + OUTER + '\n'); + outer.append('<'); + outer.append(Helper.getResourceURL(NESTED_PATH).toExternalForm()); + outer.append(">\n"); + outer.append("2" + OUTER + '\n'); + outer.append(";-2" + OUTER + '\n'); + InputStream in = new ByteArrayInputStream(outer.toString().getBytes()); + Config cfg = new Config(); + + cfg.setInclude(true); + IniSource src = new IniSource(in, handler, COMMENTS, cfg); + + assertEquals("1" + OUTER, src.readLine()); + assertEquals(2, src.getLineNumber()); + assertEquals("1" + NESTED, src.readLine()); + assertEquals(2, src.getLineNumber()); + assertEquals("1" + INCLUDE, src.readLine()); + assertEquals(2, src.getLineNumber()); + assertEquals("1" + PART1, src.readLine()); + assertEquals(2, src.getLineNumber()); + assertEquals("2" + PART1, src.readLine()); + assertEquals(4, src.getLineNumber()); + assertEquals("3" + PART1 + "\\\\", src.readLine()); + assertEquals(5, src.getLineNumber()); + assertEquals("4:\\\\part1.txt", src.readLine()); + assertEquals(7, src.getLineNumber()); + assertEquals("5" + PART1 + "\\\\\\\\", src.readLine()); + assertEquals(8, src.getLineNumber()); + assertEquals("6" + PART1 + ";", src.readLine()); + assertEquals(10, src.getLineNumber()); + assertEquals("2" + INCLUDE, src.readLine()); + assertEquals(6, src.getLineNumber()); + assertEquals("3" + INCLUDE, src.readLine()); + assertEquals(10, src.getLineNumber()); + assertEquals("1" + PART2, src.readLine()); + assertEquals(3, src.getLineNumber()); + assertEquals("4" + INCLUDE, src.readLine()); + assertEquals(14, src.getLineNumber()); + assertEquals("2" + NESTED, src.readLine()); + assertEquals(6, src.getLineNumber()); + assertEquals("2" + OUTER, src.readLine()); + assertEquals(4, src.getLineNumber()); + assertNull(src.readLine()); + EasyMock.verify(handler); + } + + @Test + public void testWithoutInclude() throws Exception { + HandlerBase handler = EasyMock.createMock(HandlerBase.class); + + handler.handleComment("-1" + NESTED); + handler.handleComment("-2" + NESTED); + handler.handleComment("-3" + NESTED); + handler.handleComment("-4" + NESTED); + EasyMock.replay(handler); + Config cfg = new Config(); + + cfg.setInclude(false); + IniSource src = new IniSource(Helper.getResourceURL(NESTED_PATH), handler, COMMENTS, cfg); + + assertEquals("1" + NESTED, src.readLine()); + assertEquals("", src.readLine()); + assertEquals("2" + NESTED, src.readLine()); + assertNull(src.readLine()); + EasyMock.verify(handler); + } } diff --git a/src/test/java/org/ini4j/spi/OptionsFormatterTest.java b/src/test/java/org/ini4j/spi/OptionsFormatterTest.java index 18720ca..094d788 100644 --- a/src/test/java/org/ini4j/spi/OptionsFormatterTest.java +++ b/src/test/java/org/ini4j/spi/OptionsFormatterTest.java @@ -15,369 +15,370 @@ */ package org.ini4j.spi; -import org.easymock.EasyMock; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import java.io.PrintWriter; +import java.io.StringReader; +import java.io.StringWriter; +import org.easymock.EasyMock; import org.ini4j.Config; import org.ini4j.Ini4jCase; import org.ini4j.Options; - import org.ini4j.sample.Dwarf; import org.ini4j.sample.Dwarfs; - import org.ini4j.test.DwarfsData; import org.ini4j.test.Helper; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; - import org.junit.Test; -import java.io.PrintWriter; -import java.io.StringReader; -import java.io.StringWriter; - -public class OptionsFormatterTest extends Ini4jCase -{ - private static final String NL = System.getProperty("line.separator"); - private static final String DUMMY = "dummy"; - private static final String ESCAPE_KEY_UNESCAPED = "apple:orange=lemon"; - private static final String ESCAPE_KEY_ESCAPED = "apple\\:orange\\=lemon"; - private static final String ESCAPE_VALUE_UNESCAPED = "http://foo.bar?parameter=1"; - private static final String ESCAPE_VALUE_ESCAPED = "http\\://foo.bar?parameter\\=1"; - - @Test public void testEscape() throws Exception - { - Config cfg = new Config(); - - cfg.setStrictOperator(false); - cfg.setEscape(true); - cfg.setEscapeKeyOnly(false); - Options opts = new Options(); - - opts.setConfig(cfg); - opts.put(ESCAPE_KEY_UNESCAPED, ESCAPE_VALUE_UNESCAPED); - opts.put(Dwarf.PROP_WEIGHT, null); - StringWriter writer = new StringWriter(); - - opts.store(writer); - StringBuilder exp = new StringBuilder(); - - exp.append(ESCAPE_KEY_ESCAPED); - exp.append(" = "); - exp.append(ESCAPE_VALUE_ESCAPED); - exp.append(NL); - assertEquals(exp.toString(), writer.toString()); - } - - @Test public void testEscapeFalse() throws Exception - { - Config cfg = new Config(); - - cfg.setStrictOperator(false); - cfg.setEscape(false); - cfg.setEscapeKeyOnly(false); - Options opts = new Options(); - - opts.setConfig(cfg); - opts.put(ESCAPE_KEY_UNESCAPED, ESCAPE_VALUE_UNESCAPED); - opts.put(Dwarf.PROP_WEIGHT, null); - StringWriter writer = new StringWriter(); - - opts.store(writer); - StringBuilder exp = new StringBuilder(); - - exp.append(ESCAPE_KEY_UNESCAPED); - exp.append(" = "); - exp.append(ESCAPE_VALUE_UNESCAPED); - exp.append(NL); - assertEquals(exp.toString(), writer.toString()); - } - - @Test public void testEscapeKeyOnly() throws Exception - { - Config cfg = new Config(); - - cfg.setStrictOperator(false); - cfg.setEscape(true); - cfg.setEscapeKeyOnly(true); - Options opts = new Options(); - - opts.setConfig(cfg); - opts.put(ESCAPE_KEY_UNESCAPED, ESCAPE_VALUE_UNESCAPED); - opts.put(Dwarf.PROP_WEIGHT, null); - StringWriter writer = new StringWriter(); - - opts.store(writer); - StringBuilder exp = new StringBuilder(); - - exp.append(ESCAPE_KEY_ESCAPED); - exp.append(" = "); - exp.append(ESCAPE_VALUE_UNESCAPED); - exp.append(NL); - assertEquals(exp.toString(), writer.toString()); - } - - @Test public void testFormat() throws Exception - { - Options opts = Helper.newDwarfsOpt(); - OptionsHandler handler = EasyMock.createMock(OptionsHandler.class); - Dwarf dwarf; - String prefix; - - handler.startOptions(); - handler.handleComment(Helper.HEADER_COMMENT); - handler.handleComment((String) EasyMock.anyObject()); - dwarf = DwarfsData.dopey; - handler.handleOption(Dwarf.PROP_WEIGHT, DwarfsData.OPT_DOPEY_WEIGHT); - handler.handleOption(Dwarf.PROP_HEIGHT, DwarfsData.OPT_DOPEY_HEIGHT); - handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, "11"); - handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, "33"); - handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, "55"); -// - - // - handler.handleComment(" " + Dwarfs.PROP_BASHFUL); - dwarf = DwarfsData.bashful; - prefix = Dwarfs.PROP_BASHFUL + "."; - - handler.handleOption(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); - handler.handleOption(prefix + Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); - handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.handleComment(" " + Dwarfs.PROP_DOC); - dwarf = DwarfsData.doc; - prefix = Dwarfs.PROP_DOC + "."; - - handler.handleOption(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); - handler.handleOption(prefix + Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); - handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.handleComment(" " + Dwarfs.PROP_DOPEY); - dwarf = DwarfsData.dopey; - prefix = Dwarfs.PROP_DOPEY + "."; - - handler.handleOption(prefix + Dwarf.PROP_WEIGHT, DwarfsData.OPT_DOPEY_WEIGHT); - handler.handleOption(prefix + Dwarf.PROP_HEIGHT, DwarfsData.OPT_DOPEY_HEIGHT); - handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.handleOption(prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[0])); - handler.handleOption(prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[1])); - handler.handleOption(prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[2])); - handler.handleComment(" " + Dwarfs.PROP_GRUMPY); - dwarf = DwarfsData.grumpy; - prefix = Dwarfs.PROP_GRUMPY + "."; - - handler.handleOption(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); - handler.handleOption(prefix + Dwarf.PROP_HEIGHT, DwarfsData.OPT_GRUMPY_HEIGHT); - handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.handleComment(" " + Dwarfs.PROP_HAPPY); - dwarf = DwarfsData.happy; - prefix = Dwarfs.PROP_HAPPY + "."; - - handler.handleOption(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); - handler.handleOption(prefix + Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); - handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.handleComment(" " + Dwarfs.PROP_SLEEPY); - dwarf = DwarfsData.sleepy; - prefix = Dwarfs.PROP_SLEEPY + "."; - - handler.handleOption(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); - handler.handleOption(prefix + Dwarf.PROP_HEIGHT, DwarfsData.OPT_SLEEPY_HEIGHT); - handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.handleOption(prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[0])); - handler.handleComment(" " + Dwarfs.PROP_SNEEZY); - dwarf = DwarfsData.sneezy; - prefix = Dwarfs.PROP_SNEEZY + "."; - - handler.handleOption(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); - handler.handleOption(prefix + Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); - handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, DwarfsData.OPT_SNEEZY_HOME_PAGE); - handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.handleOption(prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[0])); - handler.handleOption(prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[1])); - handler.handleOption(prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[2])); - handler.handleOption(prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[3])); - handler.endOptions(); - - // - EasyMock.replay(handler); - verify(opts, handler); - } - - @Test public void testNewInstance() throws Exception - { - StringWriter stringWriter; - PrintWriter printWriter; - - ; - Config cfg = new Config(); - OptionsFormatter instance; - - stringWriter = new StringWriter(); - instance = OptionsFormatter.newInstance(stringWriter, cfg); - - instance.getOutput().print(DUMMY); - instance.getOutput().flush(); - assertEquals(DUMMY, stringWriter.toString()); - assertSame(cfg, instance.getConfig()); - - // - stringWriter = new StringWriter(); - instance = OptionsFormatter.newInstance(stringWriter, cfg); - - instance.getOutput().print(DUMMY); - instance.getOutput().flush(); - assertEquals(DUMMY, stringWriter.toString()); - - // - printWriter = new PrintWriter(stringWriter); - instance = OptionsFormatter.newInstance(printWriter, cfg); - - assertSame(printWriter, instance.getOutput()); - } - - @Test public void testWithStrictOperatorEmptyOptions() throws Exception - { - Config cfg = new Config(); - - cfg.setStrictOperator(true); - cfg.setEmptyOption(true); - Options opts = new Options(); - - opts.setConfig(cfg); - opts.put(Dwarf.PROP_AGE, DwarfsData.bashful.age); - opts.put(Dwarf.PROP_WEIGHT, null); - StringWriter writer = new StringWriter(); - - opts.store(writer); - StringBuilder exp = new StringBuilder(); - - exp.append(Dwarf.PROP_AGE); - exp.append('='); - exp.append(DwarfsData.bashful.age); - exp.append(NL); - exp.append(Dwarf.PROP_WEIGHT); - exp.append('='); - exp.append(NL); - assertEquals(exp.toString(), writer.toString()); - } - - @Test public void testWithStrictOperatorEscape() throws Exception - { - Config cfg = new Config(); - - cfg.setStrictOperator(true); - cfg.setEscape(true); - cfg.setEscapeKeyOnly(false); - Options opts = new Options(); - - opts.setConfig(cfg); - opts.put(ESCAPE_KEY_UNESCAPED, ESCAPE_VALUE_UNESCAPED); - opts.put(Dwarf.PROP_WEIGHT, null); - StringWriter writer = new StringWriter(); - - opts.store(writer); - StringBuilder exp = new StringBuilder(); - - exp.append(ESCAPE_KEY_ESCAPED); - exp.append('='); - exp.append(ESCAPE_VALUE_ESCAPED); - exp.append(NL); - assertEquals(exp.toString(), writer.toString()); - } - - @Test public void testWithStrictOperatorEscapeFalse() throws Exception - { - Config cfg = new Config(); - - cfg.setStrictOperator(true); - cfg.setEscape(false); - cfg.setEscapeKeyOnly(false); - Options opts = new Options(); - - opts.setConfig(cfg); - opts.put(ESCAPE_KEY_UNESCAPED, ESCAPE_VALUE_UNESCAPED); - opts.put(Dwarf.PROP_WEIGHT, null); - StringWriter writer = new StringWriter(); - - opts.store(writer); - StringBuilder exp = new StringBuilder(); - - exp.append(ESCAPE_KEY_UNESCAPED); - exp.append('='); - exp.append(ESCAPE_VALUE_UNESCAPED); - exp.append(NL); - assertEquals(exp.toString(), writer.toString()); - } - - @Test public void testWithStrictOperatorEscapeKeyOnly() throws Exception - { - Config cfg = new Config(); - - cfg.setStrictOperator(true); - cfg.setEscape(true); - cfg.setEscapeKeyOnly(true); - Options opts = new Options(); - - opts.setConfig(cfg); - opts.put(ESCAPE_KEY_UNESCAPED, ESCAPE_VALUE_UNESCAPED); - opts.put(Dwarf.PROP_WEIGHT, null); - StringWriter writer = new StringWriter(); - - opts.store(writer); - StringBuilder exp = new StringBuilder(); - - exp.append(ESCAPE_KEY_ESCAPED); - exp.append('='); - exp.append(ESCAPE_VALUE_UNESCAPED); - exp.append(NL); - assertEquals(exp.toString(), writer.toString()); - } - - @Test public void testWithStrictOperatorNoEmptyOptions() throws Exception - { - Config cfg = new Config(); - - cfg.setStrictOperator(true); - cfg.setEmptyOption(false); - Options opts = new Options(); - - opts.setConfig(cfg); - opts.put(Dwarf.PROP_AGE, DwarfsData.bashful.age); - opts.put(Dwarf.PROP_WEIGHT, null); - StringWriter writer = new StringWriter(); - - opts.store(writer); - StringBuilder exp = new StringBuilder(); - - exp.append(Dwarf.PROP_AGE); - exp.append('='); - exp.append(DwarfsData.bashful.age); - exp.append(NL); - assertEquals(exp.toString(), writer.toString()); - } - - private void verify(Options opts, OptionsHandler mock) throws Exception - { - StringWriter writer = new StringWriter(); - - opts.store(writer); - OptionsParser parser = new OptionsParser(); - - parser.parse(new StringReader(writer.toString()), mock); - EasyMock.verify(mock); - } +public class OptionsFormatterTest extends Ini4jCase { + private static final String NL = System.getProperty("line.separator"); + private static final String DUMMY = "dummy"; + private static final String ESCAPE_KEY_UNESCAPED = "apple:orange=lemon"; + private static final String ESCAPE_KEY_ESCAPED = "apple\\:orange\\=lemon"; + private static final String ESCAPE_VALUE_UNESCAPED = "http://foo.bar?parameter=1"; + private static final String ESCAPE_VALUE_ESCAPED = "http\\://foo.bar?parameter\\=1"; + + @Test + public void testEscape() throws Exception { + Config cfg = new Config(); + + cfg.setStrictOperator(false); + cfg.setEscape(true); + cfg.setEscapeKeyOnly(false); + Options opts = new Options(); + + opts.setConfig(cfg); + opts.put(ESCAPE_KEY_UNESCAPED, ESCAPE_VALUE_UNESCAPED); + opts.put(Dwarf.PROP_WEIGHT, null); + StringWriter writer = new StringWriter(); + + opts.store(writer); + StringBuilder exp = new StringBuilder(); + + exp.append(ESCAPE_KEY_ESCAPED); + exp.append(" = "); + exp.append(ESCAPE_VALUE_ESCAPED); + exp.append(NL); + assertEquals(exp.toString(), writer.toString()); + } + + @Test + public void testEscapeFalse() throws Exception { + Config cfg = new Config(); + + cfg.setStrictOperator(false); + cfg.setEscape(false); + cfg.setEscapeKeyOnly(false); + Options opts = new Options(); + + opts.setConfig(cfg); + opts.put(ESCAPE_KEY_UNESCAPED, ESCAPE_VALUE_UNESCAPED); + opts.put(Dwarf.PROP_WEIGHT, null); + StringWriter writer = new StringWriter(); + + opts.store(writer); + StringBuilder exp = new StringBuilder(); + + exp.append(ESCAPE_KEY_UNESCAPED); + exp.append(" = "); + exp.append(ESCAPE_VALUE_UNESCAPED); + exp.append(NL); + assertEquals(exp.toString(), writer.toString()); + } + + @Test + public void testEscapeKeyOnly() throws Exception { + Config cfg = new Config(); + + cfg.setStrictOperator(false); + cfg.setEscape(true); + cfg.setEscapeKeyOnly(true); + Options opts = new Options(); + + opts.setConfig(cfg); + opts.put(ESCAPE_KEY_UNESCAPED, ESCAPE_VALUE_UNESCAPED); + opts.put(Dwarf.PROP_WEIGHT, null); + StringWriter writer = new StringWriter(); + + opts.store(writer); + StringBuilder exp = new StringBuilder(); + + exp.append(ESCAPE_KEY_ESCAPED); + exp.append(" = "); + exp.append(ESCAPE_VALUE_UNESCAPED); + exp.append(NL); + assertEquals(exp.toString(), writer.toString()); + } + + @Test + public void testFormat() throws Exception { + Options opts = Helper.newDwarfsOpt(); + OptionsHandler handler = EasyMock.createMock(OptionsHandler.class); + Dwarf dwarf; + String prefix; + + handler.startOptions(); + handler.handleComment(Helper.HEADER_COMMENT); + handler.handleComment((String) EasyMock.anyObject()); + dwarf = DwarfsData.dopey; + handler.handleOption(Dwarf.PROP_WEIGHT, DwarfsData.OPT_DOPEY_WEIGHT); + handler.handleOption(Dwarf.PROP_HEIGHT, DwarfsData.OPT_DOPEY_HEIGHT); + handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, "11"); + handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, "33"); + handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, "55"); + // + + // + handler.handleComment(" " + Dwarfs.PROP_BASHFUL); + dwarf = DwarfsData.bashful; + prefix = Dwarfs.PROP_BASHFUL + "."; + + handler.handleOption(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); + handler.handleOption(prefix + Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); + handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.handleComment(" " + Dwarfs.PROP_DOC); + dwarf = DwarfsData.doc; + prefix = Dwarfs.PROP_DOC + "."; + + handler.handleOption(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); + handler.handleOption(prefix + Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); + handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.handleComment(" " + Dwarfs.PROP_DOPEY); + dwarf = DwarfsData.dopey; + prefix = Dwarfs.PROP_DOPEY + "."; + + handler.handleOption(prefix + Dwarf.PROP_WEIGHT, DwarfsData.OPT_DOPEY_WEIGHT); + handler.handleOption(prefix + Dwarf.PROP_HEIGHT, DwarfsData.OPT_DOPEY_HEIGHT); + handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.handleOption( + prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[0])); + handler.handleOption( + prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[1])); + handler.handleOption( + prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[2])); + handler.handleComment(" " + Dwarfs.PROP_GRUMPY); + dwarf = DwarfsData.grumpy; + prefix = Dwarfs.PROP_GRUMPY + "."; + + handler.handleOption(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); + handler.handleOption(prefix + Dwarf.PROP_HEIGHT, DwarfsData.OPT_GRUMPY_HEIGHT); + handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.handleComment(" " + Dwarfs.PROP_HAPPY); + dwarf = DwarfsData.happy; + prefix = Dwarfs.PROP_HAPPY + "."; + + handler.handleOption(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); + handler.handleOption(prefix + Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); + handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.handleComment(" " + Dwarfs.PROP_SLEEPY); + dwarf = DwarfsData.sleepy; + prefix = Dwarfs.PROP_SLEEPY + "."; + + handler.handleOption(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); + handler.handleOption(prefix + Dwarf.PROP_HEIGHT, DwarfsData.OPT_SLEEPY_HEIGHT); + handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.handleOption( + prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[0])); + handler.handleComment(" " + Dwarfs.PROP_SNEEZY); + dwarf = DwarfsData.sneezy; + prefix = Dwarfs.PROP_SNEEZY + "."; + + handler.handleOption(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); + handler.handleOption(prefix + Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); + handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, DwarfsData.OPT_SNEEZY_HOME_PAGE); + handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.handleOption( + prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[0])); + handler.handleOption( + prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[1])); + handler.handleOption( + prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[2])); + handler.handleOption( + prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[3])); + handler.endOptions(); + + // + EasyMock.replay(handler); + verify(opts, handler); + } + + @Test + public void testNewInstance() throws Exception { + StringWriter stringWriter; + PrintWriter printWriter; + + ; + Config cfg = new Config(); + OptionsFormatter instance; + + stringWriter = new StringWriter(); + instance = OptionsFormatter.newInstance(stringWriter, cfg); + + instance.getOutput().print(DUMMY); + instance.getOutput().flush(); + assertEquals(DUMMY, stringWriter.toString()); + assertSame(cfg, instance.getConfig()); + + // + stringWriter = new StringWriter(); + instance = OptionsFormatter.newInstance(stringWriter, cfg); + + instance.getOutput().print(DUMMY); + instance.getOutput().flush(); + assertEquals(DUMMY, stringWriter.toString()); + + // + printWriter = new PrintWriter(stringWriter); + instance = OptionsFormatter.newInstance(printWriter, cfg); + + assertSame(printWriter, instance.getOutput()); + } + + @Test + public void testWithStrictOperatorEmptyOptions() throws Exception { + Config cfg = new Config(); + + cfg.setStrictOperator(true); + cfg.setEmptyOption(true); + Options opts = new Options(); + + opts.setConfig(cfg); + opts.put(Dwarf.PROP_AGE, DwarfsData.bashful.age); + opts.put(Dwarf.PROP_WEIGHT, null); + StringWriter writer = new StringWriter(); + + opts.store(writer); + StringBuilder exp = new StringBuilder(); + + exp.append(Dwarf.PROP_AGE); + exp.append('='); + exp.append(DwarfsData.bashful.age); + exp.append(NL); + exp.append(Dwarf.PROP_WEIGHT); + exp.append('='); + exp.append(NL); + assertEquals(exp.toString(), writer.toString()); + } + + @Test + public void testWithStrictOperatorEscape() throws Exception { + Config cfg = new Config(); + + cfg.setStrictOperator(true); + cfg.setEscape(true); + cfg.setEscapeKeyOnly(false); + Options opts = new Options(); + + opts.setConfig(cfg); + opts.put(ESCAPE_KEY_UNESCAPED, ESCAPE_VALUE_UNESCAPED); + opts.put(Dwarf.PROP_WEIGHT, null); + StringWriter writer = new StringWriter(); + + opts.store(writer); + StringBuilder exp = new StringBuilder(); + + exp.append(ESCAPE_KEY_ESCAPED); + exp.append('='); + exp.append(ESCAPE_VALUE_ESCAPED); + exp.append(NL); + assertEquals(exp.toString(), writer.toString()); + } + + @Test + public void testWithStrictOperatorEscapeFalse() throws Exception { + Config cfg = new Config(); + + cfg.setStrictOperator(true); + cfg.setEscape(false); + cfg.setEscapeKeyOnly(false); + Options opts = new Options(); + + opts.setConfig(cfg); + opts.put(ESCAPE_KEY_UNESCAPED, ESCAPE_VALUE_UNESCAPED); + opts.put(Dwarf.PROP_WEIGHT, null); + StringWriter writer = new StringWriter(); + + opts.store(writer); + StringBuilder exp = new StringBuilder(); + + exp.append(ESCAPE_KEY_UNESCAPED); + exp.append('='); + exp.append(ESCAPE_VALUE_UNESCAPED); + exp.append(NL); + assertEquals(exp.toString(), writer.toString()); + } + + @Test + public void testWithStrictOperatorEscapeKeyOnly() throws Exception { + Config cfg = new Config(); + + cfg.setStrictOperator(true); + cfg.setEscape(true); + cfg.setEscapeKeyOnly(true); + Options opts = new Options(); + + opts.setConfig(cfg); + opts.put(ESCAPE_KEY_UNESCAPED, ESCAPE_VALUE_UNESCAPED); + opts.put(Dwarf.PROP_WEIGHT, null); + StringWriter writer = new StringWriter(); + + opts.store(writer); + StringBuilder exp = new StringBuilder(); + + exp.append(ESCAPE_KEY_ESCAPED); + exp.append('='); + exp.append(ESCAPE_VALUE_UNESCAPED); + exp.append(NL); + assertEquals(exp.toString(), writer.toString()); + } + + @Test + public void testWithStrictOperatorNoEmptyOptions() throws Exception { + Config cfg = new Config(); + + cfg.setStrictOperator(true); + cfg.setEmptyOption(false); + Options opts = new Options(); + + opts.setConfig(cfg); + opts.put(Dwarf.PROP_AGE, DwarfsData.bashful.age); + opts.put(Dwarf.PROP_WEIGHT, null); + StringWriter writer = new StringWriter(); + + opts.store(writer); + StringBuilder exp = new StringBuilder(); + + exp.append(Dwarf.PROP_AGE); + exp.append('='); + exp.append(DwarfsData.bashful.age); + exp.append(NL); + assertEquals(exp.toString(), writer.toString()); + } + + private void verify(Options opts, OptionsHandler mock) throws Exception { + StringWriter writer = new StringWriter(); + + opts.store(writer); + OptionsParser parser = new OptionsParser(); + + parser.parse(new StringReader(writer.toString()), mock); + EasyMock.verify(mock); + } } diff --git a/src/test/java/org/ini4j/spi/OptionsParserTest.java b/src/test/java/org/ini4j/spi/OptionsParserTest.java index dd97230..89075bf 100644 --- a/src/test/java/org/ini4j/spi/OptionsParserTest.java +++ b/src/test/java/org/ini4j/spi/OptionsParserTest.java @@ -15,23 +15,9 @@ */ package org.ini4j.spi; -import org.easymock.EasyMock; - -import org.ini4j.Config; -import org.ini4j.Ini4jCase; -import org.ini4j.InvalidFileFormatException; - -import org.ini4j.sample.Dwarf; -import org.ini4j.sample.Dwarfs; - -import org.ini4j.test.DwarfsData; -import org.ini4j.test.Helper; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; -import org.junit.Test; - import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -40,182 +26,194 @@ import java.io.PrintWriter; import java.io.Reader; import java.io.StringReader; +import org.easymock.EasyMock; +import org.ini4j.Config; +import org.ini4j.Ini4jCase; +import org.ini4j.InvalidFileFormatException; +import org.ini4j.sample.Dwarf; +import org.ini4j.sample.Dwarfs; +import org.ini4j.test.DwarfsData; +import org.ini4j.test.Helper; +import org.junit.Test; -public class OptionsParserTest extends Ini4jCase -{ - private static final String CFG_EMPTY_OPTION = "option\n"; - private static final String NONAME = "=value\n"; - private static final String OPTION = "option"; - private static final String UNICODE_STRING = "áÁéÉíÍóÓöÖőŐúÚüÜűŰ-ÄÖÜäöü"; - - @Test public void testBad() throws Exception - { - OptionsParser parser = new OptionsParser(); - OptionsHandler handler = EasyMock.createNiceMock(OptionsHandler.class); - - try - { - parser.parse(new ByteArrayInputStream(NONAME.getBytes()), handler); - missing(InvalidFileFormatException.class); - } - catch (InvalidFileFormatException x) - { - // - } - } - - @Test public void testEmptyOption() throws Exception - { - OptionsParser parser = new OptionsParser(); - OptionsHandler handler = EasyMock.createMock(OptionsHandler.class); - - handler.startOptions(); - handler.handleOption(OPTION, null); - handler.endOptions(); - EasyMock.replay(handler); - Config cfg = new Config(); - - cfg.setEmptyOption(true); - parser.setConfig(cfg); - parser.parse(new StringReader(CFG_EMPTY_OPTION), handler); - EasyMock.verify(handler); - } - - @Test public void testEscape() throws Exception - { - } - - @Test public void testNewInstance() throws Exception - { - Config cfg = new Config(); - OptionsParser parser = OptionsParser.newInstance(); - - assertEquals(OptionsParser.class, parser.getClass()); - parser = OptionsParser.newInstance(cfg); - assertEquals(OptionsParser.class, parser.getClass()); - assertSame(cfg, parser.getConfig()); - } - - @Test public void testParse() throws Exception - { - OptionsParser parser = new OptionsParser(); - OptionsHandler handler = EasyMock.createMock(OptionsHandler.class); - Dwarf dwarf; - String prefix; - - handler.startOptions(); - handler.handleComment(Helper.HEADER_COMMENT); - handler.handleComment((String) EasyMock.anyObject()); - handler.handleComment((String) EasyMock.anyObject()); - dwarf = DwarfsData.dopey; - handler.handleOption(Dwarf.PROP_WEIGHT, DwarfsData.OPT_DOPEY_WEIGHT); - handler.handleOption(Dwarf.PROP_HEIGHT, DwarfsData.OPT_DOPEY_HEIGHT); - handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, "11"); - handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, "33"); - handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, "55"); -// - handler.handleComment((String) EasyMock.anyObject()); - - // - handler.handleComment(" " + Dwarfs.PROP_BASHFUL); - dwarf = DwarfsData.bashful; - prefix = Dwarfs.PROP_BASHFUL + "."; - - handler.handleOption(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); - handler.handleOption(prefix + Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); - handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.handleComment(" " + Dwarfs.PROP_DOC); - dwarf = DwarfsData.doc; - prefix = Dwarfs.PROP_DOC + "."; - - handler.handleOption(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); - handler.handleOption(prefix + Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); - handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.handleComment(" " + Dwarfs.PROP_DOPEY); - dwarf = DwarfsData.dopey; - prefix = Dwarfs.PROP_DOPEY + "."; - - handler.handleOption(prefix + Dwarf.PROP_WEIGHT, DwarfsData.OPT_DOPEY_WEIGHT); - handler.handleOption(prefix + Dwarf.PROP_HEIGHT, DwarfsData.OPT_DOPEY_HEIGHT); - handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.handleOption(prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[0])); - handler.handleOption(prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[1])); - handler.handleOption(prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[2])); - handler.handleComment(" " + Dwarfs.PROP_GRUMPY); - dwarf = DwarfsData.grumpy; - prefix = Dwarfs.PROP_GRUMPY + "."; - - handler.handleOption(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); - handler.handleOption(prefix + Dwarf.PROP_HEIGHT, DwarfsData.OPT_GRUMPY_HEIGHT); - handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.handleComment(" " + Dwarfs.PROP_HAPPY); - dwarf = DwarfsData.happy; - prefix = Dwarfs.PROP_HAPPY + "."; - - handler.handleOption(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); - handler.handleOption(prefix + Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); - handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(EasyMock.eq(prefix + Dwarf.PROP_HOME_PAGE), (String) EasyMock.anyObject()); - handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.handleComment(" " + Dwarfs.PROP_SLEEPY); - dwarf = DwarfsData.sleepy; - prefix = Dwarfs.PROP_SLEEPY + "."; - - handler.handleOption(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); - handler.handleOption(prefix + Dwarf.PROP_HEIGHT, DwarfsData.OPT_SLEEPY_HEIGHT); - handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.handleOption(prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[0])); - handler.handleComment(" " + Dwarfs.PROP_SNEEZY); - dwarf = DwarfsData.sneezy; - prefix = Dwarfs.PROP_SNEEZY + "."; - - handler.handleOption(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); - handler.handleOption(prefix + Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); - handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, DwarfsData.OPT_SNEEZY_HOME_PAGE); - handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); - handler.handleOption(prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[0])); - handler.handleOption(prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[1])); - handler.handleOption(prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[2])); - handler.handleOption(prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[3])); - handler.handleComment(" " + Dwarfs.PROP_HAPPY + " again"); - dwarf = DwarfsData.happy; - prefix = Dwarfs.PROP_HAPPY + "."; - - handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); - handler.handleComment("}"); - handler.endOptions(); - - // - EasyMock.replay(handler); - parser.parse(Helper.getResourceURL(Helper.DWARFS_OPT), handler); - EasyMock.verify(handler); - } - - @Test public void testUnicode() throws Exception - { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - OptionsFormatter formatter = new OptionsFormatter(); - - formatter.setOutput(new PrintWriter(new OutputStreamWriter(out))); - formatter.handleOption(OPTION, UNICODE_STRING); - formatter.getOutput().flush(); - Reader in = new InputStreamReader(new ByteArrayInputStream(out.toByteArray())); - String line = new BufferedReader(in).readLine(); - - assertEquals(OPTION + " = " + UNICODE_STRING, EscapeTool.getInstance().unescape(line)); +public class OptionsParserTest extends Ini4jCase { + private static final String CFG_EMPTY_OPTION = "option\n"; + private static final String NONAME = "=value\n"; + private static final String OPTION = "option"; + private static final String UNICODE_STRING = "áÁéÉíÍóÓöÖőŐúÚüÜűŰ-ÄÖÜäöü"; + + @Test + public void testBad() throws Exception { + OptionsParser parser = new OptionsParser(); + OptionsHandler handler = EasyMock.createNiceMock(OptionsHandler.class); + + try { + parser.parse(new ByteArrayInputStream(NONAME.getBytes()), handler); + missing(InvalidFileFormatException.class); + } catch (InvalidFileFormatException x) { + // } + } + + @Test + public void testEmptyOption() throws Exception { + OptionsParser parser = new OptionsParser(); + OptionsHandler handler = EasyMock.createMock(OptionsHandler.class); + + handler.startOptions(); + handler.handleOption(OPTION, null); + handler.endOptions(); + EasyMock.replay(handler); + Config cfg = new Config(); + + cfg.setEmptyOption(true); + parser.setConfig(cfg); + parser.parse(new StringReader(CFG_EMPTY_OPTION), handler); + EasyMock.verify(handler); + } + + @Test + public void testEscape() throws Exception {} + + @Test + public void testNewInstance() throws Exception { + Config cfg = new Config(); + OptionsParser parser = OptionsParser.newInstance(); + + assertEquals(OptionsParser.class, parser.getClass()); + parser = OptionsParser.newInstance(cfg); + assertEquals(OptionsParser.class, parser.getClass()); + assertSame(cfg, parser.getConfig()); + } + + @Test + public void testParse() throws Exception { + OptionsParser parser = new OptionsParser(); + OptionsHandler handler = EasyMock.createMock(OptionsHandler.class); + Dwarf dwarf; + String prefix; + + handler.startOptions(); + handler.handleComment(Helper.HEADER_COMMENT); + handler.handleComment((String) EasyMock.anyObject()); + handler.handleComment((String) EasyMock.anyObject()); + dwarf = DwarfsData.dopey; + handler.handleOption(Dwarf.PROP_WEIGHT, DwarfsData.OPT_DOPEY_WEIGHT); + handler.handleOption(Dwarf.PROP_HEIGHT, DwarfsData.OPT_DOPEY_HEIGHT); + handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleOption(Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, "11"); + handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, "33"); + handler.handleOption(Dwarf.PROP_FORTUNE_NUMBER, "55"); + // + handler.handleComment((String) EasyMock.anyObject()); + + // + handler.handleComment(" " + Dwarfs.PROP_BASHFUL); + dwarf = DwarfsData.bashful; + prefix = Dwarfs.PROP_BASHFUL + "."; + + handler.handleOption(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); + handler.handleOption(prefix + Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); + handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.handleComment(" " + Dwarfs.PROP_DOC); + dwarf = DwarfsData.doc; + prefix = Dwarfs.PROP_DOC + "."; + + handler.handleOption(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); + handler.handleOption(prefix + Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); + handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.handleComment(" " + Dwarfs.PROP_DOPEY); + dwarf = DwarfsData.dopey; + prefix = Dwarfs.PROP_DOPEY + "."; + + handler.handleOption(prefix + Dwarf.PROP_WEIGHT, DwarfsData.OPT_DOPEY_WEIGHT); + handler.handleOption(prefix + Dwarf.PROP_HEIGHT, DwarfsData.OPT_DOPEY_HEIGHT); + handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.handleOption( + prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[0])); + handler.handleOption( + prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[1])); + handler.handleOption( + prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[2])); + handler.handleComment(" " + Dwarfs.PROP_GRUMPY); + dwarf = DwarfsData.grumpy; + prefix = Dwarfs.PROP_GRUMPY + "."; + + handler.handleOption(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); + handler.handleOption(prefix + Dwarf.PROP_HEIGHT, DwarfsData.OPT_GRUMPY_HEIGHT); + handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.handleComment(" " + Dwarfs.PROP_HAPPY); + dwarf = DwarfsData.happy; + prefix = Dwarfs.PROP_HAPPY + "."; + + handler.handleOption(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); + handler.handleOption(prefix + Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); + handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(EasyMock.eq(prefix + Dwarf.PROP_HOME_PAGE), (String) EasyMock.anyObject()); + handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.handleComment(" " + Dwarfs.PROP_SLEEPY); + dwarf = DwarfsData.sleepy; + prefix = Dwarfs.PROP_SLEEPY + "."; + + handler.handleOption(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); + handler.handleOption(prefix + Dwarf.PROP_HEIGHT, DwarfsData.OPT_SLEEPY_HEIGHT); + handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.handleOption( + prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[0])); + handler.handleComment(" " + Dwarfs.PROP_SNEEZY); + dwarf = DwarfsData.sneezy; + prefix = Dwarfs.PROP_SNEEZY + "."; + + handler.handleOption(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); + handler.handleOption(prefix + Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); + handler.handleOption(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, DwarfsData.OPT_SNEEZY_HOME_PAGE); + handler.handleOption(prefix + Dwarf.PROP_HOME_DIR, String.valueOf(dwarf.getHomeDir())); + handler.handleOption( + prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[0])); + handler.handleOption( + prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[1])); + handler.handleOption( + prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[2])); + handler.handleOption( + prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(dwarf.getFortuneNumber()[3])); + handler.handleComment(" " + Dwarfs.PROP_HAPPY + " again"); + dwarf = DwarfsData.happy; + prefix = Dwarfs.PROP_HAPPY + "."; + + handler.handleOption(prefix + Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); + handler.handleComment("}"); + handler.endOptions(); + + // + EasyMock.replay(handler); + parser.parse(Helper.getResourceURL(Helper.DWARFS_OPT), handler); + EasyMock.verify(handler); + } + + @Test + public void testUnicode() throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + OptionsFormatter formatter = new OptionsFormatter(); + + formatter.setOutput(new PrintWriter(new OutputStreamWriter(out))); + formatter.handleOption(OPTION, UNICODE_STRING); + formatter.getOutput().flush(); + Reader in = new InputStreamReader(new ByteArrayInputStream(out.toByteArray())); + String line = new BufferedReader(in).readLine(); + + assertEquals(OPTION + " = " + UNICODE_STRING, EscapeTool.getInstance().unescape(line)); + } } diff --git a/src/test/java/org/ini4j/spi/RegEscapeToolTest.java b/src/test/java/org/ini4j/spi/RegEscapeToolTest.java index 2ee7163..c0bc752 100644 --- a/src/test/java/org/ini4j/spi/RegEscapeToolTest.java +++ b/src/test/java/org/ini4j/spi/RegEscapeToolTest.java @@ -15,31 +15,30 @@ */ package org.ini4j.spi; -import org.ini4j.Ini4jCase; - import static org.junit.Assert.assertEquals; +import org.ini4j.Ini4jCase; import org.junit.Before; import org.junit.Test; -public class RegEscapeToolTest extends Ini4jCase -{ - protected RegEscapeTool instance; +public class RegEscapeToolTest extends Ini4jCase { + protected RegEscapeTool instance; - @Before @Override public void setUp() throws Exception - { - super.setUp(); - instance = RegEscapeTool.getInstance(); - } + @Before + @Override + public void setUp() throws Exception { + super.setUp(); + instance = RegEscapeTool.getInstance(); + } - @Test public void testHexadecimal() - { - assertEquals(0, instance.hexadecimal(null).length()); - assertEquals(0, instance.hexadecimal("").length()); - } + @Test + public void testHexadecimal() { + assertEquals(0, instance.hexadecimal(null).length()); + assertEquals(0, instance.hexadecimal("").length()); + } - @Test public void testSingleton() throws Exception - { - assertEquals(RegEscapeTool.class, RegEscapeTool.getInstance().getClass()); - } + @Test + public void testSingleton() throws Exception { + assertEquals(RegEscapeTool.class, RegEscapeTool.getInstance().getClass()); + } } diff --git a/src/test/java/org/ini4j/spi/ServiceFinderTest.java b/src/test/java/org/ini4j/spi/ServiceFinderTest.java index 6f58c3b..92dfd50 100755 --- a/src/test/java/org/ini4j/spi/ServiceFinderTest.java +++ b/src/test/java/org/ini4j/spi/ServiceFinderTest.java @@ -15,72 +15,63 @@ */ package org.ini4j.spi; -import org.ini4j.Ini4jCase; - -import org.ini4j.test.Helper; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import org.ini4j.Ini4jCase; +import org.ini4j.test.Helper; import org.junit.Test; -public class ServiceFinderTest extends Ini4jCase -{ - static final String DUMMY = "dummy"; - static final String DUMMY_SERVICE = "org.ini4j.Dummy"; - static final String BAD_CONFIG_SERVICE = "org.ini4j.BadConfig"; - static final String EMPTY_CONFIG_SERVICE = "org.ini4j.EmptyConfig"; - static final String DUMMY_IMPL = "DummyImpl"; - - @Test public void testFindService() throws Exception - { - boolean flag = false; +public class ServiceFinderTest extends Ini4jCase { + static final String DUMMY = "dummy"; + static final String DUMMY_SERVICE = "org.ini4j.Dummy"; + static final String BAD_CONFIG_SERVICE = "org.ini4j.BadConfig"; + static final String EMPTY_CONFIG_SERVICE = "org.ini4j.EmptyConfig"; + static final String DUMMY_IMPL = "DummyImpl"; - System.setProperty(IniParser.class.getName(), Helper.class.getName()); - try - { - ServiceFinder.findService(IniParser.class); - } - catch (IllegalArgumentException x) - { - flag = true; - } + @Test + public void testFindService() throws Exception { + boolean flag = false; - // System.clearProperty(IniParser.SERVICE_ID); missing in 1.4 - System.getProperties().remove(IniParser.class.getName()); - assertTrue(flag); + System.setProperty(IniParser.class.getName(), Helper.class.getName()); + try { + ServiceFinder.findService(IniParser.class); + } catch (IllegalArgumentException x) { + flag = true; } - @Test public void testFindServiceClass() throws Exception - { - boolean flag = false; + // System.clearProperty(IniParser.SERVICE_ID); missing in 1.4 + System.getProperties().remove(IniParser.class.getName()); + assertTrue(flag); + } - System.setProperty(IniParser.class.getName(), DUMMY); - try - { - ServiceFinder.findServiceClass(IniParser.class); - } - catch (IllegalArgumentException x) - { - flag = true; - } + @Test + public void testFindServiceClass() throws Exception { + boolean flag = false; - // System.clearProperty(IniParser.SERVICE_ID); missing in 1.4 - System.getProperties().remove(IniParser.class.getName()); - assertTrue(flag); + System.setProperty(IniParser.class.getName(), DUMMY); + try { + ServiceFinder.findServiceClass(IniParser.class); + } catch (IllegalArgumentException x) { + flag = true; } - @Test public void testFindServiceClassName() throws Exception - { - System.setProperty(IniParser.class.getName(), DUMMY); - assertEquals(DUMMY, ServiceFinder.findServiceClassName(IniParser.class.getName())); + // System.clearProperty(IniParser.SERVICE_ID); missing in 1.4 + System.getProperties().remove(IniParser.class.getName()); + assertTrue(flag); + } - // System.clearProperty(IniParser.SERVICE_ID); missing in 1.4 - System.getProperties().remove(IniParser.class.getName()); - assertNull(ServiceFinder.findServiceClassName(IniParser.class.getName())); - assertEquals(DUMMY_IMPL, ServiceFinder.findServiceClassName(DUMMY_SERVICE)); - assertNull(DUMMY, ServiceFinder.findServiceClassName(BAD_CONFIG_SERVICE)); - assertNull(DUMMY, ServiceFinder.findServiceClassName(EMPTY_CONFIG_SERVICE)); - } + @Test + public void testFindServiceClassName() throws Exception { + System.setProperty(IniParser.class.getName(), DUMMY); + assertEquals(DUMMY, ServiceFinder.findServiceClassName(IniParser.class.getName())); + + // System.clearProperty(IniParser.SERVICE_ID); missing in 1.4 + System.getProperties().remove(IniParser.class.getName()); + assertNull(ServiceFinder.findServiceClassName(IniParser.class.getName())); + assertEquals(DUMMY_IMPL, ServiceFinder.findServiceClassName(DUMMY_SERVICE)); + assertNull(DUMMY, ServiceFinder.findServiceClassName(BAD_CONFIG_SERVICE)); + assertNull(DUMMY, ServiceFinder.findServiceClassName(EMPTY_CONFIG_SERVICE)); + } } diff --git a/src/test/java/org/ini4j/spi/UnicodeInputStreamReaderTest.java b/src/test/java/org/ini4j/spi/UnicodeInputStreamReaderTest.java index ffdc174..222136b 100644 --- a/src/test/java/org/ini4j/spi/UnicodeInputStreamReaderTest.java +++ b/src/test/java/org/ini4j/spi/UnicodeInputStreamReaderTest.java @@ -15,169 +15,150 @@ */ package org.ini4j.spi; +import java.nio.charset.Charset; import org.ini4j.Config; import org.ini4j.Ini; import org.ini4j.Ini4jCase; import org.ini4j.InvalidFileFormatException; - import org.junit.Test; -import java.nio.charset.Charset; - -public class UnicodeInputStreamReaderTest extends Ini4jCase -{ - @Test public void _testUTF32BE() throws Exception - { - test("UTF-32BE.ini", "UTF-32BE"); - } - - @Test public void _testUTF32BE_BOM() throws Exception - { - test("UTF-32BE-BOM.ini", null); - test("UTF-32BE-BOM.ini", "UTF-8"); - test("UTF-32BE-BOM.ini", "UTF-16"); - } - - @Test public void _testUTF32BE_fail() throws Exception - { - try - { - test("UTF-32BE.ini", "ISO-8859-1"); - missing(IllegalStateException.class); - } - catch (IllegalStateException x) - { - // - } - } - - @Test public void _testUTF32LE() throws Exception - { - test("UTF-32LE.ini", "UTF-32LE"); - } - - @Test public void _testUTF32LE_BOM() throws Exception - { - test("UTF-32LE-BOM.ini", null); - test("UTF-32LE-BOM.ini", "UTF-8"); - test("UTF-32LE-BOM.ini", "UTF-16"); - } - - @Test public void _testUTF32LE_fail() throws Exception - { - try - { - test("UTF-32LE.ini", "ISO-8859-1"); - missing(IllegalStateException.class); - } - catch (IllegalStateException x) - { - // - } - } - - @Test public void t_e_s_tUTF16BE_fail() throws Exception - { - try - { - test("UTF-16BE.ini", "ISO-8859-1"); - missing(IllegalStateException.class); - } - catch (IllegalStateException x) - { - // - } - } - - @Test public void t_e_s_tUTF16LE_fail() throws Exception - { - try - { - test("UTF-16LE.ini", "ISO-8859-1"); - missing(IllegalStateException.class); - } - catch (IllegalStateException x) - { - // - } - } - - @Test public void testUTF16BE() throws Exception - { - test("UTF-16BE.ini", "UTF-16BE"); - } - - @Test public void testUTF16BE_BOM() throws Exception - { - test("UTF-16BE-BOM.ini", null); - test("UTF-16BE-BOM.ini", "UTF-8"); - test("UTF-16BE-BOM.ini", "UTF-16"); - } - - @Test public void testUTF16LE() throws Exception - { - test("UTF-16LE.ini", "UTF-16LE"); - } - - @Test public void testUTF16LE_BOM() throws Exception - { - test("UTF-16LE-BOM.ini", null); - test("UTF-16LE-BOM.ini", "UTF-8"); - test("UTF-16LE-BOM.ini", "UTF-16"); - } - - @Test public void testUTF8() throws Exception - { - test("UTF-8.ini", null); - test("UTF-8.ini", "UTF-8"); - } - - @Test public void testUTF8_BOM() throws Exception - { - test("UTF-8-BOM.ini", null); - test("UTF-8-BOM.ini", "UTF-8"); - test("UTF-8-BOM.ini", "UTF-16"); - } - - @Test public void testUTF8_fail() throws Exception - { - try - { - test("UTF-8.ini", "UTF-16"); - missing(InvalidFileFormatException.class); - } - catch (InvalidFileFormatException x) - { - // - } - } - - private UnicodeInputStreamReader instantiate(String filename, String defaultEncoding) - { - Charset charset = (defaultEncoding == null) ? Charset.defaultCharset() : Charset.forName(defaultEncoding); - - return new UnicodeInputStreamReader(getClass().getResourceAsStream(filename), charset); - } - - private void test(String filename, String defaultEncoding) throws Exception - { - Charset charset = (defaultEncoding == null) ? Config.DEFAULT_FILE_ENCODING : Charset.forName(defaultEncoding); - UnicodeInputStreamReader reader = new UnicodeInputStreamReader(getClass().getResourceAsStream(filename), charset); - Ini ini = new Ini(); - - ini.setConfig(Config.getGlobal().clone()); - ini.getConfig().setFileEncoding(charset); - ini.load(reader); - Ini.Section sec = ini.get("section"); - - if (sec == null) - { - throw new IllegalStateException("Missing section: section"); - } - - if (!"value".equals(sec.get("option"))) - { - throw new IllegalStateException("Missing option: option"); - } - } +public class UnicodeInputStreamReaderTest extends Ini4jCase { + @Test + public void _testUTF32BE() throws Exception { + test("UTF-32BE.ini", "UTF-32BE"); + } + + @Test + public void _testUTF32BE_BOM() throws Exception { + test("UTF-32BE-BOM.ini", null); + test("UTF-32BE-BOM.ini", "UTF-8"); + test("UTF-32BE-BOM.ini", "UTF-16"); + } + + @Test + public void _testUTF32BE_fail() throws Exception { + try { + test("UTF-32BE.ini", "ISO-8859-1"); + missing(IllegalStateException.class); + } catch (IllegalStateException x) { + // + } + } + + @Test + public void _testUTF32LE() throws Exception { + test("UTF-32LE.ini", "UTF-32LE"); + } + + @Test + public void _testUTF32LE_BOM() throws Exception { + test("UTF-32LE-BOM.ini", null); + test("UTF-32LE-BOM.ini", "UTF-8"); + test("UTF-32LE-BOM.ini", "UTF-16"); + } + + @Test + public void _testUTF32LE_fail() throws Exception { + try { + test("UTF-32LE.ini", "ISO-8859-1"); + missing(IllegalStateException.class); + } catch (IllegalStateException x) { + // + } + } + + @Test + public void t_e_s_tUTF16BE_fail() throws Exception { + try { + test("UTF-16BE.ini", "ISO-8859-1"); + missing(IllegalStateException.class); + } catch (IllegalStateException x) { + // + } + } + + @Test + public void t_e_s_tUTF16LE_fail() throws Exception { + try { + test("UTF-16LE.ini", "ISO-8859-1"); + missing(IllegalStateException.class); + } catch (IllegalStateException x) { + // + } + } + + @Test + public void testUTF16BE() throws Exception { + test("UTF-16BE.ini", "UTF-16BE"); + } + + @Test + public void testUTF16BE_BOM() throws Exception { + test("UTF-16BE-BOM.ini", null); + test("UTF-16BE-BOM.ini", "UTF-8"); + test("UTF-16BE-BOM.ini", "UTF-16"); + } + + @Test + public void testUTF16LE() throws Exception { + test("UTF-16LE.ini", "UTF-16LE"); + } + + @Test + public void testUTF16LE_BOM() throws Exception { + test("UTF-16LE-BOM.ini", null); + test("UTF-16LE-BOM.ini", "UTF-8"); + test("UTF-16LE-BOM.ini", "UTF-16"); + } + + @Test + public void testUTF8() throws Exception { + test("UTF-8.ini", null); + test("UTF-8.ini", "UTF-8"); + } + + @Test + public void testUTF8_BOM() throws Exception { + test("UTF-8-BOM.ini", null); + test("UTF-8-BOM.ini", "UTF-8"); + test("UTF-8-BOM.ini", "UTF-16"); + } + + @Test + public void testUTF8_fail() throws Exception { + try { + test("UTF-8.ini", "UTF-16"); + missing(InvalidFileFormatException.class); + } catch (InvalidFileFormatException x) { + // + } + } + + private UnicodeInputStreamReader instantiate(String filename, String defaultEncoding) { + Charset charset = + (defaultEncoding == null) ? Charset.defaultCharset() : Charset.forName(defaultEncoding); + + return new UnicodeInputStreamReader(getClass().getResourceAsStream(filename), charset); + } + + private void test(String filename, String defaultEncoding) throws Exception { + Charset charset = + (defaultEncoding == null) ? Config.DEFAULT_FILE_ENCODING : Charset.forName(defaultEncoding); + UnicodeInputStreamReader reader = + new UnicodeInputStreamReader(getClass().getResourceAsStream(filename), charset); + Ini ini = new Ini(); + + ini.setConfig(Config.getGlobal().clone()); + ini.getConfig().setFileEncoding(charset); + ini.load(reader); + Ini.Section sec = ini.get("section"); + + if (sec == null) { + throw new IllegalStateException("Missing section: section"); + } + + if (!"value".equals(sec.get("option"))) { + throw new IllegalStateException("Missing option: option"); + } + } } diff --git a/src/test/java/org/ini4j/spi/WinEscapeToolTest.java b/src/test/java/org/ini4j/spi/WinEscapeToolTest.java index a00694d..5e9fb52 100644 --- a/src/test/java/org/ini4j/spi/WinEscapeToolTest.java +++ b/src/test/java/org/ini4j/spi/WinEscapeToolTest.java @@ -15,83 +15,76 @@ */ package org.ini4j.spi; -import org.ini4j.Ini4jCase; - import static org.junit.Assert.assertEquals; +import org.ini4j.Ini4jCase; import org.junit.Before; import org.junit.Test; -public class WinEscapeToolTest extends Ini4jCase -{ - public static final String VALUE1 = "simple"; - public static final String ESCAPE1 = "simple"; - public static final String VALUE2 = "Iván"; - public static final String ESCAPE2 = "Iv\\xe1n"; - public static final String VALUE3 = "1\t2\n3\f4\b5\r6"; - public static final String ESCAPE3 = "1\\t2\\n3\\f4\\b5\\r6"; - public static final String VALUE4 = "Iv\u0017n"; - public static final String ESCAPE4 = "Iv\\x17n"; - public static final String VALUE5 = "Árvíztrtükörfúrógép"; - public static final String ESCAPE5 = "\\xc1rv\\xedztrt\\xfck\\xf6rf\\xfar\\xf3g\\xe9p"; - private static final String INVALID_HEX = "\\x1_"; - private static final String INVALID_OCT = "\\o19_"; - protected WinEscapeTool instance; +public class WinEscapeToolTest extends Ini4jCase { + public static final String VALUE1 = "simple"; + public static final String ESCAPE1 = "simple"; + public static final String VALUE2 = "Iván"; + public static final String ESCAPE2 = "Iv\\xe1n"; + public static final String VALUE3 = "1\t2\n3\f4\b5\r6"; + public static final String ESCAPE3 = "1\\t2\\n3\\f4\\b5\\r6"; + public static final String VALUE4 = "Iv\u0017n"; + public static final String ESCAPE4 = "Iv\\x17n"; + public static final String VALUE5 = "Árvíztrtükörfúrógép"; + public static final String ESCAPE5 = "\\xc1rv\\xedztrt\\xfck\\xf6rf\\xfar\\xf3g\\xe9p"; + private static final String INVALID_HEX = "\\x1_"; + private static final String INVALID_OCT = "\\o19_"; + protected WinEscapeTool instance; - @Before @Override public void setUp() throws Exception - { - super.setUp(); - instance = WinEscapeTool.getInstance(); - } + @Before + @Override + public void setUp() throws Exception { + super.setUp(); + instance = WinEscapeTool.getInstance(); + } - @Test public void testEscape() throws Exception - { - assertEquals(ESCAPE1, instance.escape(VALUE1)); - assertEquals(ESCAPE2, instance.escape(VALUE2)); - assertEquals(ESCAPE3, instance.escape(VALUE3)); - assertEquals(ESCAPE4, instance.escape(VALUE4)); - assertEquals(ESCAPE5, instance.escape(VALUE5)); - } + @Test + public void testEscape() throws Exception { + assertEquals(ESCAPE1, instance.escape(VALUE1)); + assertEquals(ESCAPE2, instance.escape(VALUE2)); + assertEquals(ESCAPE3, instance.escape(VALUE3)); + assertEquals(ESCAPE4, instance.escape(VALUE4)); + assertEquals(ESCAPE5, instance.escape(VALUE5)); + } - @Test public void testInvalidHex() - { - try - { - instance.unescape(INVALID_HEX); - missing(IllegalArgumentException.class); - } - catch (IllegalArgumentException x) - { - // - } + @Test + public void testInvalidHex() { + try { + instance.unescape(INVALID_HEX); + missing(IllegalArgumentException.class); + } catch (IllegalArgumentException x) { + // } + } - @Test public void testInvalidOctal() - { - try - { - instance.unescape(INVALID_OCT); - missing(IllegalArgumentException.class); - } - catch (IllegalArgumentException x) - { - // - } + @Test + public void testInvalidOctal() { + try { + instance.unescape(INVALID_OCT); + missing(IllegalArgumentException.class); + } catch (IllegalArgumentException x) { + // } + } - @Test public void testSingleton() throws Exception - { - assertEquals(WinEscapeTool.class, WinEscapeTool.getInstance().getClass()); - } + @Test + public void testSingleton() throws Exception { + assertEquals(WinEscapeTool.class, WinEscapeTool.getInstance().getClass()); + } - @Test public void testUnescape() throws Exception - { - assertEquals(VALUE1, instance.unescape(ESCAPE1)); - assertEquals(VALUE2, instance.unescape(ESCAPE2)); - assertEquals(VALUE3, instance.unescape(ESCAPE3)); - assertEquals(VALUE4, instance.unescape(ESCAPE4)); - assertEquals(VALUE5, instance.unescape(ESCAPE5)); - assertEquals("=", instance.unescape("\\=")); - assertEquals("xAx", instance.unescape("x\\o101x")); - } + @Test + public void testUnescape() throws Exception { + assertEquals(VALUE1, instance.unescape(ESCAPE1)); + assertEquals(VALUE2, instance.unescape(ESCAPE2)); + assertEquals(VALUE3, instance.unescape(ESCAPE3)); + assertEquals(VALUE4, instance.unescape(ESCAPE4)); + assertEquals(VALUE5, instance.unescape(ESCAPE5)); + assertEquals("=", instance.unescape("\\=")); + assertEquals("xAx", instance.unescape("x\\o101x")); + } } diff --git a/src/test/java/org/ini4j/test/DwarfsData.java b/src/test/java/org/ini4j/test/DwarfsData.java index 18644fd..9e1f056 100644 --- a/src/test/java/org/ini4j/test/DwarfsData.java +++ b/src/test/java/org/ini4j/test/DwarfsData.java @@ -15,213 +15,225 @@ */ package org.ini4j.test; -import org.ini4j.sample.Dwarf; -import org.ini4j.sample.Dwarfs; - import java.beans.PropertyChangeListener; import java.beans.PropertyVetoException; import java.beans.VetoableChangeListener; - import java.net.URI; +import org.ini4j.sample.Dwarf; +import org.ini4j.sample.Dwarfs; + +public final class DwarfsData implements Dwarfs { + public static final DwarfData bashful; + public static final DwarfData doc; + public static final DwarfData dopey; + public static final DwarfData grumpy; + public static final DwarfData happy; + public static final DwarfData sleepy; + public static final DwarfData sneezy; + public static final Dwarfs dwarfs; + public static final String[] dwarfNames; + public static final String INI_DOPEY_WEIGHT = "${bashful/weight}"; + public static final String INI_DOPEY_HEIGHT = "${doc/height}"; + public static final String INI_GRUMPY_HEIGHT = "${dopey/height}"; + public static final String INI_SLEEPY_HEIGHT = "${doc/height}8"; + public static final String INI_SNEEZY_HOME_PAGE = "${happy/homePage}/~sneezy"; + public static final String OPT_DOPEY_WEIGHT = "${bashful.weight}"; + public static final String OPT_DOPEY_HEIGHT = "${doc.height}"; + public static final String OPT_GRUMPY_HEIGHT = "${dopey.height}"; + public static final String OPT_SLEEPY_HEIGHT = "${doc.height}8"; + public static final String OPT_SNEEZY_HOME_PAGE = "${happy.homePage}/~sneezy"; + + static { + + // age, fortuneNumber, height, homeDir, homePage, weight + bashful = + new DwarfData( + PROP_BASHFUL, 67, null, 98.8, "/home/bashful", "http://snowwhite.tale/~bashful", 45.7); + doc = + new DwarfData( + PROP_DOC, 63, null, 87.7, "c:Documents and Settingsdoc", "http://doc.dwarfs", 49.5); + dopey = + new DwarfData( + PROP_DOPEY, + 23, + new int[] {11, 33, 55}, + doc.height, + "c:\\Documents and Settings\\dopey", + "http://dopey.snowwhite.tale/", + bashful.weight); + grumpy = + new DwarfData( + PROP_GRUMPY, + 76, + null, + dopey.height, + "/home/grumpy", + "http://snowwhite.tale/~grumpy/", + 65.3); + happy = new DwarfData(PROP_HAPPY, 99, null, 77.66, "/home/happy", "http://happy.smurf", 56.4); + sleepy = + new DwarfData( + PROP_SLEEPY, + 121, + new int[] {99}, + doc.height + 0.08, + "/home/sleepy", + "http://snowwhite.tale/~sleepy", + 76.11); + sneezy = + new DwarfData( + PROP_SNEEZY, + 64, + new int[] {11, 22, 33, 44}, + 76.88, + "/home/sneezy", + happy.homePage.toString() + "/~sneezy", + 69.7); + dwarfs = new DwarfsData(); + dwarfNames = + new String[] { + bashful.name, doc.name, dopey.name, grumpy.name, happy.name, sleepy.name, sneezy.name + }; + } + + @SuppressWarnings("empty-statement") + private DwarfsData() { + ; + } + + public Dwarf getBashful() { + return bashful; + } + + public Dwarf getDoc() { + return doc; + } + + public Dwarf getDopey() { + return dopey; + } + + public Dwarf getGrumpy() { + return grumpy; + } + + public Dwarf getHappy() { + return happy; + } + + public Dwarf getSleepy() { + return sleepy; + } + + public Dwarf getSneezy() { + return sneezy; + } + + public static class DwarfData implements Dwarf { + private static final String READ_ONLY_INSTANCE = "Read only instance"; + public final int age; + public final int[] fortuneNumber; + public final double height; + public final String homeDir; + public final URI homePage; + public final String name; + public final double weight; + + public DwarfData( + String name, + int age, + int[] fortuneNumber, + double height, + String homeDir, + String homePage, + double weight) { + this.name = name; + this.age = age; + this.fortuneNumber = fortuneNumber; + this.height = height; + this.homeDir = homeDir; + this.homePage = URI.create(homePage); + this.weight = weight; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + throw new UnsupportedOperationException(READ_ONLY_INSTANCE); + } + + public int[] getFortuneNumber() { + return fortuneNumber; + } + + public void setFortuneNumber(int[] value) { + throw new UnsupportedOperationException(READ_ONLY_INSTANCE); + } + + public double getHeight() { + return height; + } + + public void setHeight(double height) throws PropertyVetoException { + throw new UnsupportedOperationException(READ_ONLY_INSTANCE); + } + + public String getHomeDir() { + return homeDir; + } + + public void setHomeDir(String dir) { + throw new UnsupportedOperationException(READ_ONLY_INSTANCE); + } + + public URI getHomePage() { + return homePage; + } + + public void setHomePage(URI location) { + throw new UnsupportedOperationException(READ_ONLY_INSTANCE); + } + + public double getWeight() { + return weight; + } + + public void setWeight(double weight) { + throw new UnsupportedOperationException(READ_ONLY_INSTANCE); + } + + public void addPropertyChangeListener(String property, PropertyChangeListener listener) { + throw new UnsupportedOperationException(READ_ONLY_INSTANCE); + } + + public void addVetoableChangeListener(String property, VetoableChangeListener listener) { + throw new UnsupportedOperationException(READ_ONLY_INSTANCE); + } + + public boolean hasAge() { + return age != 0; + } + + public boolean hasHeight() { + return height != 0.0; + } + + public boolean hasHomePage() { + return homePage != null; + } + + public boolean hasWeight() { + return weight != 0.0; + } + + public void removePropertyChangeListener(String property, PropertyChangeListener listener) { + throw new UnsupportedOperationException(READ_ONLY_INSTANCE); + } -public final class DwarfsData implements Dwarfs -{ - public static final DwarfData bashful; - public static final DwarfData doc; - public static final DwarfData dopey; - public static final DwarfData grumpy; - public static final DwarfData happy; - public static final DwarfData sleepy; - public static final DwarfData sneezy; - public static final Dwarfs dwarfs; - public static final String[] dwarfNames; - public static final String INI_DOPEY_WEIGHT = "${bashful/weight}"; - public static final String INI_DOPEY_HEIGHT = "${doc/height}"; - public static final String INI_GRUMPY_HEIGHT = "${dopey/height}"; - public static final String INI_SLEEPY_HEIGHT = "${doc/height}8"; - public static final String INI_SNEEZY_HOME_PAGE = "${happy/homePage}/~sneezy"; - public static final String OPT_DOPEY_WEIGHT = "${bashful.weight}"; - public static final String OPT_DOPEY_HEIGHT = "${doc.height}"; - public static final String OPT_GRUMPY_HEIGHT = "${dopey.height}"; - public static final String OPT_SLEEPY_HEIGHT = "${doc.height}8"; - public static final String OPT_SNEEZY_HOME_PAGE = "${happy.homePage}/~sneezy"; - - static - { - - // age, fortuneNumber, height, homeDir, homePage, weight - bashful = new DwarfData(PROP_BASHFUL, 67, null, 98.8, "/home/bashful", "http://snowwhite.tale/~bashful", 45.7); - doc = new DwarfData(PROP_DOC, 63, null, 87.7, "c:Documents and Settingsdoc", "http://doc.dwarfs", 49.5); - dopey = new DwarfData(PROP_DOPEY, 23, new int[] { 11, 33, 55 }, doc.height, "c:\\Documents and Settings\\dopey", "http://dopey.snowwhite.tale/", bashful.weight); - grumpy = new DwarfData(PROP_GRUMPY, 76, null, dopey.height, "/home/grumpy", "http://snowwhite.tale/~grumpy/", 65.3); - happy = new DwarfData(PROP_HAPPY, 99, null, 77.66, "/home/happy", "http://happy.smurf", 56.4); - sleepy = new DwarfData(PROP_SLEEPY, 121, new int[] { 99 }, doc.height + 0.08, "/home/sleepy", "http://snowwhite.tale/~sleepy", 76.11); - sneezy = new DwarfData(PROP_SNEEZY, 64, new int[] { 11, 22, 33, 44 }, 76.88, "/home/sneezy", happy.homePage.toString() + "/~sneezy", 69.7); - dwarfs = new DwarfsData(); - dwarfNames = new String[] { bashful.name, doc.name, dopey.name, grumpy.name, happy.name, sleepy.name, sneezy.name }; - } - - @SuppressWarnings("empty-statement") - private DwarfsData() - { - ; - } - - public Dwarf getBashful() - { - return bashful; - } - - public Dwarf getDoc() - { - return doc; - } - - public Dwarf getDopey() - { - return dopey; - } - - public Dwarf getGrumpy() - { - return grumpy; - } - - public Dwarf getHappy() - { - return happy; - } - - public Dwarf getSleepy() - { - return sleepy; - } - - public Dwarf getSneezy() - { - return sneezy; - } - - public static class DwarfData implements Dwarf - { - private static final String READ_ONLY_INSTANCE = "Read only instance"; - public final int age; - public final int[] fortuneNumber; - public final double height; - public final String homeDir; - public final URI homePage; - public final String name; - public final double weight; - - public DwarfData(String name, int age, int[] fortuneNumber, double height, String homeDir, String homePage, double weight) - { - this.name = name; - this.age = age; - this.fortuneNumber = fortuneNumber; - this.height = height; - this.homeDir = homeDir; - this.homePage = URI.create(homePage); - this.weight = weight; - } - - public int getAge() - { - return age; - } - - public void setAge(int age) - { - throw new UnsupportedOperationException(READ_ONLY_INSTANCE); - } - - public int[] getFortuneNumber() - { - return fortuneNumber; - } - - public void setFortuneNumber(int[] value) - { - throw new UnsupportedOperationException(READ_ONLY_INSTANCE); - } - - public double getHeight() - { - return height; - } - - public void setHeight(double height) throws PropertyVetoException - { - throw new UnsupportedOperationException(READ_ONLY_INSTANCE); - } - - public String getHomeDir() - { - return homeDir; - } - - public void setHomeDir(String dir) - { - throw new UnsupportedOperationException(READ_ONLY_INSTANCE); - } - - public URI getHomePage() - { - return homePage; - } - - public void setHomePage(URI location) - { - throw new UnsupportedOperationException(READ_ONLY_INSTANCE); - } - - public double getWeight() - { - return weight; - } - - public void setWeight(double weight) - { - throw new UnsupportedOperationException(READ_ONLY_INSTANCE); - } - - public void addPropertyChangeListener(String property, PropertyChangeListener listener) - { - throw new UnsupportedOperationException(READ_ONLY_INSTANCE); - } - - public void addVetoableChangeListener(String property, VetoableChangeListener listener) - { - throw new UnsupportedOperationException(READ_ONLY_INSTANCE); - } - - public boolean hasAge() - { - return age != 0; - } - - public boolean hasHeight() - { - return height != 0.0; - } - - public boolean hasHomePage() - { - return homePage != null; - } - - public boolean hasWeight() - { - return weight != 0.0; - } - - public void removePropertyChangeListener(String property, PropertyChangeListener listener) - { - throw new UnsupportedOperationException(READ_ONLY_INSTANCE); - } - - public void removeVetoableChangeListener(String property, VetoableChangeListener listener) - { - throw new UnsupportedOperationException(READ_ONLY_INSTANCE); - } + public void removeVetoableChangeListener(String property, VetoableChangeListener listener) { + throw new UnsupportedOperationException(READ_ONLY_INSTANCE); } + } } diff --git a/src/test/java/org/ini4j/test/Helper.java b/src/test/java/org/ini4j/test/Helper.java index c389102..0681d4f 100755 --- a/src/test/java/org/ini4j/test/Helper.java +++ b/src/test/java/org/ini4j/test/Helper.java @@ -15,6 +15,12 @@ */ package org.ini4j.test; +import java.io.File; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.net.URL; +import java.util.Properties; import org.ini4j.Config; import org.ini4j.Ini; import org.ini4j.OptionMap; @@ -22,330 +28,294 @@ import org.ini4j.Profile; import org.ini4j.Reg; import org.ini4j.Registry; - import org.ini4j.sample.Dwarf; import org.ini4j.sample.Dwarfs; - import org.ini4j.spi.IniFormatter; import org.ini4j.spi.IniParser; - import org.ini4j.test.DwarfsData.DwarfData; - import org.junit.Assert; -import java.io.File; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; - -import java.net.URL; - -import java.util.Properties; - -public class Helper -{ - private static final String RESOURCE_PREFIX = "org/ini4j/sample/"; - private static final File _sourceDir = new File(System.getProperty("basedir") + "/src/test/java/"); - private static final File _targetDir = new File(System.getProperty("basedir") + "/target"); - public static final String DWARFS_INI = RESOURCE_PREFIX + "dwarfs.ini"; - public static final String TALE_INI = RESOURCE_PREFIX + "tale.ini"; - public static final String DWARFS_OPT = RESOURCE_PREFIX + "dwarfs.opt"; - public static final String DWARFS_REG = RESOURCE_PREFIX + "dwarfs.reg"; - public static final String TEST_REG = "org/ini4j/mozilla.reg"; - public static final String DWARFS_REG_PATH = Reg.Hive.HKEY_CURRENT_USER + "\\Software\\ini4j-test"; - public static final float DELTA = 0.00000001f; - private static final String[] CONFIG_PROPERTIES = - { - Config.PROP_EMPTY_OPTION, Config.PROP_GLOBAL_SECTION, Config.PROP_GLOBAL_SECTION_NAME, Config.PROP_INCLUDE, Config.PROP_LOWER_CASE_OPTION, - Config.PROP_LOWER_CASE_SECTION, Config.PROP_MULTI_OPTION, Config.PROP_MULTI_SECTION, Config.PROP_STRICT_OPERATOR, - Config.PROP_UNNAMED_SECTION, Config.PROP_ESCAPE, Config.PROP_ESCAPE_NEWLINE, - Config.PROP_ESCAPE_KEY_ONLY, Config.PROP_PATH_SEPARATOR, Config.PROP_TREE, Config.PROP_PROPERTY_FIRST_UPPER, - Config.PROP_FILE_ENCODING, Config.PROP_LINE_SEPARATOR, Config.PROP_COMMENT, Config.PROP_HEADER_COMMENT, - Config.PROP_EMPTY_SECTION - }; - private static final String[] FACTORY_PROPERTIES = { IniFormatter.class.getName(), IniParser.class.getName() }; - public static final String HEADER_COMMENT = " Copyright 2005,2009 Ivan SZKIBA\n" + "\n" - + " Licensed under the Apache License, Version 2.0 (the \"License\");\n" - + " you may not use this file except in compliance with the License.\n" + " You may obtain a copy of the License at\n" + "\n" - + " http://www.apache.org/licenses/LICENSE-2.0\n" + "\n" + " Unless required by applicable law or agreed to in writing, software\n" - + " distributed under the License is distributed on an \"AS IS\" BASIS,\n" - + " WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" - + " See the License for the specific language governing permissions and\n" + " limitations under the License."; - - private Helper() - { +public class Helper { + private static final String RESOURCE_PREFIX = "org/ini4j/sample/"; + private static final File _sourceDir = + new File(System.getProperty("basedir") + "/src/test/java/"); + private static final File _targetDir = new File(System.getProperty("basedir") + "/target"); + public static final String DWARFS_INI = RESOURCE_PREFIX + "dwarfs.ini"; + public static final String TALE_INI = RESOURCE_PREFIX + "tale.ini"; + public static final String DWARFS_OPT = RESOURCE_PREFIX + "dwarfs.opt"; + public static final String DWARFS_REG = RESOURCE_PREFIX + "dwarfs.reg"; + public static final String TEST_REG = "org/ini4j/mozilla.reg"; + public static final String DWARFS_REG_PATH = + Reg.Hive.HKEY_CURRENT_USER + "\\Software\\ini4j-test"; + public static final float DELTA = 0.00000001f; + private static final String[] CONFIG_PROPERTIES = { + Config.PROP_EMPTY_OPTION, + Config.PROP_GLOBAL_SECTION, + Config.PROP_GLOBAL_SECTION_NAME, + Config.PROP_INCLUDE, + Config.PROP_LOWER_CASE_OPTION, + Config.PROP_LOWER_CASE_SECTION, + Config.PROP_MULTI_OPTION, + Config.PROP_MULTI_SECTION, + Config.PROP_STRICT_OPERATOR, + Config.PROP_UNNAMED_SECTION, + Config.PROP_ESCAPE, + Config.PROP_ESCAPE_NEWLINE, + Config.PROP_ESCAPE_KEY_ONLY, + Config.PROP_PATH_SEPARATOR, + Config.PROP_TREE, + Config.PROP_PROPERTY_FIRST_UPPER, + Config.PROP_FILE_ENCODING, + Config.PROP_LINE_SEPARATOR, + Config.PROP_COMMENT, + Config.PROP_HEADER_COMMENT, + Config.PROP_EMPTY_SECTION + }; + private static final String[] FACTORY_PROPERTIES = { + IniFormatter.class.getName(), IniParser.class.getName() + }; + public static final String HEADER_COMMENT = + " Copyright 2005,2009 Ivan SZKIBA\n" + + "\n" + + " Licensed under the Apache License, Version 2.0 (the \"License\");\n" + + " you may not use this file except in compliance with the License.\n" + + " You may obtain a copy of the License at\n" + + "\n" + + " http://www.apache.org/licenses/LICENSE-2.0\n" + + "\n" + + " Unless required by applicable law or agreed to in writing, software\n" + + " distributed under the License is distributed on an \"AS IS\" BASIS,\n" + + " WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" + + " See the License for the specific language governing permissions and\n" + + " limitations under the License."; + + private Helper() {} + + public static File getBuildDirectory() { + return _targetDir; + } + + public static Reader getResourceReader(String path) throws Exception { + return new InputStreamReader(getResourceURL(path).openStream()); + } + + public static InputStream getResourceStream(String path) throws Exception { + return getResourceURL(path).openStream(); + } + + public static URL getResourceURL(String path) throws Exception { + return Helper.class.getClassLoader().getResource(path); + } + + public static File getSourceFile(String path) throws Exception { + return new File(_sourceDir, path).getCanonicalFile(); + } + + public static void addDwarf(OptionMap opts, DwarfData dwarf) { + addDwarf(opts, dwarf, true); + } + + public static Profile.Section addDwarf(Profile prof, DwarfData dwarf) { + Profile.Section s = prof.add(dwarf.name); + + inject(s, dwarf, ""); + if (dwarf.name.equals(Dwarfs.PROP_DOPEY)) { + s.put(Dwarf.PROP_WEIGHT, DwarfsData.INI_DOPEY_WEIGHT, 0); + s.put(Dwarf.PROP_HEIGHT, DwarfsData.INI_DOPEY_HEIGHT, 0); + } else if (dwarf.name.equals(Dwarfs.PROP_GRUMPY)) { + s.put(Dwarf.PROP_HEIGHT, DwarfsData.INI_GRUMPY_HEIGHT, 0); + } else if (dwarf.name.equals(Dwarfs.PROP_SLEEPY)) { + s.put(Dwarf.PROP_HEIGHT, DwarfsData.INI_SLEEPY_HEIGHT, 0); + } else if (dwarf.name.equals(Dwarfs.PROP_SNEEZY)) { + s.put(Dwarf.PROP_HOME_PAGE, DwarfsData.INI_SNEEZY_HOME_PAGE, 0); } - public static File getBuildDirectory() - { - return _targetDir; - } + return s; + } - public static Reader getResourceReader(String path) throws Exception - { - return new InputStreamReader(getResourceURL(path).openStream()); - } + public static Ini.Section addDwarf(Ini ini, DwarfData dwarf) { + Ini.Section s = addDwarf((Profile) ini, dwarf); - public static InputStream getResourceStream(String path) throws Exception - { - return getResourceURL(path).openStream(); - } + ini.putComment(dwarf.name, " " + dwarf.name); - public static URL getResourceURL(String path) throws Exception - { - return Helper.class.getClassLoader().getResource(path); - } + return s; + } - public static File getSourceFile(String path) throws Exception - { - return new File(_sourceDir, path).getCanonicalFile(); - } + public static void addDwarf(OptionMap opts, DwarfData dwarf, boolean addNamePrefix) { + String prefix = addNamePrefix ? (dwarf.name + '.') : ""; - public static void addDwarf(OptionMap opts, DwarfData dwarf) - { - addDwarf(opts, dwarf, true); + opts.putComment(prefix + Dwarf.PROP_WEIGHT, " " + dwarf.name); + inject(opts, dwarf, prefix); + if (dwarf.name.equals(Dwarfs.PROP_DOPEY)) { + opts.put(prefix + Dwarf.PROP_WEIGHT, DwarfsData.OPT_DOPEY_WEIGHT, 0); + opts.put(prefix + Dwarf.PROP_HEIGHT, DwarfsData.OPT_DOPEY_HEIGHT, 0); + } else if (dwarf.name.equals(Dwarfs.PROP_GRUMPY)) { + opts.put(prefix + Dwarf.PROP_HEIGHT, DwarfsData.OPT_GRUMPY_HEIGHT, 0); + } else if (dwarf.name.equals(Dwarfs.PROP_SLEEPY)) { + opts.put(prefix + Dwarf.PROP_HEIGHT, DwarfsData.OPT_SLEEPY_HEIGHT, 0); + } else if (dwarf.name.equals(Dwarfs.PROP_SNEEZY)) { + opts.put(prefix + Dwarf.PROP_HOME_PAGE, DwarfsData.OPT_SNEEZY_HOME_PAGE, 0); } - - public static Profile.Section addDwarf(Profile prof, DwarfData dwarf) - { - Profile.Section s = prof.add(dwarf.name); - - inject(s, dwarf, ""); - if (dwarf.name.equals(Dwarfs.PROP_DOPEY)) - { - s.put(Dwarf.PROP_WEIGHT, DwarfsData.INI_DOPEY_WEIGHT, 0); - s.put(Dwarf.PROP_HEIGHT, DwarfsData.INI_DOPEY_HEIGHT, 0); - } - else if (dwarf.name.equals(Dwarfs.PROP_GRUMPY)) - { - s.put(Dwarf.PROP_HEIGHT, DwarfsData.INI_GRUMPY_HEIGHT, 0); - } - else if (dwarf.name.equals(Dwarfs.PROP_SLEEPY)) - { - s.put(Dwarf.PROP_HEIGHT, DwarfsData.INI_SLEEPY_HEIGHT, 0); - } - else if (dwarf.name.equals(Dwarfs.PROP_SNEEZY)) - { - s.put(Dwarf.PROP_HOME_PAGE, DwarfsData.INI_SNEEZY_HOME_PAGE, 0); - } - - return s; + } + + public static void addDwarfs(Profile prof) { + addDwarf(prof, DwarfsData.bashful); + addDwarf(prof, DwarfsData.doc); + addDwarf(prof, DwarfsData.dopey); + addDwarf(prof, DwarfsData.grumpy); + addDwarf(prof, DwarfsData.happy); + addDwarf(prof, DwarfsData.sleepy); + addDwarf(prof, DwarfsData.sneezy); + } + + public static void assertEquals(Registry.Key exp, Registry.Key act) { + Assert.assertNotNull(exp); + Assert.assertEquals(exp.size(), act.size()); + for (String child : exp.childrenNames()) { + assertEquals(exp.getChild(child), act.getChild(child)); } - public static Ini.Section addDwarf(Ini ini, DwarfData dwarf) - { - Ini.Section s = addDwarf((Profile) ini, dwarf); - - ini.putComment(dwarf.name, " " + dwarf.name); - - return s; - } - - public static void addDwarf(OptionMap opts, DwarfData dwarf, boolean addNamePrefix) - { - String prefix = addNamePrefix ? (dwarf.name + '.') : ""; - - opts.putComment(prefix + Dwarf.PROP_WEIGHT, " " + dwarf.name); - inject(opts, dwarf, prefix); - if (dwarf.name.equals(Dwarfs.PROP_DOPEY)) - { - opts.put(prefix + Dwarf.PROP_WEIGHT, DwarfsData.OPT_DOPEY_WEIGHT, 0); - opts.put(prefix + Dwarf.PROP_HEIGHT, DwarfsData.OPT_DOPEY_HEIGHT, 0); - } - else if (dwarf.name.equals(Dwarfs.PROP_GRUMPY)) - { - opts.put(prefix + Dwarf.PROP_HEIGHT, DwarfsData.OPT_GRUMPY_HEIGHT, 0); - } - else if (dwarf.name.equals(Dwarfs.PROP_SLEEPY)) - { - opts.put(prefix + Dwarf.PROP_HEIGHT, DwarfsData.OPT_SLEEPY_HEIGHT, 0); - } - else if (dwarf.name.equals(Dwarfs.PROP_SNEEZY)) - { - opts.put(prefix + Dwarf.PROP_HOME_PAGE, DwarfsData.OPT_SNEEZY_HOME_PAGE, 0); - } - } - - public static void addDwarfs(Profile prof) - { - addDwarf(prof, DwarfsData.bashful); - addDwarf(prof, DwarfsData.doc); - addDwarf(prof, DwarfsData.dopey); - addDwarf(prof, DwarfsData.grumpy); - addDwarf(prof, DwarfsData.happy); - addDwarf(prof, DwarfsData.sleepy); - addDwarf(prof, DwarfsData.sneezy); - } - - public static void assertEquals(Registry.Key exp, Registry.Key act) - { - Assert.assertNotNull(exp); - Assert.assertEquals(exp.size(), act.size()); - for (String child : exp.childrenNames()) - { - assertEquals(exp.getChild(child), act.getChild(child)); - } - - for (String name : exp.keySet()) - { - Assert.assertEquals(exp.get(name), act.get(name)); - } + for (String name : exp.keySet()) { + Assert.assertEquals(exp.get(name), act.get(name)); } - - public static void assertEquals(Dwarfs expected, Dwarfs actual) - { - assertEquals(expected.getBashful(), actual.getBashful()); - assertEquals(expected.getDoc(), actual.getDoc()); - assertEquals(expected.getDopey(), actual.getDopey()); - assertEquals(expected.getGrumpy(), actual.getGrumpy()); - assertEquals(expected.getHappy(), actual.getHappy()); - assertEquals(expected.getSleepy(), actual.getSleepy()); - assertEquals(expected.getSneezy(), actual.getSneezy()); + } + + public static void assertEquals(Dwarfs expected, Dwarfs actual) { + assertEquals(expected.getBashful(), actual.getBashful()); + assertEquals(expected.getDoc(), actual.getDoc()); + assertEquals(expected.getDopey(), actual.getDopey()); + assertEquals(expected.getGrumpy(), actual.getGrumpy()); + assertEquals(expected.getHappy(), actual.getHappy()); + assertEquals(expected.getSleepy(), actual.getSleepy()); + assertEquals(expected.getSneezy(), actual.getSneezy()); + } + + public static void assertEquals(Dwarf expected, Dwarf actual) { + Assert.assertEquals(expected.getAge(), actual.getAge()); + Assert.assertEquals(expected.getHeight(), actual.getHeight(), DELTA); + Assert.assertEquals(expected.getWeight(), actual.getWeight(), DELTA); + Assert.assertEquals(expected.getHomePage().toString(), actual.getHomePage().toString()); + Assert.assertEquals(expected.getHomeDir().toString(), actual.getHomeDir().toString()); + Assert.assertEquals(expected.hasAge(), actual.hasAge()); + Assert.assertEquals(expected.hasHeight(), actual.hasHeight()); + Assert.assertEquals(expected.hasWeight(), actual.hasWeight()); + Assert.assertEquals(expected.hasHomePage(), actual.hasHomePage()); + } + + public static Ini loadDwarfsIni() throws Exception { + return new Ini(Helper.class.getClassLoader().getResourceAsStream(DWARFS_INI)); + } + + public static Ini loadDwarfsIni(Config config) throws Exception { + Ini ini = new Ini(); + + ini.setConfig(config); + ini.load(Helper.class.getClassLoader().getResourceAsStream(DWARFS_INI)); + + return ini; + } + + public static Options loadDwarfsOpt() throws Exception { + return new Options(Helper.class.getClassLoader().getResourceAsStream(DWARFS_OPT)); + } + + public static Options loadDwarfsOpt(Config config) throws Exception { + Options opt = new Options(); + + opt.setConfig(config); + opt.load(Helper.class.getClassLoader().getResourceAsStream(DWARFS_OPT)); + + return opt; + } + + public static Reg loadDwarfsReg() throws Exception { + return new Reg(Helper.class.getClassLoader().getResourceAsStream(DWARFS_REG)); + } + + public static Ini loadTaleIni() throws Exception { + return new Ini(Helper.class.getClassLoader().getResourceAsStream(TALE_INI)); + } + + public static Ini loadTaleIni(Config config) throws Exception { + Ini ini = new Ini(); + + ini.setConfig(config); + ini.load(Helper.class.getClassLoader().getResourceAsStream(TALE_INI)); + + return ini; + } + + public static Ini newDwarfsIni() { + Ini ini = new Ini(); + + ini.setComment(HEADER_COMMENT); + addDwarf(ini, DwarfsData.bashful); + addDwarf(ini, DwarfsData.doc); + addDwarf(ini, DwarfsData.dopey); + addDwarf(ini, DwarfsData.grumpy); + addDwarf(ini, DwarfsData.happy); + addDwarf(ini, DwarfsData.sleepy); + addDwarf(ini, DwarfsData.sneezy); + + return ini; + } + + public static Options newDwarfsOpt() { + Options opts = new Options(); + + opts.setComment(HEADER_COMMENT); + addDwarf(opts, DwarfsData.dopey, false); + addDwarf(opts, DwarfsData.bashful); + addDwarf(opts, DwarfsData.doc); + addDwarf(opts, DwarfsData.dopey); + addDwarf(opts, DwarfsData.grumpy); + addDwarf(opts, DwarfsData.happy); + addDwarf(opts, DwarfsData.sleepy); + addDwarf(opts, DwarfsData.sneezy); + + return opts; + } + + public static Ini newTaleIni() { + Ini ini = new Ini(); + + ini.setComment(HEADER_COMMENT); + ini.add(TaleData.PROP_DWARFS); + addDwarf(ini, TaleData.bashful); + addDwarf(ini, TaleData.doc); + addDwarf(ini, TaleData.dopey); + addDwarf(ini, TaleData.grumpy); + addDwarf(ini, TaleData.happy); + addDwarf(ini, TaleData.sleepy); + addDwarf(ini, TaleData.sneezy); + + return ini; + } + + public static void resetConfig() throws Exception { + Properties props = System.getProperties(); + + for (String name : CONFIG_PROPERTIES) { + props.remove(Config.KEY_PREFIX + name); } - public static void assertEquals(Dwarf expected, Dwarf actual) - { - Assert.assertEquals(expected.getAge(), actual.getAge()); - Assert.assertEquals(expected.getHeight(), actual.getHeight(), DELTA); - Assert.assertEquals(expected.getWeight(), actual.getWeight(), DELTA); - Assert.assertEquals(expected.getHomePage().toString(), actual.getHomePage().toString()); - Assert.assertEquals(expected.getHomeDir().toString(), actual.getHomeDir().toString()); - Assert.assertEquals(expected.hasAge(), actual.hasAge()); - Assert.assertEquals(expected.hasHeight(), actual.hasHeight()); - Assert.assertEquals(expected.hasWeight(), actual.hasWeight()); - Assert.assertEquals(expected.hasHomePage(), actual.hasHomePage()); + for (String name : FACTORY_PROPERTIES) { + props.remove(name); } - - public static Ini loadDwarfsIni() throws Exception - { - return new Ini(Helper.class.getClassLoader().getResourceAsStream(DWARFS_INI)); - } - - public static Ini loadDwarfsIni(Config config) throws Exception - { - Ini ini = new Ini(); - - ini.setConfig(config); - ini.load(Helper.class.getClassLoader().getResourceAsStream(DWARFS_INI)); - - return ini; - } - - public static Options loadDwarfsOpt() throws Exception - { - return new Options(Helper.class.getClassLoader().getResourceAsStream(DWARFS_OPT)); - } - - public static Options loadDwarfsOpt(Config config) throws Exception - { - Options opt = new Options(); - - opt.setConfig(config); - opt.load(Helper.class.getClassLoader().getResourceAsStream(DWARFS_OPT)); - - return opt; - } - - public static Reg loadDwarfsReg() throws Exception - { - return new Reg(Helper.class.getClassLoader().getResourceAsStream(DWARFS_REG)); - } - - public static Ini loadTaleIni() throws Exception - { - return new Ini(Helper.class.getClassLoader().getResourceAsStream(TALE_INI)); - } - - public static Ini loadTaleIni(Config config) throws Exception - { - Ini ini = new Ini(); - - ini.setConfig(config); - ini.load(Helper.class.getClassLoader().getResourceAsStream(TALE_INI)); - - return ini; - } - - public static Ini newDwarfsIni() - { - Ini ini = new Ini(); - - ini.setComment(HEADER_COMMENT); - addDwarf(ini, DwarfsData.bashful); - addDwarf(ini, DwarfsData.doc); - addDwarf(ini, DwarfsData.dopey); - addDwarf(ini, DwarfsData.grumpy); - addDwarf(ini, DwarfsData.happy); - addDwarf(ini, DwarfsData.sleepy); - addDwarf(ini, DwarfsData.sneezy); - - return ini; - } - - public static Options newDwarfsOpt() - { - Options opts = new Options(); - - opts.setComment(HEADER_COMMENT); - addDwarf(opts, DwarfsData.dopey, false); - addDwarf(opts, DwarfsData.bashful); - addDwarf(opts, DwarfsData.doc); - addDwarf(opts, DwarfsData.dopey); - addDwarf(opts, DwarfsData.grumpy); - addDwarf(opts, DwarfsData.happy); - addDwarf(opts, DwarfsData.sleepy); - addDwarf(opts, DwarfsData.sneezy); - - return opts; - } - - public static Ini newTaleIni() - { - Ini ini = new Ini(); - - ini.setComment(HEADER_COMMENT); - ini.add(TaleData.PROP_DWARFS); - addDwarf(ini, TaleData.bashful); - addDwarf(ini, TaleData.doc); - addDwarf(ini, TaleData.dopey); - addDwarf(ini, TaleData.grumpy); - addDwarf(ini, TaleData.happy); - addDwarf(ini, TaleData.sleepy); - addDwarf(ini, TaleData.sneezy); - - return ini; - } - - public static void resetConfig() throws Exception - { - Properties props = System.getProperties(); - - for (String name : CONFIG_PROPERTIES) - { - props.remove(Config.KEY_PREFIX + name); - } - - for (String name : FACTORY_PROPERTIES) - { - props.remove(name); - } - } - - private static void inject(OptionMap map, Dwarf dwarf, String prefix) - { - map.put(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); - map.put(prefix + Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); - map.put(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - map.put(prefix + Dwarf.PROP_HOME_PAGE, dwarf.getHomePage().toString()); - map.put(prefix + Dwarf.PROP_HOME_DIR, dwarf.getHomeDir()); - int[] numbers = dwarf.getFortuneNumber(); - - if ((numbers != null) && (numbers.length > 0)) - { - for (int i = 0; i < numbers.length; i++) - { - map.add(prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(numbers[i])); - } - } + } + + private static void inject(OptionMap map, Dwarf dwarf, String prefix) { + map.put(prefix + Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); + map.put(prefix + Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); + map.put(prefix + Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); + map.put(prefix + Dwarf.PROP_HOME_PAGE, dwarf.getHomePage().toString()); + map.put(prefix + Dwarf.PROP_HOME_DIR, dwarf.getHomeDir()); + int[] numbers = dwarf.getFortuneNumber(); + + if ((numbers != null) && (numbers.length > 0)) { + for (int i = 0; i < numbers.length; i++) { + map.add(prefix + Dwarf.PROP_FORTUNE_NUMBER, String.valueOf(numbers[i])); + } } + } } diff --git a/src/test/java/org/ini4j/test/SampleRunnerTest.java b/src/test/java/org/ini4j/test/SampleRunnerTest.java index 70210e6..560a226 100755 --- a/src/test/java/org/ini4j/test/SampleRunnerTest.java +++ b/src/test/java/org/ini4j/test/SampleRunnerTest.java @@ -15,6 +15,23 @@ */ package org.ini4j.test; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.LineNumberReader; +import java.io.PrintStream; +import java.io.PrintWriter; +import java.io.Reader; +import java.lang.reflect.Method; +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.Collection; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.ini4j.sample.BeanEventSample; import org.ini4j.sample.BeanSample; import org.ini4j.sample.DumpSample; @@ -31,7 +48,6 @@ import org.ini4j.sample.ReadStringSample; import org.ini4j.sample.StreamSample; import org.ini4j.sample.ToSample; - import org.ini4j.tutorial.BeanTutorial; import org.ini4j.tutorial.IniTutorial; import org.ini4j.tutorial.OneMinuteTutorial; @@ -39,312 +55,239 @@ import org.ini4j.tutorial.PrefsTutorial; import org.ini4j.tutorial.RegTutorial; import org.ini4j.tutorial.WindowsRegistryTutorial; - import org.junit.Test; - import org.junit.runner.RunWith; - import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.LineNumberReader; -import java.io.PrintStream; -import java.io.PrintWriter; -import java.io.Reader; - -import java.lang.reflect.Method; - -import java.nio.charset.Charset; - -import java.util.Arrays; -import java.util.Collection; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - @RunWith(Parameterized.class) -public class SampleRunnerTest -{ - private static final String DOC_PATH = "generated-site/apt"; - private static final String JAVA_SUFFIX = ".java"; - private static final String PACKAGE_INFO = "package-info" + JAVA_SUFFIX; - private static final String APT_SUFFIX = ".apt"; - private static final String APT_INDEX = "index" + APT_SUFFIX; - private static final String CODE_BEGIN = "\n+----+\n"; - private static final String CODE_END = "+----+\n\n"; - private static File _documentDir; - - static - { - System.setProperty("java.util.prefs.PreferencesFactory", "org.ini4j.IniPreferencesFactory"); - _documentDir = new File(Helper.getBuildDirectory(), DOC_PATH); - _documentDir.mkdirs(); - try - { - document(sourceFile(Dwarf.class), "//"); - document(sourceFile(DwarfBean.class), "//"); - document(sourceFile(Dwarfs.class), "//"); - document(sourceFile(DwarfsBean.class), "//"); - document(sourceFile(IniTutorial.class.getPackage()), "//"); - document(sourceFile(IniSample.class.getPackage()), "//"); - } - catch (Exception x) - { - throw new IllegalStateException(x); - } +public class SampleRunnerTest { + private static final String DOC_PATH = "generated-site/apt"; + private static final String JAVA_SUFFIX = ".java"; + private static final String PACKAGE_INFO = "package-info" + JAVA_SUFFIX; + private static final String APT_SUFFIX = ".apt"; + private static final String APT_INDEX = "index" + APT_SUFFIX; + private static final String CODE_BEGIN = "\n+----+\n"; + private static final String CODE_END = "+----+\n\n"; + private static File _documentDir; + + static { + System.setProperty("java.util.prefs.PreferencesFactory", "org.ini4j.IniPreferencesFactory"); + _documentDir = new File(Helper.getBuildDirectory(), DOC_PATH); + _documentDir.mkdirs(); + try { + document(sourceFile(Dwarf.class), "//"); + document(sourceFile(DwarfBean.class), "//"); + document(sourceFile(Dwarfs.class), "//"); + document(sourceFile(DwarfsBean.class), "//"); + document(sourceFile(IniTutorial.class.getPackage()), "//"); + document(sourceFile(IniSample.class.getPackage()), "//"); + } catch (Exception x) { + throw new IllegalStateException(x); } - - private final Class _clazz; - private final File _sourceFile; - - public SampleRunnerTest(Class sampleClass) throws Exception - { - _clazz = sampleClass; - _sourceFile = sourceFile(_clazz); + } + + private final Class _clazz; + private final File _sourceFile; + + public SampleRunnerTest(Class sampleClass) throws Exception { + _clazz = sampleClass; + _sourceFile = sourceFile(_clazz); + } + + @Parameters + public static Collection data() { + return Arrays.asList( + new Object[][] { + + // samples + {ReadStringSample.class}, + {ReadPrimitiveSample.class}, + {IniSample.class}, + {StreamSample.class}, + {DumpSample.class}, + {NoImportSample.class}, + {ListenerSample.class}, + {BeanSample.class}, + {BeanEventSample.class}, + {FromSample.class}, + {ToSample.class}, + {PyReadSample.class}, + + // tutorials + {OneMinuteTutorial.class}, + {IniTutorial.class}, + {RegTutorial.class}, + {WindowsRegistryTutorial.class}, + {OptTutorial.class}, + {BeanTutorial.class}, + {PrefsTutorial.class}, + }); + } + + @Test + public void test() throws Exception { + System.out.println("Executing " + _clazz.getName()); + PrintStream saved = System.out; + File tmp = File.createTempFile(getClass().getSimpleName(), ".out"); + PrintStream out = new PrintStream(new FileOutputStream(tmp)); + + System.setOut(out); + try { + execute(); + } finally { + System.setOut(saved); + out.flush(); } - @Parameters public static Collection data() - { - return Arrays.asList( - new Object[][] - { - - // samples - { ReadStringSample.class }, - { ReadPrimitiveSample.class }, - { IniSample.class }, - { StreamSample.class }, - { DumpSample.class }, - { NoImportSample.class }, - { ListenerSample.class }, - { BeanSample.class }, - { BeanEventSample.class }, - { FromSample.class }, - { ToSample.class }, - { PyReadSample.class }, - - // tutorials - { OneMinuteTutorial.class }, - { IniTutorial.class }, - { RegTutorial.class }, - { WindowsRegistryTutorial.class }, - { OptTutorial.class }, - { BeanTutorial.class }, - { PrefsTutorial.class }, - }); + document(_sourceFile, "//"); + index(source2document(_sourceFile), source2index(_clazz)); + if (tmp.length() > 0) { + append(tmp); } - @Test public void test() throws Exception - { - System.out.println("Executing " + _clazz.getName()); - PrintStream saved = System.out; - File tmp = File.createTempFile(getClass().getSimpleName(), ".out"); - PrintStream out = new PrintStream(new FileOutputStream(tmp)); - - System.setOut(out); - try - { - execute(); - } - finally - { - System.setOut(saved); - out.flush(); + tmp.delete(); + } + + private static void document(File src, String comment) throws Exception { + Pattern docPattern = Pattern.compile(String.format("^\\s*%s\\|(.*)$", comment)); + Pattern beginPattern = Pattern.compile(String.format("^\\s*%s\\{.*$", comment)); + Pattern endPattern = Pattern.compile(String.format("^\\s*%s\\}.*$", comment)); + LineNumberReader reader = new LineNumberReader(openReader(src)); + PrintWriter writer = new PrintWriter(new FileWriter(source2document(src))); + boolean in = false; + + for (String line = reader.readLine(); line != null; line = reader.readLine()) { + if (in) { + if (endPattern.matcher(line).matches()) { + in = false; + writer.println(CODE_END); + } else { + writer.println(line); } - - document(_sourceFile, "//"); - index(source2document(_sourceFile), source2index(_clazz)); - if (tmp.length() > 0) - { - append(tmp); + } else { + if (beginPattern.matcher(line).matches()) { + in = true; + writer.println(CODE_BEGIN); + } else { + Matcher m = docPattern.matcher(line); + + if (m.matches()) { + writer.println(m.group(1)); + } } - - tmp.delete(); + } } - private static void document(File src, String comment) throws Exception - { - Pattern docPattern = Pattern.compile(String.format("^\\s*%s\\|(.*)$", comment)); - Pattern beginPattern = Pattern.compile(String.format("^\\s*%s\\{.*$", comment)); - Pattern endPattern = Pattern.compile(String.format("^\\s*%s\\}.*$", comment)); - LineNumberReader reader = new LineNumberReader(openReader(src)); - PrintWriter writer = new PrintWriter(new FileWriter(source2document(src))); - boolean in = false; - - for (String line = reader.readLine(); line != null; line = reader.readLine()) - { - if (in) - { - if (endPattern.matcher(line).matches()) - { - in = false; - writer.println(CODE_END); - } - else - { - writer.println(line); - } - } - else - { - if (beginPattern.matcher(line).matches()) - { - in = true; - writer.println(CODE_BEGIN); - } - else - { - Matcher m = docPattern.matcher(line); - - if (m.matches()) - { - writer.println(m.group(1)); - } - } - } + reader.close(); + writer.close(); + } + + private static void index(File src, File dst) throws Exception { + LineNumberReader reader = new LineNumberReader(new FileReader(src)); + PrintWriter writer = new PrintWriter(new FileWriter(dst, true)); + String name = src.getName().replace(".apt", ".html"); + boolean h1 = false; + boolean p = false; + + for (String line = reader.readLine(); line != null; line = reader.readLine()) { + if (line.length() == 0) { + if (p) { + writer.println(); + + break; + } else if (h1) { + p = true; } - - reader.close(); - writer.close(); - } - - private static void index(File src, File dst) throws Exception - { - LineNumberReader reader = new LineNumberReader(new FileReader(src)); - PrintWriter writer = new PrintWriter(new FileWriter(dst, true)); - String name = src.getName().replace(".apt", ".html"); - boolean h1 = false; - boolean p = false; - - for (String line = reader.readLine(); line != null; line = reader.readLine()) - { - if (line.length() == 0) - { - if (p) - { - writer.println(); - - break; - } - else if (h1) - { - p = true; - } - } - else - { - if (Character.isSpaceChar(line.charAt(0))) - { - if (p) - { - writer.println(line); - } - } - else - { - if (!h1) - { - h1 = true; - writer.print(String.format(" *{{{%s}%s}}", name, line)); - writer.println(); - writer.println(); - } - } - } + } else { + if (Character.isSpaceChar(line.charAt(0))) { + if (p) { + writer.println(line); + } + } else { + if (!h1) { + h1 = true; + writer.print(String.format(" *{{{%s}%s}}", name, line)); + writer.println(); + writer.println(); + } } - - writer.close(); - reader.close(); + } } - private static Reader openReader(File src) throws Exception - { - InputStream stream = new FileInputStream(src); - byte[] head = new byte[2]; - int n = stream.read(head); + writer.close(); + reader.close(); + } - stream.close(); - Charset charset; + private static Reader openReader(File src) throws Exception { + InputStream stream = new FileInputStream(src); + byte[] head = new byte[2]; + int n = stream.read(head); - if ((n == 2) && (head[0] == -1) && (head[1] == -2)) - { - charset = Charset.forName("UnicodeLittle"); - } - else - { - charset = Charset.forName("UTF-8"); - } + stream.close(); + Charset charset; - return new InputStreamReader(new FileInputStream(src), charset); + if ((n == 2) && (head[0] == -1) && (head[1] == -2)) { + charset = Charset.forName("UnicodeLittle"); + } else { + charset = Charset.forName("UTF-8"); } - private static File source2document(File sourceFile) throws Exception - { - String name = sourceFile.getName(); - File dir = new File(_documentDir, sourceFile.getParentFile().getName()); + return new InputStreamReader(new FileInputStream(src), charset); + } - dir.mkdir(); + private static File source2document(File sourceFile) throws Exception { + String name = sourceFile.getName(); + File dir = new File(_documentDir, sourceFile.getParentFile().getName()); - return new File(dir, name.equals(PACKAGE_INFO) ? APT_INDEX : (name + APT_SUFFIX)); - } + dir.mkdir(); - private static File source2index(Class clazz) throws Exception - { - return source2document(sourceFile(clazz.getPackage())); - } + return new File(dir, name.equals(PACKAGE_INFO) ? APT_INDEX : (name + APT_SUFFIX)); + } - private static File sourceFile(Class clazz) throws Exception - { - return Helper.getSourceFile(clazz.getName().replaceAll("\\.", "/") + JAVA_SUFFIX); - } + private static File source2index(Class clazz) throws Exception { + return source2document(sourceFile(clazz.getPackage())); + } - private static File sourceFile(Package pkg) throws Exception - { - return Helper.getSourceFile(pkg.getName().replaceAll("\\.", "/") + '/' + PACKAGE_INFO); - } + private static File sourceFile(Class clazz) throws Exception { + return Helper.getSourceFile(clazz.getName().replaceAll("\\.", "/") + JAVA_SUFFIX); + } - private void append(File stdout) throws Exception - { - PrintWriter writer = new PrintWriter(new FileWriter(source2document(_sourceFile), true)); + private static File sourceFile(Package pkg) throws Exception { + return Helper.getSourceFile(pkg.getName().replaceAll("\\.", "/") + '/' + PACKAGE_INFO); + } - writer.println("\n Standard output:\n"); - writer.println(CODE_BEGIN); - LineNumberReader reader = new LineNumberReader(new FileReader(stdout)); + private void append(File stdout) throws Exception { + PrintWriter writer = new PrintWriter(new FileWriter(source2document(_sourceFile), true)); - for (String line = reader.readLine(); line != null; line = reader.readLine()) - { - writer.println(line); - } + writer.println("\n Standard output:\n"); + writer.println(CODE_BEGIN); + LineNumberReader reader = new LineNumberReader(new FileReader(stdout)); - writer.println(CODE_END); - reader.close(); - writer.close(); + for (String line = reader.readLine(); line != null; line = reader.readLine()) { + writer.println(line); } - @SuppressWarnings("unchecked") - private void execute() throws Exception - { - Method main = _clazz.getMethod("main", String[].class); - String[] args; + writer.println(CODE_END); + reader.close(); + writer.close(); + } - try - { - File argument = new File(_sourceFile.getParentFile(), (String) _clazz.getField("FILENAME").get(null)); + @SuppressWarnings("unchecked") + private void execute() throws Exception { + Method main = _clazz.getMethod("main", String[].class); + String[] args; - document(argument, "[#;!]"); - args = new String[] { argument.getCanonicalPath() }; - } - catch (NoSuchFieldException x) - { - args = new String[] {}; - } + try { + File argument = + new File(_sourceFile.getParentFile(), (String) _clazz.getField("FILENAME").get(null)); - main.invoke(null, (Object) args); + document(argument, "[#;!]"); + args = new String[] {argument.getCanonicalPath()}; + } catch (NoSuchFieldException x) { + args = new String[] {}; } + + main.invoke(null, (Object) args); + } } diff --git a/src/test/java/org/ini4j/test/TaleData.java b/src/test/java/org/ini4j/test/TaleData.java index 75ad3b3..b144078 100644 --- a/src/test/java/org/ini4j/test/TaleData.java +++ b/src/test/java/org/ini4j/test/TaleData.java @@ -17,35 +17,37 @@ import org.ini4j.test.DwarfsData.DwarfData; -public final class TaleData -{ - public static final String PROP_DWARFS = "dwarfs"; - public static final char PATH_SEPARATOR = '/'; - public static final DwarfData bashful; - public static final DwarfData doc; - public static final DwarfData dopey; - public static final DwarfData grumpy; - public static final DwarfData happy; - public static final DwarfData sleepy; - public static final DwarfData sneezy; +public final class TaleData { + public static final String PROP_DWARFS = "dwarfs"; + public static final char PATH_SEPARATOR = '/'; + public static final DwarfData bashful; + public static final DwarfData doc; + public static final DwarfData dopey; + public static final DwarfData grumpy; + public static final DwarfData happy; + public static final DwarfData sleepy; + public static final DwarfData sneezy; - static - { - bashful = newDwarfData(DwarfsData.bashful); - doc = newDwarfData(DwarfsData.doc); - dopey = newDwarfData(DwarfsData.dopey); - grumpy = newDwarfData(DwarfsData.grumpy); - happy = newDwarfData(DwarfsData.happy); - sleepy = newDwarfData(DwarfsData.sleepy); - sneezy = newDwarfData(DwarfsData.sneezy); - } + static { + bashful = newDwarfData(DwarfsData.bashful); + doc = newDwarfData(DwarfsData.doc); + dopey = newDwarfData(DwarfsData.dopey); + grumpy = newDwarfData(DwarfsData.grumpy); + happy = newDwarfData(DwarfsData.happy); + sleepy = newDwarfData(DwarfsData.sleepy); + sneezy = newDwarfData(DwarfsData.sneezy); + } - private TaleData() - { - } + private TaleData() {} - private static DwarfData newDwarfData(DwarfData orig) - { - return new DwarfData(PROP_DWARFS + PATH_SEPARATOR + orig.name, orig.age, orig.fortuneNumber, orig.height, orig.homeDir, orig.homePage.toString(), orig.weight); - } + private static DwarfData newDwarfData(DwarfData orig) { + return new DwarfData( + PROP_DWARFS + PATH_SEPARATOR + orig.name, + orig.age, + orig.fortuneNumber, + orig.height, + orig.homeDir, + orig.homePage.toString(), + orig.weight); + } } diff --git a/src/test/java/org/ini4j/tutorial/AbstractTutorial.java b/src/test/java/org/ini4j/tutorial/AbstractTutorial.java index a138153..c3fbb81 100644 --- a/src/test/java/org/ini4j/tutorial/AbstractTutorial.java +++ b/src/test/java/org/ini4j/tutorial/AbstractTutorial.java @@ -17,14 +17,12 @@ import java.io.File; -public abstract class AbstractTutorial -{ - public static final String FILENAME = "../sample/dwarfs.ini"; +public abstract class AbstractTutorial { + public static final String FILENAME = "../sample/dwarfs.ini"; - protected abstract void run(File arg) throws Exception; + protected abstract void run(File arg) throws Exception; - protected static File filearg(String[] args) - { - return new File((args.length > 0) ? args[0] : FILENAME); - } + protected static File filearg(String[] args) { + return new File((args.length > 0) ? args[0] : FILENAME); + } } diff --git a/src/test/java/org/ini4j/tutorial/BeanTutorial.java b/src/test/java/org/ini4j/tutorial/BeanTutorial.java index 046a342..6ed38ed 100644 --- a/src/test/java/org/ini4j/tutorial/BeanTutorial.java +++ b/src/test/java/org/ini4j/tutorial/BeanTutorial.java @@ -15,232 +15,220 @@ */ package org.ini4j.tutorial; +import static org.junit.Assert.*; + +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.net.URL; import org.ini4j.Config; import org.ini4j.Ini; import org.ini4j.Options; - import org.ini4j.sample.Dwarf; import org.ini4j.sample.DwarfBean; import org.ini4j.sample.Dwarfs; - import org.ini4j.test.DwarfsData; -import static org.junit.Assert.*; - -import java.io.File; -import java.io.IOException; - -import java.net.URI; -import java.net.URL; - -// -//| -//| ------------- -//| Bean Tutorial -//| -//|Bean Tutorial - Using your own API ! -//| -//| Yes, it can be done! To access the contents of sections you can use any of -//| your self-defined Java Beans compatible API. -//| In order to do this you only have to create a Java Beans-style interface or class. -//| -//| Source code for beans: {{{../sample/Dwarf.java.html}Dwarf}}, -//| {{{../sample/DwarfBean.java.html}DwarfBean}} -//| -//| Code sniplets in this tutorial tested with the following .ini file: -//| {{{../sample/dwarfs.ini.html}dwarfs.ini}} -//| -// -public class BeanTutorial extends AbstractTutorial -{ - public static void main(String[] args) throws Exception - { - new BeanTutorial().run(filearg(args)); - } - - @Override protected void run(File arg) throws Exception - { - Ini ini = new Ini(arg.toURI().toURL()); - - sample01(ini); - sample02(ini); - sample03(ini); - sample04(arg.toURI().toURL()); - Options opts = new Options(); - - opts.putAll(ini.get(Dwarfs.PROP_BASHFUL)); - sample05(opts); - - // - File optFile = new File(arg.getParentFile(), OptTutorial.FILENAME); - - sample06(optFile.toURI().toURL()); - } - -//| -//|* Accessing sections as beans -//| -//| While writing a program we usually know the type of the section's values, -//| so we can define one or more java interfaces to access them. An advantage of -//| this solution is that the programmer doesn't have to convert the values -//| because they are converted automatically to the type defined in the -//| interface. -//| -//| Ofcourse you may use setters as well, not just getters. In this way you can -//| change values type safe way. -//{ - void sample01(Ini ini) - { - Ini.Section sec = ini.get("happy"); - Dwarf happy = sec.as(Dwarf.class); - int age = happy.getAge(); - URI homePage = happy.getHomePage(); - - happy.setWeight(45.55); - -//} -//| -//| The <<>> relation is of course fulfilled in the -//| example above. -//| - assertEquals(DwarfsData.happy.homePage.toString(), homePage.toString()); - assertEquals(DwarfsData.happy.age, age); - assertEquals(45.55, happy.getWeight(), 0.01); - } - -//| -//|* Marshalling beans -//| -//| Sometimes we want to store existing java beans in text file. This operation -//| usually called marshalling. -//| -//| With [ini4j] it is easy to store bean properties in a section. You simply -//| create a section, and call the sections's <<>> method. Thats it. -//{ - void sample02(Ini ini) - { - DwarfBean sleepy = new DwarfBean(); - - sleepy.setAge(87); - sleepy.setWeight(44.3); - Ini.Section sec = ini.add("sleepy"); - - sec.from(sleepy); - -//} -//| - assertTrue(sec.containsKey(Dwarf.PROP_AGE)); - assertTrue(sec.containsKey(Dwarf.PROP_WEIGHT)); - } - -//| -//|* Unmarshalling beans -//| -//| If you have a marshalled bean in text file then you may want to read it -//| into bean. This operation usually called unmarshalling. -//| -//| With [ini4j] it is easy to load bean properties from a section. You simply -//| instantiate a bean, and call the sections's <<>> method. Thats it. -//{ - void sample03(Ini ini) - { - DwarfBean grumpy = new DwarfBean(); - - ini.get("grumpy").to(grumpy); - -//} -//| - assertEquals(DwarfsData.grumpy.age, grumpy.getAge()); - assertEquals(DwarfsData.grumpy.homeDir, grumpy.getHomeDir()); - } - -//| -//|* Indexed properties -//| -//| For handling indexed properties, you should allow mulpti option value -//| handling in configuration. After enabling this feature, option may contains -//| multiply values (multi line in file). These values can mapped to indexed -//| bean property. -//{ - void sample04(URL location) throws IOException - { - Config cfg = new Config(); - - cfg.setMultiOption(true); - Ini ini = new Ini(); - - ini.setConfig(cfg); - ini.load(location); - Ini.Section sec = ini.get("sneezy"); - Dwarf sneezy = sec.as(Dwarf.class); - int[] numbers = sneezy.getFortuneNumber(); - - // - // same as above but with unmarshalling... - // - DwarfBean sneezyBean = new DwarfBean(); - - sec.to(sneezyBean); - numbers = sneezyBean.getFortuneNumber(); - -//} - assertArrayEquals(DwarfsData.sneezy.fortuneNumber, numbers); - assertEquals(DwarfsData.sneezy.fortuneNumber.length, sec.length("fortuneNumber")); - assertArrayEquals(DwarfsData.sneezy.fortuneNumber, sneezy.getFortuneNumber()); - assertArrayEquals(DwarfsData.sneezy.fortuneNumber, sneezyBean.getFortuneNumber()); - } - -//| -//|* Options -//| -//| Not only Ini and Ini.Section has bean interface. There is a bean interface -//| for OptionMap class and each derived class for example for Options. -//| Options is an improved java.util.Properties replacement. -//{ - void sample05(Options opts) - { - Dwarf dwarf = opts.as(Dwarf.class); - int age = dwarf.getAge(); - - // - // same as above but with unmarshalling - // - DwarfBean dwarfBean = new DwarfBean(); - - opts.to(dwarfBean); - age = dwarfBean.getAge(); - -//} -//| -//| In sample above the top level properties (like "age") mapped to bean -//| properties. -//| - assertEquals(DwarfsData.bashful.age, dwarf.getAge()); - assertEquals(DwarfsData.bashful.age, dwarfBean.getAge()); - } - -//| -//|* Prefixed mapping -//| -//| Both Ini.Section and Options has possibility to add a prefix to property -//| names while mapping from bean property name to Ini.Section or Options -//| key. -//{ - void sample06(URL optPath) throws IOException - { - Options opt = new Options(optPath); - Dwarf dwarf = opt.as(Dwarf.class, "happy."); - DwarfBean bean = new DwarfBean(); - - opt.to(bean, "dopey."); - -//} -//| -//| In the above example, <<>> bean will contain properties starts with -//| <<>> while <<>> will contain properties starts with -//| <<>> - assertEquals(DwarfsData.happy.age, dwarf.getAge()); - assertEquals(DwarfsData.dopey.age, bean.getAge()); - } -//} +// +// | +// | ------------- +// | Bean Tutorial +// | +// |Bean Tutorial - Using your own API ! +// | +// | Yes, it can be done! To access the contents of sections you can use any of +// | your self-defined Java Beans compatible API. +// | In order to do this you only have to create a Java Beans-style interface or class. +// | +// | Source code for beans: {{{../sample/Dwarf.java.html}Dwarf}}, +// | {{{../sample/DwarfBean.java.html}DwarfBean}} +// | +// | Code sniplets in this tutorial tested with the following .ini file: +// | {{{../sample/dwarfs.ini.html}dwarfs.ini}} +// | +// +public class BeanTutorial extends AbstractTutorial { + public static void main(String[] args) throws Exception { + new BeanTutorial().run(filearg(args)); + } + + @Override + protected void run(File arg) throws Exception { + Ini ini = new Ini(arg.toURI().toURL()); + + sample01(ini); + sample02(ini); + sample03(ini); + sample04(arg.toURI().toURL()); + Options opts = new Options(); + + opts.putAll(ini.get(Dwarfs.PROP_BASHFUL)); + sample05(opts); + + // + File optFile = new File(arg.getParentFile(), OptTutorial.FILENAME); + + sample06(optFile.toURI().toURL()); + } + + // | + // |* Accessing sections as beans + // | + // | While writing a program we usually know the type of the section's values, + // | so we can define one or more java interfaces to access them. An advantage of + // | this solution is that the programmer doesn't have to convert the values + // | because they are converted automatically to the type defined in the + // | interface. + // | + // | Ofcourse you may use setters as well, not just getters. In this way you can + // | change values type safe way. + // { + void sample01(Ini ini) { + Ini.Section sec = ini.get("happy"); + Dwarf happy = sec.as(Dwarf.class); + int age = happy.getAge(); + URI homePage = happy.getHomePage(); + + happy.setWeight(45.55); + + // } + // | + // | The <<>> relation is of course fulfilled in the + // | example above. + // | + assertEquals(DwarfsData.happy.homePage.toString(), homePage.toString()); + assertEquals(DwarfsData.happy.age, age); + assertEquals(45.55, happy.getWeight(), 0.01); + } + + // | + // |* Marshalling beans + // | + // | Sometimes we want to store existing java beans in text file. This operation + // | usually called marshalling. + // | + // | With [ini4j] it is easy to store bean properties in a section. You simply + // | create a section, and call the sections's <<>> method. Thats it. + // { + void sample02(Ini ini) { + DwarfBean sleepy = new DwarfBean(); + + sleepy.setAge(87); + sleepy.setWeight(44.3); + Ini.Section sec = ini.add("sleepy"); + + sec.from(sleepy); + + // } + // | + assertTrue(sec.containsKey(Dwarf.PROP_AGE)); + assertTrue(sec.containsKey(Dwarf.PROP_WEIGHT)); + } + + // | + // |* Unmarshalling beans + // | + // | If you have a marshalled bean in text file then you may want to read it + // | into bean. This operation usually called unmarshalling. + // | + // | With [ini4j] it is easy to load bean properties from a section. You simply + // | instantiate a bean, and call the sections's <<>> method. Thats it. + // { + void sample03(Ini ini) { + DwarfBean grumpy = new DwarfBean(); + + ini.get("grumpy").to(grumpy); + + // } + // | + assertEquals(DwarfsData.grumpy.age, grumpy.getAge()); + assertEquals(DwarfsData.grumpy.homeDir, grumpy.getHomeDir()); + } + + // | + // |* Indexed properties + // | + // | For handling indexed properties, you should allow mulpti option value + // | handling in configuration. After enabling this feature, option may contains + // | multiply values (multi line in file). These values can mapped to indexed + // | bean property. + // { + void sample04(URL location) throws IOException { + Config cfg = new Config(); + + cfg.setMultiOption(true); + Ini ini = new Ini(); + + ini.setConfig(cfg); + ini.load(location); + Ini.Section sec = ini.get("sneezy"); + Dwarf sneezy = sec.as(Dwarf.class); + int[] numbers = sneezy.getFortuneNumber(); + + // + // same as above but with unmarshalling... + // + DwarfBean sneezyBean = new DwarfBean(); + + sec.to(sneezyBean); + numbers = sneezyBean.getFortuneNumber(); + + // } + assertArrayEquals(DwarfsData.sneezy.fortuneNumber, numbers); + assertEquals(DwarfsData.sneezy.fortuneNumber.length, sec.length("fortuneNumber")); + assertArrayEquals(DwarfsData.sneezy.fortuneNumber, sneezy.getFortuneNumber()); + assertArrayEquals(DwarfsData.sneezy.fortuneNumber, sneezyBean.getFortuneNumber()); + } + + // | + // |* Options + // | + // | Not only Ini and Ini.Section has bean interface. There is a bean interface + // | for OptionMap class and each derived class for example for Options. + // | Options is an improved java.util.Properties replacement. + // { + void sample05(Options opts) { + Dwarf dwarf = opts.as(Dwarf.class); + int age = dwarf.getAge(); + + // + // same as above but with unmarshalling + // + DwarfBean dwarfBean = new DwarfBean(); + + opts.to(dwarfBean); + age = dwarfBean.getAge(); + + // } + // | + // | In sample above the top level properties (like "age") mapped to bean + // | properties. + // | + assertEquals(DwarfsData.bashful.age, dwarf.getAge()); + assertEquals(DwarfsData.bashful.age, dwarfBean.getAge()); + } + + // | + // |* Prefixed mapping + // | + // | Both Ini.Section and Options has possibility to add a prefix to property + // | names while mapping from bean property name to Ini.Section or Options + // | key. + // { + void sample06(URL optPath) throws IOException { + Options opt = new Options(optPath); + Dwarf dwarf = opt.as(Dwarf.class, "happy."); + DwarfBean bean = new DwarfBean(); + + opt.to(bean, "dopey."); + + // } + // | + // | In the above example, <<>> bean will contain properties starts with + // | <<>> while <<>> will contain properties starts with + // | <<>> + assertEquals(DwarfsData.happy.age, dwarf.getAge()); + assertEquals(DwarfsData.dopey.age, bean.getAge()); + } + // } } diff --git a/src/test/java/org/ini4j/tutorial/IniTutorial.java b/src/test/java/org/ini4j/tutorial/IniTutorial.java index 08e300f..cbb82d0 100644 --- a/src/test/java/org/ini4j/tutorial/IniTutorial.java +++ b/src/test/java/org/ini4j/tutorial/IniTutorial.java @@ -15,228 +15,217 @@ */ package org.ini4j.tutorial; -import org.ini4j.Ini; - -import org.ini4j.sample.Dwarf; -import org.ini4j.sample.Dwarfs; - -import org.ini4j.test.DwarfsData; -import org.ini4j.test.Helper; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.File; import java.io.FileReader; import java.io.IOException; - import java.util.Map; import java.util.Set; +import org.ini4j.Ini; +import org.ini4j.sample.Dwarf; +import org.ini4j.sample.Dwarfs; +import org.ini4j.test.DwarfsData; +import org.ini4j.test.Helper; -// -//| -//| ------------- -//| Ini Tutorial -//| -//|Ini Tutorial - How to use \[ini4j\] api -//| -//| This tutorial familiarize the reader with the usage of -//| the [ini4j] library's natural interface. -//| -//| Code sniplets in this tutorial tested with the following .ini file: -//| {{{../sample/dwarfs.ini.html}dwarfs.ini}} -//| -// -public class IniTutorial extends AbstractTutorial -{ - public static void main(String[] args) throws Exception - { - new IniTutorial().run(filearg(args)); - } - - @Override protected void run(File arg) throws Exception - { - Ini ini = new Ini(arg.toURI().toURL()); - - sample01(ini); - sample02(arg); - sample03(ini); - sample04(ini); - } - -//|* Data model -//| -//| Data model for .ini files is represented by org.ini4j.Ini class. This class -//| implements Map\. It mean you can access sections using -//| java.util.Map collection API interface. The Section is also a map, which is -//| implements Map\. -//{ - void sample01(Ini ini) - { - Ini.Section section = ini.get("happy"); - - // - // read some values - // - String age = section.get("age"); - String weight = section.get("weight"); - String homeDir = section.get("homeDir"); - - // - // .. or just use java.util.Map interface... - // - Map map = ini.get("happy"); - - age = map.get("age"); - weight = map.get("weight"); - homeDir = map.get("homeDir"); - - // get all section names - Set sectionNames = ini.keySet(); - -//} - Helper.assertEquals(DwarfsData.happy, section.as(Dwarf.class)); - } - -//| -//|* Loading and storing data -//| -//| There is several way to load data into Ini object. It can be done by using -//| <<>> methods or overloaded constructors. Data can be load from -//| InputStream, Reader, URL or File. -//| -//| You can store data using <<>> methods. Data can store to OutputStream, -//| Writer, or File. -//{ - void sample02(File file) throws IOException - { - Ini ini = new Ini(); - - ini.load(new FileReader(file)); - - // - // or instantiate and load data: - // - ini = new Ini(new FileReader(file)); - File copy = File.createTempFile("sample", ".ini"); - - ini.store(copy); -//} - ini = new Ini(copy); - Helper.assertEquals(DwarfsData.dwarfs, ini.as(Dwarfs.class)); - copy.delete(); - } - -//| -//|* Macro/variable substitution -//| -//| To get a value, besides <<>> you can also -//| use <<>> which resolves any occurrent $\{section/option\} format -//| variable references in the needed value. -//| -//{ - void sample03(Ini ini) - { - Ini.Section dopey = ini.get("dopey"); - - // get method doesn't resolve variable references - String weightRaw = dopey.get("weight"); // = ${bashful/weight} - String heightRaw = dopey.get("height"); // = ${doc/height} - - // to resolve references, you should use fetch method - String weight = dopey.fetch("weight"); // = 45.7 - String height = dopey.fetch("height"); // = 87.7 - -//} -//| Assuming we have an .ini file with the following sections: -//| -//|+--------------+ -//| [dopey] -//| weight = ${bashful/weight} -//| height = ${doc/height} -//| -//|[bashful] -//| weight = 45.7 -//| height = 98.8 -//| -//| [doc] -//| weight = 49.5 -//| height = 87.7 -//|+--------------+ -//| - assertEquals(DwarfsData.INI_DOPEY_WEIGHT, weightRaw); - assertEquals(DwarfsData.INI_DOPEY_HEIGHT, heightRaw); - assertEquals(String.valueOf(DwarfsData.dopey.weight), weight); - assertEquals(String.valueOf(DwarfsData.dopey.height), height); - } - -//| -//|* Multi values -//| -//| \[ini4j\] library introduces MultiMap interface, which is extends normal -//| Map, but allows multiply values per keys. You can simply index values for -//| a given key, similar to indexed properties in JavaBeans api. -//| -//{ - void sample04(Ini ini) - { - Ini.Section sneezy = ini.get("sneezy"); - String n1 = sneezy.get("fortuneNumber", 0); // = 11 - String n2 = sneezy.get("fortuneNumber", 1); // = 22 - String n3 = sneezy.get("fortuneNumber", 2); // = 33 - String n4 = sneezy.get("fortuneNumber", 3); // = 44 - - // ok, lets do in it easier... - int[] n = sneezy.getAll("fortuneNumber", int[].class); -//} - // #2817399 - - assertEquals("11", n1); - assertEquals("22", n2); - assertEquals("33", n3); - assertEquals("44", n4); - assertEquals(4, n.length); - assertEquals(11, n[0]); - assertEquals(22, n[1]); - assertEquals(33, n[2]); - assertEquals(44, n[3]); - } - -//| -//|* Tree model -//| -//| Beyond two level map model, Ini class provides tree model. You can access -//| Sections as tree. It means that section names becomes path names, with a -//| path separator character ('/' and '\' on Wini and Reg). -//| -//{ - void sample05() - { - Ini ini = new Ini(); - - // lets add a section, it will create needed intermediate sections as well - ini.add("root/child/sub"); - - // - Ini.Section root; - Ini.Section sec; - - root = ini.get("root"); - sec = root.getChild("child").getChild("sub"); - - // or... - sec = root.lookup("child", "sub"); - - // or... - sec = root.lookup("child/sub"); - - // or even... - sec = ini.get("root/child/sub"); - -//} -//| If you are using Wini instead of Ini class, the path separator become '\'. -//| - assertNotNull(root.lookup("child", "sub")); - assertNotNull(ini.get("root/child")); - } +// +// | +// | ------------- +// | Ini Tutorial +// | +// |Ini Tutorial - How to use \[ini4j\] api +// | +// | This tutorial familiarize the reader with the usage of +// | the [ini4j] library's natural interface. +// | +// | Code sniplets in this tutorial tested with the following .ini file: +// | {{{../sample/dwarfs.ini.html}dwarfs.ini}} +// | +// +public class IniTutorial extends AbstractTutorial { + public static void main(String[] args) throws Exception { + new IniTutorial().run(filearg(args)); + } + + @Override + protected void run(File arg) throws Exception { + Ini ini = new Ini(arg.toURI().toURL()); + + sample01(ini); + sample02(arg); + sample03(ini); + sample04(ini); + } + + // |* Data model + // | + // | Data model for .ini files is represented by org.ini4j.Ini class. This class + // | implements Map\. It mean you can access sections using + // | java.util.Map collection API interface. The Section is also a map, which is + // | implements Map\. + // { + void sample01(Ini ini) { + Ini.Section section = ini.get("happy"); + + // + // read some values + // + String age = section.get("age"); + String weight = section.get("weight"); + String homeDir = section.get("homeDir"); + + // + // .. or just use java.util.Map interface... + // + Map map = ini.get("happy"); + + age = map.get("age"); + weight = map.get("weight"); + homeDir = map.get("homeDir"); + + // get all section names + Set sectionNames = ini.keySet(); + + // } + Helper.assertEquals(DwarfsData.happy, section.as(Dwarf.class)); + } + + // | + // |* Loading and storing data + // | + // | There is several way to load data into Ini object. It can be done by using + // | <<>> methods or overloaded constructors. Data can be load from + // | InputStream, Reader, URL or File. + // | + // | You can store data using <<>> methods. Data can store to OutputStream, + // | Writer, or File. + // { + void sample02(File file) throws IOException { + Ini ini = new Ini(); + + ini.load(new FileReader(file)); + + // + // or instantiate and load data: + // + ini = new Ini(new FileReader(file)); + File copy = File.createTempFile("sample", ".ini"); + + ini.store(copy); + // } + ini = new Ini(copy); + Helper.assertEquals(DwarfsData.dwarfs, ini.as(Dwarfs.class)); + copy.delete(); + } + + // | + // |* Macro/variable substitution + // | + // | To get a value, besides <<>> you can also + // | use <<>> which resolves any occurrent $\{section/option\} format + // | variable references in the needed value. + // | + // { + void sample03(Ini ini) { + Ini.Section dopey = ini.get("dopey"); + + // get method doesn't resolve variable references + String weightRaw = dopey.get("weight"); // = ${bashful/weight} + String heightRaw = dopey.get("height"); // = ${doc/height} + + // to resolve references, you should use fetch method + String weight = dopey.fetch("weight"); // = 45.7 + String height = dopey.fetch("height"); // = 87.7 + + // } + // | Assuming we have an .ini file with the following sections: + // | + // |+--------------+ + // | [dopey] + // | weight = ${bashful/weight} + // | height = ${doc/height} + // | + // |[bashful] + // | weight = 45.7 + // | height = 98.8 + // | + // | [doc] + // | weight = 49.5 + // | height = 87.7 + // |+--------------+ + // | + assertEquals(DwarfsData.INI_DOPEY_WEIGHT, weightRaw); + assertEquals(DwarfsData.INI_DOPEY_HEIGHT, heightRaw); + assertEquals(String.valueOf(DwarfsData.dopey.weight), weight); + assertEquals(String.valueOf(DwarfsData.dopey.height), height); + } + + // | + // |* Multi values + // | + // | \[ini4j\] library introduces MultiMap interface, which is extends normal + // | Map, but allows multiply values per keys. You can simply index values for + // | a given key, similar to indexed properties in JavaBeans api. + // | + // { + void sample04(Ini ini) { + Ini.Section sneezy = ini.get("sneezy"); + String n1 = sneezy.get("fortuneNumber", 0); // = 11 + String n2 = sneezy.get("fortuneNumber", 1); // = 22 + String n3 = sneezy.get("fortuneNumber", 2); // = 33 + String n4 = sneezy.get("fortuneNumber", 3); // = 44 + + // ok, lets do in it easier... + int[] n = sneezy.getAll("fortuneNumber", int[].class); + // } + // #2817399 + + assertEquals("11", n1); + assertEquals("22", n2); + assertEquals("33", n3); + assertEquals("44", n4); + assertEquals(4, n.length); + assertEquals(11, n[0]); + assertEquals(22, n[1]); + assertEquals(33, n[2]); + assertEquals(44, n[3]); + } + + // | + // |* Tree model + // | + // | Beyond two level map model, Ini class provides tree model. You can access + // | Sections as tree. It means that section names becomes path names, with a + // | path separator character ('/' and '\' on Wini and Reg). + // | + // { + void sample05() { + Ini ini = new Ini(); + + // lets add a section, it will create needed intermediate sections as well + ini.add("root/child/sub"); + + // + Ini.Section root; + Ini.Section sec; + + root = ini.get("root"); + sec = root.getChild("child").getChild("sub"); + + // or... + sec = root.lookup("child", "sub"); + + // or... + sec = root.lookup("child/sub"); + + // or even... + sec = ini.get("root/child/sub"); + + // } + // | If you are using Wini instead of Ini class, the path separator become '\'. + // | + assertNotNull(root.lookup("child", "sub")); + assertNotNull(ini.get("root/child")); + } } diff --git a/src/test/java/org/ini4j/tutorial/OneMinuteTutorial.java b/src/test/java/org/ini4j/tutorial/OneMinuteTutorial.java index da6cb80..2839261 100644 --- a/src/test/java/org/ini4j/tutorial/OneMinuteTutorial.java +++ b/src/test/java/org/ini4j/tutorial/OneMinuteTutorial.java @@ -15,121 +15,113 @@ */ package org.ini4j.tutorial; -import org.ini4j.Wini; - -import org.ini4j.sample.Dwarf; -import org.ini4j.sample.Dwarfs; - -import org.ini4j.test.DwarfsData; -import org.ini4j.test.Helper; - import static org.junit.Assert.*; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; +import org.ini4j.Wini; +import org.ini4j.sample.Dwarf; +import org.ini4j.sample.Dwarfs; +import org.ini4j.test.DwarfsData; +import org.ini4j.test.Helper; -// -//| -//| ------------------- -//| One minute Tutorial -//| -//|One minute Tutorial - First step -//| -//| First step with \[ini4j\] library. No data model, no interfaces, no design -//| patterns, simply read and write windows .ini files. -//| -// -public class OneMinuteTutorial extends AbstractTutorial -{ - public static void main(String[] args) throws Exception - { - new OneMinuteTutorial().run(filearg(args)); - } - - protected void copy(File inputFile, File outputFile) throws IOException - { - FileInputStream is = new FileInputStream(inputFile); - FileOutputStream os = new FileOutputStream(outputFile); - byte[] buff = new byte[8192]; - int n; - - while ((n = is.read(buff)) > 0) - { - os.write(buff, 0, n); - } - - is.close(); - os.close(); - } - - @Override protected void run(File arg) throws Exception - { - File file = File.createTempFile("tutorial", ".ini"); - - file.deleteOnExit(); - copy(arg, file); - sample01(file.getCanonicalPath()); - sample02(file.getCanonicalPath()); - } - -//| -//| Lets read some value from .ini file... -//| -//{ - void sample01(String filename) throws IOException - { - Wini ini = new Wini(new File(filename)); - int age = ini.get("happy", "age", int.class); - double height = ini.get("happy", "height", double.class); - String dir = ini.get("happy", "homeDir"); - -//} -//| ... assuming there is a section with name <<>>, which contains at least -//| the following options: <<>>, <<>> and <<>>, something like -//| this: -//| -//|+---------+ -//| [happy] -//| age = 99 -//| height = 77.66 -//| homeDir = /home/happy -//|+---------+ -//| -//| - assertEquals(DwarfsData.happy.age, age); - assertEquals(DwarfsData.happy.height, height, Helper.DELTA); - assertEquals(DwarfsData.happy.homeDir, dir); - } - -//| Now let see how to write values.... -//| -//{ - void sample02(String filename) throws IOException - { - Wini ini = new Wini(new File(filename)); - - ini.put("sleepy", "age", 55); - ini.put("sleepy", "weight", 45.6); - ini.store(); - -//} -//| ... and then file will have a section <<>> and this section -//| will contains at least two options: <<>> with value <<<55>>> and <<>> -//| with value <<<45.6>>>, something like this: -//| -//|+---------+ -//| [sleepy] -//| age = 55 -//| weight = 45.6 -//|+---------+ -//| - assertEquals(55, (int) ini.get(Dwarfs.PROP_SLEEPY, Dwarf.PROP_AGE, int.class)); - assertEquals(45.6, (double) ini.get(Dwarfs.PROP_SLEEPY, Dwarf.PROP_WEIGHT, double.class), Helper.DELTA); +// +// | +// | ------------------- +// | One minute Tutorial +// | +// |One minute Tutorial - First step +// | +// | First step with \[ini4j\] library. No data model, no interfaces, no design +// | patterns, simply read and write windows .ini files. +// | +// +public class OneMinuteTutorial extends AbstractTutorial { + public static void main(String[] args) throws Exception { + new OneMinuteTutorial().run(filearg(args)); + } + + protected void copy(File inputFile, File outputFile) throws IOException { + FileInputStream is = new FileInputStream(inputFile); + FileOutputStream os = new FileOutputStream(outputFile); + byte[] buff = new byte[8192]; + int n; + + while ((n = is.read(buff)) > 0) { + os.write(buff, 0, n); } -//| -//| If you want to know more about this library, read -//| {{{../tutorial/index.html}tutorials}} + is.close(); + os.close(); + } + + @Override + protected void run(File arg) throws Exception { + File file = File.createTempFile("tutorial", ".ini"); + + file.deleteOnExit(); + copy(arg, file); + sample01(file.getCanonicalPath()); + sample02(file.getCanonicalPath()); + } + + // | + // | Lets read some value from .ini file... + // | + // { + void sample01(String filename) throws IOException { + Wini ini = new Wini(new File(filename)); + int age = ini.get("happy", "age", int.class); + double height = ini.get("happy", "height", double.class); + String dir = ini.get("happy", "homeDir"); + + // } + // | ... assuming there is a section with name <<>>, which contains at least + // | the following options: <<>>, <<>> and <<>>, something like + // | this: + // | + // |+---------+ + // | [happy] + // | age = 99 + // | height = 77.66 + // | homeDir = /home/happy + // |+---------+ + // | + // | + assertEquals(DwarfsData.happy.age, age); + assertEquals(DwarfsData.happy.height, height, Helper.DELTA); + assertEquals(DwarfsData.happy.homeDir, dir); + } + + // | Now let see how to write values.... + // | + // { + void sample02(String filename) throws IOException { + Wini ini = new Wini(new File(filename)); + + ini.put("sleepy", "age", 55); + ini.put("sleepy", "weight", 45.6); + ini.store(); + + // } + // | ... and then file will have a section <<>> and this section + // | will contains at least two options: <<>> with value <<<55>>> and <<>> + // | with value <<<45.6>>>, something like this: + // | + // |+---------+ + // | [sleepy] + // | age = 55 + // | weight = 45.6 + // |+---------+ + // | + assertEquals(55, (int) ini.get(Dwarfs.PROP_SLEEPY, Dwarf.PROP_AGE, int.class)); + assertEquals( + 45.6, (double) ini.get(Dwarfs.PROP_SLEEPY, Dwarf.PROP_WEIGHT, double.class), Helper.DELTA); + } + + // | + // | If you want to know more about this library, read + // | {{{../tutorial/index.html}tutorials}} } diff --git a/src/test/java/org/ini4j/tutorial/OptTutorial.java b/src/test/java/org/ini4j/tutorial/OptTutorial.java index b0e9d05..adf34c2 100644 --- a/src/test/java/org/ini4j/tutorial/OptTutorial.java +++ b/src/test/java/org/ini4j/tutorial/OptTutorial.java @@ -15,147 +15,138 @@ */ package org.ini4j.tutorial; -import org.ini4j.Options; - -import org.ini4j.sample.Dwarf; - -import org.ini4j.test.DwarfsData; -import org.ini4j.test.Helper; - import static org.junit.Assert.*; import java.io.File; import java.io.FileReader; import java.io.IOException; - import java.util.Set; +import org.ini4j.Options; +import org.ini4j.sample.Dwarf; +import org.ini4j.test.DwarfsData; +import org.ini4j.test.Helper; -// -//| -//| ---------------- -//| Options Tutorial -//| -//|Options Tutorial - java.util.Properties replacement -//| -//| Options (org.ini4j.Options) is a java.util.Properties replacement with -//| several useful features, like: -//| -//| * variable/macro substitution. You may refer to other property's value with -//| $\{NAME\} expression, where NAME is the name of the referred property. -//| ofcourse you can use more than one property reference per property, and -//| you can mix constant text and property references: -//| -//|+-------------------+ -//|player.name = Joe -//|player.greetings = Hi ${player.name}! -//|player.domain = foo.bar -//|player.email = ${player.name}@${player.domain} -//|+-------------------+ -//| -//| * multiply property values. You can refer to multi value properties with -//| integer indexes. Ofcource it is also works in macro/variable substitutions: -//| $\{user.fortuneNumber\[2\]\} -//| -//|+-------------------+ -//|player.fortuneNumber = 33 -//|player.fortuneNumber = 44 -//|player.fortuneNumber = 55 -//|player.fortuneNumber = 66 -//| -//|magicNumber = ${player.foruneNumber[1]} -//|+--------------------+ -//| -//| The magicNumber property will have value: <<<44>>> -//| -//| * as Java class, Options is basicly map of Strings indexed with Strings. It -//| is standard Collection API (ok, it is a bit enhanced to deal with multi -//| values, but in general it is a Map\). -//| -//| * Java Beans api. You can read/write properties in type safe way. To do it -//| you just define an interface, call Options#as() method. This method will -//| provide an implementation of given interface on top of Options. Property -//| types are mapped automatically between Java type and String. -//| -//|* Why need Options -//| -//| With standard Properties class there is several small problem. Most of them -//| came from backward compatibility. -//| -//| * not implements Map\, but Map\. If you -//| want to use Collections api, it is a bit unconfortable. -//| -//| * only single property values allowed. Probably you already see ugly -//| workarounds: index number in property names, like: file.1, file.2 ... -//| -//| * no macro/variable substitution. In some environment, like -//| Apache Ant, you can use ${name} like references, but with standard -//| java.util.Properties you can't. -//| -//| As side effect of \[ini4j\] development, there is a solution for aboves. -//| This is the org.ini4j.Options class, which is basicly a feature rich -//| replacement for java.util.Properties. -//| -//| Code sniplets in this tutorial tested with the following .opt file: -//| {{{../sample/dwarfs.opt.html}dwarfs.opt}} -//| -// -public class OptTutorial extends AbstractTutorial -{ - public static final String FILENAME = "../sample/dwarfs.opt"; - - public static void main(String[] args) throws Exception - { - new OptTutorial().run(filearg(args)); - } - - protected void run(File arg) throws Exception - { - Options opt = new Options(arg.toURI().toURL()); - - sample01(arg); - sample02(opt); - } - -//| -//|* Instantiating -//| -//| There is nothing special with instantiating Options object, but there is a -//| few constructor, to simplify loading data. These constructors simply call -//| the <<>> method on newly created instance. Ofcource these -//| constructors are throws IOException. -//{ - void sample01(File file) throws IOException - { - Options opt = new Options(); - - // - // or instantiate and load data: - // - opt = new Options(new FileReader(file)); - -//} - assertFalse(opt.keySet().isEmpty()); - } - -//| -//|* Map of String -//{ - void sample02(Options opt) - { - Set optionNames = opt.keySet(); - - // - String age = opt.get("age"); - String weight = opt.fetch("weight"); - String height = opt.fetch("height"); - -//} -//| -//| The Options is a MultiMap\, that is, a map that assigns -//| String values to String keys. So the <<>> method is used to get values -//| inside the options. To get a value, besides <<>> you can also -//| use <<>> which resolves any occurrent $\{option\} format -//| variable references in the needed value. - Helper.assertEquals(DwarfsData.dopey, opt.as(Dwarf.class)); - } +// +// | +// | ---------------- +// | Options Tutorial +// | +// |Options Tutorial - java.util.Properties replacement +// | +// | Options (org.ini4j.Options) is a java.util.Properties replacement with +// | several useful features, like: +// | +// | * variable/macro substitution. You may refer to other property's value with +// | $\{NAME\} expression, where NAME is the name of the referred property. +// | ofcourse you can use more than one property reference per property, and +// | you can mix constant text and property references: +// | +// |+-------------------+ +// |player.name = Joe +// |player.greetings = Hi ${player.name}! +// |player.domain = foo.bar +// |player.email = ${player.name}@${player.domain} +// |+-------------------+ +// | +// | * multiply property values. You can refer to multi value properties with +// | integer indexes. Ofcource it is also works in macro/variable substitutions: +// | $\{user.fortuneNumber\[2\]\} +// | +// |+-------------------+ +// |player.fortuneNumber = 33 +// |player.fortuneNumber = 44 +// |player.fortuneNumber = 55 +// |player.fortuneNumber = 66 +// | +// |magicNumber = ${player.foruneNumber[1]} +// |+--------------------+ +// | +// | The magicNumber property will have value: <<<44>>> +// | +// | * as Java class, Options is basicly map of Strings indexed with Strings. It +// | is standard Collection API (ok, it is a bit enhanced to deal with multi +// | values, but in general it is a Map\). +// | +// | * Java Beans api. You can read/write properties in type safe way. To do it +// | you just define an interface, call Options#as() method. This method will +// | provide an implementation of given interface on top of Options. Property +// | types are mapped automatically between Java type and String. +// | +// |* Why need Options +// | +// | With standard Properties class there is several small problem. Most of them +// | came from backward compatibility. +// | +// | * not implements Map\, but Map\. If you +// | want to use Collections api, it is a bit unconfortable. +// | +// | * only single property values allowed. Probably you already see ugly +// | workarounds: index number in property names, like: file.1, file.2 ... +// | +// | * no macro/variable substitution. In some environment, like +// | Apache Ant, you can use ${name} like references, but with standard +// | java.util.Properties you can't. +// | +// | As side effect of \[ini4j\] development, there is a solution for aboves. +// | This is the org.ini4j.Options class, which is basicly a feature rich +// | replacement for java.util.Properties. +// | +// | Code sniplets in this tutorial tested with the following .opt file: +// | {{{../sample/dwarfs.opt.html}dwarfs.opt}} +// | +// +public class OptTutorial extends AbstractTutorial { + public static final String FILENAME = "../sample/dwarfs.opt"; + + public static void main(String[] args) throws Exception { + new OptTutorial().run(filearg(args)); + } + + protected void run(File arg) throws Exception { + Options opt = new Options(arg.toURI().toURL()); + + sample01(arg); + sample02(opt); + } + + // | + // |* Instantiating + // | + // | There is nothing special with instantiating Options object, but there is a + // | few constructor, to simplify loading data. These constructors simply call + // | the <<>> method on newly created instance. Ofcource these + // | constructors are throws IOException. + // { + void sample01(File file) throws IOException { + Options opt = new Options(); + + // + // or instantiate and load data: + // + opt = new Options(new FileReader(file)); + + // } + assertFalse(opt.keySet().isEmpty()); + } + + // | + // |* Map of String + // { + void sample02(Options opt) { + Set optionNames = opt.keySet(); + + // + String age = opt.get("age"); + String weight = opt.fetch("weight"); + String height = opt.fetch("height"); + + // } + // | + // | The Options is a MultiMap\, that is, a map that assigns + // | String values to String keys. So the <<>> method is used to get values + // | inside the options. To get a value, besides <<>> you can also + // | use <<>> which resolves any occurrent $\{option\} format + // | variable references in the needed value. + Helper.assertEquals(DwarfsData.dopey, opt.as(Dwarf.class)); + } } diff --git a/src/test/java/org/ini4j/tutorial/OptionMapTutorial.java b/src/test/java/org/ini4j/tutorial/OptionMapTutorial.java index 21fce1b..a93fe03 100644 --- a/src/test/java/org/ini4j/tutorial/OptionMapTutorial.java +++ b/src/test/java/org/ini4j/tutorial/OptionMapTutorial.java @@ -15,140 +15,131 @@ */ package org.ini4j.tutorial; -import org.ini4j.Ini; - -import org.ini4j.sample.Dwarfs; - -import org.ini4j.test.DwarfsData; - import static org.junit.Assert.*; import java.io.File; - import java.util.Set; +import org.ini4j.Ini; +import org.ini4j.sample.Dwarfs; +import org.ini4j.test.DwarfsData; -// -//| -//| ------------- -//| OptionMap Tutorial -//| -//|OptionMap Tutorial - more than just String,String map -//| -//| Option is a name/value pair stored in OptionMap. But OptionMap adds a lot of -//| usefull data access methods than simple get. OptionMap is base interface for -//| both Ini.Section, Registry.Key and Options classes, so this tutorial will -//| usefull for all of these. -//| -//| So in samples bellow you can use either Ini.Section, Registry.Key or Options -//| classes instead of OptionMap interface, because these classes implements -//| OptionMap. -//| -//| Code sniplets in this tutorial tested with the following files: -//| {{{../sample/dwarfs.ini.html}dwarfs.ini}} -//| {{{../sample/dwarfs.opt.html}dwarfs.opt}} -//| -// -public class OptionMapTutorial extends AbstractTutorial -{ - public static void main(String[] args) throws Exception - { - new OptionMapTutorial().run(filearg(args)); - } - - @Override protected void run(File arg) throws Exception - { - Ini ini = new Ini(arg.toURI().toURL()); - - sample01(ini.get(Dwarfs.PROP_HAPPY)); - sample03(ini); - sample04(ini); - } - -//|* Data model -//| -//| OptionMap implements Map\, so you can access options using -//| standard collection api. -//{ - void sample01(Ini.Section section) - { - - // - // read some values - // - String age = section.get("age"); - String weight = section.get("weight"); - String homeDir = section.get("homeDir"); - - // get all option names - Set optionNames = section.keySet(); - -//} - assertEquals(String.valueOf(DwarfsData.happy.age), age); - assertEquals(String.valueOf(DwarfsData.happy.weight), weight); - assertEquals(String.valueOf(DwarfsData.happy.homeDir), homeDir); - } - -//| -//|* Macro/variable substitution -//| -//| To get a value, besides <<>> you can also -//| use <<>> which resolves any occurrent $\{section/option\} format -//| variable references in the needed value. -//| -//{ - void sample03(Ini ini) - { - Ini.Section dopey = ini.get("dopey"); - - // get method doesn't resolve variable references - String weightRaw = dopey.get("weight"); // = ${bashful/weight} - String heightRaw = dopey.get("height"); // = ${doc/height} - - // to resolve references, you should use fetch method - String weight = dopey.fetch("weight"); // = 45.7 - String height = dopey.fetch("height"); // = 87.7 - -//} -//| Assuming we have an .ini file with the following sections: -//| -//|+--------------+ -//| [dopey] -//| weight = ${bashful/weight} -//| height = ${doc/height} -//| -//|[bashful] -//| weight = 45.7 -//| height = 98.8 -//| -//| [doc] -//| weight = 49.5 -//| height = 87.7 -//|+--------------+ -//| - assertEquals(DwarfsData.INI_DOPEY_WEIGHT, weightRaw); - assertEquals(DwarfsData.INI_DOPEY_HEIGHT, heightRaw); - assertEquals(String.valueOf(DwarfsData.dopey.weight), weight); - assertEquals(String.valueOf(DwarfsData.dopey.height), height); - } - -//| -//|* Multi values -//| -//| \[ini4j\] library introduces MultiMap interface, which is extends normal -//| Map, but allows multiply values per keys. You can simply index values for -//| a given key, similar to indexed properties in JavaBeans api. -//| -//{ - void sample04(Ini ini) - { - Ini.Section sneezy = ini.get("sneezy"); - String n1 = sneezy.get("fortuneNumber", 0); // = 11 - String n2 = sneezy.get("fortuneNumber", 1); // = 22 - String n3 = sneezy.get("fortuneNumber", 2); // = 33 - String n4 = sneezy.get("fortuneNumber", 3); // = 44 - - // ok, lets do in it easier... - int[] n = sneezy.get("fortuneNumber", int[].class); -//} - } +// +// | +// | ------------- +// | OptionMap Tutorial +// | +// |OptionMap Tutorial - more than just String,String map +// | +// | Option is a name/value pair stored in OptionMap. But OptionMap adds a lot of +// | usefull data access methods than simple get. OptionMap is base interface for +// | both Ini.Section, Registry.Key and Options classes, so this tutorial will +// | usefull for all of these. +// | +// | So in samples bellow you can use either Ini.Section, Registry.Key or Options +// | classes instead of OptionMap interface, because these classes implements +// | OptionMap. +// | +// | Code sniplets in this tutorial tested with the following files: +// | {{{../sample/dwarfs.ini.html}dwarfs.ini}} +// | {{{../sample/dwarfs.opt.html}dwarfs.opt}} +// | +// +public class OptionMapTutorial extends AbstractTutorial { + public static void main(String[] args) throws Exception { + new OptionMapTutorial().run(filearg(args)); + } + + @Override + protected void run(File arg) throws Exception { + Ini ini = new Ini(arg.toURI().toURL()); + + sample01(ini.get(Dwarfs.PROP_HAPPY)); + sample03(ini); + sample04(ini); + } + + // |* Data model + // | + // | OptionMap implements Map\, so you can access options using + // | standard collection api. + // { + void sample01(Ini.Section section) { + + // + // read some values + // + String age = section.get("age"); + String weight = section.get("weight"); + String homeDir = section.get("homeDir"); + + // get all option names + Set optionNames = section.keySet(); + + // } + assertEquals(String.valueOf(DwarfsData.happy.age), age); + assertEquals(String.valueOf(DwarfsData.happy.weight), weight); + assertEquals(String.valueOf(DwarfsData.happy.homeDir), homeDir); + } + + // | + // |* Macro/variable substitution + // | + // | To get a value, besides <<>> you can also + // | use <<>> which resolves any occurrent $\{section/option\} format + // | variable references in the needed value. + // | + // { + void sample03(Ini ini) { + Ini.Section dopey = ini.get("dopey"); + + // get method doesn't resolve variable references + String weightRaw = dopey.get("weight"); // = ${bashful/weight} + String heightRaw = dopey.get("height"); // = ${doc/height} + + // to resolve references, you should use fetch method + String weight = dopey.fetch("weight"); // = 45.7 + String height = dopey.fetch("height"); // = 87.7 + + // } + // | Assuming we have an .ini file with the following sections: + // | + // |+--------------+ + // | [dopey] + // | weight = ${bashful/weight} + // | height = ${doc/height} + // | + // |[bashful] + // | weight = 45.7 + // | height = 98.8 + // | + // | [doc] + // | weight = 49.5 + // | height = 87.7 + // |+--------------+ + // | + assertEquals(DwarfsData.INI_DOPEY_WEIGHT, weightRaw); + assertEquals(DwarfsData.INI_DOPEY_HEIGHT, heightRaw); + assertEquals(String.valueOf(DwarfsData.dopey.weight), weight); + assertEquals(String.valueOf(DwarfsData.dopey.height), height); + } + + // | + // |* Multi values + // | + // | \[ini4j\] library introduces MultiMap interface, which is extends normal + // | Map, but allows multiply values per keys. You can simply index values for + // | a given key, similar to indexed properties in JavaBeans api. + // | + // { + void sample04(Ini ini) { + Ini.Section sneezy = ini.get("sneezy"); + String n1 = sneezy.get("fortuneNumber", 0); // = 11 + String n2 = sneezy.get("fortuneNumber", 1); // = 22 + String n3 = sneezy.get("fortuneNumber", 2); // = 33 + String n4 = sneezy.get("fortuneNumber", 3); // = 44 + + // ok, lets do in it easier... + int[] n = sneezy.get("fortuneNumber", int[].class); + // } + } } diff --git a/src/test/java/org/ini4j/tutorial/PrefsTutorial.java b/src/test/java/org/ini4j/tutorial/PrefsTutorial.java index 5931b8e..b90accb 100644 --- a/src/test/java/org/ini4j/tutorial/PrefsTutorial.java +++ b/src/test/java/org/ini4j/tutorial/PrefsTutorial.java @@ -15,73 +15,69 @@ */ package org.ini4j.tutorial; -import org.ini4j.Ini; -import org.ini4j.IniPreferences; - -import org.ini4j.test.DwarfsData; - import static org.junit.Assert.*; import java.io.File; import java.io.IOException; - import java.util.prefs.Preferences; +import org.ini4j.Ini; +import org.ini4j.IniPreferences; +import org.ini4j.test.DwarfsData; -// -//| -//| ------------- -//| Preferences Tutorial -//| -//|Preferences Tutorial -//| -//| The purpose of this document is to familiarize the reader with the usage of -//| the [ini4j] library's Preferences interface. Each chapter contains all the -//| necessary code portions and explanation for a given function. -//| -//| Code sniplets in this tutorial tested with the following .ini file: -//| {{{../sample/dwarfs.ini.html}dwarfs.ini}} -//| -//| As soon as the Preferences object is created it functions as a standard Preferences node, and should be -//| used as such. Implicitly only new nodes can be created in the root node (these will be the sections). -//| In the first level nodes (sections) only values can be created (these will be the options). -//| -//| In the case of an invalid operation an <<>> type runtime exception is generated. -//| This happens if we try to set a value at the root node or to create a node on the second level, -//| since these operations cannot be interpreted on the whole .ini file under Preferences. -//| -// -public class PrefsTutorial extends AbstractTutorial -{ - public static void main(String[] args) throws Exception - { - new PrefsTutorial().run(filearg(args)); - } +// +// | +// | ------------- +// | Preferences Tutorial +// | +// |Preferences Tutorial +// | +// | The purpose of this document is to familiarize the reader with the usage of +// | the [ini4j] library's Preferences interface. Each chapter contains all the +// | necessary code portions and explanation for a given function. +// | +// | Code sniplets in this tutorial tested with the following .ini file: +// | {{{../sample/dwarfs.ini.html}dwarfs.ini}} +// | +// | As soon as the Preferences object is created it functions as a standard Preferences node, and +// should be +// | used as such. Implicitly only new nodes can be created in the root node (these will be the +// sections). +// | In the first level nodes (sections) only values can be created (these will be the options). +// | +// | In the case of an invalid operation an <<>> type runtime +// exception is generated. +// | This happens if we try to set a value at the root node or to create a node on the second level, +// | since these operations cannot be interpreted on the whole .ini file under Preferences. +// | +// +public class PrefsTutorial extends AbstractTutorial { + public static void main(String[] args) throws Exception { + new PrefsTutorial().run(filearg(args)); + } - protected void run(File arg) throws Exception - { - Ini ini = new Ini(arg.toURI().toURL()); + protected void run(File arg) throws Exception { + Ini ini = new Ini(arg.toURI().toURL()); - sample01(ini); - } + sample01(ini); + } -//| -//|* Reading and writing values -//| -//| Values can read and write like any other Preferences node, there is no -//| differences. -//{ - void sample01(Ini ini) throws IOException - { - Preferences prefs = new IniPreferences(ini); - Preferences bashful = prefs.node("bashful"); - String home = bashful.get("homeDir", "/home"); - int age = bashful.getInt("age", -1); + // | + // |* Reading and writing values + // | + // | Values can read and write like any other Preferences node, there is no + // | differences. + // { + void sample01(Ini ini) throws IOException { + Preferences prefs = new IniPreferences(ini); + Preferences bashful = prefs.node("bashful"); + String home = bashful.get("homeDir", "/home"); + int age = bashful.getInt("age", -1); - bashful.putDouble("weight", 55.6); + bashful.putDouble("weight", 55.6); -//} - assertEquals(DwarfsData.bashful.homeDir, bashful.get("homeDir", null)); - assertEquals(DwarfsData.bashful.age, bashful.getInt("age", -1)); - assertEquals(55.6, bashful.getDouble("weight", -1), 0.001); - } + // } + assertEquals(DwarfsData.bashful.homeDir, bashful.get("homeDir", null)); + assertEquals(DwarfsData.bashful.age, bashful.getInt("age", -1)); + assertEquals(55.6, bashful.getDouble("weight", -1), 0.001); + } } diff --git a/src/test/java/org/ini4j/tutorial/RegTutorial.java b/src/test/java/org/ini4j/tutorial/RegTutorial.java index 4703b17..799b41c 100644 --- a/src/test/java/org/ini4j/tutorial/RegTutorial.java +++ b/src/test/java/org/ini4j/tutorial/RegTutorial.java @@ -15,128 +15,121 @@ */ package org.ini4j.tutorial; -import org.ini4j.Reg; - -import org.ini4j.sample.Dwarf; - -import org.ini4j.test.DwarfsData; -import org.ini4j.test.Helper; - import static org.junit.Assert.*; import java.io.File; import java.io.IOException; - import java.net.URI; +import org.ini4j.Reg; +import org.ini4j.sample.Dwarf; +import org.ini4j.test.DwarfsData; +import org.ini4j.test.Helper; -// -//| -//| ------------- -//| Reg Tutorial -//| -//|Reg Tutorial - Windows .REG file handling -//| -//| Windows regedit commands .REG file format is very close to .ini format. -//| \[ini4j\] provides org.ini4j.Reg class to model .REG format. This tutorial -//| show the differences between Ini and Reg classes. -//| -//| Code sniplets in this tutorial tested with the following .reg file: -//| {{{../sample/dwarfs.reg.html}dwarfs.reg}} -//| -// -public class RegTutorial extends AbstractTutorial -{ - public static final String FILENAME = "../sample/dwarfs.reg"; - - public static void main(String[] args) throws Exception - { - new RegTutorial().run(filearg(args)); - } - - @Override protected void run(File arg) throws Exception - { - Reg reg = new Reg(arg.toURI().toURL()); - - sample01(arg); - sample02(); - } - -//| -//|* Loading and storing -//| -//| There is nothing special with loading and storing data, it works exactly same -//| as in Ini class. But while loading data, Reg class will strip .REG special -//| values (double qoute around strings, type data from option, etc). So after -//| loading a .REG file, you can use it exactly same way as Ini class. Ofcource -//| if you store Reg class, it will put all above meta information int file, so -//| the result will be a valid .REG file. You don't need to worry about file -//| encoding, version in first line, etc,etc. -//| -//| Assume you have a .REG file, with the following section/key: -//| -//|+---+ -//|[HKEY_CURRENT_USER\Software\ini4j-test\dwarfs\bashful] -//|@="bashful" -//|"weight"=hex(2):34,00,35,00,2e,00,37,00,00,00 -//|"height"="98.8" -//|"age"=dword:00000043 -//|"homePage"="http://snowwhite.tale/~bashful" -//|"homeDir"="/home/bashful" -//|+---+ -//| -//| As you see, "weight" and "age" is not simlpe strings. The "height" is a REG_DWORD -//| type while "weight" is REG_EXPAND_SZ. Don't worry, Reg class take care about -//| type conversion, you will access these as with regular .ini files: -//{ - void sample01(File file) throws IOException - { - Reg reg = new Reg(file); - Reg.Key hive = reg.get(Reg.Hive.HKEY_CURRENT_USER.toString()); - Reg.Key bashful; - - bashful = hive.lookup("Software", "ini4j-test", "dwarfs", "bashful"); - - // or ... - bashful = hive.lookup("Software\\ini4j-test\\dwarfs\\bashful"); - - // or even... - bashful = reg.get("HKEY_CURRENT_USER\\Software\\ini4j-test\\dwarfs\\bashful"); - - // read some data - double weight = bashful.get("weight", double.class); // = 45.7 - double height = bashful.get("height", double.class); // = 98.8 - int age = bashful.get("age", int.class); // = 67 - URI homePage = bashful.get("homePage", URI.class); // = new URI("http://snowwhite.tale/~bashful"); - String homeDir = bashful.get("homeDir"); // = "/home/bashful" - -//} - assertNotNull(reg.get(Helper.DWARFS_REG_PATH + "\\dwarfs")); - Helper.assertEquals(DwarfsData.bashful, bashful.as(Dwarf.class)); - } - -//| -//|* Types -//| -//| When you load data into Reg class, it will preserve meta informations, such as -//| type informations. If you create new values, by default these will have -//| tpye REG_SZ. Ofcource you may specify type information for values. -//{ - void sample02() - { - Reg reg = new Reg(); - Reg.Key key = reg.add("HKEY_CURRENT_USER\\Software\\ini4j-test\\dwarfs\\sleepy"); - - key.put("fortuneNumber", 99); - key.putType("fortuneNumber", Reg.Type.REG_MULTI_SZ); - -//} -//| -//| If you store reg object above, it will contains a section similar to this: -//| -//|+---+ -//|[HKEY_CURRENT_USER\Software\ini4j-test\dwarfs\sleepy] -//|"fortuneNumber"=hex(7):39,00,39,00,00,00,00,00 -//|+---+ -//| - } +// +// | +// | ------------- +// | Reg Tutorial +// | +// |Reg Tutorial - Windows .REG file handling +// | +// | Windows regedit commands .REG file format is very close to .ini format. +// | \[ini4j\] provides org.ini4j.Reg class to model .REG format. This tutorial +// | show the differences between Ini and Reg classes. +// | +// | Code sniplets in this tutorial tested with the following .reg file: +// | {{{../sample/dwarfs.reg.html}dwarfs.reg}} +// | +// +public class RegTutorial extends AbstractTutorial { + public static final String FILENAME = "../sample/dwarfs.reg"; + + public static void main(String[] args) throws Exception { + new RegTutorial().run(filearg(args)); + } + + @Override + protected void run(File arg) throws Exception { + Reg reg = new Reg(arg.toURI().toURL()); + + sample01(arg); + sample02(); + } + + // | + // |* Loading and storing + // | + // | There is nothing special with loading and storing data, it works exactly same + // | as in Ini class. But while loading data, Reg class will strip .REG special + // | values (double qoute around strings, type data from option, etc). So after + // | loading a .REG file, you can use it exactly same way as Ini class. Ofcource + // | if you store Reg class, it will put all above meta information int file, so + // | the result will be a valid .REG file. You don't need to worry about file + // | encoding, version in first line, etc,etc. + // | + // | Assume you have a .REG file, with the following section/key: + // | + // |+---+ + // |[HKEY_CURRENT_USER\Software\ini4j-test\dwarfs\bashful] + // |@="bashful" + // |"weight"=hex(2):34,00,35,00,2e,00,37,00,00,00 + // |"height"="98.8" + // |"age"=dword:00000043 + // |"homePage"="http://snowwhite.tale/~bashful" + // |"homeDir"="/home/bashful" + // |+---+ + // | + // | As you see, "weight" and "age" is not simlpe strings. The "height" is a REG_DWORD + // | type while "weight" is REG_EXPAND_SZ. Don't worry, Reg class take care about + // | type conversion, you will access these as with regular .ini files: + // { + void sample01(File file) throws IOException { + Reg reg = new Reg(file); + Reg.Key hive = reg.get(Reg.Hive.HKEY_CURRENT_USER.toString()); + Reg.Key bashful; + + bashful = hive.lookup("Software", "ini4j-test", "dwarfs", "bashful"); + + // or ... + bashful = hive.lookup("Software\\ini4j-test\\dwarfs\\bashful"); + + // or even... + bashful = reg.get("HKEY_CURRENT_USER\\Software\\ini4j-test\\dwarfs\\bashful"); + + // read some data + double weight = bashful.get("weight", double.class); // = 45.7 + double height = bashful.get("height", double.class); // = 98.8 + int age = bashful.get("age", int.class); // = 67 + URI homePage = + bashful.get("homePage", URI.class); // = new URI("http://snowwhite.tale/~bashful"); + String homeDir = bashful.get("homeDir"); // = "/home/bashful" + + // } + assertNotNull(reg.get(Helper.DWARFS_REG_PATH + "\\dwarfs")); + Helper.assertEquals(DwarfsData.bashful, bashful.as(Dwarf.class)); + } + + // | + // |* Types + // | + // | When you load data into Reg class, it will preserve meta informations, such as + // | type informations. If you create new values, by default these will have + // | tpye REG_SZ. Ofcource you may specify type information for values. + // { + void sample02() { + Reg reg = new Reg(); + Reg.Key key = reg.add("HKEY_CURRENT_USER\\Software\\ini4j-test\\dwarfs\\sleepy"); + + key.put("fortuneNumber", 99); + key.putType("fortuneNumber", Reg.Type.REG_MULTI_SZ); + + // } + // | + // | If you store reg object above, it will contains a section similar to this: + // | + // |+---+ + // |[HKEY_CURRENT_USER\Software\ini4j-test\dwarfs\sleepy] + // |"fortuneNumber"=hex(7):39,00,39,00,00,00,00,00 + // |+---+ + // | + } } diff --git a/src/test/java/org/ini4j/tutorial/WindowsRegistryTutorial.java b/src/test/java/org/ini4j/tutorial/WindowsRegistryTutorial.java index 95b9eda..a144f58 100644 --- a/src/test/java/org/ini4j/tutorial/WindowsRegistryTutorial.java +++ b/src/test/java/org/ini4j/tutorial/WindowsRegistryTutorial.java @@ -15,91 +15,84 @@ */ package org.ini4j.tutorial; -import org.ini4j.Reg; - import static org.junit.Assert.*; import java.io.File; import java.io.IOException; +import org.ini4j.Reg; -// -//| -//| ------------------------- -//| Windows Registry Tutorial -//| -//|Windows Registry Tutorial - Read/Write windows registry -//| -//| Yes, it is possible now to read/write registry from java programs -//| without native (JNI) code ! -//| -// -public class WindowsRegistryTutorial extends AbstractTutorial -{ - public static final String FILENAME = "../sample/dwarfs.reg"; +// +// | +// | ------------------------- +// | Windows Registry Tutorial +// | +// |Windows Registry Tutorial - Read/Write windows registry +// | +// | Yes, it is possible now to read/write registry from java programs +// | without native (JNI) code ! +// | +// +public class WindowsRegistryTutorial extends AbstractTutorial { + public static final String FILENAME = "../sample/dwarfs.reg"; - public static void main(String[] args) throws Exception - { - if (Reg.isWindows()) - { - new WindowsRegistryTutorial().run(filearg(args)); - } + public static void main(String[] args) throws Exception { + if (Reg.isWindows()) { + new WindowsRegistryTutorial().run(filearg(args)); } + } - @Override protected void run(File arg) throws Exception - { - sample01(); - sample02(); - sample03(); - } + @Override + protected void run(File arg) throws Exception { + sample01(); + sample02(); + sample03(); + } -//| -//|* Write -//| -//| Lets write something to registry -//{ - void sample01() throws IOException - { - Reg reg = new Reg(); - Reg.Key key = reg.add("HKEY_CURRENT_USER\\hello"); + // | + // |* Write + // | + // | Lets write something to registry + // { + void sample01() throws IOException { + Reg reg = new Reg(); + Reg.Key key = reg.add("HKEY_CURRENT_USER\\hello"); - key.put("world", "Hello World !"); - reg.write(); -//} -//| This code will create a "hello" key in HKEY_CURRENT_USER hive, and -//| put "Hello World !" with name "world". - } + key.put("world", "Hello World !"); + reg.write(); + // } + // | This code will create a "hello" key in HKEY_CURRENT_USER hive, and + // | put "Hello World !" with name "world". + } -//| -//|* Read -//| -//| Lets read something from Control Panel settings... -//{ - void sample02() throws IOException - { - Reg reg = new Reg("HKEY_CURRENT_USER\\Control Panel"); - Reg.Key cp = reg.get("HKEY_CURRENT_USER\\Control Panel"); - Reg.Key sound = cp.getChild("Sound"); - String beep = sound.get("Beep"); + // | + // |* Read + // | + // | Lets read something from Control Panel settings... + // { + void sample02() throws IOException { + Reg reg = new Reg("HKEY_CURRENT_USER\\Control Panel"); + Reg.Key cp = reg.get("HKEY_CURRENT_USER\\Control Panel"); + Reg.Key sound = cp.getChild("Sound"); + String beep = sound.get("Beep"); -//} -//| - } + // } + // | + } -//| -//|* Create environment variable -//| -//| Lets create a new environment variable under current users environment.... -//{ - void sample03() throws IOException - { - Reg reg = new Reg(); - Reg.Key env = reg.add("HKEY_CURRENT_USER\\Environment"); + // | + // |* Create environment variable + // | + // | Lets create a new environment variable under current users environment.... + // { + void sample03() throws IOException { + Reg reg = new Reg(); + Reg.Key env = reg.add("HKEY_CURRENT_USER\\Environment"); - env.put("SAMPLE_HOME", "c:\\sample"); - reg.write(); -//} -//| Thats it ! Now your environment contains variable SAMPLE_HOME ! Unfortunetly -//| you have to restart Windows to see this variable.... but hey, we crated new -//| environment variable from java without any native code ! - } + env.put("SAMPLE_HOME", "c:\\sample"); + reg.write(); + // } + // | Thats it ! Now your environment contains variable SAMPLE_HOME ! Unfortunetly + // | you have to restart Windows to see this variable.... but hey, we crated new + // | environment variable from java without any native code ! + } } diff --git a/src/test/java/org/ini4j/tutorial/package-info.java b/src/test/java/org/ini4j/tutorial/package-info.java index c56d20a..50f02e6 100644 --- a/src/test/java/org/ini4j/tutorial/package-info.java +++ b/src/test/java/org/ini4j/tutorial/package-info.java @@ -14,13 +14,13 @@ * limitations under the License. */ package org.ini4j.tutorial; -//| -//| --------- -//| Tutorials -//| -//|Tutorials -//| -//| The following tutorials organized on different tpye of API that ini4j provide. -//| The build process of [ini4j] guarantees compilability and runability, since no -//| distribution may be created without compiling and running the tutorial codes. -//| +// | +// | --------- +// | Tutorials +// | +// |Tutorials +// | +// | The following tutorials organized on different tpye of API that ini4j provide. +// | The build process of [ini4j] guarantees compilability and runability, since no +// | distribution may be created without compiling and running the tutorial codes. +// |