From 0f120393ad753361b5918033b8be6ae1df4dd3f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Iv=C3=A1n=20SZKIBA?= Date: Mon, 16 Nov 2026 09:13:52 +0100 Subject: [PATCH 1/9] docs: document the core contracts of org.ini4j IDEs and the generated HTML showed nothing for the main interfaces. This describes MultiMap, CommentedMap, OptionMap, Profile, Persistable, Configurable, Registry and the exceptions: value conversion, variable syntax, the section tree, and what load and store do with streams and flags. Each statement was checked against the implementations. Refs: #13 --- .../org/ini4j/CircularReferenceException.java | 27 +- src/main/java/org/ini4j/CommentedMap.java | 42 +++ src/main/java/org/ini4j/Configurable.java | 22 ++ .../org/ini4j/InvalidFileFormatException.java | 16 + src/main/java/org/ini4j/MultiMap.java | 91 +++++ src/main/java/org/ini4j/OptionMap.java | 316 ++++++++++++++++++ src/main/java/org/ini4j/Persistable.java | 106 ++++++ src/main/java/org/ini4j/Profile.java | 246 ++++++++++++++ src/main/java/org/ini4j/Registry.java | 209 ++++++++++++ 9 files changed, 1063 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/ini4j/CircularReferenceException.java b/src/main/java/org/ini4j/CircularReferenceException.java index 2a97d71..cd6e2ba 100644 --- a/src/main/java/org/ini4j/CircularReferenceException.java +++ b/src/main/java/org/ini4j/CircularReferenceException.java @@ -16,11 +16,12 @@ package org.ini4j; /** - * Exception thrown when a circular reference is detected during variable resolution. + * Signals that variable substitution went deeper than the allowed depth. * - *

This exception is thrown when the maximum recursion depth is exceeded while resolving variable - * substitutions in INI files or option maps. This typically indicates a circular reference in the - * configuration, such as: + *

The variables in a value can refer to options whose values contain variables again, and the + * resolver follows them one level at a time. The exception is thrown when the nesting reaches the + * limit set by {@link Config#getMaxResolveDepth()}. The usual cause is a circular reference, such + * as: * *

  * [section1]
@@ -30,23 +31,25 @@
  * b = ${section1/a}
  * 
* - *

This exception prevents {@link StackOverflowError} that would otherwise occur from infinite - * recursion. + *

The limit also stops a very deep chain of references that is not circular. It is an {@link + * IllegalArgumentException}, so it is unchecked. The limit prevents the {@link StackOverflowError} + * that unbounded recursion would cause. * - *

Security Note: This exception is part of the fix for CVE-2022-41404, which addressed a - * Denial of Service vulnerability where circular variable references could crash the JVM. + *

The limit was added to fix CVE-2022-41404, a denial of service through circular variable + * references. * * @see Config#getMaxResolveDepth() * @see Config#setMaxResolveDepth(int) + * @see OptionMap#fetch(Object) * @since 0.6.0 */ public class CircularReferenceException extends IllegalArgumentException { private static final long serialVersionUID = 1L; /** - * Constructs a new circular reference exception with the specified maximum resolve depth. + * Creates an exception with a standard message that names the depth limit. * - * @param maxResolveDepth the maximum recursion depth that was exceeded + * @param maxResolveDepth the depth limit that was reached */ public CircularReferenceException(int maxResolveDepth) { super( @@ -59,7 +62,7 @@ public CircularReferenceException(int maxResolveDepth) { } /** - * Constructs a new circular reference exception with the specified detail message. + * Creates an exception with a detail message. * * @param message the detail message */ @@ -68,7 +71,7 @@ public CircularReferenceException(String message) { } /** - * Constructs a new circular reference exception with the specified detail message and cause. + * Creates an exception with a detail message and a cause. * * @param message the detail message * @param cause the cause diff --git a/src/main/java/org/ini4j/CommentedMap.java b/src/main/java/org/ini4j/CommentedMap.java index fbed485..f50fd85 100644 --- a/src/main/java/org/ini4j/CommentedMap.java +++ b/src/main/java/org/ini4j/CommentedMap.java @@ -17,10 +17,52 @@ import java.util.Map; +/** + * A {@link Map} that can keep a comment for each key. + * + *

A comment belongs to a key, not to one of its values. A key can have no comment, which is + * reported as {@code null}. When {@link Config#isComment()} is on, loading a file stores the + * comment lines in front of an option or a section as the comment of that option or section, with + * two exceptions: only the comment directly in front of the entry is kept, and the comment at the + * top of the file becomes the comment of the whole {@link Profile} or {@link Options} object when + * {@link Config#isHeaderComment()} is on (see {@link org.ini4j.spi.IniBuilder}). The leading + * comment character of each line is removed, and the lines are joined with the line separator of + * the {@link Config}. Storing a file writes the comments back. + * + *

In {@link CommonMultiMap}, removing a key with {@code remove(Object)}, removing its last value + * with {@code remove(Object, int)}, and {@code clear()} also remove the comment. Removing a key in + * another way, for example through {@code keySet()}, does not. + * + * @param the type of the keys + * @param the type of the values + * @see CommonMultiMap + * @since 0.5.0 + */ public interface CommentedMap extends Map { + /** + * Returns the comment of a key. + * + * @param key the key + * @return the comment, or {@code null} if the key has no comment + */ String getComment(Object key); + /** + * Sets the comment of a key. + * + *

The key does not have to be in the map. {@link CommonMultiMap} stores the comment anyway. + * + * @param key the key + * @param comment the new comment + * @return the previous comment of the key, or {@code null} if it had none + */ String putComment(K key, String comment); + /** + * Removes the comment of a key. + * + * @param key the key + * @return the removed comment, or {@code null} if the key had none + */ String removeComment(Object key); } diff --git a/src/main/java/org/ini4j/Configurable.java b/src/main/java/org/ini4j/Configurable.java index 074d7a5..654c280 100644 --- a/src/main/java/org/ini4j/Configurable.java +++ b/src/main/java/org/ini4j/Configurable.java @@ -15,8 +15,30 @@ */ package org.ini4j; +/** + * An object whose parsing and formatting behavior is set by a {@link Config}. + * + *

{@link Ini}, {@link Options} and {@link Reg} are configurable. {@link Ini} starts with the + * {@linkplain Config#getGlobal() global} configuration itself, which other objects share, so a + * change to it affects all of them. {@link Options} and {@link Reg} start with their own copy of + * the global configuration with some flags set for their format. Call {@link #setConfig(Config)} + * with a {@linkplain Config#clone() clone} to change the settings of one object only. + * + * @see Config + * @since 0.5.0 + */ public interface Configurable { + /** + * Returns the configuration. + * + * @return the configuration in use + */ Config getConfig(); + /** + * Sets the configuration. + * + * @param value the configuration to use from now on + */ void setConfig(Config value); } diff --git a/src/main/java/org/ini4j/InvalidFileFormatException.java b/src/main/java/org/ini4j/InvalidFileFormatException.java index 5a75dc7..1550070 100755 --- a/src/main/java/org/ini4j/InvalidFileFormatException.java +++ b/src/main/java/org/ini4j/InvalidFileFormatException.java @@ -17,9 +17,25 @@ import java.io.IOException; +/** + * Signals that the content being loaded is not valid for the format. + * + *

The parsers throw it, for example, for a line that is neither a section header nor an option, + * or for a registry file with a missing or unsupported version header. The message of a parse error + * names the line number and the line. It is an {@link IOException}, so the {@code load} methods of + * {@link Persistable} declare it without a new checked type. + * + * @see Persistable#load() + * @since 0.5.0 + */ public class InvalidFileFormatException extends IOException { private static final long serialVersionUID = -4354616830804732309L; + /** + * Constructs an exception with a detail message. + * + * @param message the detail 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 d363d20..4b5c552 100644 --- a/src/main/java/org/ini4j/MultiMap.java +++ b/src/main/java/org/ini4j/MultiMap.java @@ -18,20 +18,111 @@ import java.util.List; import java.util.Map; +/** + * A {@link Map} that can hold more than one value for a key. + * + *

The values of a key are kept in insertion order and are addressed by a zero-based index. The + * methods inherited from {@link Map} work on the whole key: {@link #get(Object)} returns the last + * value, {@link #put(Object, Object)} replaces the last value (or adds the first one) and {@link + * #remove(Object)} removes every value of the key. The methods declared here give access to the + * other values. + * + *

A {@link Profile} is a multi-map of sections and an {@link OptionMap} is a multi-map of + * options, so a profile can hold several sections with the same name and a section can hold several + * options with the same name. {@link Config#isMultiSection()} and {@link Config#isMultiOption()} + * decide whether loading a file keeps such repeats. For example, if a section has the option {@code + * fortuneNumber} three times, {@code section.get("fortuneNumber", 1)} returns the second one and + * {@code section.length("fortuneNumber")} returns {@code 3}. + * + * @param the type of the keys + * @param the type of the values + * @see BasicMultiMap + * @since 0.4.0 + */ public interface MultiMap extends Map { + /** + * Returns all the values of a key. + * + *

{@link BasicMultiMap} returns the list it stores, not a copy, so changes to the list change + * the map. + * + * @param key the key + * @return the values of the key in insertion order, or {@code null} if the key is not in the map + */ List getAll(Object key); + /** + * Adds a value after the existing values of a key. + * + * @param key the key; it is added to the map if it is not there yet + * @param value the value to add + */ void add(K key, V value); + /** + * Inserts a value at the given position in the values of a key. + * + *

The values at that position and after it move one place up. + * + * @param key the key; it is added to the map if it is not there yet + * @param value the value to insert + * @param index the position of the new value + * @throws IndexOutOfBoundsException if the index is negative or greater than the number of values + * the key has + */ void add(K key, V value, int index); + /** + * Returns the value of a key at the given position. + * + * @param key the key + * @param index the position of the value + * @return the value, or {@code null} if the key is not in the map + * @throws IndexOutOfBoundsException if the key is in the map and the index is out of range + */ V get(Object key, int index); + /** + * Returns the number of values a key has. + * + * @param key the key + * @return the number of values, or {@code 0} if the key is not in the map + */ int length(Object key); + /** + * Replaces the value of a key at the given position. + * + * @param key the key; it must be in the map + * @param value the new value + * @param index the position of the value to replace + * @return the value that was replaced + * @throws IndexOutOfBoundsException if the index is out of range + * @throws NullPointerException if the key is not in the map (this is what {@link BasicMultiMap} + * does) + */ V put(K key, V value, int index); + /** + * Replaces all the values of a key with a copy of the given values. + * + * @param key the key + * @param values the new values; {@link BasicMultiMap} copies the list, so later changes to it do + * not affect the map + * @return the list of the values the key had before, or {@code null} if the key was not in the + * map + */ List putAll(K key, List values); + /** + * Removes the value of a key at the given position. + * + *

When the last value of a key is removed, the key is removed from the map too. + * + * @param key the key + * @param index the position of the value to remove + * @return the removed value, or {@code null} if the key is not in the map + * @throws IndexOutOfBoundsException if the key is in the map and the index is out of range + */ 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 8943d00..add928f 100644 --- a/src/main/java/org/ini4j/OptionMap.java +++ b/src/main/java/org/ini4j/OptionMap.java @@ -15,50 +15,366 @@ */ package org.ini4j; +/** + * A map of named options, where each option can have several values. + * + *

An option map is the content of a section of a {@link Profile}, or of an {@link Options} file. + * Names and values are strings. The values of one name are indexed as in {@link MultiMap}, and + * every name can also have a comment as in {@link CommentedMap}. A stored value can be {@code + * null}, for example for an option that has a name but no value in the file. + * + *

On top of the string access this interface offers methods that convert values, resolve + * variables and work with beans. + * + *

The {@code get} and {@code getAll} methods with a {@link Class} argument convert the stored + * text to another type. Supported types are the primitive types and their wrappers, {@link String}, + * {@link Character}, {@link java.io.File}, {@link java.net.URL}, {@link java.net.URI}, {@link + * Class}, {@link java.util.TimeZone}, and any class with a static {@code valueOf(String)} method. A + * conversion that fails throws an {@link IllegalArgumentException}, except that converting an empty + * value to {@link Character} throws a {@link StringIndexOutOfBoundsException}. A missing name or a + * {@code null} value converts to the zero value of a primitive type ({@code 0}, {@code false} or + * {@code '\0'}) and to {@code null} for any other type. The {@code put} and {@code add} methods + * that take an {@link Object} store {@link String#valueOf(Object)} of the value, and keep {@code + * null} as {@code null}. + * + *

The {@code fetch} methods work like the {@code get} methods, but they first replace variables + * in the value. A variable is written as {@code ${name}} for the last value of the option {@code + * name} in the same map, or {@code ${name[2]}} for the value at index 2. A variable written as + * {@code ${@env/NAME}} reads the environment variable {@code NAME} and {@code ${@prop/name}} reads + * the system property {@code name}. A variable with a backslash in front of the dollar sign is not + * resolved. A variable that refers to a missing option, environment variable or property is left in + * the text unchanged. A value can contain variables that contain variables, up to the limit of + * {@link Config#getMaxResolveDepth()}; deeper nesting, such as an option that refers to itself, + * throws a {@link CircularReferenceException}. In a section of a {@link Profile} a variable can + * also name an option of another section; see {@link Profile#fetch(Object, Object)}. + * + *

{@link #as(Class)} gives a typed view of the map through an interface, and {@link + * #from(Object)} and {@link #to(Object)} copy the values between the map and a bean. The option + * name of a bean property is the property name, for example {@code homeDir} for {@code + * getHomeDir()}, with the first letter in upper case if the map was created that way (see {@link + * Config#isPropertyFirstUpper()}). + * + * @see Profile.Section + * @see Options + * @since 0.4.1 + */ public interface OptionMap extends MultiMap, CommentedMap { + /** + * Returns all the values of an option, converted to the component type of an array class. + * + *

The values are returned as stored, without variable substitution. Use {@link + * #fetchAll(Object, Class)} to resolve variables. + * + * @param the array type + * @param key the option name + * @param clazz the array class, for example {@code int[].class} + * @return a new array with one element for each value; it is empty if the option is missing + * @throws IllegalArgumentException if {@code clazz} is not an array class, or if a value cannot + * be converted + */ T getAll(Object key, Class clazz); + /** + * Adds a value after the existing values of an option. + * + * @param key the option name + * @param value the value; it is stored as {@link String#valueOf(Object)}, or as {@code null} if + * it is {@code null} + */ void add(String key, Object value); + /** + * Inserts a value at the given position in the values of an option. + * + * @param key the option name + * @param value the value; it is stored as {@link String#valueOf(Object)}, or as {@code null} if + * it is {@code null} + * @param index the position of the new value + * @throws IndexOutOfBoundsException if the index is negative or greater than the number of values + * the option has + */ void add(String key, Object value, int index); + /** + * Returns a view of this map as an object of the given interface. + * + *

The returned object is a dynamic proxy. It is backed by this map, so it always shows the + * current content and its setters change the map. A getter such as {@code getAge()} reads the + * option {@code age} as {@link #fetch(Object)} does (variables are resolved) and converts the + * value to the return type. A getter returns the zero value of its type if the option is missing + * or the value cannot be converted. A setter such as {@code setAge(int)} replaces the last value + * of the option with the given value. A {@code hasAge()} method tells whether the option exists. + * For an array property, the getter reads all the values and the setter replaces all of them. A + * setter does not accept {@code null}: it throws a {@link NullPointerException} for a {@code + * null} value, array or array element, and an array setter has already removed the existing + * values by then. Interfaces can also declare the {@code addPropertyChangeListener} and {@code + * addVetoableChangeListener} methods (and the matching {@code remove} methods), which take the + * property name and the listener. The proxy does not implement the methods of {@link Object}: + * {@code toString()} returns {@code null}, and {@code equals} and {@code hashCode} throw an + * exception. + * + * @param the interface type + * @param clazz the interface to implement + * @return the proxy + * @throws IllegalArgumentException if {@code clazz} is not an interface + */ T as(Class clazz); + /** + * Returns a view of this map as an object of the given interface, with a prefix on the option + * names. + * + *

It works like {@link #as(Class)}, except that the option for a property is named by the + * prefix followed by the property name. With the prefix {@code "dwarf."}, the getter {@code + * getAge()} reads the option {@code dwarf.age}. + * + * @param the interface type + * @param clazz the interface to implement + * @param keyPrefix the text put in front of every property name + * @return the proxy + * @throws IllegalArgumentException if {@code clazz} is not an interface + */ T as(Class clazz, String keyPrefix); + /** + * Returns the last value of an option, with variables resolved. + * + *

See the description of this interface for the variable syntax. + * + * @param key the option name + * @return the resolved value, or {@code null} if the option is missing or its value is {@code + * null} + * @throws CircularReferenceException if the variables are nested deeper than {@link + * Config#getMaxResolveDepth()} + */ String fetch(Object key); + /** + * Returns the last value of an option, or a default if the option is missing. + * + *

In {@link BasicOptionMap} the value is returned as stored, the same as {@link #get(Object, + * String)}: variables are not resolved. + * + * @param key the option name + * @param defaultValue the value to return when there is no value + * @return the last value, or {@code defaultValue} if there is none + */ String fetch(Object key, String defaultValue); + /** + * Returns the value of an option at the given position, with variables resolved. + * + * @param key the option name + * @param index the position of the value + * @return the resolved value, or {@code null} if the option is missing + * @throws IndexOutOfBoundsException if the option exists and the index is out of range + * @throws CircularReferenceException if the variables are nested deeper than {@link + * Config#getMaxResolveDepth()} + */ String fetch(Object key, int index); + /** + * Returns the last value of an option, with variables resolved, converted to a type. + * + * @param the target type + * @param key the option name + * @param clazz the target type + * @return the converted value; the zero value of a primitive type, or {@code null}, if the option + * is missing + * @throws IllegalArgumentException if the value cannot be converted + * @throws CircularReferenceException if the variables are nested deeper than {@link + * Config#getMaxResolveDepth()} + */ T fetch(Object key, Class clazz); + /** + * Returns the last value of an option, with variables resolved, converted to a type, or a default + * if the option is missing. + * + * @param the target type + * @param key the option name + * @param clazz the target type + * @param defaultValue the value to return when there is no value + * @return the converted value, or {@code defaultValue} if there is none + * @throws IllegalArgumentException if the value cannot be converted + * @throws CircularReferenceException if the variables are nested deeper than {@link + * Config#getMaxResolveDepth()} + */ T fetch(Object key, Class clazz, T defaultValue); + /** + * Returns the value of an option at the given position, with variables resolved, converted to a + * type. + * + * @param the target type + * @param key the option name + * @param index the position of the value + * @param clazz the target type + * @return the converted value; the zero value of a primitive type, or {@code null}, if the option + * is missing + * @throws IllegalArgumentException if the value cannot be converted + * @throws IndexOutOfBoundsException if the option exists and the index is out of range + * @throws CircularReferenceException if the variables are nested deeper than {@link + * Config#getMaxResolveDepth()} + */ T fetch(Object key, int index, Class clazz); + /** + * Returns all the values of an option, with variables resolved, converted to the component type + * of an array class. + * + * @param the array type + * @param key the option name + * @param clazz the array class, for example {@code int[].class} + * @return a new array with one element for each value; it is empty if the option is missing + * @throws IllegalArgumentException if {@code clazz} is not an array class, or if a value cannot + * be converted + * @throws CircularReferenceException if the variables are nested deeper than {@link + * Config#getMaxResolveDepth()} + */ T fetchAll(Object key, Class clazz); + /** + * Copies the properties of a bean into this map. + * + *

Each readable property (except {@code class}) whose value is not {@code null} is written to + * the option of the same name, as {@link String#valueOf(Object)} of the value. A single value + * replaces the last value of the option. The elements of an array property are added after the + * existing values. + * + * @param bean the bean to read + * @throws IllegalArgumentException if a property cannot be read + */ void from(Object bean); + /** + * Copies the properties of a bean into this map, with a prefix on the option names. + * + *

It works like {@link #from(Object)}, except that the option for a property is named by the + * prefix followed by the property name. + * + * @param bean the bean to read + * @param keyPrefix the text put in front of every property name + * @throws IllegalArgumentException if a property cannot be read + */ void from(Object bean, String keyPrefix); + /** + * Returns the last value of an option, or a default if the option is missing. + * + *

The value is returned as stored, without variable substitution. + * + * @param key the option name + * @param defaultValue the value to return when there is no value + * @return the last value, or {@code defaultValue} if there is none + */ String get(Object key, String defaultValue); + /** + * Returns the last value of an option, converted to a type. + * + *

The value is converted as stored, without variable substitution. + * + * @param the target type + * @param key the option name + * @param clazz the target type + * @return the converted value; the zero value of a primitive type, or {@code null}, if the option + * is missing + * @throws IllegalArgumentException if the value cannot be converted + */ T get(Object key, Class clazz); + /** + * Returns the last value of an option, converted to a type, or a default if the option is + * missing. + * + *

The value is converted as stored, without variable substitution. + * + * @param the target type + * @param key the option name + * @param clazz the target type + * @param defaultValue the value to return when there is no value + * @return the converted value, or {@code defaultValue} if there is none + * @throws IllegalArgumentException if the value cannot be converted + */ T get(Object key, Class clazz, T defaultValue); + /** + * Returns the value of an option at the given position, converted to a type. + * + *

The value is converted as stored, without variable substitution. + * + * @param the target type + * @param key the option name + * @param index the position of the value + * @param clazz the target type + * @return the converted value; the zero value of a primitive type, or {@code null}, if the option + * is missing + * @throws IllegalArgumentException if the value cannot be converted + * @throws IndexOutOfBoundsException if the option exists and the index is out of range + */ T get(Object key, int index, Class clazz); + /** + * Replaces the last value of an option. + * + *

If the option has no value yet, the value is added. + * + * @param key the option name + * @param value the value; it is stored as {@link String#valueOf(Object)}, or as {@code null} if + * it is {@code null} + * @return the replaced value, or {@code null} if there was none + */ String put(String key, Object value); + /** + * Replaces the value of an option at the given position. + * + * @param key the option name; it must be in the map + * @param value the value; it is stored as {@link String#valueOf(Object)}, or as {@code null} if + * it is {@code null} + * @param index the position of the value to replace + * @return the replaced value + * @throws IndexOutOfBoundsException if the index is out of range + * @throws NullPointerException if the option is not in the map (this is what {@link + * BasicOptionMap} does) + */ String put(String key, Object value, int index); + /** + * Replaces all the values of an option with the elements of an array. + * + *

The option is removed first, so its comment is removed too. Each element is stored as {@link + * String#valueOf(Object)}, or as {@code null} if it is {@code null}. If {@code value} is {@code + * null}, the option is only removed. + * + * @param key the option name + * @param value an array, of an object or a primitive type, or {@code null} + * @throws IllegalArgumentException if {@code value} is not an array + */ void putAll(String key, Object value); + /** + * Copies the values of this map into the properties of a bean. + * + *

For each writable property of the bean that has an option of the same name, the option value + * is read as {@link #fetch(Object)} does (variables are resolved), converted to the property type + * and set. An array property gets all the values. A property without an option is not touched. + * + * @param bean the bean to change + * @throws IllegalArgumentException if a property cannot be set; the message names the property + */ void to(Object bean); + /** + * Copies the values of this map into the properties of a bean, with a prefix on the option names. + * + *

It works like {@link #to(Object)}, except that the option for a property is named by the + * prefix followed by the property name. + * + * @param bean the bean to change + * @param keyPrefix the text put in front of every property name + * @throws IllegalArgumentException if a property cannot be set; the message names the property + */ void to(Object bean, String keyPrefix); } diff --git a/src/main/java/org/ini4j/Persistable.java b/src/main/java/org/ini4j/Persistable.java index 7258b4f..37d6c46 100644 --- a/src/main/java/org/ini4j/Persistable.java +++ b/src/main/java/org/ini4j/Persistable.java @@ -23,26 +23,132 @@ import java.io.Writer; import java.net.URL; +/** + * An object that can load its content from, and store it to, a file, a stream, a reader or a + * writer, or a URL. + * + *

An object can have an associated file, which is used by {@link #load()} and {@link #store()}. + * The constructors of {@link Ini}, {@link Options} and {@link Reg} that take a {@link File} set it. + * + *

Loading does not clear the object first. It adds what it reads to the existing content, and + * the {@link Config} flags such as {@link Config#isMultiSection()} and {@link + * Config#isMultiOption()} decide what happens to names that are already there. When loading has + * read the input to its end, it closes the input. If loading fails before that, the input is left + * open. + * + *

Storing writes the content as the {@link Config} flags allow. For example, comments, empty + * sections, options without a value and, when {@link Config#isMultiOption()} is off, all but one + * value of an option can be left out (see that method for the value that is kept). The methods that + * take an {@link OutputStream} or a {@link Writer} flush it but do not close it. {@link + * #store(File)} creates the file or overwrites it, and closes it. The text is encoded with {@link + * Config#getFileEncoding()}. The writers used for storing are {@link java.io.PrintWriter}s, which + * do not throw an exception when a write fails. An {@link IOException} is mostly raised when a file + * cannot be opened. + * + * @see Configurable + * @since 0.5.0 + */ public interface Persistable { + /** + * Returns the file used by {@link #load()} and {@link #store()}. + * + * @return the file, or {@code null} if none is set + */ File getFile(); + /** + * Sets the file used by {@link #load()} and {@link #store()}. + * + * @param value the file, or {@code null} to have none + */ void setFile(File value); + /** + * Loads the content from the associated file. + * + * @throws java.io.FileNotFoundException if there is no associated file, or the file does not + * exist + * @throws IOException if reading fails + * @throws InvalidFileFormatException if the content is not valid + */ void load() throws IOException, InvalidFileFormatException; + /** + * Loads the content from a stream. + * + *

The bytes are decoded with {@link Config#getFileEncoding()}. + * + * @param input the stream to read + * @throws IOException if reading fails + * @throws InvalidFileFormatException if the content is not valid + */ void load(InputStream input) throws IOException, InvalidFileFormatException; + /** + * Loads the content from a reader. + * + * @param input the reader to read + * @throws IOException if reading fails + * @throws InvalidFileFormatException if the content is not valid + */ void load(Reader input) throws IOException, InvalidFileFormatException; + /** + * Loads the content from a file. + * + *

This does not change the associated file. + * + * @param input the file to read + * @throws IOException if the file cannot be read + * @throws InvalidFileFormatException if the content is not valid + */ void load(File input) throws IOException, InvalidFileFormatException; + /** + * Loads the content from a URL. + * + * @param input the location to read + * @throws IOException if reading fails + * @throws InvalidFileFormatException if the content is not valid + */ void load(URL input) throws IOException, InvalidFileFormatException; + /** + * Stores the content to the associated file. + * + * @throws java.io.FileNotFoundException if there is no associated file, or it cannot be opened + * @throws IOException if writing fails + */ void store() throws IOException; + /** + * Stores the content to a stream. + * + *

The text is encoded with {@link Config#getFileEncoding()}. The stream is flushed, not + * closed. + * + * @param output the stream to write + * @throws IOException if writing fails + */ void store(OutputStream output) throws IOException; + /** + * Stores the content to a writer. + * + *

The writer is flushed, not closed. + * + * @param output the writer to write + * @throws IOException if writing fails + */ void store(Writer output) throws IOException; + /** + * Stores the content to a file. + * + *

This does not change the associated file. + * + * @param output the file to write; it is created or overwritten + * @throws IOException if the file cannot be opened or written + */ 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 b51ed3d..611593a 100644 --- a/src/main/java/org/ini4j/Profile.java +++ b/src/main/java/org/ini4j/Profile.java @@ -15,51 +15,297 @@ */ package org.ini4j; +/** + * A set of named sections, each holding options. + * + *

A profile is a {@link MultiMap} from section names to {@link Section}s and a {@link + * CommentedMap}, so a name can have several sections and every section can have a comment. The + * profile itself can have a header comment. Besides the plain map access, it offers shortcuts that + * address an option by section name and option name, for example {@link #get(Object, Object)} and + * {@link #put(String, String, Object)}. + * + *

Section names can form a tree. The name {@code dwarfs/happy} is the name of a child of the + * section {@code dwarfs}, and {@code /} is the path separator (see {@link #PATH_SEPARATOR} and + * {@link Config#getPathSeparator()}). The {@link Section} interface has methods to walk this tree. + * + *

The example reads two options from a file, adds a section and writes the file back. + * + *

{@code
+ * Ini ini = new Ini(new File("dwarfs.ini"));
+ * int age = ini.get("happy", "age", int.class);
+ * String dir = ini.get("happy", "homeDir");
+ *
+ * ini.put("sleepy", "age", 55);
+ * ini.store();
+ * }
+ * + * @see Ini + * @see Registry + * @since 0.5.0 + */ public interface Profile extends MultiMap, CommentedMap { + /** The default path separator in section names. */ char PATH_SEPARATOR = '/'; + /** + * Returns the header comment of the profile. + * + *

When a file is loaded with {@link Config#isHeaderComment()} and {@link Config#isComment()} + * on, the comment at the top of the file, before the first section or option, becomes the header + * comment. + * + * @return the comment, or {@code null} if there is none + */ String getComment(); + /** + * Sets the header comment of the profile. + * + * @param value the new comment, or {@code null} to have none + */ void setComment(String value); + /** + * Adds a new, empty section. + * + *

A section is added even if one with this name exists already. In tree mode (see {@link + * Config#isTree()}), if the section name has a parent (for example {@code a/b} for {@code a/b/c}) + * and the parent is missing, the parent is added first, as far up as needed. + * + * @param sectionName the name of the new section + * @return the new section + */ Section add(String sectionName); + /** + * Adds an option value to a section. + * + *

The section is the last one with the given name; it is created if there is none. The value + * is added after the values the option has already. + * + * @param sectionName the section name + * @param optionName the option name + * @param value the value, stored as in {@link OptionMap#add(String, Object)} + */ void add(String sectionName, String optionName, Object value); + /** + * Returns a view of this profile as an object of the given interface. + * + *

The returned object is a dynamic proxy backed by this profile. Each property of the + * interface stands for a section of the same name, and its value is a view of that section + * created as {@link OptionMap#as(Class)} does. A property of an array type stands for all the + * sections of that name. A getter returns the zero value of its type if there is no such section. + * A setter removes the sections of that name and adds new ones filled with {@link + * OptionMap#from(Object)}; a {@code null} value only removes them. The listener methods work as + * described in {@link OptionMap#as(Class)}. + * + * @param the interface type + * @param clazz the interface to implement + * @return the proxy + * @throws IllegalArgumentException if {@code clazz} is not an interface + */ T as(Class clazz); + /** + * Returns a view of this profile as an object of the given interface, with a prefix on the + * section names. + * + *

It works like {@link #as(Class)}, except that the section for a property is named by the + * prefix followed by the property name. In {@link BasicProfile}, the prefix is not applied when + * {@link Config#isPropertyFirstUpper()} is on. + * + * @param the interface type + * @param clazz the interface to implement + * @param prefix the text put in front of every property name + * @return the proxy + * @throws IllegalArgumentException if {@code clazz} is not an interface + */ T as(Class clazz, String prefix); + /** + * Returns the last value of an option, with variables resolved. + * + *

The section is the last one with the given name. Variables are written as described in + * {@link OptionMap}, with these additions: + * + *

    + *
  • {@code ${option}} is an option of the same section. + *
  • {@code ${section/option}} is an option of another section. Both parts can carry an index, + * as in {@code ${section[1]/option[2]}}. Without an index, the last section and the last + * value are used. + *
  • {@code ${@env/NAME}} and {@code ${@prop/name}} read an environment variable and a system + * property. + *
+ * + * @param sectionName the section name + * @param optionName the option name + * @return the resolved value, or {@code null} if the section or the option is missing + * @throws CircularReferenceException if the variables are nested deeper than {@link + * Config#getMaxResolveDepth()} + */ String fetch(Object sectionName, Object optionName); + /** + * Returns the last value of an option, with variables resolved, converted to a type. + * + * @param the target type + * @param sectionName the section name + * @param optionName the option name + * @param clazz the target type + * @return the converted value; the zero value of a primitive type, or {@code null}, if the + * section or the option is missing + * @throws IllegalArgumentException if the value cannot be converted + * @throws CircularReferenceException if the variables are nested deeper than {@link + * Config#getMaxResolveDepth()} + * @see #fetch(Object, Object) + */ T fetch(Object sectionName, Object optionName, Class clazz); + /** + * Returns the last value of an option, as stored. + * + *

The section is the last one with the given name. Variables are not resolved. + * + * @param sectionName the section name + * @param optionName the option name + * @return the value, or {@code null} if the section or the option is missing + */ String get(Object sectionName, Object optionName); + /** + * Returns the last value of an option, as stored, converted to a type. + * + * @param the target type + * @param sectionName the section name + * @param optionName the option name + * @param clazz the target type + * @return the converted value; the zero value of a primitive type, or {@code null}, if the + * section or the option is missing + * @throws IllegalArgumentException if the value cannot be converted + * @see OptionMap#get(Object, Class) + */ T get(Object sectionName, Object optionName, Class clazz); + /** + * Sets an option value in a section. + * + *

The section is the last one with the given name; it is created if there is none. The value + * replaces the last value of the option. + * + * @param sectionName the section name + * @param optionName the option name + * @param value the value, stored as in {@link OptionMap#put(String, Object)} + * @return the replaced value, or {@code null} if there was none + */ String put(String sectionName, String optionName, Object value); + /** + * Removes the sections that have the name of the given section. + * + *

The removal is by name: every section with that name is removed, not only the given object. + * + * @param section the section whose name is removed + * @return the first section that was removed, or {@code null} if there was none + */ Section remove(Profile.Section section); + /** + * Removes all the values of an option from a section. + * + *

The section is the last one with the given name. + * + * @param sectionName the section name + * @param optionName the option name + * @return the first value that was removed, or {@code null} if there was none or the section is + * missing + */ String removeOption(Object sectionName, Object optionName); + /** + * A section of a {@link Profile}: a named {@link OptionMap}. + * + *

A section knows the profile it belongs to. Its name can contain path separators, which makes + * it a node in the section tree of the profile. The tree methods build the names of the related + * sections from this name and look them up in the profile, so they only find sections that exist. + * Variables in the values of a section are resolved by the profile, so they can refer to other + * sections, see {@link Profile#fetch(Object, Object)}. + * + * @since 0.5.0 + */ interface Section extends OptionMap { + /** + * Returns a child section. + * + * @param key the name of the child relative to this section, for example {@code b} for the + * child {@code a/b} of {@code a} + * @return the child, or {@code null} if there is none; if several sections have the name, the + * last one + */ Section getChild(String key); + /** + * Returns the full name of the section. + * + * @return the name, including the path of its ancestors + */ String getName(); + /** + * Returns the parent section. + * + * @return the section whose name is this name up to the last path separator, or {@code null} if + * the name has no path separator or there is no such section + */ Section getParent(); + /** + * Returns the last part of the section name. + * + * @return the name after the last path separator, or the whole name if there is none + */ String getSimpleName(); + /** + * Adds a new child section. + * + *

It works like {@link Profile#add(String)} with the name of this section, a path separator + * and the key. + * + * @param key the name of the child relative to this section + * @return the new section + */ Section addChild(String key); + /** + * Returns the names of the child sections. + * + *

Only direct children are listed, and each name is relative to this section. They come in + * the order of the profile. + * + * @return a new array of names; it is empty if there are no children + */ String[] childrenNames(); + /** + * Finds a descendant section by its path below this section. + * + *

The parts are joined with the path separator, so {@code lookup("b", "c")} on the section + * {@code a} finds {@code a/b/c}. + * + * @param path the names of the sections on the way down from this section + * @return the section, or {@code null} if there is none + */ Section lookup(String... path); + /** + * Removes a child section. + * + *

The sections with that name are removed. Their own children stay. + * + * @param key the name of the child relative to this section + */ void removeChild(String key); } } diff --git a/src/main/java/org/ini4j/Registry.java b/src/main/java/org/ini4j/Registry.java index 515aac7..e9552f4 100644 --- a/src/main/java/org/ini4j/Registry.java +++ b/src/main/java/org/ini4j/Registry.java @@ -19,28 +19,103 @@ import java.util.HashMap; import java.util.Map; +/** + * A {@link Profile} that models a Windows registry as it appears in a {@code .reg} export file. + * + *

The sections are registry {@linkplain Key keys}. The name of a key is its full path, written + * with {@link #KEY_SEPARATOR} between the parts and starting with a {@linkplain Hive hive}, for + * example {@code HKEY_CURRENT_USER\Software\ini4j}. The options of a key are its values; the option + * named {@link Key#DEFAULT_NAME} is the default value of the key. Each value also has a {@linkplain + * Type type}. + * + *

The constants of this interface describe the {@code .reg} file format: a version header line + * followed by the keys, in UTF-16 little endian text with {@code CR LF} line ends. The class that + * reads, writes and, on Windows, exchanges data with the real registry is {@link Reg}. + * + * @see Reg + * @see BasicRegistry + * @since 0.5.0 + */ public interface Registry extends Profile { + /** + * The root keys of the registry, called hives. + * + *

Their names, as returned by {@link #toString()}, are the first part of a key path. + * + * @since 0.5.0 + */ enum Hive { + /** The root key {@code HKEY_CLASSES_ROOT}. */ HKEY_CLASSES_ROOT, + + /** The root key {@code HKEY_CURRENT_CONFIG}. */ HKEY_CURRENT_CONFIG, + + /** The root key {@code HKEY_CURRENT_USER}. */ HKEY_CURRENT_USER, + + /** The root key {@code HKEY_LOCAL_MACHINE}. */ HKEY_LOCAL_MACHINE, + + /** The root key {@code HKEY_USERS}. */ HKEY_USERS; } // TODO handle delete operations with special Type + /** + * The type of a registry value. + * + *

The text form of a type, returned by {@link #toString()}, is the prefix that a {@code .reg} + * file puts in front of the data of a value, for example {@code dword} in {@code dword:0000002a}. + * A string value has no prefix, so the text of {@link #REG_SZ} is empty. This differs from {@link + * #name()}. + * + * @since 0.5.0 + */ enum Type { + /** A value with no defined type. The data text is kept as written in the file. */ REG_NONE("hex(0)"), + + /** A string, written in double quotes. This is the type of a value that has no prefix. */ REG_SZ(""), + + /** + * A string that can contain references to environment variables. The file holds the string as + * hexadecimal UTF-16 little endian bytes, and the value in the map is the decoded text. + */ REG_EXPAND_SZ("hex(2)"), + + /** Binary data. The data text is kept as written in the file. */ REG_BINARY("hex"), + + /** + * A 32-bit number. The file holds it as eight hexadecimal digits, and the value in the map is + * the decimal text. + */ REG_DWORD("dword"), + + /** A 32-bit number in big endian order. The data text is kept as written in the file. */ REG_DWORD_BIG_ENDIAN("hex(5)"), + + /** A symbolic link. The data text is kept as written in the file. */ REG_LINK("hex(6)"), + + /** + * A list of strings. The file holds them as hexadecimal UTF-16 little endian bytes, and the map + * has one value for each string. + */ REG_MULTI_SZ("hex(7)"), + + /** A resource list. The data text is kept as written in the file. */ REG_RESOURCE_LIST("hex(8)"), + + /** A full resource descriptor. The data text is kept as written in the file. */ REG_FULL_RESOURCE_DESCRIPTOR("hex(9)"), + + /** A resource requirements list. The data text is kept as written in the file. */ REG_RESOURCE_REQUIREMENTS_LIST("hex(a)"), + + /** A 64-bit number. The data text is kept as written in the file. */ REG_QWORD("hex(b)"); private static final Map MAPPING; @@ -51,56 +126,161 @@ enum Type { } } + /** The character between the type prefix and the data of a value in a {@code .reg} file. */ public static final char SEPARATOR_CHAR = ':'; + + /** {@link #SEPARATOR_CHAR} as a string. */ public static final String SEPARATOR = String.valueOf(SEPARATOR_CHAR); + + /** + * The minus sign, which marks a removal in a {@code .reg} file. The parsers and formatters of + * this library do not use it. + */ public static final char REMOVE_CHAR = '-'; + + /** {@link #REMOVE_CHAR} as a string. */ public static final String REMOVE = String.valueOf(REMOVE_CHAR); + private final String _prefix; Type(String prefix) { _prefix = prefix; } + /** + * Returns the type for a text prefix. + * + * @param str the prefix as in {@link #toString()}, for example {@code "hex(7)"}; an empty text + * gives {@link #REG_SZ} + * @return the type, or {@code null} if the prefix is unknown + */ public static Type fromString(String str) { return MAPPING.get(str); } + /** + * Returns the prefix that a {@code .reg} file uses for this type. + * + * @return the prefix; it is empty for {@link #REG_SZ} + */ @Override public String toString() { return _prefix; } } + /** The escape character inside a quoted string of a {@code .reg} file. */ char ESCAPE_CHAR = '\\'; + + /** The character set of a {@code .reg} file: UTF-16 little endian. */ Charset FILE_ENCODING = Charset.forName("UnicodeLittle"); + + /** The character between the parts of a key path. */ char KEY_SEPARATOR = '\\'; + + /** The line separator of a {@code .reg} file: {@code CR LF}. */ String LINE_SEPARATOR = "\r\n"; + + /** The character between the type prefix and the data of a value. */ char TYPE_SEPARATOR = ':'; + + /** The text of the version header, the first line of a {@code .reg} file. */ String VERSION = "Windows Registry Editor Version 5.00"; + /** + * Returns the version header text. + * + * @return the header; it is {@link #VERSION} unless it was changed + */ String getVersion(); + /** + * Sets the version header text. + * + *

{@link Reg} writes it as the first line when storing, and requires it to be the first line + * when loading. + * + * @param value the header text + */ void setVersion(String value); + /** + * Returns the last key with the given path. + * + * @param key the key path + * @return the key, or {@code null} if there is none + */ @Override Key get(Object key); + /** + * Returns the key with the given path at the given position. + * + * @param key the key path + * @param index the position of the key among the keys with the same path + * @return the key, or {@code null} if the path is not in the registry + * @throws IndexOutOfBoundsException if the path is in the registry and the index is out of range + */ @Override Key get(Object key, int index); + /** + * Replaces the last key with the given path. + * + * @param key the key path + * @param value the new key + * @return the replaced key, or {@code null} if there was none + */ @Override Key put(String key, Section value); + /** + * Replaces the key with the given path at the given position. + * + *

The path must be in the registry already. + * + * @param key the key path + * @param value the new key + * @param index the position of the key to replace + * @return the replaced key + * @throws IndexOutOfBoundsException if the index is out of range + * @throws NullPointerException if the path is not in the registry (this is what {@link + * BasicRegistry} does) + */ @Override Key put(String key, Section value, int index); + /** + * Removes all the keys with the given path. + * + * @param key the key path + * @return the first key that was removed, or {@code null} if there was none + */ @Override Key remove(Object key); + /** + * Removes the key with the given path at the given position. + * + * @param key the key path + * @param index the position of the key to remove + * @return the removed key, or {@code null} if the path is not in the registry + * @throws IndexOutOfBoundsException if the path is in the registry and the index is out of range + */ @Override Key remove(Object key, int index); + /** + * A registry key: a {@link Section} whose options are registry values. + * + *

A key also remembers the {@linkplain Type type} of each value. The type applies to all the + * values of one name. The tree methods inherited from {@link Section} work on the key paths and + * return keys. + * + * @since 0.5.0 + */ interface Key extends Section { + /** The name of the default value of a key. */ String DEFAULT_NAME = "@"; @Override @@ -109,8 +289,21 @@ interface Key extends Section { @Override Key getParent(); + /** + * Returns the type of a value. + * + * @param key the value name + * @return the type, or {@code null} if no type was set + */ Type getType(Object key); + /** + * Returns the type of a value, or a default. + * + * @param key the value name + * @param defaulType the type to return if none was set + * @return the type, or {@code defaulType} if none was set + */ Type getType(Object key, Type defaulType); @Override @@ -119,8 +312,24 @@ interface Key extends Section { @Override Key lookup(String... path); + /** + * Sets the type of a value. + * + *

When storing, a value with no type is written as {@link Type#REG_SZ}. Loading sets a type + * only for the values that are not {@link Type#REG_SZ}. + * + * @param key the value name + * @param type the type + * @return the previous type, or {@code null} if none was set + */ Type putType(String key, Type type); + /** + * Removes the type of a value. + * + * @param key the value name + * @return the removed type, or {@code null} if none was set + */ Type removeType(Object key); } } From d24880f7844e7b4f93cbd678729623a6bd53239f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Iv=C3=A1n=20SZKIBA?= Date: Mon, 16 Nov 2026 09:13:52 +0100 Subject: [PATCH 2/9] docs: document every option of Config Config has about 45 public constants and an accessor pair for each option, and nothing explained what a flag changes. Each option is now described once at its getter, with its default and system property, after checking how the parsers, formatters and maps use it. Refs: #13 --- src/main/java/org/ini4j/Config.java | 671 ++++++++++++++++++++++++++++ 1 file changed, 671 insertions(+) diff --git a/src/main/java/org/ini4j/Config.java b/src/main/java/org/ini4j/Config.java index 0450594..25d0e7c 100644 --- a/src/main/java/org/ini4j/Config.java +++ b/src/main/java/org/ini4j/Config.java @@ -19,57 +19,260 @@ import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; +/** + * The settings that control how files are read and written. + * + *

A configuration is a set of flags and a few other values, such as the file encoding and the + * line separator. They decide, for example, whether an option can have several values, whether + * comments are kept and how special characters are escaped. {@link Ini}, {@link Options} and {@link + * Reg} are {@link Configurable}, and the parsers and formatters of the {@code org.ini4j.spi} + * package read it. Each option is described once, at its getter. The matching setter, the {@code + * PROP_} constant (the name of the system property) and the {@code DEFAULT_} constant point to it. + * + *

The initial value of an option is read from a system property whose name is {@link + * #KEY_PREFIX} followed by the {@code PROP_} constant, for example {@code + * -Dorg.ini4j.config.multiSection=true}. If the property is not set, the {@code DEFAULT_} constant + * is used. The properties are read when a {@code Config} is created and again by {@link #reset()}. + * + *

To change the behavior of one object, give it its own copy: + * + *

{@code
+ * Config cfg = Config.getGlobal().clone();
+ * cfg.setMultiSection(true);
+ *
+ * Ini ini = new Ini();
+ * ini.setConfig(cfg);
+ * ini.load(new File("dwarfs.ini"));
+ * }
+ * + *

A {@code Config} can be serialized, but the file encoding is not part of the serialized form: + * it is {@code null} in a deserialized object. + * + *

Thread safety. A {@code Config} has no synchronization. {@link #getGlobal()} + * is shared by all the {@link Ini} objects that use it, so a change to it is a change to all of + * them, and it is not safe while another thread reads or writes. Set up a configuration before + * sharing it. + * + * @see Configurable + * @since 0.4.0 + */ @SuppressWarnings("PMD.ExcessivePublicCount") @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({ "SING_SINGLETON_IMPLEMENTS_CLONEABLE", "SING_SINGLETON_IMPLEMENTS_SERIALIZABLE" }) public class Config implements Cloneable, Serializable { + /** + * The prefix of the system properties that set the initial values of a {@link Config}. + * + *

The full name of a property is this prefix followed by the {@code PROP_} constant of the + * option, for example {@code org.ini4j.config.multiSection}. + */ public static final String KEY_PREFIX = "org.ini4j.config."; + + /** + * The system property {@code org.ini4j.config.emptyOption} sets the initial value of {@link + * #isEmptyOption()}. This constant is the part after {@link #KEY_PREFIX}. + */ public static final String PROP_EMPTY_OPTION = "emptyOption"; + + /** + * The system property {@code org.ini4j.config.emptySection} sets the initial value of {@link + * #isEmptySection()}. This constant is the part after {@link #KEY_PREFIX}. + */ public static final String PROP_EMPTY_SECTION = "emptySection"; + + /** + * The system property {@code org.ini4j.config.globalSection} sets the initial value of {@link + * #isGlobalSection()}. This constant is the part after {@link #KEY_PREFIX}. + */ public static final String PROP_GLOBAL_SECTION = "globalSection"; + + /** + * The system property {@code org.ini4j.config.globalSectionName} sets the initial value of {@link + * #getGlobalSectionName()}. This constant is the part after {@link #KEY_PREFIX}. + */ public static final String PROP_GLOBAL_SECTION_NAME = "globalSectionName"; + + /** + * The system property {@code org.ini4j.config.include} sets the initial value of {@link + * #isInclude()}. This constant is the part after {@link #KEY_PREFIX}. + */ public static final String PROP_INCLUDE = "include"; + + /** + * The system property {@code org.ini4j.config.lowerCaseOption} sets the initial value of {@link + * #isLowerCaseOption()}. This constant is the part after {@link #KEY_PREFIX}. + */ public static final String PROP_LOWER_CASE_OPTION = "lowerCaseOption"; + + /** + * The system property {@code org.ini4j.config.lowerCaseSection} sets the initial value of {@link + * #isLowerCaseSection()}. This constant is the part after {@link #KEY_PREFIX}. + */ public static final String PROP_LOWER_CASE_SECTION = "lowerCaseSection"; + + /** + * The system property {@code org.ini4j.config.multiOption} sets the initial value of {@link + * #isMultiOption()}. This constant is the part after {@link #KEY_PREFIX}. + */ public static final String PROP_MULTI_OPTION = "multiOption"; + + /** + * The system property {@code org.ini4j.config.multiSection} sets the initial value of {@link + * #isMultiSection()}. This constant is the part after {@link #KEY_PREFIX}. + */ public static final String PROP_MULTI_SECTION = "multiSection"; + + /** + * The system property {@code org.ini4j.config.strictOperator} sets the initial value of {@link + * #isStrictOperator()}. This constant is the part after {@link #KEY_PREFIX}. + */ public static final String PROP_STRICT_OPERATOR = "strictOperator"; + + /** + * The system property {@code org.ini4j.config.unnamedSection} sets the initial value of {@link + * #isUnnamedSection()}. This constant is the part after {@link #KEY_PREFIX}. + */ public static final String PROP_UNNAMED_SECTION = "unnamedSection"; + + /** + * The system property {@code org.ini4j.config.escape} sets the initial value of {@link + * #isEscape()}. This constant is the part after {@link #KEY_PREFIX}. + */ public static final String PROP_ESCAPE = "escape"; + + /** + * The system property {@code org.ini4j.config.escapeNewline} sets the initial value of {@link + * #isEscapeNewline()}. This constant is the part after {@link #KEY_PREFIX}. + */ public static final String PROP_ESCAPE_NEWLINE = "escapeNewline"; + + /** + * The system property {@code org.ini4j.config.escapeKey} sets the initial value of {@link + * #isEscapeKeyOnly()}. This constant is the part after {@link #KEY_PREFIX}. + * + *

The value is {@code escapeKey}, not {@code escapeKeyOnly}. + */ public static final String PROP_ESCAPE_KEY_ONLY = "escapeKey"; + + /** + * The system property {@code org.ini4j.config.pathSeparator} sets the initial value of {@link + * #getPathSeparator()}. This constant is the part after {@link #KEY_PREFIX}. + */ public static final String PROP_PATH_SEPARATOR = "pathSeparator"; + + /** + * The system property {@code org.ini4j.config.tree} sets the initial value of {@link #isTree()}. + * This constant is the part after {@link #KEY_PREFIX}. + */ public static final String PROP_TREE = "tree"; + + /** + * The system property {@code org.ini4j.config.propertyFirstUpper} sets the initial value of + * {@link #isPropertyFirstUpper()}. This constant is the part after {@link #KEY_PREFIX}. + */ public static final String PROP_PROPERTY_FIRST_UPPER = "propertyFirstUpper"; + + /** + * The system property {@code org.ini4j.config.fileEncoding} sets the initial value of {@link + * #getFileEncoding()}. This constant is the part after {@link #KEY_PREFIX}. + */ public static final String PROP_FILE_ENCODING = "fileEncoding"; + + /** + * The system property {@code org.ini4j.config.lineSeparator} sets the initial value of {@link + * #getLineSeparator()}. This constant is the part after {@link #KEY_PREFIX}. + */ public static final String PROP_LINE_SEPARATOR = "lineSeparator"; + + /** + * The system property {@code org.ini4j.config.comment} sets the initial value of {@link + * #isComment()}. This constant is the part after {@link #KEY_PREFIX}. + */ public static final String PROP_COMMENT = "comment"; + + /** + * The system property {@code org.ini4j.config.headerComment} sets the initial value of {@link + * #isHeaderComment()}. This constant is the part after {@link #KEY_PREFIX}. + */ public static final String PROP_HEADER_COMMENT = "headerComment"; + + /** + * The system property {@code org.ini4j.config.maxResolveDepth} sets the initial value of {@link + * #getMaxResolveDepth()}. This constant is the part after {@link #KEY_PREFIX}. + */ public static final String PROP_MAX_RESOLVE_DEPTH = "maxResolveDepth"; + + /** The default of {@link #isEmptyOption()}: {@code false}. */ public static final boolean DEFAULT_EMPTY_OPTION = false; + + /** The default of {@link #isEmptySection()}: {@code false}. */ public static final boolean DEFAULT_EMPTY_SECTION = false; + + /** The default of {@link #isGlobalSection()}: {@code false}. */ public static final boolean DEFAULT_GLOBAL_SECTION = false; + + /** The default of {@link #getGlobalSectionName()}: {@code "?"}. */ public static final String DEFAULT_GLOBAL_SECTION_NAME = "?"; + + /** The default of {@link #isInclude()}: {@code false}. */ public static final boolean DEFAULT_INCLUDE = false; + + /** The default of {@link #isLowerCaseOption()}: {@code false}. */ public static final boolean DEFAULT_LOWER_CASE_OPTION = false; + + /** The default of {@link #isLowerCaseSection()}: {@code false}. */ public static final boolean DEFAULT_LOWER_CASE_SECTION = false; + + /** The default of {@link #isMultiOption()}: {@code true}. */ public static final boolean DEFAULT_MULTI_OPTION = true; + + /** The default of {@link #isMultiSection()}: {@code false}. */ public static final boolean DEFAULT_MULTI_SECTION = false; + + /** The default of {@link #isStrictOperator()}: {@code false}. */ public static final boolean DEFAULT_STRICT_OPERATOR = false; + + /** The default of {@link #isUnnamedSection()}: {@code false}. */ public static final boolean DEFAULT_UNNAMED_SECTION = false; + + /** The default of {@link #isEscape()}: {@code true}. */ public static final boolean DEFAULT_ESCAPE = true; + + /** The default of {@link #isEscapeNewline()}: {@code true}. */ public static final boolean DEFAULT_ESCAPE_NEWLINE = true; + + /** The default of {@link #isEscapeKeyOnly()}: {@code false}. */ public static final boolean DEFAULT_ESCAPE_KEY_ONLY = false; + + /** The default of {@link #isTree()}: {@code true}. */ public static final boolean DEFAULT_TREE = true; + + /** The default of {@link #isPropertyFirstUpper()}: {@code false}. */ public static final boolean DEFAULT_PROPERTY_FIRST_UPPER = false; + + /** The default of {@link #isComment()}: {@code true}. */ public static final boolean DEFAULT_COMMENT = true; + + /** The default of {@link #isHeaderComment()}: {@code true}. */ public static final boolean DEFAULT_HEADER_COMMENT = true; + + /** The default of {@link #getPathSeparator()}: {@code '/'}. */ public static final char DEFAULT_PATH_SEPARATOR = '/'; + + /** + * The default of {@link #getLineSeparator()}: the value of the system property {@code + * line.separator}, or {@code "\n"} if that cannot be read. + */ public static final String DEFAULT_LINE_SEPARATOR = getSystemProperty("line.separator", "\n"); + + /** The default of {@link #getFileEncoding()}: UTF-8. */ public static final Charset DEFAULT_FILE_ENCODING = StandardCharsets.UTF_8; + + /** The default of {@link #getMaxResolveDepth()}: {@code 16}. */ public static final int DEFAULT_MAX_RESOLVE_DEPTH = 16; + private static final Config GLOBAL = new Config(); private static final long serialVersionUID = 2865793267410367814L; private boolean _comment; @@ -95,15 +298,43 @@ public class Config implements Cloneable, Serializable { private boolean _unnamedSection; private int _maxResolveDepth; + /** + * Creates a configuration. + * + *

Every option gets the value of its system property, or its default if the property is not + * set. See {@link #reset()}. + * + * @throws StringIndexOutOfBoundsException if the {@link #PROP_PATH_SEPARATOR} property is empty + * @throws java.nio.charset.UnsupportedCharsetException if the {@link #PROP_FILE_ENCODING} + * property names an unknown character set + * @throws java.nio.charset.IllegalCharsetNameException if the {@link #PROP_FILE_ENCODING} + * property is not a legal character set name + */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings("SING_SINGLETON_HAS_NONPRIVATE_CONSTRUCTOR") public Config() { reset(); } + /** + * Returns an environment variable. + * + * @param name the name of the variable + * @return the value, or {@code null} if the variable is not set or cannot be read + */ public static String getEnvironment(String name) { return getEnvironment(name, null); } + /** + * Returns an environment variable, or a default. + * + *

A {@link SecurityException} from the security manager is treated as if the variable were not + * set. + * + * @param name the name of the variable + * @param defaultValue the value to return when the variable is not set or cannot be read + * @return the value of the variable, or {@code defaultValue} + */ public static String getEnvironment(String name, String defaultValue) { String value; @@ -116,15 +347,43 @@ public static String getEnvironment(String name, String defaultValue) { return (value == null) ? defaultValue : value; } + /** + * Returns the global configuration. + * + *

The global configuration is one shared object. {@link Ini} starts with it directly, while + * {@link Options} and {@link Reg} start with a copy of it. {@link BasicProfile} and {@link + * BasicOptionMap} objects that are not one of those classes use it too, and so do the parsers and + * formatters of the {@code org.ini4j.spi} package until they are given another configuration. A + * change to it therefore affects all of them. It reads the system properties once, when this + * class is loaded. + * + * @return the global configuration, not a copy + */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings("MS_EXPOSE_REP") public static Config getGlobal() { return GLOBAL; } + /** + * Returns a system property. + * + * @param name the name of the property + * @return the value, or {@code null} if the property is not set or cannot be read + */ public static String getSystemProperty(String name) { return getSystemProperty(name, null); } + /** + * Returns a system property, or a default. + * + *

A {@link SecurityException} from the security manager is treated as if the property were not + * set. + * + * @param name the name of the property + * @param defaultValue the value to return when the property is not set or cannot be read + * @return the value of the property, or {@code defaultValue} + */ public static String getSystemProperty(String name, String defaultValue) { String value; @@ -137,182 +396,580 @@ public static String getSystemProperty(String name, String defaultValue) { return (value == null) ? defaultValue : value; } + /** + * Sets the value of {@link #isComment()}. + * + * @param value the new value + */ public void setComment(boolean value) { _comment = value; } + /** + * Tells whether special characters are escaped with a backslash. + * + *

When it is on, the parser decodes backslash sequences in names and values: {@code \t}, + * {@code \n}, {@code \f}, {@code \b}, {@code \r}, {@code \:}, {@code \=} and {@code \\}, and a + * backslash followed by {@code u} and four hexadecimal digits for a character by its code. A + * backslash before any other character is dropped. A malformed sequence with {@code u} throws an + * {@link IllegalArgumentException}. The formatter writes those characters in the same form, and + * every other character outside the printable ASCII range with the {@code u} form, even if the + * file encoding could hold it. Section names are escaped like option names. See also {@link + * #isEscapeKeyOnly()}. + * + *

{@link Reg} starts with it off. + * + *

The initial value comes from the system property {@code org.ini4j.config.escape} if it is + * set, otherwise from {@link #DEFAULT_ESCAPE}. + * + * @return {@code true} if it is on + */ public boolean isEscape() { return _escape; } + /** + * Tells whether a backslash at the end of a line continues the line. + * + *

When it is on, the parser removes a backslash that ends a line (an odd number of + * backslashes) and appends the next line, with its leading white space removed, to the same + * logical line. This applies to the parser only. + * + *

The initial value comes from the system property {@code org.ini4j.config.escapeNewline} if + * it is set, otherwise from {@link #DEFAULT_ESCAPE_NEWLINE}. + * + * @return {@code true} if it is on + */ public boolean isEscapeNewline() { return _escapeNewline; } + /** + * Tells whether the parser follows include lines. + * + *

When it is on, a line of the form {@code } is replaced by the content of that + * location, which is read as part of the same input. A line of the form {@code } is + * the same, but an {@link java.io.IOException} when opening the location is ignored. A relative + * location is resolved against the URL that is being loaded. When the input is a stream or a + * reader, the location must be an absolute URL. {@link Reg} reads through a reader even when it + * loads a file or a URL, so it needs absolute locations. The line is recognized only when its + * first character is {@code <} and its last is {@code >}. + * + *

The initial value comes from the system property {@code org.ini4j.config.include} if it is + * set, otherwise from {@link #DEFAULT_INCLUDE}. + * + * @return {@code true} if it is on + */ public boolean isInclude() { return _include; } + /** + * Tells whether adding a section also adds its missing parents. + * + *

When it is on, {@link Profile#add(String)} on an {@link Ini} or a {@link Reg} adds the + * sections for the missing levels of the name first, so that adding {@code a/b/c} also adds + * {@code a} and {@code a/b}. The tree methods of {@link Profile.Section} work either way, but + * they find only the sections that exist. + * + *

The initial value comes from the system property {@code org.ini4j.config.tree} if it is set, + * otherwise from {@link #DEFAULT_TREE}. + * + * @return {@code true} if it is on + */ public boolean isTree() { return _tree; } + /** + * Sets the value of {@link #isEmptyOption()}. + * + * @param value the new value + */ public void setEmptyOption(boolean value) { _emptyOption = value; } + /** + * Sets the value of {@link #isEmptySection()}. + * + * @param value the new value + */ public void setEmptySection(boolean value) { _emptySection = value; } + /** + * Sets the value of {@link #isEscape()}. + * + * @param value the new value + */ public void setEscape(boolean value) { _escape = value; } + /** + * Sets the value of {@link #isEscapeKeyOnly()}. + * + * @param value the new value + */ public void setEscapeKeyOnly(boolean value) { _escapeKeyOnly = value; } + /** + * Sets the value of {@link #isEscapeNewline()}. + * + * @param value the new value + */ public void setEscapeNewline(boolean value) { _escapeNewline = value; } + /** + * Returns the character set used to read and write streams and files. + * + *

It is used by the load and store methods that take a stream, a file or a URL. The methods + * that take a {@link java.io.Reader} or a {@link java.io.Writer} do not use it. When an {@link + * Ini} or an {@link Options} loads from a URL or a file, a byte order mark at the start of the + * input overrides it. {@link Reg} starts with UTF-16 little endian. + * + *

The initial value comes from the system property {@code org.ini4j.config.fileEncoding} if it + * is set, otherwise from {@link #DEFAULT_FILE_ENCODING}. + * + * @return the character set + */ public Charset getFileEncoding() { return _fileEncoding; } + /** + * Sets the value of {@link #getFileEncoding()}. + * + * @param value the new value + */ public void setFileEncoding(Charset value) { _fileEncoding = value; } + /** + * Sets the value of {@link #isGlobalSection()}. + * + * @param value the new value + */ public void setGlobalSection(boolean value) { _globalSection = value; } + /** + * Returns the name of the section that holds the options before the first section header. + * + *

It is used only when {@link #isGlobalSection()} is on. + * + *

The initial value comes from the system property {@code org.ini4j.config.globalSectionName} + * if it is set, otherwise from {@link #DEFAULT_GLOBAL_SECTION_NAME}. + * + * @return the section name + */ public String getGlobalSectionName() { return _globalSectionName; } + /** + * Sets the value of {@link #getGlobalSectionName()}. + * + * @param value the new value + */ public void setGlobalSectionName(String value) { _globalSectionName = value; } + /** + * Sets the value of {@link #isHeaderComment()}. + * + * @param value the new value + */ public void setHeaderComment(boolean value) { _headerComment = value; } + /** + * Sets the value of {@link #isInclude()}. + * + * @param value the new value + */ public void setInclude(boolean value) { _include = value; } + /** + * Returns the line separator. + * + *

The formatter ends every line with it. The parser joins the lines of a multi-line comment + * with it, and the formatter splits a comment into lines at it. {@link Reg} starts with {@code CR + * LF}. + * + *

The initial value comes from the system property {@code org.ini4j.config.lineSeparator} if + * it is set, otherwise from {@link #DEFAULT_LINE_SEPARATOR}. + * + * @return the line separator + */ public String getLineSeparator() { return _lineSeparator; } + /** + * Sets the value of {@link #getLineSeparator()}. + * + * @param value the new value + */ public void setLineSeparator(String value) { _lineSeparator = value; } + /** + * Sets the value of {@link #isLowerCaseOption()}. + * + * @param value the new value + */ public void setLowerCaseOption(boolean value) { _lowerCaseOption = value; } + /** + * Sets the value of {@link #isLowerCaseSection()}. + * + * @param value the new value + */ public void setLowerCaseSection(boolean value) { _lowerCaseSection = value; } + /** + * Sets the value of {@link #isMultiOption()}. + * + * @param value the new value + */ public void setMultiOption(boolean value) { _multiOption = value; } + /** + * Sets the value of {@link #isMultiSection()}. + * + * @param value the new value + */ public void setMultiSection(boolean value) { _multiSection = value; } + /** + * Tells whether an option may have no value. + * + *

When it is on, the parser accepts a line that has no operator and reads it as an option with + * that text as its name and a {@code null} value. The formatter writes a {@code null} value as an + * empty value. When it is off, the parser reports such a line as an {@link + * InvalidFileFormatException} and the formatter leaves the option out. + * + *

{@link Options} and {@link Reg} start with it on. + * + *

The initial value comes from the system property {@code org.ini4j.config.emptyOption} if it + * is set, otherwise from {@link #DEFAULT_EMPTY_OPTION}. + * + * @return {@code true} if it is on + */ public boolean isEmptyOption() { return _emptyOption; } + /** + * Tells whether sections without options are stored. + * + *

When it is off, {@link Ini#store(java.io.Writer)} leaves out the sections that have no + * options. Loading is not affected: a section with no options in the input is loaded either way. + * + *

{@link Reg} starts with it on. + * + *

The initial value comes from the system property {@code org.ini4j.config.emptySection} if it + * is set, otherwise from {@link #DEFAULT_EMPTY_SECTION}. + * + * @return {@code true} if it is on + */ public boolean isEmptySection() { return _emptySection; } + /** + * Tells whether options before the first section header are allowed. + * + *

When it is on, the parser puts such options in a section named {@link + * #getGlobalSectionName()}. The formatter writes the options of that section without a section + * header. When it is off, the parser reports an option before the first header as an {@link + * InvalidFileFormatException}. + * + *

The initial value comes from the system property {@code org.ini4j.config.globalSection} if + * it is set, otherwise from {@link #DEFAULT_GLOBAL_SECTION}. + * + * @return {@code true} if it is on + */ public boolean isGlobalSection() { return _globalSection; } + /** + * Tells whether the parser converts option names to lower case. + * + *

The conversion uses the default locale. It applies when loading only; names set in code are + * not changed. + * + *

The initial value comes from the system property {@code org.ini4j.config.lowerCaseOption} if + * it is set, otherwise from {@link #DEFAULT_LOWER_CASE_OPTION}. + * + * @return {@code true} if it is on + */ public boolean isLowerCaseOption() { return _lowerCaseOption; } + /** + * Tells whether the parser converts section names to lower case. + * + *

The conversion uses the default locale. It applies when loading only; names set in code are + * not changed. + * + *

The initial value comes from the system property {@code org.ini4j.config.lowerCaseSection} + * if it is set, otherwise from {@link #DEFAULT_LOWER_CASE_SECTION}. + * + * @return {@code true} if it is on + */ public boolean isLowerCaseSection() { return _lowerCaseSection; } + /** + * Tells whether an option name can have several values. + * + *

When it is on, the parser keeps every value of an option that appears more than once in a + * section, and the formatter writes them all. When it is off, a later value replaces the earlier + * one when loading. When storing an {@link Ini}, only the last value of each option is written, + * and when storing an {@link Options}, only the first. {@link Reg} starts with it on, and always + * writes all the values of a registry value name. + * + *

The initial value comes from the system property {@code org.ini4j.config.multiOption} if it + * is set, otherwise from {@link #DEFAULT_MULTI_OPTION}. + * + * @return {@code true} if it is on + */ public boolean isMultiOption() { return _multiOption; } + /** + * Tells whether a section name can be used for several sections. + * + *

When it is on, every section header in the input adds a new section, even if a section of + * that name exists already. When it is off, the options under a repeated header are added to the + * existing section. It applies when loading only. + * + *

The initial value comes from the system property {@code org.ini4j.config.multiSection} if it + * is set, otherwise from {@link #DEFAULT_MULTI_SECTION}. + * + * @return {@code true} if it is on + */ public boolean isMultiSection() { return _multiSection; } + /** + * Tells whether a section may have an empty name. + * + *

When it is on, the parser accepts the header {@code []}. When it is off, it reports that + * header as an {@link InvalidFileFormatException}. + * + *

The initial value comes from the system property {@code org.ini4j.config.unnamedSection} if + * it is set, otherwise from {@link #DEFAULT_UNNAMED_SECTION}. + * + * @return {@code true} if it is on + */ public boolean isUnnamedSection() { return _unnamedSection; } + /** + * Returns the character that separates the levels of a section name. + * + *

A section named {@code a/b} (with the default) is a child of the section {@code a}. See + * {@link #isTree()} and {@link Profile.Section}. {@link Reg} starts with a backslash. + * + *

The initial value comes from the system property {@code org.ini4j.config.pathSeparator} if + * it is set, otherwise from {@link #DEFAULT_PATH_SEPARATOR}. + * + * @return the path separator + */ public char getPathSeparator() { return _pathSeparator; } + /** + * Sets the value of {@link #getPathSeparator()}. + * + * @param value the new value + */ public void setPathSeparator(char value) { _pathSeparator = value; } + /** + * Sets the value of {@link #isPropertyFirstUpper()}. + * + * @param value the new value + */ public void setPropertyFirstUpper(boolean value) { _propertyFirstUpper = value; } + /** + * Tells whether bean property names start with an upper case letter in the file. + * + *

When it is on, the bean methods ({@link OptionMap#as(Class)}, {@link + * OptionMap#from(Object)}, {@link OptionMap#to(Object)} and {@link Profile#as(Class)}) change the + * first letter of the property name to upper case to get the option or section name, so the + * property {@code age} is the option {@code Age}. + * + *

The initial value comes from the system property {@code org.ini4j.config.propertyFirstUpper} + * if it is set, otherwise from {@link #DEFAULT_PROPERTY_FIRST_UPPER}. + * + * @return {@code true} if it is on + */ public boolean isPropertyFirstUpper() { return _propertyFirstUpper; } + /** + * Tells whether options are written without spaces around the operator. + * + *

When it is on, an option is written as {@code name=value}. When it is off, it is written as + * {@code name = value}. The parser accepts both forms either way. + * + *

{@link Reg} starts with it on. + * + *

The initial value comes from the system property {@code org.ini4j.config.strictOperator} if + * it is set, otherwise from {@link #DEFAULT_STRICT_OPERATOR}. + * + * @return {@code true} if it is on + */ public boolean isStrictOperator() { return _strictOperator; } + /** + * Sets the value of {@link #isStrictOperator()}. + * + * @param value the new value + */ public void setStrictOperator(boolean value) { _strictOperator = value; } + /** + * Tells whether comments are loaded and stored. + * + *

When it is on, the parser keeps comments and the formatter writes them, as described in + * {@link CommentedMap}. When it is off, comments are skipped when loading and not written when + * storing. + * + *

The initial value comes from the system property {@code org.ini4j.config.comment} if it is + * set, otherwise from {@link #DEFAULT_COMMENT}. + * + * @return {@code true} if it is on + */ public boolean isComment() { return _comment; } + /** + * Tells whether the first comment of a file is its header comment. + * + *

When it is on, the comment at the top of the input, before the first section or option, is + * loaded as the comment of the whole {@link Profile} or {@link Options} object, and the formatter + * writes that comment first, followed by an empty line. When it is off, that comment belongs to + * the first section or option, and the formatter does not write the comment of the whole object. + * It works together with {@link #isComment()}. + * + *

The initial value comes from the system property {@code org.ini4j.config.headerComment} if + * it is set, otherwise from {@link #DEFAULT_HEADER_COMMENT}. + * + * @return {@code true} if it is on + */ public boolean isHeaderComment() { return _headerComment; } + /** + * Sets the value of {@link #isTree()}. + * + * @param value the new value + */ public void setTree(boolean value) { _tree = value; } + /** + * Sets the value of {@link #isUnnamedSection()}. + * + * @param value the new value + */ public void setUnnamedSection(boolean value) { _unnamedSection = value; } + /** + * Tells whether only names are escaped, not values. + * + *

It has an effect only when {@link #isEscape()} is on. Then names and section names are + * escaped and unescaped as usual, and values are not escaped or unescaped. + * + *

The initial value comes from the system property {@code org.ini4j.config.escapeKey} if it is + * set, otherwise from {@link #DEFAULT_ESCAPE_KEY_ONLY}. + * + * @return {@code true} if it is on + */ public boolean isEscapeKeyOnly() { return _escapeKeyOnly; } + /** + * Returns the longest chain of variable references that is resolved. + * + *

A value can contain variables whose values contain variables again. With a limit of {@code + * n}, a chain of {@code n} references is resolved, and a longer chain throws a {@link + * CircularReferenceException}. A value is only checked when it contains a dollar sign, and with a + * limit of {@code 0} every such value throws. The limit stops circular references, which would + * otherwise never end. A system property that is not a number is ignored. See {@link OptionMap}. + * + *

The initial value comes from the system property {@code org.ini4j.config.maxResolveDepth} if + * it is set, otherwise from {@link #DEFAULT_MAX_RESOLVE_DEPTH}. + * + * @return the limit + */ public int getMaxResolveDepth() { return _maxResolveDepth; } + /** + * Sets the value of {@link #getMaxResolveDepth()}. + * + * @param value the new value + */ public void setMaxResolveDepth(int value) { _maxResolveDepth = value; } + /** + * Returns a copy of this configuration. + * + * @return a new configuration with the same values + */ @Override public Config clone() { try { @@ -322,6 +979,20 @@ public Config clone() { } } + /** + * Sets every option to the value of its system property, or to its default if the property is not + * set. + * + *

Values set with the setters are lost. A boolean property with a value other than {@code + * true} (in any letter case) is read as {@code false}, and a number property that cannot be + * parsed is ignored. + * + * @throws StringIndexOutOfBoundsException if the {@link #PROP_PATH_SEPARATOR} property is empty + * @throws java.nio.charset.UnsupportedCharsetException if the {@link #PROP_FILE_ENCODING} + * property names an unknown character set + * @throws java.nio.charset.IllegalCharsetNameException if the {@link #PROP_FILE_ENCODING} + * property is not a legal character set name + */ public final void reset() { _emptyOption = getBoolean(PROP_EMPTY_OPTION, DEFAULT_EMPTY_OPTION); _emptySection = getBoolean(PROP_EMPTY_SECTION, DEFAULT_EMPTY_SECTION); From 159a3f7d0b70d558e3690ed53171dcdbb67938d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Iv=C3=A1n=20SZKIBA?= Date: Mon, 16 Nov 2026 09:13:52 +0100 Subject: [PATCH 3/9] docs: document the base map and profile implementations The default implementations differ from what the interfaces suggest in a few places: remove returns the first value, entrySet is a snapshot, a comment stays when a key is removed through keySet, and the global Config limits variable nesting. These are now written down. Refs: #13 --- src/main/java/org/ini4j/BasicMultiMap.java | 96 +++++++++++++++++++++ src/main/java/org/ini4j/BasicOptionMap.java | 65 +++++++++++++- src/main/java/org/ini4j/BasicProfile.java | 47 +++++++++- src/main/java/org/ini4j/BasicRegistry.java | 10 +++ src/main/java/org/ini4j/CommonMultiMap.java | 16 ++++ 5 files changed, 232 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/ini4j/BasicMultiMap.java b/src/main/java/org/ini4j/BasicMultiMap.java index 61da621..fa00749 100644 --- a/src/main/java/org/ini4j/BasicMultiMap.java +++ b/src/main/java/org/ini4j/BasicMultiMap.java @@ -25,14 +25,49 @@ import java.util.Set; import org.ini4j.spi.Warnings; +/** + * A {@link MultiMap} that keeps the values of each key in a list. + * + *

The map stores a {@link java.util.List} for each key in an underlying map, which is a {@link + * java.util.LinkedHashMap} unless another one is given to the constructor. Keys therefore come in + * insertion order by default. The values of a key are in insertion order too. A value can be {@code + * null}. + * + *

The inherited {@link java.util.Map} methods work on the whole key as described in {@link + * MultiMap}. The differences from a plain map are these: {@link #size()} counts keys, not values; + * {@link #values()} returns all the values of all the keys, so it can have more elements than + * {@link #size()}; {@link #entrySet()} has one entry for each key, and the entry reads and replaces + * the last value. The class does not override {@code equals} and {@code hashCode}, so two maps are + * equal only if they are the same object. + * + *

Thread safety. The class has no synchronization. Several threads can read a + * map built on the default underlying map while no thread changes it. A map built on a collection + * that changes on reads, such as an access-ordered {@link java.util.LinkedHashMap}, is not safe to + * read from several threads. Any change needs outside locking. + * + * @param the type of the keys + * @param the type of the values + * @see CommonMultiMap + * @since 0.5.0 + */ public class BasicMultiMap implements MultiMap, Serializable { private static final long serialVersionUID = 4716749660560043989L; private final Map> _impl; + /** Creates an empty map that keeps its keys in insertion order. */ public BasicMultiMap() { this(new LinkedHashMap>()); } + /** + * Creates a map on top of an underlying map. + * + *

The given map is used directly, not copied, so changes to it show in this map and the other + * way round. It must map each key to a modifiable list. The order of the keys is the iteration + * order of the given map. + * + * @param impl the underlying map, used as it is + */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings("EI_EXPOSE_REP2") public BasicMultiMap(Map> impl) { _impl = impl; @@ -83,6 +118,15 @@ public boolean containsValue(Object value) { return ret; } + /** + * Returns the entries of this map, one for each key. + * + *

The set is a new one and is not backed by the map: removing from it does not change the map, + * and it is not ordered. The value of an entry is the last value of its key, and {@link + * java.util.Map.Entry#setValue(Object)} replaces that last value. + * + * @return a new set of entries + */ @Override public Set> entrySet() { Set> ret = new HashSet>(); @@ -108,6 +152,14 @@ public V get(Object key, int index) { return (values == null) ? null : values.get(index); } + /** + * Returns the keys of the underlying map. + * + *

The set is a live view of the underlying map, so removing a key from it removes all the + * values of the key. + * + * @return the set of keys + */ @Override public Set keySet() { return _impl.keySet(); @@ -139,6 +191,15 @@ public V put(K key, V value, int index) { return getList(key, false).set(index, value); } + /** + * Copies the entries of another map. + * + *

If the argument is a {@link MultiMap}, all the values of each of its keys replace the values + * of that key in this map (as {@link #putAll(Object, List)} does). Otherwise each entry replaces + * the last value of its key. + * + * @param map the map to copy from + */ @SuppressWarnings(Warnings.UNCHECKED) @Override public void putAll(Map map) { @@ -155,6 +216,17 @@ public void putAll(Map map) { } } + /** + * Replaces all the values of a key with a copy of the given list. + * + *

Do not pass an empty list. The key would then be in the map with no value, and {@link + * #get(Object)} for it would throw an {@link IndexOutOfBoundsException}. + * + * @param key the key + * @param values the new values, copied + * @return the list of values the key had before, as the map stored it, or {@code null} if the key + * was not in the map + */ @Override public List putAll(K key, List values) { List ret = _impl.get(key); @@ -164,6 +236,12 @@ public List putAll(K key, List values) { return ret; } + /** + * Removes all the values of a key. + * + * @param key the key + * @return the first value the key had, or {@code null} if the key was not in the map + */ @Override public V remove(Object key) { List prev = _impl.remove(key); @@ -186,16 +264,34 @@ public V remove(Object key, int index) { return ret; } + /** + * Returns the number of keys. + * + * @return the number of keys, not the number of values + */ @Override public int size() { return _impl.size(); } + /** + * Returns the text form of the underlying map, for example {@code {a=[1, 2], b=[3]}}. + * + * @return the text form + */ @Override public String toString() { return _impl.toString(); } + /** + * Returns all the values of all the keys. + * + *

The collection is a new list, in key order and, for each key, in value order. Changes to it + * do not change the map. + * + * @return a new collection of values + */ @Override public Collection values() { List all = new ArrayList(_impl.size()); diff --git a/src/main/java/org/ini4j/BasicOptionMap.java b/src/main/java/org/ini4j/BasicOptionMap.java index 7675aeb..59afe3c 100644 --- a/src/main/java/org/ini4j/BasicOptionMap.java +++ b/src/main/java/org/ini4j/BasicOptionMap.java @@ -22,6 +22,25 @@ import org.ini4j.spi.BeanTool; import org.ini4j.spi.Warnings; +/** + * The default implementation of {@link OptionMap}. + * + *

It is a {@link CommonMultiMap} of option names to values, so every option name can have + * several values and a comment. The conversion, variable and bean methods are described in {@link + * OptionMap}. Variables are resolved by the {@code fetch} methods, except {@link #fetch(Object, + * String)}, up to the depth given by the configuration (see {@link Config#getMaxResolveDepth()}). + * This class uses {@link Config#getGlobal()} for that limit; {@link Options} and the sections of an + * {@link Ini} use their own configuration. + * + *

The {@link #as(Class)} methods create a dynamic proxy with the context class loader of the + * calling thread, so the interface must be visible from that class loader. + * + *

The thread safety of {@link BasicMultiMap} applies. + * + * @see Options + * @see Profile.Section + * @since 0.5.0 + */ public class BasicOptionMap extends CommonMultiMap implements OptionMap { private static final char SUBST_CHAR = '$'; private static final String SYSTEM_PROPERTY_PREFIX = "@prop/"; @@ -36,10 +55,21 @@ public class BasicOptionMap extends CommonMultiMap implements Op private transient BeanAccess _defaultBeanAccess; private final boolean _propertyFirstUpper; + /** + * Creates an empty option map. + * + *

The names of bean properties are used as they are for the option names. + */ public BasicOptionMap() { this(false); } + /** + * Creates an empty option map and tells how bean property names map to option names. + * + * @param propertyFirstUpper if {@code true}, the first letter of a bean property name is changed + * to upper case to get the option name (see {@link #as(Class)}) + */ public BasicOptionMap(boolean propertyFirstUpper) { _propertyFirstUpper = propertyFirstUpper; } @@ -110,6 +140,26 @@ public String fetch(Object key, int index) { return fetchInternal(key, index, 0); } + /** + * Returns the value of an option at the given position, with variables resolved at a given + * nesting depth. + * + *

The {@code fetch} methods call this method, except {@link #fetch(Object, String)}, which + * does not resolve variables. A subclass can override it to change how variables are resolved. + * {@code depth} is {@code 0} when a value is fetched by a caller, and it is one more for a value + * that is fetched because a variable refers to it. When {@code depth} has reached the limit of + * {@link Config#getMaxResolveDepth()}, a value that contains a dollar sign throws a {@link + * CircularReferenceException}, whether or not it holds a valid variable. A value without a dollar + * sign is returned as it is. + * + * @param key the option name + * @param index the position of the value + * @param depth the current nesting depth of variable references + * @return the value with its variables resolved, or {@code null} if the option is missing + * @throws IndexOutOfBoundsException if the option exists and the index is out of range + * @throws CircularReferenceException if {@code depth} has reached the depth limit and the value + * contains a dollar sign + */ protected String fetchInternal(Object key, int index, int depth) { String value = get(key, index); @@ -253,6 +303,19 @@ void resolve(StringBuilder buffer) { resolve(buffer, 0); } + /** + * Replaces the variables in a buffer with their values. + * + *

The buffer is changed in place. After each replacement the scan starts again from the + * beginning, so a value that holds a variable is resolved as well. A variable whose option, + * environment variable or system property is missing stays in the text. The variable syntax is + * described in {@link OptionMap}. + * + * @param buffer the text to resolve + * @param depth the nesting depth of this call + * @throws CircularReferenceException if {@code depth} has reached {@link + * Config#getMaxResolveDepth()} + */ void resolve(StringBuilder buffer, int depth) { if (depth >= getConfig().getMaxResolveDepth()) { throw new CircularReferenceException(getConfig().getMaxResolveDepth()); @@ -271,7 +334,7 @@ void resolve(StringBuilder buffer, int depth) { value = Config.getSystemProperty(name.substring(SYSTEM_PROPERTY_PREFIX_LEN)); } else { if (index == -1) { - // When no index specified, use the default behavior: get the last value + // When no index is specified, use the default behavior: get the last value int len = length(name); value = (len == 0) ? null : fetchInternal(name, len - 1, depth + 1); } else { diff --git a/src/main/java/org/ini4j/BasicProfile.java b/src/main/java/org/ini4j/BasicProfile.java index 116e9f0..313b0cf 100644 --- a/src/main/java/org/ini4j/BasicProfile.java +++ b/src/main/java/org/ini4j/BasicProfile.java @@ -23,6 +23,27 @@ import org.ini4j.spi.BeanTool; import org.ini4j.spi.IniHandler; +/** + * The default implementation of {@link Profile}. + * + *

It is a {@link CommonMultiMap} of section names to sections, so a name can have several + * sections and each section has a comment. The sections are {@link Profile.Section}s that resolve + * variables through this profile, so a variable can name an option of another section (see {@link + * #fetch(Object, Object)}). + * + *

This class works with the path separator {@link #PATH_SEPARATOR} and with {@link + * Config#getGlobal()} for the limit of variable nesting. {@link Ini} and {@link Reg} take the path + * separator, the tree mode and the property naming rule from their own {@link Config} instead. + * + *

The {@link #as(Class)} methods create a dynamic proxy with the context class loader of the + * calling thread, so the interface must be visible from that class loader. + * + *

The thread safety of {@link BasicMultiMap} applies. + * + * @see Ini + * @see BasicRegistry + * @since 0.5.0 + */ public class BasicProfile extends CommonMultiMap implements Profile { private static final String SECTION_SYSTEM_PROPERTIES = "@prop"; private static final String SECTION_ENVIRONMENT = "@env"; @@ -38,10 +59,19 @@ public class BasicProfile extends CommonMultiMap implem private final boolean _propertyFirstUpper; private final boolean _treeMode; + /** Creates an empty profile that is not in tree mode and uses bean property names as they are. */ public BasicProfile() { this(false, false); } + /** + * Creates an empty profile. + * + * @param treeMode if {@code true}, {@link #add(String)} also adds the missing parent sections of + * a new section + * @param propertyFirstUpper if {@code true}, the first letter of a bean property name is changed + * to upper case to get the section name (see {@link #as(Class)}) + */ public BasicProfile(boolean treeMode, boolean propertyFirstUpper) { _treeMode = treeMode; _propertyFirstUpper = propertyFirstUpper; @@ -166,6 +196,21 @@ void resolve(StringBuilder buffer, Section owner) { resolve(buffer, owner, 0); } + /** + * Replaces the variables in a buffer with their values. + * + *

The buffer is changed in place. After each replacement the scan starts again from the + * beginning, so a value that holds a variable is resolved as well. A variable whose option, + * section, environment variable or system property is missing stays in the text. The variable + * syntax is described in {@link Profile#fetch(Object, Object)}. + * + * @param buffer the text to resolve + * @param owner the section of the option that holds the text; a variable without a section name + * refers to it + * @param depth the nesting depth of this call + * @throws CircularReferenceException if {@code depth} has reached {@link + * Config#getMaxResolveDepth()} + */ void resolve(StringBuilder buffer, Section owner, int depth) { if (depth >= getConfig().getMaxResolveDepth()) { throw new CircularReferenceException(getConfig().getMaxResolveDepth()); @@ -187,7 +232,7 @@ void resolve(StringBuilder buffer, Section owner, int depth) { } else if (section instanceof BasicProfileSection) { BasicProfileSection bps = (BasicProfileSection) section; if (optionIndex == -1) { - // When no index specified, use the default behavior: get the last value + // When no index is specified, use the default behavior: get the last value int len = bps.length(optionName); value = (len == 0) ? null : bps.fetchInternal(optionName, len - 1, depth + 1); } else { diff --git a/src/main/java/org/ini4j/BasicRegistry.java b/src/main/java/org/ini4j/BasicRegistry.java index 9c0d1c4..c8d7e0c 100644 --- a/src/main/java/org/ini4j/BasicRegistry.java +++ b/src/main/java/org/ini4j/BasicRegistry.java @@ -19,10 +19,20 @@ import org.ini4j.spi.RegEscapeTool; import org.ini4j.spi.TypeValuesPair; +/** + * The default implementation of {@link Registry}. + * + *

It is a {@link BasicProfile} whose sections are {@link Registry.Key}s. The methods that return + * a section return a key instead. The version header starts as {@link Registry#VERSION}. + * + * @see Reg + * @since 0.5.0 + */ public class BasicRegistry extends BasicProfile implements Registry { private static final long serialVersionUID = -6432826330714504802L; private String _version; + /** Creates an empty registry with the version header {@link Registry#VERSION}. */ public BasicRegistry() { _version = VERSION; } diff --git a/src/main/java/org/ini4j/CommonMultiMap.java b/src/main/java/org/ini4j/CommonMultiMap.java index 5293e5c..6857db2 100644 --- a/src/main/java/org/ini4j/CommonMultiMap.java +++ b/src/main/java/org/ini4j/CommonMultiMap.java @@ -19,6 +19,22 @@ import java.util.SortedMap; import java.util.TreeMap; +/** + * A {@link BasicMultiMap} that also keeps a comment for each key. + * + *

The comments are kept in a separate map and are removed together with the key by {@link + * #remove(Object)}, by {@link #remove(Object, int)} when it removes the last value of the key, and + * by {@link #clear()}. A key removed in another way, for example through {@link #keySet()}, keeps + * its comment. Adding or replacing values does not change comments. + * + *

{@link #putAll(Map)} from another {@code CommonMultiMap} also copies all the per-key data of + * that map, which are its comments and, for a {@link Registry.Key}, the types of its values. + * + * @param the type of the keys + * @param the type of the values + * @see CommentedMap + * @since 0.5.0 + */ public class CommonMultiMap extends BasicMultiMap implements CommentedMap { private static final long serialVersionUID = 3012579878005541746L; private static final String SEPARATOR = ";#;"; From 7bb45e7cfbcfd2a19c1fdfc6981f1fee7a832f6e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Iv=C3=A1n=20SZKIBA?= Date: Mon, 16 Nov 2026 09:13:52 +0100 Subject: [PATCH 4/9] docs: document the user-facing classes Ini, Wini, Options, Reg, ConfigParser and the java.util.prefs classes had no type docs. This adds them, with the encoding and byte order mark rules and the Windows-only registry methods. The old IniPreferences text said childSpi and childrenNamesSpi were unsupported, which the code contradicts, so it is rewritten, and its typos and the broken @parem tag are fixed. Refs: #13 --- src/main/java/org/ini4j/ConfigParser.java | 349 ++++++++++++++++++ src/main/java/org/ini4j/Ini.java | 95 +++++ src/main/java/org/ini4j/IniPreferences.java | 280 +++++++------- .../java/org/ini4j/IniPreferencesFactory.java | 66 ++++ src/main/java/org/ini4j/Options.java | 91 +++++ src/main/java/org/ini4j/Reg.java | 116 ++++++ src/main/java/org/ini4j/Wini.java | 79 ++++ 7 files changed, 930 insertions(+), 146 deletions(-) diff --git a/src/main/java/org/ini4j/ConfigParser.java b/src/main/java/org/ini4j/ConfigParser.java index 0f4a74d..93eb4f4 100644 --- a/src/main/java/org/ini4j/ConfigParser.java +++ b/src/main/java/org/ini4j/ConfigParser.java @@ -35,19 +35,70 @@ import org.ini4j.spi.IniHandler; import org.ini4j.spi.Warnings; +/** + * A reader and writer for INI files that follows the API of the Python {@code ConfigParser} module. + * + *

It is meant for code that is ported from Python, or that wants methods such as {@link + * #getInt(String, String)} and {@link #items(String)}. The class is built on an {@link Ini} with + * its own configuration (a copy of the global one), in which escaping is off, the options of a + * repeated section name are added to the existing section, a repeated option replaces the earlier + * value, and the names of sections and options are converted to lower case when a file is read. + * Names given to the methods are not converted, so use lower case names to find what was read. + * + *

A section named {@code DEFAULT} (in any letter case) is not a normal section. It does not show + * up in {@link #sections()}, and {@link #hasSection(String)} is {@code false} for it. Its options + * are used only to fill in the references of a value. + * + *

A value can refer to other options with {@code %(name)}. It is replaced by the value of {@code + * name} in the same section, or, when there is no such option, in the {@code variables} map of the + * call, in the map given to the constructor, or in the {@code DEFAULT} section, in this order. A + * reference to a name that none of them has throws an {@link InterpolationMissingOptionException}. + * A percent sign preceded by a backslash is not a reference, and the backslash stays in the value. + * Unlike in Python, the reference has no trailing {@code s}. A value that refers to itself, + * directly or through other options, is not detected: the call does not return. + * + *

The thread safety of {@link BasicMultiMap} applies. + * + * @see Ini + * @since 0.5.0 + */ public class ConfigParser implements Serializable { private static final long serialVersionUID = 9118857036229164353L; private PyIni _ini; + /** Creates a parser with no default values. */ @SuppressWarnings(Warnings.UNCHECKED) public ConfigParser() { this(Collections.EMPTY_MAP); } + /** + * Creates a parser with default values. + * + *

The map is used as it is, not copied. It supplies values for references in the options (see + * the description of this class); it does not add options to the sections. + * + * @param defaults the default values for references, by option name + */ public ConfigParser(Map defaults) { _ini = new PyIni(defaults); } + /** + * Returns the value of an option as a boolean, with references resolved. + * + *

The values {@code 1}, {@code yes}, {@code true} and {@code on} give {@code true}, and {@code + * 0}, {@code no}, {@code false} and {@code off} give {@code false}, in any letter case. + * + * @param section the section name + * @param option the option name + * @return the value as a boolean + * @throws NoSectionException if the section does not exist + * @throws NoOptionException if the section has no such option + * @throws InterpolationException if a reference in the value cannot be resolved + * @throws IllegalArgumentException if the value is none of the accepted words; the message is the + * value + */ public boolean getBoolean(String section, String option) throws NoSectionException, NoOptionException, InterpolationException { boolean ret; @@ -70,26 +121,77 @@ public boolean getBoolean(String section, String option) return ret; } + /** + * Returns the value of an option as a {@code double}, with references resolved. + * + * @param section the section name + * @param option the option name + * @return the value as a number + * @throws NoSectionException if the section does not exist + * @throws NoOptionException if the section has no such option + * @throws InterpolationException if a reference in the value cannot be resolved + * @throws NumberFormatException if the value is not a number + */ public double getDouble(String section, String option) throws NoSectionException, NoOptionException, InterpolationException { return Double.parseDouble(get(section, option)); } + /** + * Returns the value of an option as a {@code float}, with references resolved. + * + * @param section the section name + * @param option the option name + * @return the value as a number + * @throws NoSectionException if the section does not exist + * @throws NoOptionException if the section has no such option + * @throws InterpolationException if a reference in the value cannot be resolved + * @throws NumberFormatException if the value is not a number + */ public float getFloat(String section, String option) throws NoSectionException, NoOptionException, InterpolationException { return Float.parseFloat(get(section, option)); } + /** + * Returns the value of an option as an {@code int}, with references resolved. + * + * @param section the section name + * @param option the option name + * @return the value as a number + * @throws NoSectionException if the section does not exist + * @throws NoOptionException if the section has no such option + * @throws InterpolationException if a reference in the value cannot be resolved + * @throws NumberFormatException if the value is not an integer + */ public int getInt(String section, String option) throws NoSectionException, NoOptionException, InterpolationException { return Integer.parseInt(get(section, option)); } + /** + * Returns the value of an option as a {@code long}, with references resolved. + * + * @param section the section name + * @param option the option name + * @return the value as a number + * @throws NoSectionException if the section does not exist + * @throws NoOptionException if the section has no such option + * @throws InterpolationException if a reference in the value cannot be resolved + * @throws NumberFormatException if the value is not an integer + */ public long getLong(String section, String option) throws NoSectionException, NoOptionException, InterpolationException { return Long.parseLong(get(section, option)); } + /** + * Adds an empty section. + * + * @param section the section name, used as it is + * @throws DuplicateSectionException if a section with this name exists already + * @throws IllegalArgumentException if the name is {@code DEFAULT} in any letter case + */ public void addSection(String section) throws DuplicateSectionException { if (_ini.containsKey(section)) { throw new DuplicateSectionException(section); @@ -100,22 +202,60 @@ public void addSection(String section) throws DuplicateSectionException { _ini.add(section); } + /** + * Returns the default values given to the constructor. + * + * @return the map, not a copy + */ public Map defaults() { return _ini.getDefaults(); } + /** + * Returns the value of an option, with references resolved. + * + * @param section the section name + * @param option the option name + * @return the value + * @throws NoSectionException if the section does not exist + * @throws NoOptionException if the section has no such option + * @throws InterpolationException if a reference in the value cannot be resolved + */ @SuppressWarnings(Warnings.UNCHECKED) public String get(String section, String option) throws NoSectionException, NoOptionException, InterpolationException { return get(section, option, false, Collections.EMPTY_MAP); } + /** + * Returns the value of an option, with references resolved only if asked. + * + * @param section the section name + * @param option the option name + * @param raw if {@code true}, the value is returned as stored, with the references in it + * @return the value + * @throws NoSectionException if the section does not exist + * @throws NoOptionException if the section has no such option + * @throws InterpolationException if a reference in the value cannot be resolved + */ @SuppressWarnings(Warnings.UNCHECKED) public String get(String section, String option, boolean raw) throws NoSectionException, NoOptionException, InterpolationException { return get(section, option, raw, Collections.EMPTY_MAP); } + /** + * Returns the value of an option, with references resolved only if asked, using extra variables. + * + * @param sectionName the section name + * @param optionName the option name + * @param raw if {@code true}, the value is returned as stored, with the references in it + * @param variables values for references that the section does not have, by option name + * @return the value + * @throws NoSectionException if the section does not exist + * @throws NoOptionException if the section has no such option + * @throws InterpolationException if a reference in the value cannot be resolved + */ public String get( String sectionName, String optionName, boolean raw, Map variables) throws NoSectionException, NoOptionException, InterpolationException { @@ -128,28 +268,70 @@ public String get( return value; } + /** + * Tells whether a section has an option. + * + * @param sectionName the section name + * @param optionName the option name + * @return {@code true} if the section exists and has the option + */ public boolean hasOption(String sectionName, String optionName) { Ini.Section section = _ini.get(sectionName); return (section != null) && section.containsKey(optionName); } + /** + * Tells whether a section exists. + * + * @param sectionName the section name + * @return {@code true} if there is such a section; always {@code false} for {@code DEFAULT} + */ public boolean hasSection(String sectionName) { return _ini.containsKey(sectionName); } + /** + * Returns the options of a section with their values, with references resolved. + * + * @param sectionName the section name + * @return a new list of entries, in no particular order + * @throws NoSectionException if the section does not exist + * @throws InterpolationMissingOptionException if a reference in a value cannot be resolved + */ @SuppressWarnings(Warnings.UNCHECKED) public List> items(String sectionName) throws NoSectionException, InterpolationMissingOptionException { return items(sectionName, false, Collections.EMPTY_MAP); } + /** + * Returns the options of a section with their values, with references resolved only if asked. + * + * @param sectionName the section name + * @param raw if {@code true}, the values are returned as stored + * @return a new list of entries, in no particular order + * @throws NoSectionException if the section does not exist + * @throws InterpolationMissingOptionException if a reference in a value cannot be resolved + */ @SuppressWarnings(Warnings.UNCHECKED) public List> items(String sectionName, boolean raw) throws NoSectionException, InterpolationMissingOptionException { return items(sectionName, raw, Collections.EMPTY_MAP); } + /** + * Returns the options of a section with their values, using extra variables. + * + *

Changing an entry of the returned list does not change the parser. + * + * @param sectionName the section name + * @param raw if {@code true}, the values are returned as stored + * @param variables values for references that the section does not have, by option name + * @return a new list of entries, in no particular order + * @throws NoSectionException if the section does not exist + * @throws InterpolationMissingOptionException if a reference in a value cannot be resolved + */ public List> items( String sectionName, boolean raw, Map variables) throws NoSectionException, InterpolationMissingOptionException { @@ -168,18 +350,44 @@ public List> items( return new ArrayList>(ret.entrySet()); } + /** + * Returns the option names of a section. + * + * @param sectionName the section name + * @return a new list of names, in the order of the section + * @throws NoSectionException if the section does not exist + */ public List options(String sectionName) throws NoSectionException { requireSection(sectionName); return new ArrayList(_ini.get(sectionName).keySet()); } + /** + * Reads files. + * + *

The files are read one after the other with {@link #read(File)}. A later file adds to what + * was read before and replaces options that are in both. + * + * @param filenames the names of the files + * @throws IOException if a file cannot be read + * @throws ParsingException if a file is not valid + */ public void read(String... filenames) throws IOException, ParsingException { for (String filename : filenames) { read(new File(filename)); } } + /** + * Reads from a reader. + * + *

The content is added to what the parser holds, and replaces options that are in both. + * + * @param reader the reader to read + * @throws IOException if reading fails + * @throws ParsingException if the content is not valid + */ public void read(Reader reader) throws IOException, ParsingException { try { _ini.load(reader); @@ -188,6 +396,16 @@ public void read(Reader reader) throws IOException, ParsingException { } } + /** + * Reads from a URL. + * + *

The content is decoded with the file encoding that the global configuration had when this + * parser was created, unless a byte order mark at the start says otherwise. + * + * @param url the location to read + * @throws IOException if reading fails + * @throws ParsingException if the content is not valid + */ public void read(URL url) throws IOException, ParsingException { try { _ini.load(url); @@ -196,6 +414,16 @@ public void read(URL url) throws IOException, ParsingException { } } + /** + * Reads a file. + * + *

The file is decoded with the file encoding of {@link Config#getGlobal()} at the time of the + * call. A byte order mark is not detected. + * + * @param file the file to read + * @throws IOException if the file cannot be read + * @throws ParsingException if the content is not valid + */ public void read(File file) throws IOException, ParsingException { try { FileReader reader = new FileReader(file, Config.getGlobal().getFileEncoding()); @@ -209,6 +437,16 @@ public void read(File file) throws IOException, ParsingException { } } + /** + * Reads from a stream. + * + *

The content is decoded with the file encoding that the global configuration had when this + * parser was created. A byte order mark is not detected. + * + * @param stream the stream to read + * @throws IOException if reading fails + * @throws ParsingException if the content is not valid + */ public void read(InputStream stream) throws IOException, ParsingException { try { _ini.load(stream); @@ -217,6 +455,14 @@ public void read(InputStream stream) throws IOException, ParsingException { } } + /** + * Removes an option from a section. + * + * @param sectionName the section name + * @param optionName the option name + * @return {@code true} if the option existed + * @throws NoSectionException if the section does not exist + */ public boolean removeOption(String sectionName, String optionName) throws NoSectionException { Ini.Section section = requireSection(sectionName); boolean ret = section.containsKey(optionName); @@ -226,6 +472,12 @@ public boolean removeOption(String sectionName, String optionName) throws NoSect return ret; } + /** + * Removes a section. + * + * @param sectionName the section name + * @return {@code true} if the section existed + */ public boolean removeSection(String sectionName) { boolean ret = _ini.containsKey(sectionName); @@ -234,10 +486,26 @@ public boolean removeSection(String sectionName) { return ret; } + /** + * Returns the section names. + * + * @return a new list of names, in the order of the sections, without {@code DEFAULT} + */ public List sections() { return new ArrayList(_ini.keySet()); } + /** + * Sets the value of an option. + * + *

The option name is used as it is, not converted to lower case. + * + * @param sectionName the section name + * @param optionName the option name + * @param value the new value, stored as {@link Object#toString()}; with {@code null} the option + * is removed + * @throws NoSectionException if the section does not exist + */ public void set(String sectionName, String optionName, Object value) throws NoSectionException { Ini.Section section = requireSection(sectionName); @@ -248,14 +516,40 @@ public void set(String sectionName, String optionName, Object value) throws NoSe } } + /** + * Writes the sections and options. + * + *

The {@code DEFAULT} section comes first. Comments are not written. + * + * @param writer the writer to write + * @throws IOException if writing fails + */ public void write(Writer writer) throws IOException { _ini.store(writer); } + /** + * Writes the sections and options to a stream. + * + *

The content is the same as in {@link #write(Writer)}. It is encoded with the file encoding + * that the global configuration had when this parser was created. + * + * @param stream the stream to write + * @throws IOException if writing fails + */ public void write(OutputStream stream) throws IOException { _ini.store(stream); } + /** + * Writes the sections and options to a file. + * + *

The content is the same as in {@link #write(Writer)}. The file is created or overwritten, + * and encoded with the file encoding of {@link Config#getGlobal()}. + * + * @param file the file to write + * @throws IOException if the file cannot be written + */ public void write(File file) throws IOException { FileWriter writer = new FileWriter(file, Config.getGlobal().getFileEncoding()); try { @@ -265,6 +559,11 @@ public void write(File file) throws IOException { } } + /** + * Returns the underlying {@link Ini}. + * + * @return the object that holds the sections and options + */ protected Ini getIni() { return _ini; } @@ -291,16 +590,32 @@ private Ini.Section requireSection(String sectionName) throws NoSectionException return section; } + /** + * The base class of the checked exceptions of {@link ConfigParser}. + * + * @since 0.5.0 + */ public static class ConfigParserException extends Exception { /** Use serialVersionUID for interoperability. */ private static final long serialVersionUID = -6845546313519392093L; + /** + * Creates an exception with a detail message. + * + * @param message the detail message + */ public ConfigParserException(String message) { super(message); } } + /** + * Signals that {@link ConfigParser#addSection(String)} was called for a section that exists. The + * message is the section name. + * + * @since 0.5.0 + */ public static final class DuplicateSectionException extends ConfigParserException { /** Use serialVersionUID for interoperability. */ @@ -311,16 +626,32 @@ private DuplicateSectionException(String message) { } } + /** + * The base class of the exceptions for a value that refers to other options. + * + * @since 0.5.0 + */ public static class InterpolationException extends ConfigParserException { /** Use serialVersionUID for interoperability. */ private static final long serialVersionUID = 8924443303158546939L; + /** + * Creates an exception with a detail message. + * + * @param message the detail message + */ protected InterpolationException(String message) { super(message); } } + /** + * Signals that a reference in a value names an option that cannot be found. The message is the + * option name. + * + * @since 0.5.0 + */ public static final class InterpolationMissingOptionException extends InterpolationException { /** Use serialVersionUID for interoperability. */ @@ -331,6 +662,11 @@ private InterpolationMissingOptionException(String message) { } } + /** + * Signals that a section has no option of the requested name. The message is the option name. + * + * @since 0.5.0 + */ public static final class NoOptionException extends ConfigParserException { /** Use serialVersionUID for interoperability. */ @@ -341,6 +677,11 @@ private NoOptionException(String message) { } } + /** + * Signals that there is no section of the requested name. The message is the section name. + * + * @since 0.5.0 + */ public static final class NoSectionException extends ConfigParserException { /** Use serialVersionUID for interoperability. */ @@ -351,6 +692,14 @@ private NoSectionException(String message) { } } + /** + * Signals that a file read by a {@link ConfigParser} is not valid. + * + *

The message and the cause are those of the {@link InvalidFileFormatException} that the + * parser raised. + * + * @since 0.5.0 + */ public static final class ParsingException extends IOException { /** Use serialVersionUID for interoperability. */ diff --git a/src/main/java/org/ini4j/Ini.java b/src/main/java/org/ini4j/Ini.java index f39812b..3f12e70 100755 --- a/src/main/java/org/ini4j/Ini.java +++ b/src/main/java/org/ini4j/Ini.java @@ -31,31 +31,98 @@ import org.ini4j.spi.IniHandler; import org.ini4j.spi.IniParser; +/** + * An INI file in memory: a {@link Profile} that can be loaded from and stored to a file. + * + *

An {@code Ini} holds named sections, each with options. A section name can be used more than + * once and an option can have several values (see {@link MultiMap} and the flags {@link + * Config#isMultiSection()} and {@link Config#isMultiOption()}). Values can contain variables, + * comments are kept, and the sections can be read as a tree or through your own interfaces (see + * {@link Profile}). + * + *

A new {@code Ini} uses the global {@link Config} itself, not a copy (see {@link + * Config#getGlobal()}). Call {@link #setConfig(Config)} to give it its own. Loading and storing go + * through {@link org.ini4j.spi.IniParser} and {@link org.ini4j.spi.IniFormatter}, with the + * configuration of this object. {@code load} adds to the existing content, as described in {@link + * Persistable}. + * + *

The methods that read or write a stream use the file encoding of the configuration. When a + * file or a URL is loaded, a byte order mark at the start of the input takes precedence over it. + * When an {@link java.io.InputStream} is loaded, there is no such detection. + * + *

This reads two options and writes a new section: + * + *

{@code
+ * Ini ini = new Ini(new File("dwarfs.ini"));
+ * int age = ini.get("happy", "age", int.class);
+ * String dir = ini.get("happy", "homeDir");
+ *
+ * ini.put("sleepy", "age", 55);
+ * ini.store();
+ * }
+ * + *

The thread safety of {@link BasicMultiMap} applies. + * + * @see Wini + * @see Options + * @since 0.3.0 + */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({"CT_CONSTRUCTOR_THROW", "EI_EXPOSE_REP"}) public class Ini extends BasicProfile implements Persistable, Configurable { private static final long serialVersionUID = -6029486578113700585L; private Config _config; private File _file; + /** Creates an empty {@code Ini} that uses the global {@link Config}. */ public Ini() { _config = Config.getGlobal(); } + /** + * Creates an {@code Ini} and loads it from a reader. + * + * @param input the reader to read + * @throws IOException if reading fails + * @throws InvalidFileFormatException if the content is not valid + */ public Ini(Reader input) throws IOException, InvalidFileFormatException { this(); load(input); } + /** + * Creates an {@code Ini} and loads it from a stream. + * + * @param input the stream to read + * @throws IOException if reading fails + * @throws InvalidFileFormatException if the content is not valid + */ public Ini(InputStream input) throws IOException, InvalidFileFormatException { this(); load(input); } + /** + * Creates an {@code Ini} and loads it from a URL. + * + * @param input the location to read + * @throws IOException if reading fails + * @throws InvalidFileFormatException if the content is not valid + */ public Ini(URL input) throws IOException, InvalidFileFormatException { this(); load(input); } + /** + * Creates an {@code Ini}, remembers the file and loads it. + * + *

The file stays the associated file, so {@link #store()} writes back to it. + * + * @param input the file to read and later to write + * @throws IOException if reading fails + * @throws InvalidFileFormatException if the content is not valid + */ public Ini(File input) throws IOException, InvalidFileFormatException { this(); _file = input; @@ -141,10 +208,27 @@ public void store(File output) throws IOException { } } + /** + * Creates the handler that builds this object while a file is parsed. + * + *

A subclass can override it to change how the parsed events are turned into sections and + * options. + * + * @return a new builder for this object + */ protected IniHandler newBuilder() { return IniBuilder.newInstance(this); } + /** + * Sends a section to a formatter, unless it is left out. + * + *

A section without options is left out when {@link Config#isEmptySection()} is off. A + * subclass can override this method to change what is stored. + * + * @param formatter the handler that receives the events + * @param section the section to send + */ @Override protected void store(IniHandler formatter, Profile.Section section) { if (getConfig().isEmptySection() || (section.size() != 0)) { @@ -152,6 +236,17 @@ protected void store(IniHandler formatter, Profile.Section section) { } } + /** + * Sends one value of an option to a formatter, unless it is left out. + * + *

When {@link Config#isMultiOption()} is off, only the last value of an option is sent. A + * subclass can override this method to change what is stored. + * + * @param formatter the handler that receives the events + * @param section the section of the option + * @param option the option name + * @param index the position of the value + */ @Override protected void store(IniHandler formatter, Profile.Section section, String option, int index) { if (getConfig().isMultiOption() || (index == (section.length(option) - 1))) { diff --git a/src/main/java/org/ini4j/IniPreferences.java b/src/main/java/org/ini4j/IniPreferences.java index c7d8f5f..7f2294d 100755 --- a/src/main/java/org/ini4j/IniPreferences.java +++ b/src/main/java/org/ini4j/IniPreferences.java @@ -24,19 +24,51 @@ import java.util.prefs.AbstractPreferences; import java.util.prefs.BackingStoreException; +/** + * A {@link java.util.prefs.Preferences} tree on top of an {@link Ini}. + * + *

The root node is the {@code Ini} itself. Its child nodes are the sections, and the keys of a + * section node are its options. A section named {@code a/b} (with the default path separator) is + * the child {@code b} of the section {@code a}. The root node has no keys: {@code put} and {@code + * remove} throw an {@link UnsupportedOperationException}, and {@code get} returns the default + * value. + * + *

Asking for a node that does not exist creates the section in the {@code Ini} at once. All + * changes stay in memory: {@code flush} and {@code sync} do nothing, so nothing is written to a + * file. To keep the changes, store the {@code Ini}, which you hold if you created this object with + * {@link #IniPreferences(Ini)}. + * + *

The nodes use the locking of {@link java.util.prefs.AbstractPreferences}. The {@link Ini} + * itself is not synchronized. + * + *

This example reads and changes a value: + * + *

{@code
+ * Ini ini = new Ini(new File("dwarfs.ini"));
+ * Preferences prefs = new IniPreferences(ini);
+ * Preferences bashful = prefs.node("bashful");
+ *
+ * int age = bashful.getInt("age", -1);
+ * bashful.putDouble("weight", 55.6);
+ * ini.store();
+ * }
+ * + * @see IniPreferencesFactory + * @since 0.3.0 + */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings("EI_EXPOSE_REP") public class IniPreferences extends AbstractPreferences { - /** frequently used empty String array */ + /** A shared empty array of strings. */ private static final String[] EMPTY = {}; - /** underlaying Ini implementation */ + /** The {@code Ini} that holds the data. */ private final Ini _ini; /** - * Constructs a new preferences node on top of Ini instance. + * Creates the root node on top of an {@link Ini}. * - * @param ini underlaying Ini instance + * @param ini the {@code Ini} that holds the data; it is used directly, not copied */ public IniPreferences(Ini ini) { super(null, ""); @@ -44,14 +76,11 @@ public IniPreferences(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. + * Creates the root node on top of a new {@link Ini} that is loaded from a reader. * - * @param input the Reader containing Ini data - * @throws IOException if an I/O error occured - * @throws InvalidFileFormatException if Ini parsing error occured + * @param input the reader that provides the INI data + * @throws IOException if reading fails + * @throws InvalidFileFormatException if the data is not valid */ public IniPreferences(Reader input) throws IOException, InvalidFileFormatException { super(null, ""); @@ -59,14 +88,11 @@ public IniPreferences(Reader input) throws IOException, InvalidFileFormatExcepti } /** - * Constructs a new preferences node based on newly loaded Ini instance. + * Creates the root node on top of a new {@link Ini} that is loaded from a stream. * - *

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 + * @param input the stream that provides the INI data + * @throws IOException if reading fails + * @throws InvalidFileFormatException if the data is not valid */ public IniPreferences(InputStream input) throws IOException, InvalidFileFormatException { super(null, ""); @@ -74,14 +100,11 @@ public IniPreferences(InputStream input) throws IOException, InvalidFileFormatEx } /** - * 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. + * Creates the root node on top of a new {@link Ini} that is loaded from a URL. * - * @param input the URL containing Ini data - * @throws IOException if an I/O error occured - * @throws InvalidFileFormatException if Ini parsing error occured + * @param input the location of the INI data + * @throws IOException if reading fails + * @throws InvalidFileFormatException if the data is not valid */ public IniPreferences(URL input) throws IOException, InvalidFileFormatException { super(null, ""); @@ -89,25 +112,23 @@ public IniPreferences(URL input) throws IOException, InvalidFileFormatException } /** - * Provide access to underlaying {@link org.ini4j.Ini} implementation. + * Returns the {@link Ini} that holds the data. * - * @return Ini implementation + * @return the {@code Ini}, not a copy */ protected Ini getIni() { return _ini; } /** - * Implements the getSpi method as per the specification in {@link - * java.util.prefs.AbstractPreferences#getSpi(String)}. + * Not supported. The root node has no keys. * - *

This implementation doesn't support this operation, so allways throws - * UnsupportedOperationException. + *

{@link java.util.prefs.Preferences#get(String, String)} catches the exception, so it returns + * the default value for every key of the root node. * - * @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 + * @param key the key + * @return nothing, the method always throws + * @throws UnsupportedOperationException always */ @Override protected String getSpi(String key) throws UnsupportedOperationException { @@ -115,12 +136,14 @@ protected String getSpi(String key) throws UnsupportedOperationException { } /** - * Implements the childrenNamesSpi method as per the specification in {@link - * java.util.prefs.AbstractPreferences#childrenNamesSpi()}. + * Returns the names of the child nodes, which are the sections that are not below another + * section. * - * @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. + *

A section is below another one if its name contains the path separator of the {@link Config} + * of the {@link Ini}. + * + * @return the names of the top level sections + * @throws BackingStoreException never thrown by this implementation */ @Override protected String[] childrenNamesSpi() throws BackingStoreException { @@ -136,11 +159,13 @@ protected String[] childrenNamesSpi() throws BackingStoreException { } /** - * Implements the childSpi method as per the specification in {@link - * java.util.prefs.AbstractPreferences#childSpi(String)}. + * Returns the child node for a section. + * + *

If the {@link Ini} has no such section yet, it is added at once, and the node is reported as + * new. * - * @param name child name - * @return child node + * @param name the name of the section + * @return the node of the section */ @Override protected SectionPreferences childSpi(String name) { @@ -155,13 +180,9 @@ protected SectionPreferences childSpi(String name) { } /** - * Implements the flushSpi method as per the specification in {@link - * java.util.prefs.AbstractPreferences#flushSpi()}. - * - *

This implementation does nothing. + * Does nothing. The changes stay in the {@link Ini} in memory and are not written anywhere. * - * @throws BackingStoreException if this operation cannot be completed due to a failure in the - * backing store, or inability to communicate with it. + * @throws BackingStoreException never thrown by this implementation */ @Override protected void flushSpi() throws BackingStoreException { @@ -169,14 +190,10 @@ protected void flushSpi() throws BackingStoreException { } /** - * Implements the keysSpi method as per the specification in {@link - * java.util.prefs.AbstractPreferences#keysSpi()}. + * Returns no keys. The root node has no keys. * - *

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. + * @return an empty array + * @throws BackingStoreException never thrown by this implementation */ @Override protected String[] keysSpi() throws BackingStoreException { @@ -184,15 +201,11 @@ protected String[] keysSpi() throws BackingStoreException { } /** - * 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. + * Not supported. The root node has no keys. * - * @param key key to set value for - * @param value new value for key - * @throws UnsupportedOperationException this implementation allways throws this exception + * @param key the key + * @param value the value + * @throws UnsupportedOperationException always */ @Override protected void putSpi(String key, String value) throws UnsupportedOperationException { @@ -200,14 +213,10 @@ protected void putSpi(String key, String value) throws UnsupportedOperationExcep } /** - * Implements the removeNodeSpi method as per the specification in {@link - * java.util.prefs.AbstractPreferences#removeNodeSpi()}. + * Not supported. The root node cannot be removed. * - *

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 UnsupportedOperationException always + * @throws BackingStoreException never thrown by this implementation */ @Override protected void removeNodeSpi() throws BackingStoreException, UnsupportedOperationException { @@ -215,11 +224,10 @@ protected void removeNodeSpi() throws BackingStoreException, UnsupportedOperatio } /** - * Implements the removeSpi method as per the specification in {@link - * java.util.prefs.AbstractPreferences#removeSpi(String)}. + * Not supported. The root node has no keys. * - * @param key key to remove - * @throws UnsupportedOperationException this implementation allways throws this exception + * @param key the key + * @throws UnsupportedOperationException always */ @Override protected void removeSpi(String key) throws UnsupportedOperationException { @@ -227,30 +235,37 @@ protected void removeSpi(String key) throws UnsupportedOperationException { } /** - * Implements the syncSpi method as per the specification in {@link - * java.util.prefs.AbstractPreferences#syncSpi()}. - * - *

This implementation does nothing. + * Does nothing. The data is not read again from anywhere. * - * @throws BackingStoreException if this operation cannot be completed due to a failure in the - * backing store, or inability to communicate with it. + * @throws BackingStoreException never thrown by this implementation */ @Override protected void syncSpi() throws BackingStoreException { assert true; } + /** + * The node of one section. + * + *

The keys of the node are the option names of the section. {@code get} returns the last value + * of an option with its variables resolved, {@code put} replaces the last value and {@code + * remove} removes all the values. The child nodes are the sections below this one in the section + * tree, and a child that does not exist is added to the {@link Ini} when it is requested. + * Removing the node removes the section from the {@link Ini}. + * + * @since 0.3.0 + */ protected class SectionPreferences extends AbstractPreferences { - /** underlaying Section implementation */ + /** The section of this node. */ private final Ini.Section _section; /** - * Constructs a new SectionPreferences instance on top of Ini.Section instance. + * Creates a node for a section. * - * @param parent parent preferences node - * @parem section underlaying Ini.Section instance - * @param isNew indicate is this a new node or already existing one + * @param parent the parent node + * @param section the section of this node + * @param isNew whether the node is new, which is the case if the section did not exist before */ SectionPreferences(AbstractPreferences parent, Ini.Section section, boolean isNew) { super(parent, section.getSimpleName()); @@ -259,13 +274,9 @@ protected class SectionPreferences extends AbstractPreferences { } /** - * Implements the flush method as per the specification in {@link - * java.util.prefs.Preferences#flush()}. - * - *

This implementation just call parent's flush() method. + * Calls {@code flush()} of the parent node, which 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 never thrown by this implementation */ @Override public void flush() throws BackingStoreException { @@ -273,13 +284,9 @@ public void flush() throws BackingStoreException { } /** - * Implements the sync method as per the specification in {@link - * java.util.prefs.Preferences#sync()}. - * - *

This implementation just call parent's sync() method. + * Calls {@code sync()} of the parent node, which 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 never thrown by this implementation */ @Override public void sync() throws BackingStoreException { @@ -287,13 +294,13 @@ public void sync() throws BackingStoreException { } /** - * Implements the getSpi method as per the specification in {@link - * java.util.prefs.AbstractPreferences#getSpi(String)}. + * Returns the last value of an option, with variables resolved. * - * @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 + * @param key the option name + * @return the value, or {@code null} if the section has no such option + * @throws CircularReferenceException if the variables are nested deeper than {@link + * Config#getMaxResolveDepth()}; {@link java.util.prefs.Preferences#get(String, String)} + * catches it and returns the default value */ @Override protected String getSpi(String key) { @@ -301,14 +308,10 @@ protected String getSpi(String key) { } /** - * Implements the childrenNamesSpi method as per the specification in {@link - * java.util.prefs.AbstractPreferences#childrenNamesSpi()}. + * Returns the names of the child nodes, which are the direct sub-sections of the section. * - *

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. + * @return the names of the sub-sections, relative to this section + * @throws BackingStoreException never thrown by this implementation */ @Override protected String[] childrenNamesSpi() throws BackingStoreException { @@ -316,14 +319,13 @@ protected String[] childrenNamesSpi() throws BackingStoreException { } /** - * Implements the childSpi method as per the specification in {@link - * java.util.prefs.AbstractPreferences#childSpi(String)}. + * Returns the child node for a sub-section. * - *

This implementation doesn't support this operation. + *

If the sub-section does not exist yet, it is added to the {@link Ini} at once, and the + * node is reported as new. * - * @throws UnsupportedOperationException this implementation allways throws this exception - * @param name child name - * @return child node + * @param name the name of the sub-section, relative to this section + * @return the node of the sub-section */ @Override protected SectionPreferences childSpi(String name) throws UnsupportedOperationException { @@ -338,13 +340,9 @@ protected SectionPreferences childSpi(String name) throws UnsupportedOperationEx } /** - * Implements the flushSpi method as per the specification in {@link - * java.util.prefs.AbstractPreferences#flushSpi()}. - * - *

This implementation does nothing. + * Does nothing. The changes stay in the {@link Ini} in memory and are not written anywhere. * - * @throws BackingStoreException if this operation cannot be completed due to a failure in the - * backing store, or inability to communicate with it. + * @throws BackingStoreException never thrown by this implementation */ @Override protected void flushSpi() throws BackingStoreException { @@ -352,12 +350,10 @@ protected void flushSpi() throws BackingStoreException { } /** - * Implements the keysSpi method as per the specification in {@link - * java.util.prefs.AbstractPreferences#keysSpi()}. + * Returns the keys of the node. * - * @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. + * @return the option names of the section + * @throws BackingStoreException never thrown by this implementation */ @Override protected String[] keysSpi() throws BackingStoreException { @@ -365,11 +361,10 @@ protected String[] keysSpi() throws BackingStoreException { } /** - * Implements the putSpi method as per the specification in {@link - * java.util.prefs.AbstractPreferences#putSpi(String,String)}. + * Replaces the last value of an option, or adds the option. * - * @param key key to set value for - * @param value new value of key + * @param key the option name + * @param value the new value */ @Override protected void putSpi(String key, String value) { @@ -377,11 +372,9 @@ protected void putSpi(String key, String value) { } /** - * Implements the removeNodeSpi method as per the specification in {@link - * java.util.prefs.AbstractPreferences#removeNodeSpi()}. + * Removes the sections that have the name of this node from the {@link Ini}. * - * @throws BackingStoreException if this operation cannot be completed due to a failure in the - * backing store, or inability to communicate with it. + * @throws BackingStoreException never thrown by this implementation */ @Override protected void removeNodeSpi() throws BackingStoreException { @@ -389,10 +382,9 @@ protected void removeNodeSpi() throws BackingStoreException { } /** - * Implements the removeSpi method as per the specification in {@link - * java.util.prefs.AbstractPreferences#removeSpi(String)}. + * Removes all the values of an option. * - * @param key key to remove + * @param key the option name */ @Override protected void removeSpi(String key) { @@ -400,13 +392,9 @@ protected void removeSpi(String key) { } /** - * Implements the syncSpi method as per the specification in {@link - * java.util.prefs.AbstractPreferences#syncSpi()}. - * - *

This implementation does nothing. + * Does nothing. The data is not read again from anywhere. * - * @throws BackingStoreException if this operation cannot be completed due to a failure in the - * backing store, or inability to communicate with it. + * @throws BackingStoreException never thrown by this implementation */ @Override protected void syncSpi() throws BackingStoreException { diff --git a/src/main/java/org/ini4j/IniPreferencesFactory.java b/src/main/java/org/ini4j/IniPreferencesFactory.java index 6f32e84..7e35542 100755 --- a/src/main/java/org/ini4j/IniPreferencesFactory.java +++ b/src/main/java/org/ini4j/IniPreferencesFactory.java @@ -22,14 +22,71 @@ import java.util.prefs.Preferences; import java.util.prefs.PreferencesFactory; +/** + * A {@link PreferencesFactory} that serves the {@code java.util.prefs} API from INI files. + * + *

The user root and the system root are two separate {@link IniPreferences} trees. Each is built + * from an {@link Ini} loaded from a location that is read from the system property {@link + * #KEY_USER} or {@link #KEY_SYSTEM}. If the property is not set, the same key is looked up in the + * file {@link #PROPERTIES}, which is searched on the class path with the context class loader of + * the calling thread. If there is no location, the tree starts empty. + * + *

A location with a scheme, such as {@code file:/etc/app.ini}, is used as a URL. A location + * without a scheme is the name of a resource on the class path. A location that cannot be read + * throws an {@link IllegalArgumentException} when the root is first requested. The changes made + * through the preferences stay in memory, because {@code flush} and {@code sync} do not write + * anything (see {@link IniPreferences}). + * + *

To let {@link Preferences#userRoot()} use it, name the class in the system property {@code + * java.util.prefs.PreferencesFactory} before the preferences API is used for the first time, + * because the factory is chosen only once: + * + *

{@code
+ * System.setProperty("java.util.prefs.PreferencesFactory", "org.ini4j.IniPreferencesFactory");
+ * System.setProperty("org.ini4j.prefs.user", "file:/home/joe/app.ini");
+ *
+ * Preferences prefs = Preferences.userRoot().node("happy");
+ * }
+ * + *

Thread safety. {@link #systemRoot()} and {@link #userRoot()} are + * synchronized. Each root is created on the first call and every later call returns the same + * object. + * + * @see IniPreferences + * @since 0.3.0 + */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings("EI_EXPOSE_REP") public class IniPreferencesFactory implements PreferencesFactory { + /** + * The name of the class path resource that can hold the locations, as a properties file with the + * keys {@link #KEY_USER} and {@link #KEY_SYSTEM}. + */ public static final String PROPERTIES = "ini4j.properties"; + + /** + * The key of the location of the user preferences, used as a system property and as a key in + * {@link #PROPERTIES}. + */ public static final String KEY_USER = "org.ini4j.prefs.user"; + + /** + * The key of the location of the system preferences, used as a system property and as a key in + * {@link #PROPERTIES}. + */ public static final String KEY_SYSTEM = "org.ini4j.prefs.system"; + private Preferences _system; private Preferences _user; + /** + * Returns the root of the system preferences. + * + *

The root is created on the first call, from the location named by {@link #KEY_SYSTEM}. + * + * @return the same root on every call + * @throws IllegalArgumentException if the location cannot be read or is not valid on the first + * call + */ @Override public synchronized Preferences systemRoot() { if (_system == null) { @@ -39,6 +96,15 @@ public synchronized Preferences systemRoot() { return _system; } + /** + * Returns the root of the user preferences. + * + *

The root is created on the first call, from the location named by {@link #KEY_USER}. + * + * @return the same root on every call + * @throws IllegalArgumentException if the location cannot be read or is not valid on the first + * call + */ @Override public synchronized Preferences userRoot() { if (_user == null) { diff --git a/src/main/java/org/ini4j/Options.java b/src/main/java/org/ini4j/Options.java index 9b349fa..0f2fde2 100644 --- a/src/main/java/org/ini4j/Options.java +++ b/src/main/java/org/ini4j/Options.java @@ -31,6 +31,35 @@ import org.ini4j.spi.OptionsHandler; import org.ini4j.spi.OptionsParser; +/** + * An {@link OptionMap} that can be loaded from and stored to a file of options without sections. + * + *

The file has one option on each line, written as {@code name=value} or {@code name:value}. A + * line that starts with {@code !} or {@code #} is a comment. It looks like a Java properties file. + * Unlike a properties file, an option name can have several values, comments are kept, values can + * contain variables (see {@link OptionMap}), and the content can be read through your own + * interfaces. + * + *

A new {@code Options} has its own copy of the global {@link Config}, with {@link + * Config#isEmptyOption()} turned on. The methods that read or write a stream use its file encoding. + * When a file or a URL is loaded, a byte order mark at the start of the input takes precedence over + * it. + * + *

This reads an option and writes the file back: + * + *

{@code
+ * Options opt = new Options(new File("dwarfs.opt"));
+ * String home = opt.get("homeDir");
+ *
+ * opt.put("age", 33);
+ * opt.store();
+ * }
+ * + *

The thread safety of {@link BasicMultiMap} applies. + * + * @see Ini + * @since 0.4.1 + */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({"CT_CONSTRUCTOR_THROW", "EI_EXPOSE_REP"}) public class Options extends BasicOptionMap implements Persistable, Configurable { private static final long serialVersionUID = -1119753444859181822L; @@ -38,36 +67,80 @@ public class Options extends BasicOptionMap implements Persistable, Configurable private Config _config; private File _file; + /** Creates an empty {@code Options} with its own configuration. */ public Options() { _config = Config.getGlobal().clone(); _config.setEmptyOption(true); } + /** + * Creates an {@code Options} and loads it from a reader. + * + * @param input the reader to read + * @throws IOException if reading fails + * @throws InvalidFileFormatException if the content is not valid + */ public Options(Reader input) throws IOException, InvalidFileFormatException { this(); load(input); } + /** + * Creates an {@code Options} and loads it from a stream. + * + * @param input the stream to read + * @throws IOException if reading fails + * @throws InvalidFileFormatException if the content is not valid + */ public Options(InputStream input) throws IOException, InvalidFileFormatException { this(); load(input); } + /** + * Creates an {@code Options} and loads it from a URL. + * + * @param input the location to read + * @throws IOException if reading fails + * @throws InvalidFileFormatException if the content is not valid + */ public Options(URL input) throws IOException, InvalidFileFormatException { this(); load(input); } + /** + * Creates an {@code Options}, remembers the file and loads it. + * + *

The file stays the associated file, so {@link #store()} writes back to it. + * + * @param input the file to read and later to write + * @throws IOException if reading fails + * @throws InvalidFileFormatException if the content is not valid + */ public Options(File input) throws IOException, InvalidFileFormatException { this(); _file = input; load(); } + /** + * Returns the header comment of the options. + * + *

When a file is loaded with {@link Config#isHeaderComment()} and {@link Config#isComment()} + * on, the comment at the top of the file, before the first option, becomes the header comment. + * + * @return the comment, or {@code null} if there is none + */ public String getComment() { return _comment; } + /** + * Sets the header comment of the options. + * + * @param value the new comment, or {@code null} to have none + */ public void setComment(String value) { _comment = value; } @@ -151,10 +224,28 @@ public void store(File output) throws IOException { } } + /** + * Creates the handler that builds this object while a file is parsed. + * + *

A subclass can override it to change how the parsed events are turned into options. + * + * @return a new builder for this object + */ protected OptionsHandler newBuilder() { return OptionsBuilder.newInstance(this); } + /** + * Sends the content to a formatter. + * + *

The handler gets {@link OptionsHandler#startOptions()}, the header comment, then for each + * option its comment and its values, and {@link OptionsHandler#endOptions()}. When {@link + * Config#isMultiOption()} is off, only the first value of each option is sent. A subclass can + * override this method to change what is stored. + * + * @param formatter the handler that receives the events + * @throws IOException if the handler fails + */ protected void store(OptionsHandler formatter) throws IOException { formatter.startOptions(); storeComment(formatter, _comment); diff --git a/src/main/java/org/ini4j/Reg.java b/src/main/java/org/ini4j/Reg.java index d4e75f0..d83a893 100644 --- a/src/main/java/org/ini4j/Reg.java +++ b/src/main/java/org/ini4j/Reg.java @@ -32,11 +32,45 @@ import org.ini4j.spi.IniParser; import org.ini4j.spi.RegBuilder; +/** + * A {@link Registry} that reads and writes Windows registry export files, and on Windows can + * exchange keys with the real registry. + * + *

A {@code .reg} file starts with a version header (see {@link Registry#VERSION}), followed by + * keys written as sections, whose options are the registry values with their types. The model is + * described in {@link Registry}. The load methods require the first line to be the version header, + * and they skip the line after it. + * + *

A new {@code Reg} has its own copy of the global {@link Config} with the settings of this + * format: escaping is off, the global section is off, an option without a value, an option with + * several values and a section without options are allowed, operators are written without spaces, + * the path separator is a backslash ({@link Registry#KEY_SEPARATOR}), the file encoding is {@link + * Registry#FILE_ENCODING} and the line separator is {@link Registry#LINE_SEPARATOR}. + * + *

Only the methods {@link #read(String)}, {@link #write()} and the constructor that takes a key + * name work with the real registry. They run the Windows {@code reg} command, so they are for + * Windows only (see {@link #isWindows()}) and throw an {@link UnsupportedOperationException} + * elsewhere. All the other methods work on every system. + * + *

The thread safety of {@link BasicMultiMap} applies. + * + * @see Registry + * @since 0.5.0 + */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({"CT_CONSTRUCTOR_THROW", "EI_EXPOSE_REP"}) public class Reg extends BasicRegistry implements Persistable, Configurable { private static final long serialVersionUID = -1485602876922985912L; + + /** + * The file name suffix of the temporary files used by {@link #read(String)} and {@link #write()}. + */ protected static final String DEFAULT_SUFFIX = ".reg"; + + /** + * The file name prefix of the temporary files used by {@link #read(String)} and {@link #write()}. + */ 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 = @@ -46,6 +80,10 @@ public class Reg extends BasicRegistry implements Persistable, Configurable { private Config _config; private File _file; + /** + * Creates an empty registry with its own configuration, which has the settings of the registry + * file format. + */ public Reg() { Config cfg = Config.getGlobal().clone(); @@ -61,32 +99,81 @@ public Reg() { _config = cfg; } + /** + * Creates a registry and reads a key of the real registry into it. + * + *

It is the same as {@link #Reg()} followed by {@link #read(String)}. + * + * @param registryKey the path of the key, for example {@code HKEY_CURRENT_USER\Software\ini4j} + * @throws IOException if the {@code reg} command fails + * @throws UnsupportedOperationException if this is not Windows + */ public Reg(String registryKey) throws IOException { this(); read(registryKey); } + /** + * Creates a registry, remembers the file and loads it. + * + * @param input the file to read and later to write + * @throws IOException if reading fails + * @throws InvalidFileFormatException if the version header is missing or unsupported, or the + * content is not valid + */ public Reg(File input) throws IOException, InvalidFileFormatException { this(); _file = input; load(); } + /** + * Creates a registry and loads it from a URL. + * + * @param input the location to read + * @throws IOException if reading fails + * @throws InvalidFileFormatException if the version header is missing or unsupported, or the + * content is not valid + */ public Reg(URL input) throws IOException, InvalidFileFormatException { this(); load(input); } + /** + * Creates a registry and loads it from a stream. + * + * @param input the stream to read + * @throws IOException if reading fails + * @throws InvalidFileFormatException if the version header is missing or unsupported, or the + * content is not valid + */ public Reg(InputStream input) throws IOException, InvalidFileFormatException { this(); load(input); } + /** + * Creates a registry and loads it from a reader. + * + * @param input the reader to read + * @throws IOException if reading fails + * @throws InvalidFileFormatException if the version header is missing or unsupported, or the + * content is not valid + */ public Reg(Reader input) throws IOException, InvalidFileFormatException { this(); load(input); } + /** + * Tells whether the program runs on Windows. + * + *

The answer is taken from the system property {@code os.name}, which must start with {@code + * Windows}. It is read once, when this class is loaded. + * + * @return {@code true} on Windows + */ public static boolean isWindows() { return WINDOWS; } @@ -161,6 +248,18 @@ public void load(File input) throws IOException, InvalidFileFormatException { load(input.toURI().toURL()); } + /** + * Reads a key of the real registry into this object. + * + *

The key is exported with {@code reg export} to a temporary file, and that file is loaded. + * The temporary file is deleted afterwards. As with every load, the content is added to what the + * object holds already. + * + * @param registryKey the path of the key, for example {@code HKEY_CURRENT_USER\Software\ini4j} + * @throws IOException if the {@code reg} command fails (the message is the text it wrote to its + * error output) or the exported file cannot be loaded + * @throws UnsupportedOperationException if this is not Windows + */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_BAD_PRACTICE") public void read(String registryKey) throws IOException { File tmp = createTempFile(); @@ -206,6 +305,16 @@ public void store(File output) throws IOException { } } + /** + * Writes this object to the real registry. + * + *

The content is stored to a temporary file, which is imported with {@code reg import}, and + * then deleted. This changes the registry of the machine. + * + * @throws IOException if the {@code reg} command fails (the message is the text it wrote to its + * error output) + * @throws UnsupportedOperationException if this is not Windows + */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_BAD_PRACTICE") public void write() throws IOException { File tmp = createTempFile(); @@ -218,6 +327,13 @@ public void write() throws IOException { } } + /** + * Creates the handler that builds this object while a file is parsed. + * + *

A subclass can override it to change how the parsed events are turned into keys and values. + * + * @return a new builder for this object + */ protected IniHandler newBuilder() { return RegBuilder.newInstance(this); } diff --git a/src/main/java/org/ini4j/Wini.java b/src/main/java/org/ini4j/Wini.java index b876b0e..1e1e1b6 100644 --- a/src/main/java/org/ini4j/Wini.java +++ b/src/main/java/org/ini4j/Wini.java @@ -22,11 +22,39 @@ import java.net.URL; import org.ini4j.spi.WinEscapeTool; +/** + * An {@link Ini} set up for the files that Windows applications use. + * + *

A new {@code Wini} has its own copy of the global {@link Config} with these differences: + * + *

    + *
  • backslash escapes are off (see {@link Config#isEscape()}), and so is joining of lines that + * end with a backslash, + *
  • options before the first section are accepted and kept in a section named {@link + * Config#getGlobalSectionName()}, + *
  • an option without a value is allowed (see {@link Config#isEmptyOption()}), + *
  • an option name keeps only its last value (see {@link Config#isMultiOption()}), + *
  • the path separator of section names is a backslash, {@link #PATH_SEPARATOR}. + *
+ * + *

Since escaping is off, a backslash in a name or a value is read and written as it is. The + * methods {@link #escape(String)} and {@link #unescape(String)} are there for the cases where you + * want to handle the Windows forms of escapes yourself. + * + * @see Ini + * @since 0.5.0 + */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings("CT_CONSTRUCTOR_THROW") public class Wini extends Ini { private static final long serialVersionUID = -2781377824232440728L; + + /** + * The path separator of section names in a {@code Wini}: a backslash. It hides {@link + * Profile#PATH_SEPARATOR}. + */ public static final char PATH_SEPARATOR = '\\'; + /** Creates an empty {@code Wini}. */ public Wini() { Config cfg = Config.getGlobal().clone(); @@ -39,31 +67,82 @@ public Wini() { setConfig(cfg); } + /** + * Creates a {@code Wini}, remembers the file and loads it. + * + * @param input the file to read and later to write + * @throws IOException if reading fails + * @throws InvalidFileFormatException if the content is not valid + */ public Wini(File input) throws IOException, InvalidFileFormatException { this(); setFile(input); load(); } + /** + * Creates a {@code Wini} and loads it from a URL. + * + * @param input the location to read + * @throws IOException if reading fails + * @throws InvalidFileFormatException if the content is not valid + */ public Wini(URL input) throws IOException, InvalidFileFormatException { this(); load(input); } + /** + * Creates a {@code Wini} and loads it from a stream. + * + * @param input the stream to read + * @throws IOException if reading fails + * @throws InvalidFileFormatException if the content is not valid + */ public Wini(InputStream input) throws IOException, InvalidFileFormatException { this(); load(input); } + /** + * Creates a {@code Wini} and loads it from a reader. + * + * @param input the reader to read + * @throws IOException if reading fails + * @throws InvalidFileFormatException if the content is not valid + */ public Wini(Reader input) throws IOException, InvalidFileFormatException { this(); load(input); } + /** + * Escapes a text in the Windows style. + * + *

A backslash, tab, line feed, form feed, backspace, carriage return, colon and equals sign + * are written as a backslash and a letter ({@code \\}, {@code \t}, {@code \n}, {@code \f}, {@code + * \b}, {@code \r}, {@code \:} and {@code \=}). Any other character outside the printable ASCII + * range is written as {@code \x} and two hexadecimal digits, which hold only the low byte of the + * character. + * + * @param value the text to escape + * @return the escaped text + */ public String escape(String value) { return WinEscapeTool.getInstance().escape(value); } + /** + * Reverses {@link #escape(String)}. + * + *

Besides the forms that {@link #escape(String)} writes, it reads {@code \o} followed by three + * octal digits and {@code \x} followed by two hexadecimal digits as a character with that code. A + * backslash before any other character is dropped. + * + * @param value the text to unescape + * @return the unescaped text + * @throws IllegalArgumentException if a {@code \x} or {@code \o} sequence is malformed + */ public String unescape(String value) { return WinEscapeTool.getInstance().unescape(value); } From 8dfde82411d18130d90dbe3269425354ae84984f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Iv=C3=A1n=20SZKIBA?= Date: Mon, 16 Nov 2026 09:13:52 +0100 Subject: [PATCH 5/9] docs: document the SPI parsers, formatters and handler events The handler call order, the comment timing and the provider lookup were only visible in the code. This writes them down for the parsers, the formatters and the two handler interfaces, checked against logs of real parse runs. Refs: #13 --- .../java/org/ini4j/spi/AbstractFormatter.java | 56 +++++++++++ .../java/org/ini4j/spi/AbstractParser.java | 50 ++++++++++ src/main/java/org/ini4j/spi/HandlerBase.java | 20 ++++ src/main/java/org/ini4j/spi/IniFormatter.java | 34 +++++++ src/main/java/org/ini4j/spi/IniHandler.java | 63 ++++++++++++ src/main/java/org/ini4j/spi/IniParser.java | 96 +++++++++++++++++++ .../java/org/ini4j/spi/OptionsFormatter.java | 24 +++++ .../java/org/ini4j/spi/OptionsHandler.java | 41 ++++++++ .../java/org/ini4j/spi/OptionsParser.java | 70 ++++++++++++++ 9 files changed, 454 insertions(+) diff --git a/src/main/java/org/ini4j/spi/AbstractFormatter.java b/src/main/java/org/ini4j/spi/AbstractFormatter.java index c4e75b5..9cc2f94 100644 --- a/src/main/java/org/ini4j/spi/AbstractFormatter.java +++ b/src/main/java/org/ini4j/spi/AbstractFormatter.java @@ -18,6 +18,14 @@ import java.io.PrintWriter; import org.ini4j.Config; +/** + * The common part of the formatters: it writes comments and options as text. + * + *

The output goes to a {@link java.io.PrintWriter}, which hides write errors instead of throwing + * them. The text is written as the {@link org.ini4j.Config} says. + * + * @since 0.5.0 + */ abstract class AbstractFormatter implements HandlerBase { private static final char OPERATOR = '='; private static final char COMMENT = '#'; @@ -26,6 +34,20 @@ abstract class AbstractFormatter implements HandlerBase { private boolean _header = true; private PrintWriter _output; + /** + * Writes a comment. + * + *

The comment is written as lines that start with {@code #}, one for each line of the comment, + * where a line ends at the line separator of the configuration ({@link + * org.ini4j.Config#getLineSeparator()}). Nothing is written if {@link + * org.ini4j.Config#isComment()} is off, or if the comment is {@code null} or empty. + * + *

The first call of this method, if it comes before any option or section, is for the header + * comment. A header comment is followed by an empty line, and it is written only if {@link + * org.ini4j.Config#isHeaderComment()} is on. + * + * @param comment the comment, or {@code null} for none + */ @Override public void handleComment(String comment) { if (getConfig().isComment() @@ -46,6 +68,19 @@ public void handleComment(String comment) { _header = false; } + /** + * Writes an option. + * + *

The option is written as {@code name=value} if {@link org.ini4j.Config#isStrictOperator()} + * is on, and as {@code name = value} otherwise. The name, and the value unless {@link + * org.ini4j.Config#isEscapeKeyOnly()} is on, are escaped if {@link org.ini4j.Config#isEscape()} + * is on. An option whose value is {@code null} is written with an empty value if {@link + * org.ini4j.Config#isEmptyOption()} is on, and it is left out otherwise. Every line ends with the + * line separator of the configuration. + * + * @param optionName the name of the option + * @param optionValue the value, or {@code null} for an option without a value + */ @Override public void handleOption(String optionName, String optionValue) { if (getConfig().isStrictOperator()) { @@ -77,18 +112,39 @@ public void handleOption(String optionName, String optionValue) { setHeader(false); } + /** + * Returns the configuration. + * + * @return the configuration in use; it is {@link org.ini4j.Config#getGlobal()} until another one + * is set + */ protected Config getConfig() { return _config; } + /** + * Sets the configuration. + * + * @param value the configuration to use from now on + */ protected void setConfig(Config value) { _config = value; } + /** + * Returns the output. + * + * @return the writer that receives the text + */ protected PrintWriter getOutput() { return _output; } + /** + * Sets the output. + * + * @param value the writer that receives the text; it is flushed at the end but never closed + */ protected void setOutput(PrintWriter value) { _output = value; } diff --git a/src/main/java/org/ini4j/spi/AbstractParser.java b/src/main/java/org/ini4j/spi/AbstractParser.java index 9074327..84d2c13 100644 --- a/src/main/java/org/ini4j/spi/AbstractParser.java +++ b/src/main/java/org/ini4j/spi/AbstractParser.java @@ -23,24 +23,59 @@ import org.ini4j.Config; import org.ini4j.InvalidFileFormatException; +/** + * The common part of the parsers: it holds the configuration and parses the lines with options. + * + *

A subclass tells the characters that begin a comment line and the characters that separate an + * option name from its value. The parsing of an option line follows the {@link org.ini4j.Config} + * flags such as {@link org.ini4j.Config#isEscape()}, {@link org.ini4j.Config#isEmptyOption()} and + * {@link org.ini4j.Config#isLowerCaseOption()}. + * + * @since 0.5.0 + */ abstract class AbstractParser { private final String _comments; private Config _config = Config.getGlobal(); private final String _operators; + /** + * Creates a parser. + * + * @param operators the characters that separate the name of an option from its value; the first + * one in the line that is not escaped with a backslash counts + * @param comments the characters that begin a comment line + */ protected AbstractParser(String operators, String comments) { _operators = operators; _comments = comments; } + /** + * Returns the configuration. + * + * @return the configuration in use; it is {@link org.ini4j.Config#getGlobal()} until another one + * is set + */ protected Config getConfig() { return _config; } + /** + * Sets the configuration. + * + * @param value the configuration to use from now on + */ protected void setConfig(Config value) { _config = value; } + /** + * Reports a line that cannot be parsed. + * + * @param line the text of the line + * @param lineNumber the number of the line in the input + * @throws InvalidFileFormatException always; the message contains the line number and the line + */ protected void parseError(String line, int lineNumber) throws InvalidFileFormatException { throw new InvalidFileFormatException("parse error (at line: " + lineNumber + "): " + line); } @@ -57,6 +92,21 @@ IniSource newIniSource(URL input, HandlerBase handler) throws IOException { return new IniSource(input, handler, _comments, getConfig()); } + /** + * Parses a line with an option and sends it to the handler. + * + *

The name is the text before the first operator that is not preceded by a backslash. When + * there is an operator, the name and the value are unescaped according to the configuration and + * trimmed. A line without an operator is an option without a value if {@link + * org.ini4j.Config#isEmptyOption()} is on, with the whole line as its name, and an error + * otherwise. An empty name is an error. With {@link org.ini4j.Config#isLowerCaseOption()} the + * name is converted to lower case. + * + * @param line the trimmed line + * @param handler the receiver of the option + * @param lineNumber the number of the line, for error messages + * @throws InvalidFileFormatException if the line is not a valid option + */ void parseOptionLine(String line, HandlerBase handler, int lineNumber) throws InvalidFileFormatException { int idx = indexOfOperator(line); diff --git a/src/main/java/org/ini4j/spi/HandlerBase.java b/src/main/java/org/ini4j/spi/HandlerBase.java index 9ed0525..2c7e3e6 100644 --- a/src/main/java/org/ini4j/spi/HandlerBase.java +++ b/src/main/java/org/ini4j/spi/HandlerBase.java @@ -15,8 +15,28 @@ */ package org.ini4j.spi; +/** + * The events that the parsers and the formatters of both file formats share. + * + *

A parser calls these methods while it reads a file, and a profile calls them while it is + * stored. The formats add their own start and end events: see {@link IniHandler} and {@link + * OptionsHandler}. + * + * @since 0.5.0 + */ interface HandlerBase { + /** + * Receives a comment. + * + * @param comment the text of the comment, see the description of the subinterface + */ void handleComment(String comment); + /** + * Receives an option. + * + * @param optionName the name of the option + * @param optionValue the value of the option + */ void handleOption(String optionName, String optionValue); } diff --git a/src/main/java/org/ini4j/spi/IniFormatter.java b/src/main/java/org/ini4j/spi/IniFormatter.java index b1fca30..83bd17f 100644 --- a/src/main/java/org/ini4j/spi/IniFormatter.java +++ b/src/main/java/org/ini4j/spi/IniFormatter.java @@ -19,7 +19,33 @@ import java.io.Writer; import org.ini4j.Config; +/** + * Writes the events of an INI file as text. + * + *

Each section is written as a header {@code [name]} followed by its options, and an empty line + * ends the section. If {@link org.ini4j.Config#isGlobalSection()} is on, the section that has the + * name {@link org.ini4j.Config#getGlobalSectionName()} has no header. Section names are escaped + * like option names. Comments and options are written as described in {@link + * #handleComment(String)} and {@link #handleOption(String, String)}. The writer is flushed at the + * end of the file and is never closed. + * + * @see IniHandler + * @see IniParser + * @since 0.4.1 + */ public class IniFormatter extends AbstractFormatter implements IniHandler { + /** + * Creates a formatter of this class, or of the class that a provider names. + * + *

The lookup is the same as in {@link IniParser#newInstance()}, with the name {@code + * org.ini4j.spi.IniFormatter}. + * + * @param out the writer for the text; it is used directly if it is a {@link java.io.PrintWriter}, + * and wrapped in one otherwise + * @param config the configuration to use + * @return a new formatter + * @throws IllegalArgumentException if the provider cannot be found or created + */ public static IniFormatter newInstance(Writer out, Config config) { IniFormatter instance = newInstance(); @@ -29,21 +55,29 @@ public static IniFormatter newInstance(Writer out, Config config) { return instance; } + /** Flushes the writer. */ @Override public void endIni() { getOutput().flush(); } + /** Writes an empty line. */ @Override public void endSection() { getOutput().print(getConfig().getLineSeparator()); } + /** Does nothing. */ @Override public void startIni() { assert true; } + /** + * Writes the header of a section, unless it is the global section. + * + * @param sectionName the name of the section + */ @Override public void startSection(String sectionName) { setHeader(false); diff --git a/src/main/java/org/ini4j/spi/IniHandler.java b/src/main/java/org/ini4j/spi/IniHandler.java index 069552b..8327725 100755 --- a/src/main/java/org/ini4j/spi/IniHandler.java +++ b/src/main/java/org/ini4j/spi/IniHandler.java @@ -15,18 +15,81 @@ */ package org.ini4j.spi; +/** + * Receives the events of an INI file, in the order of the file. + * + *

The same interface is used in both directions. A {@link IniParser} calls it while it reads a + * file, and an {@link org.ini4j.Ini} calls it while it is stored, so a handler is either a builder + * of the content ({@link IniBuilder}) or a writer of it ({@link IniFormatter}). + * + *

The calls come in this order: {@link #startIni()}, then the sections, then {@link #endIni()}. + * A section is {@link #startSection(String)}, any number of {@link #handleOption(String, String)} + * calls for its options in file order, and {@link #endSection()}. Options never come outside a + * section. If {@link org.ini4j.Config#isGlobalSection()} is on, the parser starts a section for the + * options that come before the first header, and uses {@link + * org.ini4j.Config#getGlobalSectionName()} as its name. + * + *

{@link #handleComment(String)} can come at any point between those calls. A comment is + * reported just before the section or the option it belongs to, so the comment above a section + * header arrives before the {@link #endSection()} of the section before it. A comment at the end of + * the file arrives before the last {@link #endSection()} (or before {@link #endIni()} if there is + * no section). The order is promised only for a successful parse. If the parser throws an + * exception, the closing calls may be missing. + * + *

When a file is stored, the calls between {@link #startIni()} and {@link #endIni()} are the + * header comment, then for each section its comment, {@link #startSection(String)}, for each option + * its comment and one {@link #handleOption(String, String)} call for each value, and {@link + * #endSection()}. In this direction a comment can be {@code null}, which means there is none. The + * {@link org.ini4j.Config} flags can leave things out: a section without options is skipped when + * {@link org.ini4j.Config#isEmptySection()} is off, and when {@link + * org.ini4j.Config#isMultiOption()} is off only one value of each option is sent, the last one. + * + * @see IniParser + * @see IniFormatter + * @see IniBuilder + * @since 0.5.0 + */ public interface IniHandler extends HandlerBase { + /** Ends the file. The parser calls it after the last section. */ void endIni(); + /** Ends the current section. */ void endSection(); + /** + * Receives a comment. + * + *

When a file is parsed, it is the text of the comment lines without the leading comment + * character. Each line is trimmed before the comment character is removed, so spaces after the + * comment character stay in the text. The lines are joined with the line separator of the + * configuration, and the last separator is cut by one character only, so with a separator of two + * characters, such as {@code CR LF}, the text ends with one of them. A blank line ends a comment, + * so one run of comment lines is one comment. A comment line with nothing after the comment + * character gives an empty line in the text. When a file is stored, it is the comment of the + * header, a section or an option, and it is {@code null} if there is none. + * + * @param comment the text of the comment + */ @Override void handleComment(String comment); + /** + * Receives an option of the current section. + * + * @param optionName the name of the option, never {@code null} + * @param optionValue the value of the option; it is {@code null} for an option without a value, + * which the parser allows only when {@link org.ini4j.Config#isEmptyOption()} is on + */ @Override void handleOption(String optionName, String optionValue); + /** Starts the file. It is the first call. */ void startIni(); + /** + * Starts a section. + * + * @param sectionName the name of the section + */ 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 c30b102..4f7c9c9 100755 --- a/src/main/java/org/ini4j/spi/IniParser.java +++ b/src/main/java/org/ini4j/spi/IniParser.java @@ -23,20 +23,85 @@ import org.ini4j.Config; import org.ini4j.InvalidFileFormatException; +/** + * Parses INI files and sends the events to an {@link IniHandler}. + * + *

A line that starts with {@code [} is a section header, and it must end with {@code ]}. The + * name between the brackets is trimmed and unescaped. Any other line is an option, written as + * {@code name=value} or {@code name:value}. A line that starts with {@code ;} or {@code #} is a + * comment. Comments exist only on lines of their own, so a comment after an option or after a + * header is part of the value, or an error. Blank lines are skipped, and lines are trimmed. The + * {@link org.ini4j.Config} flags decide a number of details, for example {@link + * org.ini4j.Config#isGlobalSection()}, {@link org.ini4j.Config#isUnnamedSection()}, {@link + * org.ini4j.Config#isLowerCaseSection()}, {@link org.ini4j.Config#isEscapeNewline()} and {@link + * org.ini4j.Config#isInclude()}. + * + *

The events and their order are described in {@link IniHandler}. A line that is not valid + * throws an {@link org.ini4j.InvalidFileFormatException} whose message has the line number and the + * line. + * + *

The input is closed when it has been read to the end. If an error is found before that, it is + * left open. + * + * @see IniHandler + * @see IniFormatter + * @since 0.5.0 + */ 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 = ']'; + /** + * Creates a parser that uses {@link org.ini4j.Config#getGlobal()}. + * + *

Use {@link #newInstance()} or {@link #newInstance(org.ini4j.Config)} unless you want to + * bypass the provider lookup. + */ public IniParser() { super(OPERATORS, COMMENTS); } + /** + * Creates a parser of this class, or of the class that a provider names. + * + *

The class is looked up in this order, and the first source that has a value wins: + * + *

    + *
  • the system property whose name is the fully qualified name of the class, for example + * {@code org.ini4j.spi.IniParser}, + *
  • the first line of the resource {@code META-INF/services/} followed by that name, found + * with the context class loader of the current thread. The line is trimmed and cut at the + * first white space or {@code #}. A blank first line means that there is no provider, and + * later lines are never read. A line that starts with {@code #} gives an empty name, + *
  • the class itself. + *
+ * + *

If the system property cannot be read because of a security manager, it is skipped. A + * resource that cannot be read counts as not found. If the thread has no context class loader, + * the system class loader is used. There is no fallback after a bad name: if the provider class + * is not found, or it is not usable, the call fails. The provider must be a subclass that has a + * public constructor with no arguments. The call throws an {@link IllegalArgumentException} if + * the class is not found, or if it cannot be created for any reason, including an exception that + * its constructor throws. Only an {@link Error} that the Java runtime throws while it loads or + * links the class, such as a {@link NoClassDefFoundError} or an {@link + * ExceptionInInitializerError}, is not wrapped. + * + * @return a new parser + * @throws IllegalArgumentException if the provider cannot be found or created + */ public static IniParser newInstance() { return ServiceFinder.findService(IniParser.class); } + /** + * Creates a parser as {@link #newInstance()} does, and gives it a configuration. + * + * @param config the configuration to use + * @return a new parser + * @throws IllegalArgumentException if the provider cannot be found or created + */ public static IniParser newInstance(Config config) { IniParser instance = newInstance(); @@ -45,16 +110,47 @@ public static IniParser newInstance(Config config) { return instance; } + /** + * Parses a stream. + * + *

The bytes are decoded with the file encoding of the configuration, unless a byte order mark + * at the start of the stream says otherwise. + * + * @param input the stream to read + * @param handler the receiver of the events + * @throws IOException if reading fails + * @throws org.ini4j.InvalidFileFormatException if the content is not valid + */ public void parse(InputStream input, IniHandler handler) throws IOException, InvalidFileFormatException { parse(newIniSource(input, handler), handler); } + /** + * Parses a reader. + * + * @param input the reader to read; the caller has chosen how it decodes + * @param handler the receiver of the events + * @throws IOException if reading fails + * @throws org.ini4j.InvalidFileFormatException if the content is not valid + */ public void parse(Reader input, IniHandler handler) throws IOException, InvalidFileFormatException { parse(newIniSource(input, handler), handler); } + /** + * Parses the content of a URL. + * + *

The bytes are decoded as in {@link #parse(InputStream, IniHandler)}. If {@link + * org.ini4j.Config#isInclude()} is on, relative locations in include lines are resolved against + * this URL. + * + * @param input the location to read + * @param handler the receiver of the events + * @throws IOException if the location cannot be opened or read + * @throws org.ini4j.InvalidFileFormatException if the content is not valid + */ public void parse(URL input, IniHandler handler) throws IOException, InvalidFileFormatException { parse(newIniSource(input, handler), handler); } diff --git a/src/main/java/org/ini4j/spi/OptionsFormatter.java b/src/main/java/org/ini4j/spi/OptionsFormatter.java index 613a2e9..caa0411 100644 --- a/src/main/java/org/ini4j/spi/OptionsFormatter.java +++ b/src/main/java/org/ini4j/spi/OptionsFormatter.java @@ -19,7 +19,29 @@ import java.io.Writer; import org.ini4j.Config; +/** + * Writes the events of a file of options as text. + * + *

Comments and options are written as described in {@link #handleComment(String)} and {@link + * #handleOption(String, String)}. The writer is flushed at the end of the file and is never closed. + * + * @see OptionsHandler + * @see OptionsParser + * @since 0.5.0 + */ public class OptionsFormatter extends AbstractFormatter implements OptionsHandler { + /** + * Creates a formatter of this class, or of the class that a provider names. + * + *

The lookup is the same as in {@link IniParser#newInstance()}, with the name {@code + * org.ini4j.spi.OptionsFormatter}. + * + * @param out the writer for the text; it is used directly if it is a {@link java.io.PrintWriter}, + * and wrapped in one otherwise + * @param config the configuration to use + * @return a new formatter + * @throws IllegalArgumentException if the provider cannot be found or created + */ public static OptionsFormatter newInstance(Writer out, Config config) { OptionsFormatter instance = newInstance(); @@ -29,10 +51,12 @@ public static OptionsFormatter newInstance(Writer out, Config config) { return instance; } + /** Flushes the writer. */ public void endOptions() { getOutput().flush(); } + /** Does nothing. */ public void startOptions() { assert true; } diff --git a/src/main/java/org/ini4j/spi/OptionsHandler.java b/src/main/java/org/ini4j/spi/OptionsHandler.java index 3f44af4..a33175f 100644 --- a/src/main/java/org/ini4j/spi/OptionsHandler.java +++ b/src/main/java/org/ini4j/spi/OptionsHandler.java @@ -15,14 +15,55 @@ */ package org.ini4j.spi; +/** + * Receives the events of a file of options without sections, in the order of the file. + * + *

The same interface is used in both directions. An {@link OptionsParser} calls it while it + * reads a file, and an {@link org.ini4j.Options} calls it while it is stored. The calls are {@link + * #startOptions()}, then {@link #handleOption(String, String)} for each option, and {@link + * #endOptions()}. + * + *

{@link #handleComment(String)} can come at any point between the start and the end. A comment + * is reported just before the option it belongs to, and a comment at the end of the file arrives + * before {@link #endOptions()}. The order is promised only for a successful parse. If the parser + * throws an exception, {@link #endOptions()} may be missing. + * + *

When a file is stored, the calls between {@link #startOptions()} and {@link #endOptions()} are + * the header comment, then for each option its comment and one {@link #handleOption(String, + * String)} call for each value. In this direction a comment can be {@code null}, which means there + * is none. When {@link org.ini4j.Config#isMultiOption()} is off, only one value of each option is + * sent, the first one. + * + * @see OptionsParser + * @see OptionsFormatter + * @see OptionsBuilder + * @since 0.5.0 + */ public interface OptionsHandler extends HandlerBase { + /** Ends the file. The parser calls it after the last option. */ void endOptions(); + /** + * Receives a comment. + * + *

The text is as described for {@link IniHandler#handleComment(String)}, with the comment + * characters of this format. + * + * @param comment the text of the comment + */ @Override void handleComment(String comment); + /** + * Receives an option. + * + * @param optionName the name of the option, never {@code null} + * @param optionValue the value of the option; it is {@code null} for an option without a value, + * which the parser allows only when {@link org.ini4j.Config#isEmptyOption()} is on + */ @Override void handleOption(String optionName, String optionValue); + /** Starts the file. It is the first call. */ void startOptions(); } diff --git a/src/main/java/org/ini4j/spi/OptionsParser.java b/src/main/java/org/ini4j/spi/OptionsParser.java index a366f60..e308208 100644 --- a/src/main/java/org/ini4j/spi/OptionsParser.java +++ b/src/main/java/org/ini4j/spi/OptionsParser.java @@ -22,18 +22,57 @@ import org.ini4j.Config; import org.ini4j.InvalidFileFormatException; +/** + * Parses files of options without sections and sends the events to an {@link OptionsHandler}. + * + *

Every line is an option, written as {@code name=value} or {@code name:value}. A line that + * starts with {@code !} or {@code #} is a comment. Blank lines are skipped and lines are trimmed. + * The rules for names, values and the {@link org.ini4j.Config} flags are the same as in {@link + * IniParser}, except that there are no sections. + * + *

The events and their order are described in {@link OptionsHandler}. A line that is not valid + * throws an {@link org.ini4j.InvalidFileFormatException} whose message has the line number and the + * line. The input is closed when it has been read to the end. If an error is found before that, it + * is left open. + * + * @see OptionsHandler + * @see OptionsFormatter + * @since 0.5.0 + */ public class OptionsParser extends AbstractParser { private static final String COMMENTS = "!#"; private static final String OPERATORS = ":="; + /** + * Creates a parser that uses {@link org.ini4j.Config#getGlobal()}. + * + *

Use {@link #newInstance()} or {@link #newInstance(org.ini4j.Config)} unless you want to + * bypass the provider lookup. + */ public OptionsParser() { super(OPERATORS, COMMENTS); } + /** + * Creates a parser of this class, or of the class that a provider names. + * + *

The lookup is the same as in {@link IniParser#newInstance()}, with the name {@code + * org.ini4j.spi.OptionsParser}. + * + * @return a new parser + * @throws IllegalArgumentException if the provider cannot be found or created + */ public static OptionsParser newInstance() { return ServiceFinder.findService(OptionsParser.class); } + /** + * Creates a parser as {@link #newInstance()} does, and gives it a configuration. + * + * @param config the configuration to use + * @return a new parser + * @throws IllegalArgumentException if the provider cannot be found or created + */ public static OptionsParser newInstance(Config config) { OptionsParser instance = newInstance(); @@ -42,16 +81,47 @@ public static OptionsParser newInstance(Config config) { return instance; } + /** + * Parses a stream. + * + *

The bytes are decoded with the file encoding of the configuration, unless a byte order mark + * at the start of the stream says otherwise. + * + * @param input the stream to read + * @param handler the receiver of the events + * @throws IOException if reading fails + * @throws org.ini4j.InvalidFileFormatException if the content is not valid + */ public void parse(InputStream input, OptionsHandler handler) throws IOException, InvalidFileFormatException { parse(newIniSource(input, handler), handler); } + /** + * Parses a reader. + * + * @param input the reader to read; the caller has chosen how it decodes + * @param handler the receiver of the events + * @throws IOException if reading fails + * @throws org.ini4j.InvalidFileFormatException if the content is not valid + */ public void parse(Reader input, OptionsHandler handler) throws IOException, InvalidFileFormatException { parse(newIniSource(input, handler), handler); } + /** + * Parses the content of a URL. + * + *

The bytes are decoded as in {@link #parse(InputStream, OptionsHandler)}. If {@link + * org.ini4j.Config#isInclude()} is on, relative locations in include lines are resolved against + * this URL. + * + * @param input the location to read + * @param handler the receiver of the events + * @throws IOException if the location cannot be opened or read + * @throws org.ini4j.InvalidFileFormatException if the content is not valid + */ public void parse(URL input, OptionsHandler handler) throws IOException, InvalidFileFormatException { parse(newIniSource(input, handler), handler); From 9468649db0289d2200ddc42875d10b2956011422 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Iv=C3=A1n=20SZKIBA?= Date: Mon, 16 Nov 2026 09:13:52 +0100 Subject: [PATCH 6/9] docs: document the SPI builders How a parsed file becomes sections, options and comments (which comment is kept, which is lost, what the header comment is) was not written down anywhere. This documents it for the Ini, Reg and Options builders. Refs: #13 --- .../org/ini4j/spi/AbstractProfileBuilder.java | 41 ++++++++++++- src/main/java/org/ini4j/spi/IniBuilder.java | 38 ++++++++++++ .../java/org/ini4j/spi/OptionsBuilder.java | 61 ++++++++++++++++++- src/main/java/org/ini4j/spi/RegBuilder.java | 39 ++++++++++++ 4 files changed, 177 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/ini4j/spi/AbstractProfileBuilder.java b/src/main/java/org/ini4j/spi/AbstractProfileBuilder.java index 025ecb1..285d8b4 100644 --- a/src/main/java/org/ini4j/spi/AbstractProfileBuilder.java +++ b/src/main/java/org/ini4j/spi/AbstractProfileBuilder.java @@ -20,25 +20,44 @@ import org.ini4j.Ini; import org.ini4j.Profile; +/** + * The common part of the builders that fill a {@link org.ini4j.Profile} from the events of a + * parser. + * + *

The rules are described in {@link IniBuilder}. + * + * @since 0.5.0 + */ abstract class AbstractProfileBuilder implements IniHandler { private Profile.Section _currentSection; private boolean _header; private String _lastComment; + /** + * Ends the file. A comment that is the only content of the file becomes the comment of the + * profile, if {@link org.ini4j.Config#isComment()} and {@link org.ini4j.Config#isHeaderComment()} + * are on. The rules are described in {@link IniBuilder}. + */ @Override public void endIni() { - // comment only .ini files.... + // a file that has nothing but a comment if ((_lastComment != null) && _header) { setHeaderComment(); } } + /** Ends the current section. */ @Override public void endSection() { _currentSection = null; } + /** + * Receives a comment. + * + * @param comment the text of the comment + */ @Override public void handleComment(String comment) { if ((_lastComment != null) && _header) { @@ -49,6 +68,16 @@ public void handleComment(String comment) { _lastComment = comment; } + /** + * Adds an option to the current section. + * + *

The value is added or replaces the last value as {@link org.ini4j.Config#isMultiOption()} + * says. A held comment becomes the comment of the option. + * + * @param name the name of the option + * @param value the value of the option, or {@code null} + * @throws NullPointerException if there is no current section + */ @Override public void handleOption(String name, String value) { _header = false; @@ -64,6 +93,7 @@ public void handleOption(String name, String value) { } } + /** Starts the file. */ @Override public void startIni() { if (getConfig().isHeaderComment()) { @@ -71,6 +101,15 @@ public void startIni() { } } + /** + * Starts a section. + * + *

The section is added to the profile, or an existing one is reused as {@link + * org.ini4j.Config#isMultiSection()} says. A held comment becomes the comment of the section, or + * of the profile if no section or option came before it and header comments are on. + * + * @param sectionName the name of the section + */ @Override public void startSection(String sectionName) { if (getConfig().isMultiSection()) { diff --git a/src/main/java/org/ini4j/spi/IniBuilder.java b/src/main/java/org/ini4j/spi/IniBuilder.java index 3246357..f72a59b 100644 --- a/src/main/java/org/ini4j/spi/IniBuilder.java +++ b/src/main/java/org/ini4j/spi/IniBuilder.java @@ -19,10 +19,43 @@ import org.ini4j.Ini; import org.ini4j.Profile; +/** + * Fills an {@link org.ini4j.Ini} from the events of an {@link IniParser}. + * + *

The builder receives the events described in {@link IniHandler}. {@code startSection} adds a + * section to the {@code Ini}, or, if {@link org.ini4j.Config#isMultiSection()} is off and a section + * of that name exists, selects the existing one. {@code handleOption} adds the value to the current + * section, or replaces the last value if {@link org.ini4j.Config#isMultiOption()} is off. It must + * be called between {@code startSection} and {@code endSection}. The configuration is that of the + * {@code Ini}. + * + *

Comments are kept only if {@link org.ini4j.Config#isComment()} is on. A comment is held until + * the next section or option, and becomes the comment of that section or option. If another comment + * arrives first, it replaces the held one, which is lost. The exception is the first comment of the + * file: with {@link org.ini4j.Config#isHeaderComment()} on, the first comment before any section or + * option is not lost but becomes the comment of the {@code Ini} itself, whether it is followed by a + * section, another comment, or the end of the file. A comment that is not followed by a section or + * an option, such as the comments at the end of the file, is lost. + * + *

{@link RegBuilder} follows the same rules. + * + * @see IniParser + * @since 0.5.0 + */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings("EI_EXPOSE_REP2") public class IniBuilder extends AbstractProfileBuilder { private Ini _ini; + /** + * Creates a builder of this class, or of the class that a provider names, for an {@code Ini}. + * + *

The lookup is the same as in {@link IniParser#newInstance()}, with the name {@code + * org.ini4j.spi.IniBuilder}. + * + * @param ini the object to fill; it is used directly, not copied + * @return a new builder + * @throws IllegalArgumentException if the provider cannot be found or created + */ public static IniBuilder newInstance(Ini ini) { IniBuilder instance = newInstance(); @@ -31,6 +64,11 @@ public static IniBuilder newInstance(Ini ini) { return instance; } + /** + * Sets the object to fill. + * + * @param value the object to fill; it is used directly, not copied + */ public void setIni(Ini value) { _ini = value; } diff --git a/src/main/java/org/ini4j/spi/OptionsBuilder.java b/src/main/java/org/ini4j/spi/OptionsBuilder.java index d9baa39..83c998f 100644 --- a/src/main/java/org/ini4j/spi/OptionsBuilder.java +++ b/src/main/java/org/ini4j/spi/OptionsBuilder.java @@ -18,12 +18,38 @@ import org.ini4j.Config; import org.ini4j.Options; +/** + * Fills an {@link org.ini4j.Options} from the events of an {@link OptionsParser}. + * + *

{@code handleOption} adds the value, or replaces the last value if {@link + * org.ini4j.Config#isMultiOption()} is off. Comments are kept only if {@link + * org.ini4j.Config#isComment()} is on, as follows. A comment is held until the next option and + * becomes the comment of that option. If another comment arrives first, it replaces the held one, + * which is lost. The exception is the first comment of the file: with {@link + * org.ini4j.Config#isHeaderComment()} on, the first comment before the first option is not lost but + * becomes the comment of the {@code Options} itself, whether it is followed by an option, another + * comment, or the end of the file. A comment that is not followed by an option, such as a comment + * at the end of the file, is lost. + * + * @see OptionsParser + * @since 0.5.0 + */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings("EI_EXPOSE_REP2") public class OptionsBuilder implements OptionsHandler { private boolean _header; private String _lastComment; private Options _options; + /** + * Creates a builder of this class, or of the class that a provider names, for an {@code Options}. + * + *

The lookup is the same as in {@link IniParser#newInstance()}, with the name {@code + * org.ini4j.spi.OptionsBuilder}. + * + * @param opts the object to fill; it is used directly, not copied + * @return a new builder + * @throws IllegalArgumentException if the provider cannot be found or created + */ public static OptionsBuilder newInstance(Options opts) { OptionsBuilder instance = newInstance(); @@ -32,19 +58,34 @@ public static OptionsBuilder newInstance(Options opts) { return instance; } + /** + * Sets the object to fill. + * + * @param value the object to fill; it is used directly, not copied + */ public void setOptions(Options value) { _options = value; } + /** + * Ends the file. A comment that is the only content of the file becomes the comment of the {@code + * Options}, if {@link org.ini4j.Config#isComment()} and {@link + * org.ini4j.Config#isHeaderComment()} are on. + */ @Override public void endOptions() { - // comment only .opt file ... + // a file that has nothing but a comment if ((_lastComment != null) && _header) { setHeaderComment(); } } + /** + * Receives a comment. + * + * @param comment the text of the comment + */ @Override public void handleComment(String comment) { if ((_lastComment != null) && _header) { @@ -55,6 +96,12 @@ public void handleComment(String comment) { _lastComment = comment; } + /** + * Adds an option. + * + * @param name the name of the option + * @param value the value of the option, or {@code null} + */ @Override public void handleOption(String name, String value) { if (getConfig().isMultiOption()) { @@ -76,6 +123,7 @@ public void handleOption(String name, String value) { _header = false; } + /** Starts the file. */ @Override public void startOptions() { if (getConfig().isHeaderComment()) { @@ -83,6 +131,17 @@ public void startOptions() { } } + /** + * Creates a builder of this class, or of the class that a provider names, without an object to + * fill. + * + *

The lookup is the same as in {@link IniParser#newInstance()}, with the name {@code + * org.ini4j.spi.OptionsBuilder}. Call {@link #setOptions(Options)} before the builder receives + * events. + * + * @return a new builder + * @throws IllegalArgumentException if the provider cannot be found or created + */ protected static OptionsBuilder newInstance() { return ServiceFinder.findService(OptionsBuilder.class); } diff --git a/src/main/java/org/ini4j/spi/RegBuilder.java b/src/main/java/org/ini4j/spi/RegBuilder.java index 1200738..43aad27 100644 --- a/src/main/java/org/ini4j/spi/RegBuilder.java +++ b/src/main/java/org/ini4j/spi/RegBuilder.java @@ -21,10 +21,34 @@ import org.ini4j.Registry.Key; import org.ini4j.Registry.Type; +/** + * Fills a {@link org.ini4j.Reg} from the events of an {@link IniParser}. + * + *

Sections, options and comments are handled as described in {@link IniBuilder}. In addition, + * each option is a registry value. A name in double quotes is unquoted, and the name {@code @} is + * kept as it is. The raw value is decoded by {@link RegEscapeTool}: the value types that are not + * {@link org.ini4j.Registry.Type#REG_SZ} are remembered in the key with {@link + * org.ini4j.Registry.Key#putType(String, org.ini4j.Registry.Type)}, and a multi-string value gives + * one value for each string, or only the last string if {@link org.ini4j.Config#isMultiOption()} is + * off. A comment before a value is the comment of its name. + * + * @see org.ini4j.Reg + * @since 0.5.0 + */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings("EI_EXPOSE_REP2") public class RegBuilder extends AbstractProfileBuilder { private Reg _reg; + /** + * Creates a builder of this class, or of the class that a provider names, for a {@code Reg}. + * + *

The lookup is the same as in {@link IniParser#newInstance()}, with the name {@code + * org.ini4j.spi.RegBuilder}. + * + * @param reg the object to fill; it is used directly, not copied + * @return a new builder + * @throws IllegalArgumentException if the provider cannot be found or created + */ public static RegBuilder newInstance(Reg reg) { RegBuilder instance = newInstance(); @@ -33,10 +57,25 @@ public static RegBuilder newInstance(Reg reg) { return instance; } + /** + * Sets the object to fill. + * + * @param value the object to fill; it is used directly, not copied + */ public void setReg(Reg value) { _reg = value; } + /** + * Adds a registry value to the current key. + * + * @param rawName the name as written in the file, in double quotes unless it is {@code @} + * @param rawValue the value as written in the file, with its type prefix if it has one + * @throws NullPointerException if there is no current key + * @throws StringIndexOutOfBoundsException if {@code rawName} or {@code rawValue} is empty + * @throws IllegalArgumentException if the value cannot be decoded, for example a {@code dword} + * that is not a hexadecimal number + */ @Override public void handleOption(String rawName, String rawValue) { String name = From 558f4bcf5e74c6c9dcb139c78b2dd1fcfce8480c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Iv=C3=A1n=20SZKIBA?= Date: Mon, 16 Nov 2026 09:13:53 +0100 Subject: [PATCH 7/9] docs: document the SPI escape, bean and registry utilities The escape forms, the registry value encoding and the rules of the bean proxy were undocumented, and several have edge cases (empty registry strings, unquote with stray backslashes, Object methods on a proxy). These are written down after running each case. Refs: #13 --- .../spi/AbstractBeanInvocationHandler.java | 142 ++++++++++++++++++ src/main/java/org/ini4j/spi/BeanAccess.java | 59 ++++++++ src/main/java/org/ini4j/spi/BeanTool.java | 91 +++++++++++ src/main/java/org/ini4j/spi/EscapeTool.java | 85 +++++++++++ .../java/org/ini4j/spi/RegEscapeTool.java | 56 +++++++ .../java/org/ini4j/spi/TypeValuesPair.java | 26 ++++ src/main/java/org/ini4j/spi/Warnings.java | 9 ++ .../java/org/ini4j/spi/WinEscapeTool.java | 19 +++ 8 files changed, 487 insertions(+) diff --git a/src/main/java/org/ini4j/spi/AbstractBeanInvocationHandler.java b/src/main/java/org/ini4j/spi/AbstractBeanInvocationHandler.java index 7bdd08a..abcfdaa 100755 --- a/src/main/java/org/ini4j/spi/AbstractBeanInvocationHandler.java +++ b/src/main/java/org/ini4j/spi/AbstractBeanInvocationHandler.java @@ -25,6 +25,34 @@ import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; +/** + * The base class for the handlers of the dynamic proxies that show a store as a bean. + * + *

The handler maps the methods of the proxy to properties by the first letters of the method + * name: {@code getX} and {@code isX} read the property {@code x}, {@code setX} writes it, and + * {@code hasX} tells whether it exists. The property name is the rest of the method name changed as + * {@link java.beans.Introspector#decapitalize(String)} does. The methods {@code + * addPropertyChangeListener}, {@code addVetoableChangeListener} and the two matching {@code remove} + * methods take the property name and a listener. Only the start of the name is checked, so a method + * such as {@code issue()} is a read of the property {@code sue}. + * + *

A subclass tells how to read, write and test a property in the store. The text from the store + * is converted to the type of the property here. A read that fails with an exception gives the + * {@linkplain BeanTool#zero(Class) zero value} of the type, not an exception. A write first asks + * the vetoable listeners of the property, if there are some, then writes, then tells the property + * change listeners. The old value for the listeners is read only if there are listeners. + * + *

The methods of {@link Object} are not handled. A call of {@code toString()} returns {@code + * null}, {@code equals} throws a {@link NullPointerException}, and {@code hashCode} throws a {@link + * ClassCastException} because its name starts with {@code has}. + * + *

Thread safety. The methods that read or write a property, and the ones that + * change the listeners, are synchronized on the handler, so two threads do not run them at the same + * time. The store behind it is not protected. + * + * @see BeanTool + * @since 0.4.1 + */ public abstract class AbstractBeanInvocationHandler implements InvocationHandler { private static final String PROPERTY_CHANGE_LISTENER = "PropertyChangeListener"; private static final String VETOABLE_CHANGE_LISTENER = "VetoableChangeListener"; @@ -79,6 +107,15 @@ public String getValue() { private Object _proxy; private VetoableChangeSupport _vcSupport; + /** + * Handles a call of a method of the proxy, as described in the description of this class. + * + * @param proxy the proxy + * @param method the method that was called + * @param args the arguments of the call + * @return the value for a read or a {@code has} method, and {@code null} otherwise + * @throws PropertyVetoException if a vetoable listener rejects the new value of a write + */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws PropertyVetoException { Object ret = null; @@ -129,12 +166,41 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Property return ret; } + /** + * Reads a property from the store. + * + * @param property the property name + * @param clazz the type of the property + * @return the value; text is converted to {@code clazz} by the caller, and for an array type the + * caller accepts an array of text. {@code null} means that there is no value + */ protected abstract Object getPropertySpi(String property, Class clazz); + /** + * Writes a property to the store. + * + * @param property the property name + * @param value the new value + * @param clazz the type of the property + */ protected abstract void setPropertySpi(String property, Object value, Class clazz); + /** + * Tells whether the store has a property. + * + * @param property the property name + * @return {@code true} if the property has a value + */ protected abstract boolean hasPropertySpi(String property); + /** + * Reads a property and converts it to a type. + * + * @param property the property name + * @param clazz the type of the property + * @return the value, or the zero value of the type if there is none or the read or the conversion + * fails + */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings("REC_CATCH_EXCEPTION") protected synchronized Object getProperty(String property, Class clazz) { Object o; @@ -160,6 +226,17 @@ protected synchronized Object getProperty(String property, Class clazz) { return o; } + /** + * Writes a property and notifies the listeners. + * + *

A value of a type other than {@link String} for a {@code String} property is stored as its + * text. + * + * @param property the property name + * @param value the new value + * @param clazz the type of the property + * @throws PropertyVetoException if a vetoable listener rejects the new value + */ protected synchronized void setProperty(String property, Object value, Class clazz) throws PropertyVetoException { boolean pc = (_pcSupport != null) && _pcSupport.hasListeners(property); @@ -184,10 +261,22 @@ protected synchronized void setProperty(String property, Object value, Class } } + /** + * Returns the proxy that this handler serves. + * + * @return the proxy, or {@code null} if no method that the handler maps to a property or a + * listener has been called yet + */ protected synchronized Object getProxy() { return _proxy; } + /** + * Adds a listener for the changes of a property. + * + * @param property the property name + * @param listener the listener + */ protected synchronized void addPropertyChangeListener( String property, PropertyChangeListener listener) { if (_pcSupport == null) { @@ -197,6 +286,12 @@ protected synchronized void addPropertyChangeListener( _pcSupport.addPropertyChangeListener(property, listener); } + /** + * Adds a listener that can veto the changes of a property. + * + * @param property the property name + * @param listener the listener + */ protected synchronized void addVetoableChangeListener( String property, VetoableChangeListener listener) { if (_vcSupport == null) { @@ -206,6 +301,13 @@ protected synchronized void addVetoableChangeListener( _vcSupport.addVetoableChangeListener(property, listener); } + /** + * Tells the property change listeners about a change. + * + * @param property the property name + * @param oldValue the old value + * @param newValue the new value + */ protected synchronized void firePropertyChange( String property, Object oldValue, Object newValue) { if (_pcSupport != null) { @@ -213,6 +315,14 @@ protected synchronized void firePropertyChange( } } + /** + * Asks the vetoable change listeners about a change. + * + * @param property the property name + * @param oldValue the old value + * @param newValue the new value + * @throws PropertyVetoException if a listener rejects the change + */ protected synchronized void fireVetoableChange(String property, Object oldValue, Object newValue) throws PropertyVetoException { if (_vcSupport != null) { @@ -220,6 +330,12 @@ protected synchronized void fireVetoableChange(String property, Object oldValue, } } + /** + * Tells whether a property has a value. + * + * @param property the property name + * @return {@code true} if it has; {@code false} if it has not, or the test fails + */ protected synchronized boolean hasProperty(String property) { boolean ret; @@ -232,10 +348,24 @@ protected synchronized boolean hasProperty(String property) { return ret; } + /** + * Converts a text to a type with {@link BeanTool#parse(String, Class)}. + * + * @param value the text + * @param clazz the type + * @return the value + * @throws IllegalArgumentException if the text cannot be converted + */ protected Object parse(String value, Class clazz) throws IllegalArgumentException { return BeanTool.getInstance().parse(value, clazz); } + /** + * Removes a listener for the changes of a property. + * + * @param property the property name + * @param listener the listener + */ protected synchronized void removePropertyChangeListener( String property, PropertyChangeListener listener) { if (_pcSupport != null) { @@ -243,6 +373,12 @@ protected synchronized void removePropertyChangeListener( } } + /** + * Removes a listener that can veto the changes of a property. + * + * @param property the property name + * @param listener the listener + */ protected synchronized void removeVetoableChangeListener( String property, VetoableChangeListener listener) { if (_vcSupport != null) { @@ -250,6 +386,12 @@ protected synchronized void removeVetoableChangeListener( } } + /** + * Returns the zero value of a type with {@link BeanTool#zero(Class)}. + * + * @param clazz the type + * @return the zero value + */ protected Object zero(Class clazz) { return BeanTool.getInstance().zero(clazz); } diff --git a/src/main/java/org/ini4j/spi/BeanAccess.java b/src/main/java/org/ini4j/spi/BeanAccess.java index 23781a0..a998250 100644 --- a/src/main/java/org/ini4j/spi/BeanAccess.java +++ b/src/main/java/org/ini4j/spi/BeanAccess.java @@ -15,18 +15,77 @@ */ package org.ini4j.spi; +/** + * A view of a store of named, multi-valued properties, as a bean needs it. + * + *

{@link BeanTool} uses it to copy values between a bean and a store such as an {@link + * org.ini4j.OptionMap}. The names are the names of bean properties, and each can have several + * values, indexed from zero. {@link org.ini4j.OptionMap#as(Class)} and {@link + * org.ini4j.OptionMap#from(Object)} are built on it. In the implementation of {@link + * org.ini4j.BasicOptionMap}, the property name is turned into an option name with the prefix and + * the upper case rule, and reading resolves variables. + * + * @since 0.4.1 + */ public interface BeanAccess { + /** + * Adds a value after the existing values of a property. + * + * @param propertyName the name of the property + * @param value the value + */ void propAdd(String propertyName, String value); + /** + * Removes all the values of a property. + * + * @param propertyName the name of the property + * @return a removed value; {@link org.ini4j.BasicOptionMap} returns the first one, or {@code + * null} if there was none + */ String propDel(String propertyName); + /** + * Returns the last value of a property. + * + * @param propertyName the name of the property + * @return the value, or {@code null} if there is none + */ String propGet(String propertyName); + /** + * Returns a value of a property. + * + * @param propertyName the name of the property + * @param index the position of the value + * @return the value, or {@code null} if the property has no value + */ String propGet(String propertyName, int index); + /** + * Returns the number of values of a property. + * + * @param propertyName the name of the property + * @return the number of values, {@code 0} if there is none + */ int propLength(String propertyName); + /** + * Replaces the last value of a property, or adds it if there is none. + * + * @param propertyName the name of the property + * @param value the new value + * @return the replaced value, or {@code null} if there was none + */ String propSet(String propertyName, String value); + /** + * Replaces a value of a property. + * + * @param propertyName the name of the property + * @param value the new value + * @param index the position of the value to replace + * @return the replaced value + */ 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 775cd82..0efc924 100644 --- a/src/main/java/org/ini4j/spi/BeanTool.java +++ b/src/main/java/org/ini4j/spi/BeanTool.java @@ -26,14 +26,46 @@ import java.net.URL; import java.util.TimeZone; +/** + * Converts text to Java values and connects beans with a store of properties. + * + *

It does the work behind {@link org.ini4j.OptionMap#get(Object, Class)}, {@link + * org.ini4j.OptionMap#as(Class)}, {@link org.ini4j.OptionMap#from(Object)} and {@link + * org.ini4j.OptionMap#to(Object)}. Properties are found with {@link java.beans.Introspector}, so + * the property names are those of the Java Beans conventions. + * + *

The instance is created once, when the class is first used, with the provider lookup described + * in {@link IniParser#newInstance()}, using the name {@code org.ini4j.spi.BeanTool}. A provider + * that cannot be created makes the class initialization fail. The class has no state, so it can be + * used from several threads. + * + * @see BeanAccess + * @since 0.4.1 + */ public class BeanTool { private static final String PARSE_METHOD = "valueOf"; private static final BeanTool INSTANCE = ServiceFinder.findService(BeanTool.class); + /** + * Returns the shared instance. + * + * @return the instance + */ public static final BeanTool getInstance() { return INSTANCE; } + /** + * Copies the values of a store into the properties of a bean. + * + *

Each writable property of the bean for which the store has a value is set. An array property + * gets all the values, and any other property gets the last one, converted with {@link + * #parse(String, Class)}. Other properties are not touched. + * + * @param bean the bean to change + * @param props the store to read + * @throws IllegalArgumentException if a property cannot be set; the message names the property + */ public void inject(Object bean, BeanAccess props) { for (PropertyDescriptor pd : getPropertyDescriptors(bean.getClass())) { try { @@ -63,6 +95,17 @@ public void inject(Object bean, BeanAccess props) { } } + /** + * Copies the properties of a bean into a store. + * + *

Each readable property, except {@code class}, whose value is not {@code null} is written as + * the text of the value. The elements of an array property are added one by one after the + * existing values, and any other value replaces the last one. + * + * @param props the store to change + * @param bean the bean to read + * @throws IllegalArgumentException if a property cannot be read; the message names the property + */ public void inject(BeanAccess props, Object bean) { for (PropertyDescriptor pd : getPropertyDescriptors(bean.getClass())) { try { @@ -93,6 +136,24 @@ public void inject(BeanAccess props, Object bean) { } } + /** + * Converts a text to a value of a type. + * + *

A {@code null} text gives the {@linkplain #zero(Class) zero value} of the type. A primitive + * type is parsed with the {@code valueOf} method of its wrapper, so any text other than {@code + * true} (in any letter case) is {@code false} for a {@code boolean}. {@link String} is returned + * as it is, and {@link Character} is the first character. {@link java.io.File}, {@link + * java.net.URL}, {@link java.net.URI}, {@link Class} (by name) and {@link java.util.TimeZone} are + * created from the text. Any other type must have a static {@code valueOf(String)} method. + * + * @param the type to convert to + * @param value the text, or {@code null} + * @param clazz the type + * @return the value + * @throws IllegalArgumentException if {@code clazz} is {@code null}, or the text cannot be + * converted; the cause tells why + * @throws StringIndexOutOfBoundsException if the text is empty and the type is {@code Character} + */ @SuppressWarnings("unchecked") public T parse(String value, Class clazz) throws IllegalArgumentException { if (clazz == null) { @@ -118,6 +179,18 @@ public T parse(String value, Class clazz) throws IllegalArgumentException return (T) o; } + /** + * Creates an object of an interface that reads and writes a store. + * + *

The object is a dynamic proxy that is created with the context class loader of the calling + * thread. The rules for the methods are described in {@link org.ini4j.OptionMap#as(Class)}. + * + * @param the interface type + * @param clazz the interface to implement + * @param props the store behind the object + * @return the proxy + * @throws IllegalArgumentException if {@code clazz} is not an interface + */ public T proxy(Class clazz, BeanAccess props) { return clazz.cast( Proxy.newProxyInstance( @@ -126,6 +199,14 @@ public T proxy(Class clazz, BeanAccess props) { new BeanInvocationHandler(props))); } + /** + * Returns the value that stands for "nothing" for a type. + * + * @param the type + * @param clazz the type + * @return {@code false}, {@code 0} or {@code '\0'} for a primitive type, and {@code null} for any + * other type, including {@code void} + */ @SuppressWarnings("unchecked") public T zero(Class clazz) { Object o = null; @@ -153,6 +234,16 @@ public T zero(Class clazz) { return (T) o; } + /** + * Converts a text to a value of a type that is not a primitive, a string or a character. + * + *

A subclass can override it to support more types. + * + * @param value the text + * @param clazz the type + * @return the value + * @throws IllegalArgumentException if the text cannot be converted; the cause tells why + */ protected Object parseSpecialValue(String value, Class clazz) throws IllegalArgumentException { Object o; diff --git a/src/main/java/org/ini4j/spi/EscapeTool.java b/src/main/java/org/ini4j/spi/EscapeTool.java index 10b6943..fda9681 100644 --- a/src/main/java/org/ini4j/spi/EscapeTool.java +++ b/src/main/java/org/ini4j/spi/EscapeTool.java @@ -15,6 +15,26 @@ */ package org.ini4j.spi; +/** + * Converts text to and from the backslash-escaped form of INI and options files. + * + *

This is the escaping that is used when {@link org.ini4j.Config#isEscape()} is on. The + * characters backslash, tab, line feed, form feed, backspace, carriage return, colon and equals + * sign are written as a backslash and a letter or sign ({@code \\}, {@code \t}, {@code \n}, {@code + * \f}, {@code \b}, {@code \r}, {@code \:} and {@code \=}). Every other character outside the + * printable ASCII range ({@code U+0020} to {@code U+007E}) is written as a backslash, the letter + * {@code u} and four lower case hexadecimal digits. {@link #unescape(String)} reverses {@link + * #escape(String)} for any text. {@link WinEscapeTool} and {@link RegEscapeTool} have their own + * forms. + * + *

The instance is created once, when the class is first used, with the provider lookup described + * in {@link IniParser#newInstance()}, using the name {@code org.ini4j.spi.EscapeTool}. A provider + * that cannot be created makes the class initialization fail. + * + *

The class has no state, so it can be used from several threads. + * + * @since 0.4.1 + */ public class EscapeTool { private static final String ESCAPE_LETTERS = "\\tnfbr:="; private static final String ESCAPEABLE_CHARS = "\\\t\n\f\b\r:="; @@ -31,10 +51,21 @@ public class EscapeTool { private static final int UNICODE_HEX_DIGITS = 4; static final char DOUBLE_QUOTE = '"'; + /** + * Returns the shared instance. + * + * @return the instance + */ public static EscapeTool getInstance() { return INSTANCE; } + /** + * Escapes a text. + * + * @param line the text to escape + * @return the escaped text + */ public String escape(String line) { int len = line.length(); StringBuilder buffer = new StringBuilder(len * 2); @@ -58,6 +89,15 @@ public String escape(String line) { return buffer.toString(); } + /** + * Puts a text in double quotes. + * + *

A backslash and a double quote inside the text get a backslash in front of them. + * + * @param value the text to quote + * @return the quoted text; {@code null} and an empty text are returned as they are, without + * quotes + */ public String quote(String value) { String ret = value; @@ -82,6 +122,19 @@ public String quote(String value) { return ret; } + /** + * Unescapes a text. + * + *

A backslash followed by a letter or sign of the table in the description of this class gives + * the character. A backslash followed by {@code u} and four hexadecimal digits gives the + * character with that code. A backslash before any other character is dropped and the character + * stays. + * + * @param line the escaped text + * @return the unescaped text + * @throws IllegalArgumentException if an escape with {@code u} is malformed + * @throws StringIndexOutOfBoundsException if the text ends with a single backslash + */ public String unescape(String line) { int n = line.length(); StringBuilder buffer = new StringBuilder(n); @@ -113,6 +166,17 @@ public String unescape(String line) { return buffer.toString(); } + /** + * Removes the quotes from a quoted text. + * + *

The first and the last character are removed, whatever they are. The text is expected to + * have the form that {@link #quote(String)} writes, where a backslash before a backslash or a + * double quote is removed. Other uses of the backslash are not handled consistently: a backslash + * before any other character is dropped, and the next backslash after it is then kept. + * + * @param value the quoted text + * @return the text without the quotes + */ public String unquote(String value) { StringBuilder buff = new StringBuilder(); boolean escape = false; @@ -136,6 +200,14 @@ public String unquote(String value) { return buff.toString(); } + /** + * Writes a character that has no short form as a {@code u} escape. + * + *

A subclass overrides it to use another form. + * + * @param buff the buffer to write to + * @param c the character + */ void escapeBinary(StringBuilder buff, char c) { buff.append("\\u"); buff.append(HEX[(c >>> HEX_DIGIT_1_OFFSET) & HEX_DIGIT_MASK]); @@ -144,6 +216,19 @@ void escapeBinary(StringBuilder buff, char c) { buff.append(HEX[c & HEX_DIGIT_MASK]); } + /** + * Reads an escape that has more than one character after the backslash. + * + *

A subclass overrides it to read other forms. When the type is not one it knows, it returns + * {@code index} and the caller treats the type as a plain escaped character. + * + * @param buff the buffer to write the character to + * @param escapeType the character after the backslash + * @param line the whole text + * @param index the position after {@code escapeType} + * @return the position after the escape, or {@code index} if this is not an escape of this kind + * @throws IllegalArgumentException if the escape is malformed + */ int unescapeBinary(StringBuilder buff, char escapeType, String line, int index) { int ret = index; diff --git a/src/main/java/org/ini4j/spi/RegEscapeTool.java b/src/main/java/org/ini4j/spi/RegEscapeTool.java index 0807f75..d9ed55f 100644 --- a/src/main/java/org/ini4j/spi/RegEscapeTool.java +++ b/src/main/java/org/ini4j/spi/RegEscapeTool.java @@ -21,6 +21,23 @@ import org.ini4j.Registry; import org.ini4j.Registry.Type; +/** + * Converts registry values between the text of a {@code .reg} file and their type and values. + * + *

The text of a value in a {@code .reg} file is either a quoted string, or a type prefix, a + * colon and the data (see {@link org.ini4j.Registry.Type}). {@link #decode(String)} and {@link + * #encode(TypeValuesPair)} convert between that text and a {@link TypeValuesPair}. Quoting is + * inherited from {@link EscapeTool}. + * + *

The instance is created once, when the class is first used, with the provider lookup described + * in {@link IniParser#newInstance()}, using the name {@code org.ini4j.spi.RegEscapeTool}. A + * provider that cannot be created makes the class initialization fail. + * + *

The class has no state, so it can be used from several threads. + * + * @see org.ini4j.Reg + * @since 0.5.0 + */ public class RegEscapeTool extends EscapeTool { private static final RegEscapeTool INSTANCE = ServiceFinder.findService(RegEscapeTool.class); private static final Charset HEX_CHARSET = StandardCharsets.UTF_16LE; @@ -28,10 +45,33 @@ public class RegEscapeTool extends EscapeTool { private static final int UPPER_DIGIT = 0xf0; private static final int DIGIT_SIZE = 4; + /** + * Returns the shared instance. + * + * @return the instance + */ public static final RegEscapeTool getInstance() { return INSTANCE; } + /** + * Splits the text of a value into its type and values. + * + *

A text that starts with a double quote is a {@link org.ini4j.Registry.Type#REG_SZ} string, + * and a text without a colon is one too. For a string, the first and last character are removed, + * whatever they are, and the escapes are resolved. The types {@link + * org.ini4j.Registry.Type#REG_EXPAND_SZ} and {@link org.ini4j.Registry.Type#REG_MULTI_SZ} hold + * hexadecimal bytes of UTF-16 little endian text, which are decoded; the multi-string gives one + * value for each string. A {@link org.ini4j.Registry.Type#REG_DWORD} gives its decimal text. For + * any other type, the data after the colon is the only value, as written. + * + * @param raw the text of the value + * @return the type and the values + * @throws NullPointerException if the type prefix is not known + * @throws NumberFormatException if a {@code dword} is not a hexadecimal number + * @throws StringIndexOutOfBoundsException if the text is empty, or the data of a {@code + * REG_EXPAND_SZ} value is empty + */ public TypeValuesPair decode(String raw) { Type type = type(raw); String value = @@ -65,6 +105,22 @@ public TypeValuesPair decode(String raw) { return new TypeValuesPair(type, values); } + /** + * Writes a type and values as the text of a value. + * + *

A {@link org.ini4j.Registry.Type#REG_SZ} string is quoted, and only its first value is used. + * An empty string is written as empty text, without quotes, as {@link #quote(String)} does, and + * {@link #decode(String)} cannot read that either. For the other types the text is the prefix of + * the type, a colon and the data, written in the form that {@link #decode(String)} reads, except + * that an empty {@code REG_EXPAND_SZ} value is written as empty data, which {@link + * #decode(String)} cannot read. Only the first value is used except for {@link + * org.ini4j.Registry.Type#REG_MULTI_SZ}, which writes all of them. + * + * @param data the type and values + * @return the text, or {@code null} if the first value is {@code null} + * @throws NumberFormatException if the type is {@code REG_DWORD} and the value is not a number + * @throws ArrayIndexOutOfBoundsException if the array of values is empty + */ public String encode(TypeValuesPair data) { String ret = null; diff --git a/src/main/java/org/ini4j/spi/TypeValuesPair.java b/src/main/java/org/ini4j/spi/TypeValuesPair.java index bd8abc3..131de99 100644 --- a/src/main/java/org/ini4j/spi/TypeValuesPair.java +++ b/src/main/java/org/ini4j/spi/TypeValuesPair.java @@ -17,21 +17,47 @@ import org.ini4j.Registry.Type; +/** + * A registry value type with the values of that type. + * + *

It is the result of {@link RegEscapeTool#decode(String)} and the argument of {@link + * RegEscapeTool#encode(TypeValuesPair)}. The array of values is not copied, neither by the + * constructor nor by {@link #getValues()}, so a change to the array shows in the pair. The class + * has no synchronization. + * + * @since 0.5.0 + */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings("EI_EXPOSE_REP") public class TypeValuesPair { private final Type _type; private final String[] _values; + /** + * Creates a pair. + * + * @param type the type of the values + * @param values the values; the array is stored, not copied + */ @SuppressWarnings("PMD.ArrayIsStoredDirectly") public TypeValuesPair(Type type, String[] values) { _type = type; _values = values; } + /** + * Returns the type. + * + * @return the type + */ public Type getType() { return _type; } + /** + * Returns the values. + * + * @return the array that was given to the constructor, not a copy + */ public String[] getValues() { return _values; } diff --git a/src/main/java/org/ini4j/spi/Warnings.java b/src/main/java/org/ini4j/spi/Warnings.java index a085d10..90a042e 100644 --- a/src/main/java/org/ini4j/spi/Warnings.java +++ b/src/main/java/org/ini4j/spi/Warnings.java @@ -15,7 +15,16 @@ */ package org.ini4j.spi; +/** + * Constants for {@link SuppressWarnings}. + * + *

The class only gives a name to the strings, so the library uses one spelling. It cannot be + * instantiated. + * + * @since 0.4.1 + */ public final class Warnings { + /** The name of the {@code unchecked} warning. */ public static final String UNCHECKED = "unchecked"; private Warnings() { diff --git a/src/main/java/org/ini4j/spi/WinEscapeTool.java b/src/main/java/org/ini4j/spi/WinEscapeTool.java index 50bafc2..ac6f7e7 100644 --- a/src/main/java/org/ini4j/spi/WinEscapeTool.java +++ b/src/main/java/org/ini4j/spi/WinEscapeTool.java @@ -15,6 +15,20 @@ */ package org.ini4j.spi; +/** + * The escape form of Windows INI files. + * + *

It is like {@link EscapeTool}, but a character without a short form is written as a backslash, + * the letter {@code x} and two hexadecimal digits that hold the low byte of the character, so + * characters above {@code U+00FF} lose their upper byte. When reading, a backslash and {@code x} + * with two hexadecimal digits, or {@code o} with three octal digits, gives the character with that + * code, and a backslash with {@code u} has no special meaning. {@link + * org.ini4j.Wini#escape(String)} uses it. + * + *

The class has no state, so it can be used from several threads. + * + * @since 0.5.0 + */ public final class WinEscapeTool extends EscapeTool { private static final int ANSI_HEX_DIGITS = 2; private static final int ANSI_OCTAL_DIGITS = 3; @@ -25,6 +39,11 @@ private WinEscapeTool() { // singleton } + /** + * Returns the shared instance. It does not use the provider lookup. + * + * @return the instance + */ public static WinEscapeTool getInstance() { return INSTANCE; } From 0869562a7a8270b966959c2a1fea8c6d63068f4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Iv=C3=A1n=20SZKIBA?= Date: Mon, 16 Nov 2026 09:13:53 +0100 Subject: [PATCH 8/9] docs: translate ServiceFinder and document the parsing internals ServiceFinder had Hungarian Javadoc with lost accents that also described a parameter that no longer exists. It is rewritten in English from the code. IniSource and the byte order mark reader get short docs because their rules (comment timing, pushback) are not obvious. Refs: #13 --- src/main/java/org/ini4j/spi/IniSource.java | 37 ++++++++- .../java/org/ini4j/spi/ServiceFinder.java | 75 ++++++++++++++----- .../ini4j/spi/UnicodeInputStreamReader.java | 21 +++++- 3 files changed, 112 insertions(+), 21 deletions(-) diff --git a/src/main/java/org/ini4j/spi/IniSource.java b/src/main/java/org/ini4j/spi/IniSource.java index 39842af..dc1204c 100644 --- a/src/main/java/org/ini4j/spi/IniSource.java +++ b/src/main/java/org/ini4j/spi/IniSource.java @@ -22,6 +22,23 @@ import java.net.URL; import org.ini4j.Config; +/** + * Reads the logical lines of an INI or options file for the parsers. + * + *

The source reads a line at a time and trims it. It skips blank lines, which also end a + * comment. It sends the comment lines to the handler (see {@link + * IniHandler#handleComment(String)}). Comment lines that follow each other are one comment, which + * is sent when a blank line, a line that is not a comment, or the end of the input comes. When + * {@link org.ini4j.Config#isEscapeNewline()} is on, a line that ends with an odd number of + * backslashes continues in the next line. When {@link org.ini4j.Config#isInclude()} is on, a line + * of the form {@code } or {@code } is replaced by the lines of that location. + * At the end of the input, the reader is closed. + * + *

Because comments are sent while the source looks for the next line, they reach the handler + * before the parser handles that line. + * + * @since 0.5.0 + */ class IniSource { public static final char INCLUDE_BEGIN = '<'; public static final char INCLUDE_END = '>'; @@ -54,6 +71,13 @@ class IniSource { _base = input; } + /** + * Returns the number of the line that was read last. + * + *

While lines of an included file are read, it is the line number in that file. + * + * @return the line number, which is 1 for the first line and 0 before any line has been read + */ int getLineNumber() { int ret; @@ -66,6 +90,17 @@ int getLineNumber() { return ret; } + /** + * Returns the next logical line. + * + *

The line is trimmed and is neither blank nor a comment. The comments that were collected on + * the way have been sent to the handler by the time the method returns, and so have those at the + * end of the input when {@code null} is returned. Blank lines are skipped and not sent. + * + * @return the line, or {@code null} at the end of the input + * @throws IOException if reading fails, or an include line cannot be opened and is not optional, + * or its location is malformed + */ String readLine() throws IOException { String line; @@ -174,7 +209,7 @@ private String readLineSkipComments() throws IOException { } } - // handle end comments + // report the comments at the end of the input if ((line == null) && (comment.length() != 0)) { handleComment(comment); } diff --git a/src/main/java/org/ini4j/spi/ServiceFinder.java b/src/main/java/org/ini4j/spi/ServiceFinder.java index 3019016..6ea027e 100755 --- a/src/main/java/org/ini4j/spi/ServiceFinder.java +++ b/src/main/java/org/ini4j/spi/ServiceFinder.java @@ -22,10 +22,14 @@ import java.nio.charset.StandardCharsets; /** - * JDK JAR Services API alap� service keres� oszt�ly. + * Finds the provider of a service and creates it. * - * @author Szkiba Iv�n - * @version $Name: $ + *

It follows the JAR Services API of the JDK, with a system property as an extra first source. + * Every {@code newInstance()} method of the SPI classes uses it, and so do the shared instances of + * {@link EscapeTool}, {@link RegEscapeTool} and {@link BeanTool}. The public description of the + * lookup is in {@link IniParser#newInstance()}. + * + * @since 0.4.1 */ final class ServiceFinder { private static final String SERVICES_PATH = "META-INF/services/"; @@ -33,28 +37,27 @@ final class ServiceFinder { 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. + * Finds the provider class of a service and creates an instance of it. * - *

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. + *

The name of the provider class is looked up in this order: the system property that is named + * like the service class, then the first line of the resource {@code META-INF/services/} and the + * name of the service class (see {@link #findServiceClassName(String)}). If neither gives a name, + * the service class itself is the provider. The class is loaded with the context class loader of + * the current thread, and created with its constructor that has no arguments. * - *

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. + *

The result is never {@code null}: every failure throws an exception. * - * @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 + * @param the type of the service + * @param clazz the service class, which is also the default provider + * @return a new instance of the provider + * @throws IllegalArgumentException if the provider cannot be found or created, for any reason + * that is an {@link Exception}; the cause tells why */ 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... + // The cast is not needed, but without it a ClassCastException would show up only at the + // caller. return clazz.cast(findServiceClass(clazz).getDeclaredConstructor().newInstance()); } catch (Exception x) { throw (IllegalArgumentException) @@ -64,6 +67,19 @@ static T findService(Class clazz) { } } + /** + * Finds the provider class of a service. + * + *

The name comes from {@link #findServiceClassName(String)}. If there is no name, the result + * is the service class itself. A name is loaded with the context class loader of the current + * thread, or with {@link Class#forName(String)} if the thread has none. + * + * @param the type of the service + * @param clazz the service class + * @return the provider class + * @throws IllegalArgumentException if the named class cannot be found + * @throws LinkageError if the JVM fails to load or link the class; it is not wrapped + */ @SuppressWarnings(Warnings.UNCHECKED) static Class findServiceClass(Class clazz) throws IllegalArgumentException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); @@ -87,6 +103,17 @@ static Class findServiceClass(Class clazz) throws IllegalArg return ret; } + /** + * Finds the name of the provider class of a service. + * + *

The first source that gives a value wins. The sources are the system property that has the + * service name as its name, and the first line of the resource {@code META-INF/services/} + * followed by the service name. A system property that cannot be read because of a security + * manager is skipped. See {@link #loadLine(String)} for the resource. + * + * @param serviceId the fully qualified name of the service class + * @return the name of the provider class, or {@code null} if there is none + */ static String findServiceClassName(String serviceId) throws IllegalArgumentException { String serviceClassName = null; @@ -108,6 +135,18 @@ static String findServiceClassName(String serviceId) throws IllegalArgumentExcep return serviceClassName; } + /** + * Reads the provider name from a service resource. + * + *

Only the first line of the resource is read, with the UTF-8 character set, using the context + * class loader of the current thread (or the system class loader if there is none). The line is + * trimmed and cut at the first white space or {@code #}. A blank first line gives {@code null}, + * and a line that starts with {@code #} gives an empty text. Any failure while reading is ignored + * and gives {@code null}. + * + * @param servicePath the path of the resource + * @return the name from the first line, or {@code null} + */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings("REC_CATCH_EXCEPTION") private static String loadLine(String servicePath) { String ret = null; diff --git a/src/main/java/org/ini4j/spi/UnicodeInputStreamReader.java b/src/main/java/org/ini4j/spi/UnicodeInputStreamReader.java index 405f7fb..8a82204 100644 --- a/src/main/java/org/ini4j/spi/UnicodeInputStreamReader.java +++ b/src/main/java/org/ini4j/spi/UnicodeInputStreamReader.java @@ -22,6 +22,16 @@ import java.io.Reader; import java.nio.charset.Charset; +/** + * A reader for a stream whose character set is chosen by its byte order mark. + * + *

If the stream starts with a byte order mark of UTF-8, UTF-16 or UTF-32 (the ones the JVM + * supports), the mark is skipped and its character set is used. Otherwise the default character set + * that was given to the constructor is used. The check runs when the stream is first read or + * closed. + * + * @since 0.5.2 + */ class UnicodeInputStreamReader extends Reader { private static final int BOM_SIZE = 4; @@ -101,8 +111,15 @@ public int read(char[] cbuf, int off, int len) throws IOException { } /** - * Read-ahead four bytes and check for BOM marks. Extra bytes are unread back to the stream, only - * BOM bytes are skipped. + * Reads the first bytes of the stream and looks for a byte order mark. + * + *

Up to four bytes are read. If they start with a byte order mark, the mark is skipped and the + * bytes after it are pushed back to the stream. Otherwise all the bytes that were read are pushed + * back. The method does nothing after the first call. The number of bytes to push back after a + * byte order mark assumes that four bytes were read. If the input is shorter and starts with a + * byte order mark, bytes of the mark can be pushed back and then read as text. + * + * @throws IOException if reading fails */ protected void init() throws IOException { if (_reader != null) { From f7a3e2a87418b172a0aa2836324d3f1a7132a7cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Iv=C3=A1n=20SZKIBA?= Date: Mon, 16 Nov 2026 09:13:53 +0100 Subject: [PATCH 9/9] docs: add package docs and fail the build on broken Javadoc The two package.html files said ini4j has a single package and did not explain the model. They become package-info.java with a glossary, an example and the provider lookup. The javadoc plugin now runs with doclint all,-missing and fails the build, and CI uploads the generated HTML as an artifact so a reviewer can read it. Refs: #13 --- .github/workflows/ci.yml | 8 +++ pom.xml | 4 +- src/main/java/org/ini4j/package-info.java | 72 +++++++++++++++++++ src/main/java/org/ini4j/package.html | 32 --------- src/main/java/org/ini4j/spi/package-info.java | 42 +++++++++++ src/main/java/org/ini4j/spi/package.html | 30 -------- 6 files changed, 124 insertions(+), 64 deletions(-) create mode 100644 src/main/java/org/ini4j/package-info.java delete mode 100755 src/main/java/org/ini4j/package.html create mode 100644 src/main/java/org/ini4j/spi/package-info.java delete mode 100644 src/main/java/org/ini4j/spi/package.html diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6374b8c..98af2de 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,3 +39,11 @@ jobs: **/target/surefire-reports/*.xml **/target/site/ retention-days: 7 + + - name: Upload Javadoc + if: success() + uses: actions/upload-artifact@50769540e7f4bd5e21e526ee35c689e35e0d6874 # v4.4.0 + with: + name: javadoc + path: target/apidocs/ + retention-days: 7 diff --git a/pom.xml b/pom.xml index 5e822da..017903b 100755 --- a/pom.xml +++ b/pom.xml @@ -150,8 +150,8 @@ jar - false - none + true + all,-missing diff --git a/src/main/java/org/ini4j/package-info.java b/src/main/java/org/ini4j/package-info.java new file mode 100644 index 0000000..09236d5 --- /dev/null +++ b/src/main/java/org/ini4j/package-info.java @@ -0,0 +1,72 @@ +/* + * Copyright 2005,2009 Ivan SZKIBA + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The main API of ini4j: reading, changing and writing INI files, option files and Windows registry + * files. + * + *

The file formats and their classes: + * + *

    + *
  • {@link org.ini4j.Ini} is an INI file with sections. {@link org.ini4j.Wini} is the same with + * the settings of Windows files. + *
  • {@link org.ini4j.Options} is a file of options without sections. + *
  • {@link org.ini4j.Reg} is a Windows registry export file ({@code .reg}), which is modeled by + * {@link org.ini4j.Registry}. + *
+ * + *

{@link org.ini4j.ConfigParser} offers the API of the Python {@code ConfigParser} on top of + * {@code Ini}, and {@link org.ini4j.IniPreferences} and {@link org.ini4j.IniPreferencesFactory} + * serve the {@code java.util.prefs} API from an INI file. The behavior of parsing and writing is + * set with {@link org.ini4j.Config}. The parsers, the formatters and the events between them are in + * the package {@code org.ini4j.spi}. + * + *

This example loads a file, reads a value, changes it and stores the file: + * + *

{@code
+ * Ini ini = new Ini(new File("dwarfs.ini"));
+ * int age = ini.get("happy", "age", int.class);
+ *
+ * ini.put("happy", "age", age + 1);
+ * ini.store();
+ * }
+ * + *

These words have a fixed meaning in the documentation: + * + *

+ *
section + *
A named group of options, written as {@code [name]} in a file. The type is {@link + * org.ini4j.Profile.Section}. A section name can contain the path separator, such as {@code + * a/b}, which makes the section a child of the section {@code a}. + *
option + *
A named value in a section, written as {@code name=value}. The names and the values are + * text. A group of options is an {@link org.ini4j.OptionMap}. + *
multi-valued option + *
An option name that has more than one value, for example because the name is repeated in + * the file. The values are indexed from zero, see {@link org.ini4j.MultiMap} and {@link + * org.ini4j.Config#isMultiOption()}. + *
profile + *
The whole content of an INI file: its sections and the comment of the file. The type is + * {@link org.ini4j.Profile}. + *
global section + *
The section that holds the options that come before the first section header, if {@link + * org.ini4j.Config#isGlobalSection()} is on. It is named by {@link + * org.ini4j.Config#getGlobalSectionName()}. + *
registry key + *
A section of a registry file. Its name is the full path of the key, and its options are the + * values of the key, each with a type. The type is {@link org.ini4j.Registry.Key}. + *
+ */ +package org.ini4j; diff --git a/src/main/java/org/ini4j/package.html b/src/main/java/org/ini4j/package.html deleted file mode 100755 index 0b42f7f..0000000 --- a/src/main/java/org/ini4j/package.html +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - [ini4j] main package - - -

[ini4j] main package

-

This package contains [ini4j] API. This is a very small library, so - no interface and implementation separation neccessary. This is why [ini4j] - has only one package. -

- - diff --git a/src/main/java/org/ini4j/spi/package-info.java b/src/main/java/org/ini4j/spi/package-info.java new file mode 100644 index 0000000..45b929e --- /dev/null +++ b/src/main/java/org/ini4j/spi/package-info.java @@ -0,0 +1,42 @@ +/* + * Copyright 2005,2009 Ivan SZKIBA + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The parsers, formatters and handlers that read and write the files, and the tools they use. + * + *

Reading and writing work with events. A parser ({@link org.ini4j.spi.IniParser}, {@link + * org.ini4j.spi.OptionsParser}) reads a file and calls the methods of a handler ({@link + * org.ini4j.spi.IniHandler}, {@link org.ini4j.spi.OptionsHandler}) for each section, option and + * comment. A builder ({@link org.ini4j.spi.IniBuilder}, {@link org.ini4j.spi.OptionsBuilder}, + * {@link org.ini4j.spi.RegBuilder}) is a handler that fills an {@link org.ini4j.Ini}, an {@link + * org.ini4j.Options} or a {@link org.ini4j.Reg} from these events. A formatter ({@link + * org.ini4j.spi.IniFormatter}, {@link org.ini4j.spi.OptionsFormatter}) is a handler that writes the + * events as text. When an object is stored, it sends its content to a formatter as the same events. + * The order of the events is described in {@link org.ini4j.spi.IniHandler} and {@link + * org.ini4j.spi.OptionsHandler}. + * + *

The classes that do this work can be replaced. The factory methods, such as {@link + * org.ini4j.spi.IniParser#newInstance()}, look for the class to create in the system property that + * is named like the class, then in the first line of the file {@code META-INF/services/} and the + * name of the class, and use the class itself if there is no such name. The provider is a subclass + * with a public constructor without arguments. The full description is in {@link + * org.ini4j.spi.IniParser#newInstance()}. + * + *

The package also has the tools for the escape forms ({@link org.ini4j.spi.EscapeTool}, {@link + * org.ini4j.spi.WinEscapeTool}, {@link org.ini4j.spi.RegEscapeTool}) and for beans ({@link + * org.ini4j.spi.BeanTool}, {@link org.ini4j.spi.BeanAccess}, {@link + * org.ini4j.spi.AbstractBeanInvocationHandler}). + */ +package org.ini4j.spi; diff --git a/src/main/java/org/ini4j/spi/package.html b/src/main/java/org/ini4j/spi/package.html deleted file mode 100644 index ba730a2..0000000 --- a/src/main/java/org/ini4j/spi/package.html +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - [ini4j] service provider package - - -

[ini4j] service provider package

-

This package contains [ini4j] service provider API. -

- -