This is an automated email from the ASF dual-hosted git repository.
jamesbognar pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/juneau.git
The following commit(s) were added to refs/heads/master by this push:
new e94b6f6d3 Fix SonarQube issues.
e94b6f6d3 is described below
commit e94b6f6d395f126ba6d7b5ba9bb9b2c2ac5cb178
Author: James Bognar <[email protected]>
AuthorDate: Sun Jul 27 17:32:39 2025 -0400
Fix SonarQube issues.
---
.../main/java/org/apache/juneau/config/Config.java | 123 +++++----
.../main/java/org/apache/juneau/config/Entry.java | 31 ++-
.../java/org/apache/juneau/config/Section.java | 57 ++---
.../apache/juneau/config/event/ConfigEvent.java | 10 +-
.../apache/juneau/config/internal/ConfigMap.java | 278 +++++++++++----------
.../juneau/config/internal/ConfigMapEntry.java | 30 +--
.../java/org/apache/juneau/config/mod/Mod.java | 2 +-
.../org/apache/juneau/config/mod/XorEncodeMod.java | 12 +-
.../apache/juneau/config/store/ClasspathStore.java | 8 +-
.../apache/juneau/config/store/ConfigStore.java | 22 +-
.../org/apache/juneau/config/store/FileStore.java | 54 ++--
.../apache/juneau/config/store/MemoryStore.java | 2 +-
.../org/apache/juneau/config/vars/ConfigVar.java | 2 +-
.../apache/juneau/internal/CollectionUtils.java | 41 +++
.../java/org/apache/juneau/rest/RestRequest.java | 46 ++--
15 files changed, 374 insertions(+), 344 deletions(-)
diff --git
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/Config.java
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/Config.java
index 1fc7beac0..12575c29d 100644
---
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/Config.java
+++
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/Config.java
@@ -22,6 +22,7 @@ import java.io.*;
import java.lang.annotation.*;
import java.lang.reflect.*;
import java.util.*;
+import java.util.concurrent.atomic.*;
import org.apache.juneau.*;
import org.apache.juneau.collections.*;
@@ -54,16 +55,16 @@ public final class Config extends Context implements
ConfigEventListener {
// Static
//-----------------------------------------------------------------------------------------------------------------
- private static boolean DISABLE_AUTO_SYSTEM_PROPS =
Boolean.getBoolean("juneau.disableAutoSystemProps");
- private static volatile Config SYSTEM_DEFAULT = findSystemDefault();
+ private static final boolean DISABLE_AUTO_SYSTEM_PROPS =
Boolean.getBoolean("juneau.disableAutoSystemProps");
+ private static final AtomicReference<Config> SYSTEM_DEFAULT = new
AtomicReference<>(findSystemDefault());
/**
* Sets a system default configuration.
*
* @param systemDefault The new system default configuration.
*/
- public synchronized static void setSystemDefault(Config systemDefault) {
- SYSTEM_DEFAULT = systemDefault;
+ public static synchronized void setSystemDefault(Config systemDefault) {
+ SYSTEM_DEFAULT.set(systemDefault);
}
/**
@@ -71,14 +72,14 @@ public final class Config extends Context implements
ConfigEventListener {
*
* @return The system default configuration, or <jk>null</jk> if it
doesn't exist.
*/
- public synchronized static Config getSystemDefault() {
- return SYSTEM_DEFAULT;
+ public static synchronized Config getSystemDefault() {
+ return SYSTEM_DEFAULT.get();
}
- private synchronized static Config findSystemDefault() {
+ private static synchronized Config findSystemDefault() {
- for (String n : getCandidateSystemDefaultConfigNames()) {
- Config config = find(n);
+ for (var n : getCandidateSystemDefaultConfigNames()) {
+ var config = find(n);
if (config != null) {
if (! DISABLE_AUTO_SYSTEM_PROPS)
config.setSystemProperties();
@@ -112,16 +113,16 @@ public final class Config extends Context implements
ConfigEventListener {
* <br>The returned list is modifiable.
* <br>Each call constructs a new list.
*/
- public synchronized static List<String>
getCandidateSystemDefaultConfigNames() {
- List<String> l = list();
+ public static synchronized List<String>
getCandidateSystemDefaultConfigNames() {
+ var l = listOf(String.class);
- String s = System.getProperty("juneau.configFile");
+ var s = System.getProperty("juneau.configFile");
if (s != null) {
l.add(s);
return l;
}
- String cmd = System.getProperty("sun.java.command",
"not_found").split("\\s+")[0];
+ var cmd = System.getProperty("sun.java.command",
"not_found").split("\\s+")[0];
if (cmd.endsWith(".jar") && ! cmd.contains("surefirebooter")) {
cmd = cmd.replaceAll(".*?([^\\\\\\/]+)\\.jar$", "$1");
l.add(cmd + ".cfg");
@@ -129,8 +130,8 @@ public final class Config extends Context implements
ConfigEventListener {
l.add(cmd + ".cfg");
}
- Set<File> files = sortedSet(new File(".").listFiles());
- for (File f : files)
+ var files = sortedSet(new File(".").listFiles());
+ for (var f : files)
if (f.getName().endsWith(".cfg"))
l.add(f.getName());
@@ -144,7 +145,7 @@ public final class Config extends Context implements
ConfigEventListener {
return l;
}
- private synchronized static Config find(String name) {
+ private static synchronized Config find(String name) {
if (name == null)
return null;
if (FileStore.DEFAULT.exists(name))
@@ -357,7 +358,7 @@ public final class Config extends Context implements
ConfigEventListener {
* @return This object.
*/
public Builder mods(Mod...values) {
- for (Mod value : values)
+ for (var value : values)
mods.put(value.getId(), value);
return this;
}
@@ -638,10 +639,10 @@ public final class Config extends Context implements
ConfigEventListener {
*/
private String getRaw(String key) {
- String sname = sname(key);
- String skey = skey(key);
+ var sname = sname(key);
+ var skey = skey(key);
- ConfigMapEntry ce = configMap.getEntry(sname, skey);
+ var ce = configMap.getEntry(sname, skey);
if (ce == null)
return null;
@@ -651,7 +652,7 @@ public final class Config extends Context implements
ConfigEventListener {
String applyMods(String mods, String x) {
if (mods != null && x != null)
- for (int i = 0; i < mods.length(); i++)
+ for (var i = 0; i < mods.length(); i++)
x = getMod(mods.charAt(i)).doApply(x);
return x;
}
@@ -664,7 +665,7 @@ public final class Config extends Context implements
ConfigEventListener {
}
Mod getMod(char id) {
- Mod x = mods.get(id);
+ var x = mods.get(id);
return x == null ? Mod.NO_OP : x;
}
@@ -678,9 +679,9 @@ public final class Config extends Context implements
ConfigEventListener {
* @return This object.
*/
public Config setSystemProperties() {
- for (String section : getSectionNames()) {
- for (String key : getKeys(section)) {
- String k = (section.isEmpty() ? key : section +
'/' + key);
+ for (var section : getSectionNames()) {
+ for (var key : getKeys(section)) {
+ var k = (section.isEmpty() ? key : section +
'/' + key);
System.setProperty(k, getRaw(k));
}
}
@@ -702,14 +703,14 @@ public final class Config extends Context implements
ConfigEventListener {
public Config set(String key, String value) {
checkWrite();
assertArgNotNull("key", key);
- String sname = sname(key);
- String skey = skey(key);
+ var sname = sname(key);
+ var skey = skey(key);
- ConfigMapEntry ce = configMap.getEntry(sname, skey);
+ var ce = configMap.getEntry(sname, skey);
if (ce == null && value == null)
return this;
- String s = applyMods(ce == null ? null : ce.getModifiers(),
stringify(value));
+ var s = applyMods(ce == null ? null : ce.getModifiers(),
stringify(value));
configMap.setEntry(sname, skey, s, null, null, null);
return this;
@@ -776,11 +777,11 @@ public final class Config extends Context implements
ConfigEventListener {
public Config set(String key, Object value, Serializer serializer,
String modifiers, String comment, List<String> preLines) throws
SerializeException {
checkWrite();
assertArgNotNull("key", key);
- String sname = sname(key);
- String skey = skey(key);
+ var sname = sname(key);
+ var skey = skey(key);
modifiers = nullIfEmpty(modifiers);
- String s = applyMods(modifiers, serialize(value, serializer));
+ var s = applyMods(modifiers, serialize(value, serializer));
configMap.setEntry(sname, skey, s, modifiers, comment,
preLines);
return this;
@@ -795,8 +796,8 @@ public final class Config extends Context implements
ConfigEventListener {
*/
public Config remove(String key) {
checkWrite();
- String sname = sname(key);
- String skey = skey(key);
+ var sname = sname(key);
+ var skey = skey(key);
configMap.removeEntry(sname, skey);
return this;
}
@@ -813,14 +814,14 @@ public final class Config extends Context implements
ConfigEventListener {
*/
public Config applyMods() {
checkWrite();
- for (String section : configMap.getSections()) {
- for (String key : configMap.getKeys(section)) {
- ConfigMapEntry ce = configMap.getEntry(section,
key);
+ for (var section : configMap.getSections()) {
+ for (var key : configMap.getKeys(section)) {
+ var ce = configMap.getEntry(section, key);
if (ce.getModifiers() != null) {
- String mods = ce.getModifiers();
- String value = ce.getValue();
- for (int i = 0; i < mods.length(); i++)
{
- Mod mod =
getMod(mods.charAt(i));
+ var mods2 = ce.getModifiers();
+ var value = ce.getValue();
+ for (var i = 0; i < mods2.length();
i++) {
+ var mod =
getMod(mods2.charAt(i));
if (! mod.isApplied(value)) {
configMap.setEntry(section, key, mod.apply(value), null, null, null);
}
@@ -976,7 +977,7 @@ public final class Config extends Context implements
ConfigEventListener {
configMap.setSection(section(name), preLines);
if (contents != null)
- for (Map.Entry<String,Object> e : contents.entrySet())
+ for (var e : contents.entrySet())
set(section(name) + '/' + e.getKey(),
e.getValue());
return this;
@@ -1045,7 +1046,7 @@ public final class Config extends Context implements
ConfigEventListener {
*/
public Config load(Map<String,Map<String,Object>> m) throws
SerializeException {
if (m != null)
- for (Map.Entry<String,Map<String,Object>> e :
m.entrySet()) {
+ for (var e : m.entrySet()) {
setSection(e.getKey(), null, e.getValue());
}
return this;
@@ -1105,10 +1106,8 @@ public final class Config extends Context implements
ConfigEventListener {
/**
* Closes this configuration object by unregistering it from the
underlying config map.
- *
- * @throws IOException Thrown by underlying stream.
*/
- public void close() throws IOException {
+ public void close() {
configMap.unregister(this);
}
@@ -1184,8 +1183,7 @@ public final class Config extends Context implements
ConfigEventListener {
@Override /* ConfigEventListener */
public synchronized void onConfigChange(ConfigEvents events) {
- for (ConfigEventListener l : listeners)
- l.onConfigChange(events);
+ listeners.forEach(x -> x.onConfigChange(events));
}
//-----------------------------------------------------------------------------------------------------------------
@@ -1197,26 +1195,25 @@ public final class Config extends Context implements
ConfigEventListener {
return "";
if (serializer == null)
serializer = this.serializer;
- Class<?> c = value.getClass();
- if (value instanceof CharSequence)
- return nlIfMl((CharSequence)value);
+ var c = value.getClass();
+ if (value instanceof CharSequence cs)
+ return nlIfMl(cs);
if (isSimpleType(c))
return value.toString();
- if (value instanceof byte[]) {
+ if (value instanceof byte[] b) {
String s = null;
- byte[] b = (byte[])value;
if (binaryFormat == BinaryFormat.HEX)
s = toHex(b);
else if (binaryFormat == BinaryFormat.SPACED_HEX)
s = toSpacedHex(b);
else
s = base64Encode(b);
- int l = binaryLineLength;
+ var l = binaryLineLength;
if (l <= 0 || s.length() <= l)
return s;
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < s.length(); i += l)
+ var sb = new StringBuilder();
+ for (var i = 0; i < s.length(); i += l)
sb.append(binaryLineLength > 0 ? "\n" :
"").append(s.substring(i, Math.min(s.length(), i + l)));
return sb.toString();
}
@@ -1233,7 +1230,7 @@ public final class Config extends Context implements
ConfigEventListener {
}
private String nlIfMl(CharSequence cs) {
- String s = cs.toString();
+ var s = cs.toString();
if (s.indexOf('\n') != -1 && multiLineValuesOnSeparateLines)
return "\n" + s;
return s;
@@ -1242,20 +1239,20 @@ public final class Config extends Context implements
ConfigEventListener {
private boolean isSimpleType(Type t) {
if (! (t instanceof Class))
return false;
- Class<?> c = (Class<?>)t;
+ var c = (Class<?>)t;
return (c == String.class || c.isPrimitive() ||
c.isAssignableFrom(Number.class) || c == Boolean.class || c.isEnum());
}
private String sname(String key) {
assertArgNotNull("key", key);
- int i = key.indexOf('/');
+ var i = key.indexOf('/');
if (i == -1)
return "";
return key.substring(0, i);
}
private String skey(String key) {
- int i = key.indexOf('/');
+ var i = key.indexOf('/');
if (i == -1)
return key;
return key.substring(i+1);
@@ -1273,7 +1270,6 @@ public final class Config extends Context implements
ConfigEventListener {
throw new UnsupportedOperationException("Cannot call
this method on a read-only configuration.");
}
-
//-----------------------------------------------------------------------------------------------------------------
// Other methods
//-----------------------------------------------------------------------------------------------------------------
@@ -1282,9 +1278,4 @@ public final class Config extends Context implements
ConfigEventListener {
public String toString() {
return configMap.toString();
}
-
- @Override /* Object */
- protected void finalize() throws Throwable {
- close();
- }
}
diff --git
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/Entry.java
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/Entry.java
index 5ce55cae8..b969d63d3 100644
---
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/Entry.java
+++
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/Entry.java
@@ -204,11 +204,11 @@ public class Entry {
return empty();
try {
- String v = toString();
+ var v = toString();
if (type == String.class) return
(Optional<T>)asString();
if (type == String[].class) return
(Optional<T>)asStringArray();
if (type == byte[].class) return (Optional<T>)asBytes();
- if (type == int.class || type == int.class || type ==
Integer.class) return (Optional<T>)asInteger();
+ if (type == int.class || type == Integer.class) return
(Optional<T>)asInteger();
if (type == long.class || type == Long.class) return
(Optional<T>)asLong();
if (type == JsonMap.class) return (Optional<T>)asMap();
if (type == JsonList.class) return
(Optional<T>)asList();
@@ -216,7 +216,7 @@ public class Entry {
if (isSimpleType(type)) return
optional((T)config.beanSession.convertToType(v, (Class<?>)type));
if (parser instanceof JsonParser) {
- char s1 = firstNonWhitespaceChar(v);
+ var s1 = firstNonWhitespaceChar(v);
if (isArray(type) && s1 != '[')
v = '[' + v + ']';
else if (s1 != '[' && s1 != '{' && !
"null".equals(v))
@@ -270,8 +270,9 @@ public class Entry {
public Optional<String[]> asStringArray() {
if (! isPresent())
return empty();
- String v = toString();
- char s1 = firstNonWhitespaceChar(v), s2 =
lastNonWhitespaceChar(v);
+ var v = toString();
+ var s1 = firstNonWhitespaceChar(v);
+ var s2 = lastNonWhitespaceChar(v);
if (s1 == '[' && s2 == ']' && config.parser instanceof
JsonParser) {
try {
return optional(config.parser.parse(v,
String[].class));
@@ -363,7 +364,6 @@ public class Entry {
return optional(isEmpty() ? null :
(Long)parseLongWithSuffix(toString()));
}
-
/**
* Returns this entry as a double.
*
@@ -382,7 +382,6 @@ public class Entry {
return optional(isEmpty() ? null : Double.valueOf(toString()));
}
-
/**
* Returns this entry as a float.
*
@@ -401,7 +400,6 @@ public class Entry {
return optional(isEmpty() ? null : Float.valueOf(toString()));
}
-
/**
* Returns this entry as a byte array.
*
@@ -413,9 +411,9 @@ public class Entry {
public Optional<byte[]> asBytes() {
if (isNull())
return empty();
- String s = toString();
+ var s = toString();
if (s.indexOf('\n') != -1)
- s = s.replaceAll("\n", "");
+ s = s.replace("\n", "");
try {
if (config.binaryFormat == HEX)
return optional(fromHex(s));
@@ -458,9 +456,9 @@ public class Entry {
return empty();
if (parser == null)
parser = config.parser;
- String s = toString();
+ var s = toString();
if (parser instanceof JsonParser) {
- char s1 = firstNonWhitespaceChar(s);
+ var s1 = firstNonWhitespaceChar(s);
if (s1 != '{' && ! "null".equals(s))
s = '{' + s + '}';
}
@@ -483,7 +481,6 @@ public class Entry {
return asList(config.parser);
}
-
/**
* Returns this entry as a parsed list.
*
@@ -499,9 +496,9 @@ public class Entry {
return empty();
if (parser == null)
parser = config.parser;
- String s = toString();
+ var s = toString();
if (parser instanceof JsonParser) {
- char s1 = firstNonWhitespaceChar(s);
+ var s1 = firstNonWhitespaceChar(s);
if (s1 != '[' && ! "null".equals(s))
s = '[' + s + ']';
}
@@ -572,14 +569,14 @@ public class Entry {
private boolean isArray(Type t) {
if (! (t instanceof Class))
return false;
- Class<?> c = (Class<?>)t;
+ var c = (Class<?>)t;
return (c.isArray());
}
private boolean isSimpleType(Type t) {
if (! (t instanceof Class))
return false;
- Class<?> c = (Class<?>)t;
+ var c = (Class<?>)t;
return (c == String.class || c.isPrimitive() ||
c.isAssignableFrom(Number.class) || c == Boolean.class || c.isEnum());
}
}
diff --git
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/Section.java
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/Section.java
index 3fdd90566..5f0e77837 100644
---
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/Section.java
+++
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/Section.java
@@ -18,7 +18,6 @@ import java.beans.*;
import java.lang.reflect.*;
import java.util.*;
-import org.apache.juneau.*;
import org.apache.juneau.collections.*;
import org.apache.juneau.config.internal.*;
import org.apache.juneau.parser.*;
@@ -107,14 +106,15 @@ public class Section {
*/
public <T> Optional<T> asBean(Class<T> c, boolean
ignoreUnknownProperties) throws ParseException {
assertArgNotNull("c", c);
+
if (! isPresent())
return empty();
- Set<String> keys = configMap.getKeys(name);
+ var keys = configMap.getKeys(name);
- BeanMap<T> bm = config.beanSession.newBeanMap(c);
- for (String k : keys) {
- BeanPropertyMeta bpm = bm.getPropertyMeta(k);
+ var bm = config.beanSession.newBeanMap(c);
+ for (var k : keys) {
+ var bpm = bm.getPropertyMeta(k);
if (bpm == null) {
if (! ignoreUnknownProperties)
throw new ParseException("Unknown
property ''{0}'' encountered in configuration section ''{1}''.", k, name);
@@ -135,10 +135,10 @@ public class Section {
if (! isPresent())
return empty();
- Set<String> keys = configMap.getKeys(name);
+ var keys = configMap.getKeys(name);
- JsonMap m = new JsonMap();
- for (String k : keys)
+ var m = new JsonMap();
+ for (var k : keys)
m.put(k, config.get(name + '/' +
k).as(Object.class).orElse(null));
return optional(m);
}
@@ -204,24 +204,25 @@ public class Section {
* @return The proxy interface.
*/
@SuppressWarnings("unchecked")
- public <T> Optional<T> asInterface(final Class<T> c) {
- assertArgNotNull("c", c);
+ public <T> Optional<T> asInterface(final Class<T> c) {
+ assertArgNotNull("c", c);
- if (!c.isInterface())
- throw new IllegalArgumentException("Class '" + c.getName() + "'
passed to toInterface() is not an interface.");
+ if (!c.isInterface())
+ throw new IllegalArgumentException("Class '" +
c.getName() + "' passed to toInterface() is not an interface.");
- return optional((T) Proxy.newProxyInstance(c.getClassLoader(), new
Class[] { c }, (InvocationHandler) (proxy, method, args) -> {
- BeanInfo bi = Introspector.getBeanInfo(c, null);
- for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
- Method rm = pd.getReadMethod(), wm = pd.getWriteMethod();
- if (method.equals(rm))
- return config.get(name + '/' +
pd.getName()).as(rm.getGenericReturnType()).orElse(null);
- if (method.equals(wm))
- return config.set(name + '/' + pd.getName(), args[0]);
- }
- throw new UnsupportedOperationException("Unsupported interface
method. method='" + method + "'");
- }));
- }
+ return optional((T) Proxy.newProxyInstance(c.getClassLoader(),
new Class[] { c }, (InvocationHandler) (proxy, method, args) -> {
+ var bi = Introspector.getBeanInfo(c, null);
+ for (var pd : bi.getPropertyDescriptors()) {
+ var rm = pd.getReadMethod();
+ var wm = pd.getWriteMethod();
+ if (method.equals(rm))
+ return config.get(name + '/' +
pd.getName()).as(rm.getGenericReturnType()).orElse(null);
+ if (method.equals(wm))
+ return config.set(name + '/' +
pd.getName(), args[0]);
+ }
+ throw new UnsupportedOperationException("Unsupported
interface method. method='" + method + "'");
+ }));
+ }
/**
* Copies the entries in this section to the specified bean by calling
the public setters on that bean.
@@ -238,11 +239,11 @@ public class Section {
assertArgNotNull("bean", bean);
if (! isPresent()) throw new IllegalArgumentException("Section
'"+name+"' not found in configuration.");
- Set<String> keys = configMap.getKeys(name);
+ var keys = configMap.getKeys(name);
- BeanMap<?> bm = config.beanSession.toBeanMap(bean);
- for (String k : keys) {
- BeanPropertyMeta bpm = bm.getPropertyMeta(k);
+ var bm = config.beanSession.toBeanMap(bean);
+ for (var k : keys) {
+ var bpm = bm.getPropertyMeta(k);
if (bpm == null) {
if (! ignoreUnknownProperties)
throw new ParseException("Unknown
property ''{0}'' encountered in configuration section ''{1}''.", k, name);
diff --git
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/event/ConfigEvent.java
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/event/ConfigEvent.java
index 264ba5f5d..506d8aa9c 100644
---
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/event/ConfigEvent.java
+++
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/event/ConfigEvent.java
@@ -202,7 +202,7 @@ public class ConfigEvent {
@Override /* Object */
public String toString() {
- switch(type) {
+ switch (type) {
case REMOVE_SECTION:
return "REMOVE_SECTION("+section+")";
case REMOVE_ENTRY:
@@ -210,23 +210,23 @@ public class ConfigEvent {
case SET_SECTION:
return "SET_SECTION("+section+",
preLines="+StringUtils.join(preLines, '|')+")";
case SET_ENTRY:
- StringBuilder out = new StringBuilder("SET(");
+ var out = new StringBuilder("SET(");
out.append(section+(section.isEmpty() ? "" :
"/") + key);
if (modifiers != null)
out.append(modifiers);
out.append(" = ");
- String val = value == null ? "null" : value;
+ var val = value == null ? "null" : value;
if (val.indexOf('\n') != -1)
val = val.replaceAll("(\\r?\\n)",
"$1\t");
if (val.indexOf('#') != -1)
- val = val.replaceAll("#", "\\\\#");
+ val = val.replace("#", "\\#");
out.append(val);
if (isNotEmpty(comment))
out.append(" # ").append(comment);
out.append(')');
return out.toString();
default:
- return null;
+ return null; // NOSONAR - Intentional.
}
}
}
diff --git
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/internal/ConfigMap.java
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/internal/ConfigMap.java
index 51bb45cab..25b2b8df5 100644
---
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/internal/ConfigMap.java
+++
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/internal/ConfigMap.java
@@ -20,6 +20,7 @@ import static
org.apache.juneau.config.event.ConfigEventType.*;
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
+import java.util.stream.*;
import org.apache.juneau.*;
import org.apache.juneau.collections.*;
@@ -83,32 +84,32 @@ public class ConfigMap implements ConfigStoreListener {
imports.forEach(Import::unregisterAll);
imports.clear();
- Map<String,ConfigMap> imports = map();
+ var imports2 = mapOf(String.class, ConfigMap.class);
List<String> lines = linkedList();
- try (Scanner scanner = new Scanner(contents)) {
+ try (var scanner = new Scanner(contents)) {
while (scanner.hasNextLine()) {
- String line = scanner.nextLine();
- char c = firstChar(line);
- int c2 =
StringUtils.lastNonWhitespaceChar(line);
+ var line = scanner.nextLine();
+ var c = firstChar(line);
+ var c2 =
StringUtils.lastNonWhitespaceChar(line);
if (c == '[') {
- String l = line.trim();
+ var l = line.trim();
if (c2 != ']' || !
isValidNewSectionName(l.substring(1, l.length()-1)))
throw new
ConfigException("Invalid section name found in configuration: {0}", line);
} else if (c == '<') {
- String l = line.trim();
- int i = l.indexOf('>');
+ var l = line.trim();
+ var i = l.indexOf('>');
if (i != -1) {
- String l2 = l.substring(1, i);
+ var l2 = l.substring(1, i);
if (! isValidConfigName(l2))
throw new
ConfigException("Invalid import config name found in configuration: {0}",
line);
- String l3 = l.substring(i+1);
+ var l3 = l.substring(i+1);
if (! (isEmpty(l3) ||
firstChar(l3) == '#'))
throw new
ConfigException("Invalid import config name found in configuration: {0}",
line);
- String importName = l2.trim();
+ var importName = l2.trim();
try {
- if (!
imports.containsKey(importName))
-
imports.put(importName, store.getMap(importName));
+ if (!
imports2.containsKey(importName))
+
imports2.put(importName, store.getMap(importName));
} catch (StackOverflowError e) {
throw new
IOException("Import loop detected in configuration
'"+name+"'->'"+importName+"'");
}
@@ -118,16 +119,16 @@ public class ConfigMap implements ConfigStoreListener {
}
}
- List<Import> irl = list(imports.size());
- forEachReverse(listFrom(imports.values()), x -> irl.add(new
Import(x).register(listeners)));
+ List<Import> irl = list(imports2.size());
+ forEachReverse(listFrom(imports2.values()), x -> irl.add(new
Import(x).register(listeners)));
this.imports.addAll(irl);
// Add [blank] section.
- boolean inserted = false;
- boolean foundComment = false;
- for (ListIterator<String> li = lines.listIterator();
li.hasNext();) {
- String l = li.next();
- char c = firstNonWhitespaceChar(l);
+ var inserted = false;
+ var foundComment = false;
+ for (var li = lines.listIterator(); li.hasNext();) {
+ var l = li.next();
+ var c = firstNonWhitespaceChar(l);
if (c != '#') {
if (c == 0 && foundComment) {
li.set("[]");
@@ -141,18 +142,18 @@ public class ConfigMap implements ConfigStoreListener {
lines.add(0, "[]");
// Collapse any multi-lines.
- ListIterator<String> li = lines.listIterator(lines.size());
+ var li = lines.listIterator(lines.size());
String accumulator = null;
while (li.hasPrevious()) {
- String l = li.previous();
- char c = firstChar(l);
+ var l = li.previous();
+ var c = firstChar(l);
if (c == '\t') {
c = firstNonWhitespaceChar(l);
if (c != '#') {
if (accumulator == null)
accumulator = l.substring(1);
else
- accumulator = l.substring(1) +
"\n" + accumulator;
+ accumulator = l.substring(1) +
"\n" + accumulator; // NOSONAR - Intentionally not using StringBuilder.
li.remove();
}
} else if (accumulator != null) {
@@ -162,16 +163,19 @@ public class ConfigMap implements ConfigStoreListener {
}
lines = copyOf(lines);
- int last = lines.size()-1;
- int S1 = 1; // Looking for section.
- int S2 = 2; // Found section, looking for start.
- int state = S1;
+ var last = lines.size()-1;
- List<ConfigSection> sections = list();
+ final int
+ S1 = 1, // Looking for section.
+ S2 = 2; // Found section, looking for start.
- for (int i = last; i >= 0; i--) {
- String l = lines.get(i);
- char c = firstChar(l);
+ var state = S1;
+
+ var sections = listOf(ConfigSection.class);
+
+ for (var i = last; i >= 0; i--) {
+ var l = lines.get(i);
+ var c = firstChar(l);
if (state == S1) {
if (c == '[') {
@@ -180,7 +184,7 @@ public class ConfigMap implements ConfigStoreListener {
} else {
if (c != '#' && (c == '[' || l.indexOf('=') !=
-1)) {
sections.add(new
ConfigSection(lines.subList(i+1, last+1)));
- last = i + 1;// (c == '[' ? i+1 : i);
+ last = i + 1;
state = (c == '[' ? S2 : S1);
}
}
@@ -188,8 +192,8 @@ public class ConfigMap implements ConfigStoreListener {
sections.add(new ConfigSection(lines.subList(0, last+1)));
- for (int i = sections.size() - 1; i >= 0; i--) {
- ConfigSection cs = sections.get(i);
+ for (var i = sections.size() - 1; i >= 0; i--) {
+ var cs = sections.get(i);
if (entries.containsKey(cs.name))
throw new ConfigException("Duplicate section
found in configuration: [{0}]", cs.name);
entries.put(cs.name, cs);
@@ -218,9 +222,9 @@ public class ConfigMap implements ConfigStoreListener {
public ConfigMapEntry getEntry(String section, String key) {
checkSectionName(section);
checkKeyName(key);
- try (SimpleLock x = lock.read()) {
- ConfigSection cs = entries.get(section);
- ConfigMapEntry ce = cs == null ? null :
cs.entries.get(key);
+ try (var x = lock.read()) {
+ var cs = entries.get(section);
+ var ce = cs == null ? null : cs.entries.get(key);
if (ce == null)
ce = imports.stream().map(y ->
y.getConfigMap().getEntry(section, key)).filter(y -> y !=
null).findFirst().orElse(null);
@@ -244,8 +248,8 @@ public class ConfigMap implements ConfigStoreListener {
*/
public List<String> getPreLines(String section) {
checkSectionName(section);
- try (SimpleLock x = lock.read()) {
- ConfigSection cs = entries.get(section);
+ try (var x = lock.read()) {
+ var cs = entries.get(section);
return cs == null ? null : cs.preLines;
}
}
@@ -257,7 +261,7 @@ public class ConfigMap implements ConfigStoreListener {
* An unmodifiable set of keys.
*/
public Set<String> getSections() {
- Set<String> s = imports.isEmpty() ? entries.keySet() : set();
+ var s = imports.isEmpty() ? entries.keySet() :
setOf(String.class);
if (! imports.isEmpty()) {
imports.forEach(x ->
s.addAll(x.getConfigMap().getSections()));
s.addAll(entries.keySet());
@@ -277,8 +281,8 @@ public class ConfigMap implements ConfigStoreListener {
*/
public Set<String> getKeys(String section) {
checkSectionName(section);
- ConfigSection cs = entries.get(section);
- Set<String> s = imports.isEmpty() && cs != null ?
cs.entries.keySet() : set();
+ var cs = entries.get(section);
+ var s = imports.isEmpty() && cs != null ? cs.entries.keySet() :
CollectionUtils.<String>set();
if (! imports.isEmpty()) {
imports.forEach(x ->
s.addAll(x.getConfigMap().getKeys(section)));
if (cs != null)
@@ -426,15 +430,15 @@ public class ConfigMap implements ConfigStoreListener {
private ConfigMap applyChange(boolean addToChangeList, ConfigEvent ce) {
if (ce == null)
return this;
- try (SimpleLock x = lock.write()) {
- String section = ce.getSection();
- ConfigSection cs = entries.get(section);
+ try (var x = lock.write()) {
+ var section = ce.getSection();
+ var cs = entries.get(section);
if (ce.getType() == SET_ENTRY) {
if (cs == null) {
cs = new ConfigSection(section);
entries.put(section, cs);
}
- ConfigMapEntry oe = cs.entries.get(ce.getKey());
+ var oe = cs.entries.get(ce.getKey());
if (oe == null)
oe = ConfigMapEntry.NULL;
cs.addEntry(
@@ -455,7 +459,7 @@ public class ConfigMap implements ConfigStoreListener {
if (cs != null)
cs.entries.remove(ce.getKey());
} else if (ce.getType() == REMOVE_SECTION) {
- if (cs != null)
+ if (cs != null) // NOSONAR - Intentional.
entries.remove(section);
}
if (addToChangeList)
@@ -476,12 +480,15 @@ public class ConfigMap implements ConfigStoreListener {
public ConfigMap load(String contents, boolean synchronous) throws
IOException, InterruptedException {
if (synchronous) {
- final CountDownLatch latch = new CountDownLatch(1);
- ConfigStoreListener listener = contents1 ->
latch.countDown();
+ final var latch = new CountDownLatch(1);
+ var listener = (ConfigStoreListener) x ->
latch.countDown();
store.register(name, listener);
store.write(name, null, contents);
- latch.await(30, TimeUnit.SECONDS);
- store.unregister(name, listener);
+ if (latch.await(30, TimeUnit.SECONDS)) {
+ store.unregister(name, listener);
+ } else {
+ throw new ConfigException("Unable to store
contents of config to store.");
+ }
} else {
store.write(name, null, contents);
}
@@ -510,12 +517,12 @@ public class ConfigMap implements ConfigStoreListener {
* @throws IOException Thrown by underlying stream.
*/
public ConfigMap commit() throws IOException {
- try (SimpleLock x = lock.write()) {
- String newContents = asString();
- for (int i = 0; i <= 10; i++) {
+ try (var x = lock.write()) {
+ var newContents = asString();
+ for (var i = 0; i <= 10; i++) {
if (i == 10)
throw new ConfigException("Unable to
store contents of config to store.");
- String currentContents = store.write(name,
contents, newContents);
+ var currentContents = store.write(name,
contents, newContents);
if (currentContents == null)
break;
onChange(currentContents);
@@ -543,8 +550,8 @@ public class ConfigMap implements ConfigStoreListener {
}
boolean hasEntry(String section, String key) {
- ConfigSection cs = entries.get(section);
- ConfigMapEntry ce = cs == null ? null : cs.entries.get(key);
+ var cs = entries.get(section);
+ var ce = cs == null ? null : cs.entries.get(key);
return ce != null;
}
@@ -571,10 +578,10 @@ public class ConfigMap implements ConfigStoreListener {
@Override /* ConfigStoreListener */
public void onChange(String newContents) {
- ConfigEvents changes = null;
- try (SimpleLock x = lock.write()) {
+ ConfigEvents changes2 = null;
+ try (var x = lock.write()) {
if (ne(contents, newContents)) {
- changes = findDiffs(newContents);
+ changes2 = findDiffs(newContents);
load(newContents);
// Reapply our changes on top of the
modifications.
@@ -583,13 +590,13 @@ public class ConfigMap implements ConfigStoreListener {
} catch (IOException e) {
throw asRuntimeException(e);
}
- if (changes != null && ! changes.isEmpty())
- signal(changes);
+ if (changes2 != null && ! changes2.isEmpty())
+ signal(changes2);
}
@Override /* Object */
public String toString() {
- try (SimpleLock x = lock.read()) {
+ try (var x = lock.read()) {
return asString();
}
}
@@ -606,11 +613,11 @@ public class ConfigMap implements ConfigStoreListener {
* @return A copy of this config as a map of maps.
*/
public JsonMap asMap() {
- JsonMap m = new JsonMap();
- try (SimpleLock x = lock.read()) {
+ var m = new JsonMap();
+ try (var x = lock.read()) {
imports.forEach(y ->
m.putAll(y.getConfigMap().asMap()));
entries.values().forEach(z -> {
- Map<String,String> m2 = map();
+ var m2 = mapOf(String.class, String.class);
z.entries.values().forEach(y -> m2.put(y.key,
y.value));
m.put(z.name, m2);
});
@@ -626,8 +633,8 @@ public class ConfigMap implements ConfigStoreListener {
* @throws IOException Thrown by underlying stream.
*/
public Writer writeTo(Writer w) throws IOException {
- try (SimpleLock x = lock.read()) {
- for (ConfigSection cs : entries.values())
+ try (var x = lock.read()) {
+ for (var cs : entries.values())
cs.writeTo(w);
}
return w;
@@ -639,8 +646,8 @@ public class ConfigMap implements ConfigStoreListener {
* @return This object.
*/
public ConfigMap rollback() {
- if (changes.size() > 0) {
- try (SimpleLock x = lock.write()) {
+ if (!changes.isEmpty()) {
+ try (var x = lock.write()) {
changes.clear();
load(contents);
} catch (IOException e) {
@@ -671,8 +678,8 @@ public class ConfigMap implements ConfigStoreListener {
s = s.trim();
if (s.isEmpty())
return false;
- for (int i = 0; i < s.length(); i++) {
- char c = s.charAt(i);
+ for (var i = 0; i < s.length(); i++) {
+ var c = s.charAt(i);
if (c == '/' || c == '\\' || c == '[' || c == ']' || c
== '=' || c == '#')
return false;
}
@@ -685,8 +692,8 @@ public class ConfigMap implements ConfigStoreListener {
s = s.trim();
if (s.isEmpty())
return false;
- for (int i = 0; i < s.length(); i++) {
- char c = s.charAt(i);
+ for (var i = 0; i < s.length(); i++) {
+ var c = s.charAt(i);
if (c == '/' || c == '\\' || c == '[' || c == ']')
return false;
}
@@ -699,8 +706,8 @@ public class ConfigMap implements ConfigStoreListener {
s = s.trim();
if (s.isEmpty())
return false;
- for (int i = 0; i < s.length(); i++) {
- char c = s.charAt(i);
+ for (var i = 0; i < s.length(); i++) {
+ var c = s.charAt(i);
if (i == 0) {
if (! Character.isJavaIdentifierStart(c))
return false;
@@ -713,21 +720,21 @@ public class ConfigMap implements ConfigStoreListener {
}
private void signal(ConfigEvents changes) {
- if (changes.size() > 0)
+ if (isNotEmpty(changes))
listeners.forEach(x -> x.onConfigChange(changes));
}
private ConfigEvents findDiffs(String updatedContents) throws
IOException {
- ConfigEvents changes = new ConfigEvents();
- ConfigMap newMap = new ConfigMap(store, name, updatedContents);
+ var changes2 = new ConfigEvents();
+ var newMap = new ConfigMap(store, name, updatedContents);
// Imports added.
- for (Import i : newMap.imports) {
+ for (var i : newMap.imports) {
if (! imports.contains(i)) {
- for (ConfigSection s :
i.getConfigMap().entries.values()) {
- for (ConfigMapEntry e :
s.oentries.values()) {
+ for (var s : i.getConfigMap().entries.values())
{
+ for (var e : s.oentries.values()) {
if (! newMap.hasEntry(s.name,
e.key)) {
-
changes.add(ConfigEvent.setEntry(name, s.name, e.key, e.value, e.modifiers,
e.comment, e.preLines));
+
changes2.add(ConfigEvent.setEntry(name, s.name, e.key, e.value, e.modifiers,
e.comment, e.preLines));
}
}
}
@@ -735,58 +742,56 @@ public class ConfigMap implements ConfigStoreListener {
}
// Imports removed.
- for (Import i : imports) {
+ for (var i : imports) {
if (! newMap.imports.contains(i)) {
- for (ConfigSection s :
i.getConfigMap().entries.values()) {
- for (ConfigMapEntry e :
s.oentries.values()) {
+ for (var s : i.getConfigMap().entries.values())
{
+ for (var e : s.oentries.values()) {
if (! newMap.hasEntry(s.name,
e.key)) {
-
changes.add(ConfigEvent.removeEntry(name, s.name, e.key));
+
changes2.add(ConfigEvent.removeEntry(name, s.name, e.key));
}
}
}
}
}
- for (ConfigSection ns : newMap.oentries.values()) {
- ConfigSection s = oentries.get(ns.name);
+ for (var ns : newMap.oentries.values()) {
+ var s = oentries.get(ns.name);
if (s == null) {
- //changes.add(ConfigEvent.setSection(ns.name,
ns.preLines));
- for (ConfigMapEntry ne : ns.entries.values()) {
- changes.add(ConfigEvent.setEntry(name,
ns.name, ne.key, ne.value, ne.modifiers, ne.comment, ne.preLines));
+ for (var ne : ns.entries.values()) {
+ changes2.add(ConfigEvent.setEntry(name,
ns.name, ne.key, ne.value, ne.modifiers, ne.comment, ne.preLines));
}
} else {
- for (ConfigMapEntry ne : ns.oentries.values()) {
- ConfigMapEntry e =
s.oentries.get(ne.key);
+ for (var ne : ns.oentries.values()) {
+ var e = s.oentries.get(ne.key);
if (e == null || ne(e.value, ne.value))
{
-
changes.add(ConfigEvent.setEntry(name, s.name, ne.key, ne.value, ne.modifiers,
ne.comment, ne.preLines));
+
changes2.add(ConfigEvent.setEntry(name, s.name, ne.key, ne.value, ne.modifiers,
ne.comment, ne.preLines));
}
}
- for (ConfigMapEntry e : s.oentries.values()) {
- ConfigMapEntry ne =
ns.oentries.get(e.key);
+ for (var e : s.oentries.values()) {
+ var ne = ns.oentries.get(e.key);
if (ne == null) {
-
changes.add(ConfigEvent.removeEntry(name, s.name, e.key));
+
changes2.add(ConfigEvent.removeEntry(name, s.name, e.key));
}
}
}
}
- for (ConfigSection s : oentries.values()) {
- ConfigSection ns = newMap.oentries.get(s.name);
+ for (var s : oentries.values()) {
+ var ns = newMap.oentries.get(s.name);
if (ns == null) {
-
//changes.add(ConfigEvent.removeSection(s.name));
- for (ConfigMapEntry e : s.oentries.values())
-
changes.add(ConfigEvent.removeEntry(name, s.name, e.key));
+ for (var e : s.oentries.values())
+
changes2.add(ConfigEvent.removeEntry(name, s.name, e.key));
}
}
- return changes;
+ return changes2;
}
// This method should only be called from behind a lock.
private String asString() {
try {
- StringWriter sw = new StringWriter();
- for (ConfigSection cs : entries.values())
+ var sw = new StringWriter();
+ for (var cs : entries.values())
cs.writeTo(sw);
return sw.toString();
} catch (IOException e) {
@@ -822,21 +827,24 @@ public class ConfigMap implements ConfigStoreListener {
*/
ConfigSection(List<String> lines) {
- String name = null, rawLine = null;
+ String name2 = null, rawLine2 = null;
- int S1 = 1; // Looking for section.
- int S2 = 2; // Found section, looking for end.
- int state = S1;
- int start = 0;
+ final int
+ S1 = 1, // Looking for section.
+ S2 = 2; // Found section, looking for end.
- for (int i = 0; i < lines.size(); i++) {
- String l = lines.get(i);
- char c = StringUtils.firstNonWhitespaceChar(l);
+ var state = S1;
+ var start = 0;
+
+ for (var i = 0; i < lines.size(); i++) {
+ var l = lines.get(i);
+ var c = StringUtils.firstNonWhitespaceChar(l);
if (state == S1) {
if (c == '[') {
- int i1 = l.indexOf('['), i2 =
l.indexOf(']');
- name = l.substring(i1+1,
i2).trim();
- rawLine = l;
+ var i1 = l.indexOf('[');
+ var i2 = l.indexOf(']');
+ name2 = l.substring(i1+1,
i2).trim();
+ rawLine2 = l;
state = S2;
start = i+1;
} else {
@@ -844,22 +852,22 @@ public class ConfigMap implements ConfigStoreListener {
}
} else {
if (c != '#' && l.indexOf('=') != -1) {
- ConfigMapEntry e = new
ConfigMapEntry(l, lines.subList(start, i));
+ var e = new ConfigMapEntry(l,
lines.subList(start, i));
if (entries.containsKey(e.key))
- throw new
ConfigException("Duplicate entry found in section [{0}] of configuration:
{1}", name, e.key);
+ throw new
ConfigException("Duplicate entry found in section [{0}] of configuration:
{1}", name2, e.key);
entries.put(e.key, e);
start = i+1;
}
}
}
- this.name = name;
- this.rawLine = rawLine;
+ this.name = name2;
+ this.rawLine = rawLine2;
this.oentries.putAll(entries);
}
ConfigSection addEntry(String key, String value, String
modifiers, String comment, List<String> preLines) {
- ConfigMapEntry e = new ConfigMapEntry(key, value,
modifiers, comment, preLines);
+ var e = new ConfigMapEntry(key, value, modifiers,
comment, preLines);
this.entries.put(e.key, e);
return this;
}
@@ -871,7 +879,7 @@ public class ConfigMap implements ConfigStoreListener {
}
Writer writeTo(Writer w) throws IOException {
- for (String s : preLines)
+ for (var s : preLines)
w.append(s).append('\n');
if (! name.isEmpty())
@@ -882,7 +890,7 @@ public class ConfigMap implements ConfigStoreListener {
w.append('\n');
}
- for (ConfigMapEntry e : entries.values())
+ for (var e : entries.values())
e.writeTo(w);
return w;
@@ -909,12 +917,11 @@ public class ConfigMap implements ConfigStoreListener {
}
synchronized Import register(final ConfigEventListener
listener) {
- ConfigEventListener l2 = events -> {
- ConfigEvents events2 = new ConfigEvents();
- events.stream().filter(x -> ! hasEntry(x.getSection(),
x.getKey())).forEach(x -> events2.add(x));
- if (events2.size() > 0)
- listener.onConfigChange(events2);
- };
+ var l2 = (ConfigEventListener) events -> {
+ var events2 = events.stream().filter(x -> !
hasEntry(x.getSection(),
x.getKey())).collect(Collectors.toCollection(ConfigEvents::new));
+ if (!events2.isEmpty())
+ listener.onConfigChange(events2);
+ };
listenerMap.put(listener, l2);
configMap.register(l2);
return this;
@@ -926,7 +933,7 @@ public class ConfigMap implements ConfigStoreListener {
}
synchronized Import unregisterAll() {
- listenerMap.values().forEach(x ->
configMap.unregister(x));
+ listenerMap.values().forEach(configMap::unregister);
listenerMap.clear();
return this;
}
@@ -941,12 +948,7 @@ public class ConfigMap implements ConfigStoreListener {
@Override
public boolean equals(Object o) {
- if (o instanceof Import) {
- Import ir = (Import)o;
- if (ir.getConfigName().equals(getConfigName()))
- return true;
- }
- return false;
+ return o instanceof Import ir &&
ir.getConfigName().equals(getConfigName());
}
@Override
diff --git
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/internal/ConfigMapEntry.java
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/internal/ConfigMapEntry.java
index 5b486319a..b4a9679e8 100644
---
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/internal/ConfigMapEntry.java
+++
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/internal/ConfigMapEntry.java
@@ -33,23 +33,23 @@ public class ConfigMapEntry {
static final ConfigMapEntry NULL = new ConfigMapEntry(null, null, null,
null, null);
-// private final static AsciiSet MOD_CHARS = AsciiSet.create("#$%&*+^@~");
-
ConfigMapEntry(String line, List<String> preLines) {
this.rawLine = line;
- int i = line.indexOf('=');
- String key = line.substring(0, i).trim();
+ var i = line.indexOf('=');
+ var key2 = line.substring(0, i).trim();
+
+ var m1 = key2.indexOf('<');
+ var m2 = key2.indexOf('>');
- int m1 = key.indexOf('<'), m2 = key.indexOf('>');
- modifiers = nullIfEmpty((m1 > -1 && m2 > m1) ?
key.substring(m1+1, m2) : null);
+ modifiers = nullIfEmpty((m1 > -1 && m2 > m1) ?
key2.substring(m1+1, m2) : null);
- this.key = m1 == -1 ? key : key.substring(0, m1);
+ this.key = m1 == -1 ? key2 : key2.substring(0, m1);
line = line.substring(i+1);
i = line.indexOf('#');
if (i != -1) {
- String[] l2 = split(line, '#', 2);
+ var l2 = split(line, '#', 2);
line = l2[0];
if (l2.length == 2)
this.comment = l2[1].trim();
@@ -121,11 +121,11 @@ public class ConfigMapEntry {
Writer writeTo(Writer w) throws IOException {
if (value == null)
return w;
- for (String pl : preLines)
+ for (var pl : preLines)
w.append(pl).append('\n');
if (rawLine != null) {
- for (int i = 0; i < rawLine.length(); i++) {
- char c = rawLine.charAt(i);
+ for (var i = 0; i < rawLine.length(); i++) {
+ var c = rawLine.charAt(i);
if (c == '\n')
w.append('\n').append('\t');
else if (c != '\r')
@@ -135,12 +135,12 @@ public class ConfigMapEntry {
} else {
w.append(key);
if (modifiers != null)
- w.append('<').append(new
String(modifiers)).append('>');
+ w.append('<').append(modifiers).append('>');
w.append(" = ");
- String val = value;
- for (int i = 0; i < val.length(); i++) {
- char c = val.charAt(i);
+ var val = value;
+ for (var i = 0; i < val.length(); i++) {
+ var c = val.charAt(i);
if (c == '\n')
w.append('\n').append('\t');
else if (c != '\r') {
diff --git
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/mod/Mod.java
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/mod/Mod.java
index 33744163f..eb01b5bb6 100644
---
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/mod/Mod.java
+++
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/mod/Mod.java
@@ -48,7 +48,7 @@ public class Mod {
* The function to apply to detect whether the modification has
been made.
* Can be <jk>null</jk> if you override the {@link
#isApplied(String)} method.
*/
- public Mod(char id, Function<String,String> applyFunction,
Function<String,String> removeFunction, Function<String,Boolean>
detectFunction) {
+ public Mod(char id, Function<String,String> applyFunction,
Function<String,String> removeFunction, Function<String,Boolean>
detectFunction) { // NOSONAR - Intentional.
this.id = id;
this.applyFunction = applyFunction;
this.removeFunction = removeFunction;
diff --git
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/mod/XorEncodeMod.java
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/mod/XorEncodeMod.java
index e6b58a2ee..d71969859 100644
---
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/mod/XorEncodeMod.java
+++
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/mod/XorEncodeMod.java
@@ -42,9 +42,9 @@ public class XorEncodeMod extends Mod {
@Override
public String apply(String value) {
- byte[] b = value.getBytes(UTF8);
- for (int i = 0; i < b.length; i++) {
- int j = i % KEY.length();
+ var b = value.getBytes(UTF8);
+ for (var i = 0; i < b.length; i++) {
+ var j = i % KEY.length();
b[i] = (byte)(b[i] ^ KEY.charAt(j));
}
return "{" + base64Encode(b) + "}";
@@ -54,9 +54,9 @@ public class XorEncodeMod extends Mod {
public String remove(String value) {
value = value.trim();
value = value.substring(1, value.length()-1);
- byte[] b = base64Decode(value);
- for (int i = 0; i < b.length; i++) {
- int j = i % KEY.length();
+ var b = base64Decode(value);
+ for (var i = 0; i < b.length; i++) {
+ var j = i % KEY.length();
b[i] = (byte)(b[i] ^ KEY.charAt(j));
}
return new String(b, UTF8);
diff --git
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/store/ClasspathStore.java
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/store/ClasspathStore.java
index e22518486..9936959a6 100644
---
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/store/ClasspathStore.java
+++
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/store/ClasspathStore.java
@@ -185,12 +185,12 @@ public class ClasspathStore extends ConfigStore {
@Override /* ConfigStore */
public synchronized String read(String name) throws IOException {
- String s = cache.get(name);
+ var s = cache.get(name);
if (s != null)
return s;
- ClassLoader cl = Thread.currentThread().getContextClassLoader();
- try (InputStream in = cl.getResourceAsStream(name)) {
+ var cl = Thread.currentThread().getContextClassLoader();
+ try (var in = cl.getResourceAsStream(name)) {
if (in != null)
cache.put(name, IOUtils.read(in));
}
@@ -204,7 +204,7 @@ public class ClasspathStore extends ConfigStore {
if (eq(expectedContents, newContents))
return null;
- String currentContents = read(name);
+ var currentContents = read(name);
if (expectedContents != null && ! eq(currentContents,
expectedContents))
return currentContents;
diff --git
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/store/ConfigStore.java
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/store/ConfigStore.java
index 6e63fcda0..9282886ef 100644
---
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/store/ConfigStore.java
+++
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/store/ConfigStore.java
@@ -13,6 +13,7 @@
package org.apache.juneau.config.store;
import static org.apache.juneau.internal.CollectionUtils.*;
+import static java.util.Collections.*;
import java.io.*;
import java.lang.annotation.*;
@@ -199,11 +200,10 @@ public abstract class ConfigStore extends Context
implements Closeable {
*/
public synchronized ConfigStore register(String name,
ConfigStoreListener l) {
name = resolveName(name);
- Set<ConfigStoreListener> s = listeners.get(name);
- if (s == null) {
- s = synced(Collections.newSetFromMap(new
IdentityHashMap<>()));
- listeners.put(name, s);
- }
+ var s = listeners.computeIfAbsent(
+ name,
+ k -> synced(newSetFromMap(new IdentityHashMap<>()))
+ );
s.add(l);
return this;
}
@@ -217,7 +217,7 @@ public abstract class ConfigStore extends Context
implements Closeable {
*/
public synchronized ConfigStore unregister(String name,
ConfigStoreListener l) {
name = resolveName(name);
- Set<ConfigStoreListener> s = listeners.get(name);
+ var s = listeners.get(name);
if (s != null)
s.remove(l);
return this;
@@ -234,11 +234,11 @@ public abstract class ConfigStore extends Context
implements Closeable {
*/
public synchronized ConfigMap getMap(String name) throws IOException {
name = resolveName(name);
- ConfigMap cm = configMaps.get(name);
+ var cm = configMaps.get(name);
if (cm != null)
return cm;
cm = new ConfigMap(this, name);
- ConfigMap cm2 = configMaps.putIfAbsent(name, cm);
+ var cm2 = configMaps.putIfAbsent(name, cm);
if (cm2 != null)
return cm2;
register(name, cm);
@@ -257,7 +257,7 @@ public abstract class ConfigStore extends Context
implements Closeable {
*/
public synchronized ConfigStore update(String name, String contents) {
name = resolveName(name);
- Set<ConfigStoreListener> s = listeners.get(name);
+ var s = listeners.get(name);
if (s != null)
listeners.get(name).forEach(x -> x.onChange(contents));
return this;
@@ -272,8 +272,8 @@ public abstract class ConfigStore extends Context
implements Closeable {
*/
public synchronized ConfigStore update(String name,
String...contentLines) {
name = resolveName(name);
- StringBuilder sb = new StringBuilder();
- for (String l : contentLines)
+ var sb = new StringBuilder();
+ for (var l : contentLines)
sb.append(l).append('\n');
return update(name, sb.toString());
}
diff --git
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/store/FileStore.java
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/store/FileStore.java
index 823fc6777..3d63b8e0c 100644
---
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/store/FileStore.java
+++
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/store/FileStore.java
@@ -399,10 +399,10 @@ public class FileStore extends ConfigStore {
public synchronized String read(String name) throws IOException {
name = resolveName(name);
- Path p = resolveFile(name);
+ var p = resolveFile(name);
name = p.getFileName().toString();
- String s = cache.get(name);
+ var s = cache.get(name);
if (s != null)
return s;
@@ -412,13 +412,13 @@ public class FileStore extends ConfigStore {
if (! Files.exists(p))
return "";
- boolean isWritable = isWritable(p);
- OpenOption[] oo = isWritable ? new
OpenOption[]{READ,WRITE,CREATE} : new OpenOption[]{READ};
+ var isWritable = isWritable(p);
+ var oo = isWritable ? new OpenOption[]{READ,WRITE,CREATE} : new
OpenOption[]{READ};
- try (FileChannel fc = FileChannel.open(p, oo)) {
- try (FileLock lock = isWritable ? fc.lock() : null) {
- ByteBuffer buf = ByteBuffer.allocate(1024);
- StringBuilder sb = new StringBuilder();
+ try (var fc = FileChannel.open(p, oo)) {
+ try (var lock = isWritable ? fc.lock() : null) {
+ var buf = ByteBuffer.allocate(1024);
+ var sb = new StringBuilder();
while (fc.read(buf) != -1) {
sb.append(charset.decode((buf.flip()))); // Fixes Java 11 issue involving
overridden flip method.
buf.clear();
@@ -441,10 +441,10 @@ public class FileStore extends ConfigStore {
dir.mkdirs();
- Path p = resolveFile(name);
+ var p = resolveFile(name);
name = p.getFileName().toString();
- boolean exists = Files.exists(p);
+ var exists = Files.exists(p);
// Don't create the file if we're not going to match.
if ((!exists) && isNotEmpty(expectedContents))
@@ -454,12 +454,12 @@ public class FileStore extends ConfigStore {
if (newContents == null)
Files.delete(p);
else {
- try (FileChannel fc = FileChannel.open(p, READ,
WRITE, CREATE)) {
- try (FileLock lock = fc.lock()) {
- String currentContents = "";
+ try (var fc = FileChannel.open(p, READ, WRITE,
CREATE)) {
+ try (var lock = fc.lock()) {
+ var currentContents = "";
if (exists) {
- ByteBuffer buf =
ByteBuffer.allocate(1024);
- StringBuilder sb = new
StringBuilder();
+ var buf =
ByteBuffer.allocate(1024);
+ var sb = new
StringBuilder();
while (fc.read(buf) !=
-1) {
sb.append(charset.decode(buf.flip()));
buf.clear();
@@ -508,7 +508,7 @@ public class FileStore extends ConfigStore {
// Does name already have an extension?
if (n == null) {
- for (String ext : exts) {
+ for (var ext : exts) {
if (FileUtils.hasExtension(name, ext)) {
n = name;
break;
@@ -518,7 +518,7 @@ public class FileStore extends ConfigStore {
// Find file with the correct extension.
if (n == null) {
- for (String ext : exts) {
+ for (var ext : exts) {
if (FileUtils.exists(dir, name + '.' +
ext)) {
n = name + '.' + ext;
break;
@@ -539,8 +539,9 @@ public class FileStore extends ConfigStore {
try {
if (! Files.exists(p)) {
Files.createDirectories(p.getParent());
- if (! Files.exists(p))
- p.toFile().createNewFile();
+ if (! Files.exists(p) && !
p.toFile().createNewFile()) {
+ throw new IOException("Could not create
file: " + p);
+ }
}
} catch (IOException e) {
return false;
@@ -571,8 +572,8 @@ public class FileStore extends ConfigStore {
WatcherThread(File dir, WatcherSensitivity s) throws Exception {
watchService =
FileSystems.getDefault().newWatchService();
- WatchEvent.Kind<?>[] kinds = new
WatchEvent.Kind[]{ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY};
- WatchEvent.Modifier modifier = lookupModifier(s);
+ var kinds = new WatchEvent.Kind[]{ENTRY_CREATE,
ENTRY_DELETE, ENTRY_MODIFY};
+ var modifier = lookupModifier(s);
dir.toPath().register(watchService, kinds, modifier);
}
@@ -596,8 +597,8 @@ public class FileStore extends ConfigStore {
try {
WatchKey key;
while ((key = watchService.take()) != null) {
- for (WatchEvent<?> event :
key.pollEvents()) {
- WatchEvent.Kind<?> kind =
event.kind();
+ for (var event : key.pollEvents()) {
+ var kind = event.kind();
if (kind != OVERFLOW)
FileStore.this.onFileEvent(((WatchEvent<Path>)event));
}
@@ -628,11 +629,12 @@ public class FileStore extends ConfigStore {
* @throws IOException Thrown by underlying stream.
*/
protected synchronized void onFileEvent(WatchEvent<Path> e) throws
IOException {
- String fn = e.context().getFileName().toString();
+ var fn = e.context().getFileName().toString();
- String oldContents = cache.get(fn);
+ var oldContents = cache.get(fn);
cache.remove(fn);
- String newContents = read(fn);
+ var newContents = read(fn);
+
if (! eq(oldContents, newContents)) {
update(fn, newContents);
}
diff --git
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/store/MemoryStore.java
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/store/MemoryStore.java
index 2a901f82a..451ee39d1 100644
---
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/store/MemoryStore.java
+++
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/store/MemoryStore.java
@@ -191,7 +191,7 @@ public class MemoryStore extends ConfigStore {
if (eq(expectedContents, newContents))
return null;
- String currentContents = read(name);
+ var currentContents = read(name);
if (expectedContents != null && ! eq(currentContents,
expectedContents))
return currentContents;
diff --git
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/vars/ConfigVar.java
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/vars/ConfigVar.java
index 8517822cf..922b87c99 100644
---
a/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/vars/ConfigVar.java
+++
b/juneau-core/juneau-config/src/main/java/org/apache/juneau/config/vars/ConfigVar.java
@@ -64,7 +64,7 @@ public class ConfigVar extends DefaultingVar {
@Override /* Var */
public String resolve(VarResolverSession session, String key) {
- return
session.getBean(Config.class).get().get(key).orElse(null);
+ return session.getBean(Config.class).map(x ->
x.get(key).orElse(null)).orElse(null);
}
@Override /* Var */
diff --git
a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/internal/CollectionUtils.java
b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/internal/CollectionUtils.java
index 9fdc7f152..2c5bf396d 100644
---
a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/internal/CollectionUtils.java
+++
b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/internal/CollectionUtils.java
@@ -24,6 +24,8 @@ import java.util.function.*;
*/
public final class CollectionUtils {
+ private CollectionUtils() {}
+
/**
* Creates a new set from the specified collection.
*
@@ -166,6 +168,19 @@ public final class CollectionUtils {
return l;
}
+ /**
+ * Convenience method for creating an {@link ArrayList}.
+ *
+ * @param <E> The element type.
+ * @param elementType The element type.
+ * @param values The values to initialize the list with.
+ * @return A new modifiable list.
+ */
+ @SafeVarargs
+ public static <E> ArrayList<E> listOf(Class<E> elementType, E...values)
{
+ return list(values);
+ }
+
/**
* Convenience method for creating an {@link ArrayList} of the
specified size.
*
@@ -262,6 +277,19 @@ public final class CollectionUtils {
return l;
}
+ /**
+ * Convenience method for creating a {@link LinkedHashSet}.
+ *
+ * @param <E> The element type.
+ * @param elementType The element type.
+ * @param values The values to initialize the set with.
+ * @return A new modifiable set.
+ */
+ @SafeVarargs
+ public static <E> LinkedHashSet<E> setOf(Class<E> elementType,
E...values) {
+ return set(values);
+ }
+
/**
* Convenience method for creating an unmodifiable {@link
LinkedHashSet}.
*
@@ -346,6 +374,19 @@ public final class CollectionUtils {
return m;
}
+ /**
+ * Convenience method for creating a {@link LinkedHashMap}.
+ *
+ * @param <K> The key type.
+ * @param <V> The value type.
+ * @param keyType The key type.
+ * @param valueType The value type.
+ * @return A new modifiable map.
+ */
+ public static <K,V> LinkedHashMap<K,V> mapOf(Class<K> keyType, Class<V>
valueType) {
+ return map();
+ }
+
/**
* Convenience method for creating a {@link LinkedHashMap}.
*
diff --git
a/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/RestRequest.java
b/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/RestRequest.java
index a714cfcdb..b3f1231cf 100644
---
a/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/RestRequest.java
+++
b/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/RestRequest.java
@@ -1523,26 +1523,26 @@ public final class RestRequest extends
HttpServletRequestWrapper {
c.getClassLoader(),
new Class[] { c },
(InvocationHandler) (proxy, method, args) -> {
- RequestBeanPropertyMeta pm =
rbm.getProperty(method.getName());
- if (pm != null) {
- HttpPartParserSession pp =
pm.getParser(getPartParserSession());
- HttpPartSchema schema = pm.getSchema();
- String name = pm.getPartName();
- ClassMeta<?> type =
bs.getClassMeta(method.getGenericReturnType());
- HttpPartType pt = pm.getPartType();
- if (pt == HttpPartType.BODY)
- return
getContent().setSchema(schema).as(type);
- if (pt == QUERY)
- return
getQueryParam(name).parser(pp).schema(schema).as(type).orElse(null);
- if (pt == FORMDATA)
- return
getFormParam(name).parser(pp).schema(schema).as(type).orElse(null);
- if (pt == HEADER)
- return
getHeaderParam(name).parser(pp).schema(schema).as(type).orElse(null);
- if (pt == PATH)
- return
getPathParam(name).parser(pp).schema(schema).as(type).orElse(null);
- }
- return null;
- });
+ RequestBeanPropertyMeta pm =
rbm.getProperty(method.getName());
+ if (pm != null) {
+ HttpPartParserSession pp =
pm.getParser(getPartParserSession());
+ HttpPartSchema schema =
pm.getSchema();
+ String name = pm.getPartName();
+ ClassMeta<?> type =
bs.getClassMeta(method.getGenericReturnType());
+ HttpPartType pt =
pm.getPartType();
+ if (pt == HttpPartType.BODY)
+ return
getContent().setSchema(schema).as(type);
+ if (pt == QUERY)
+ return
getQueryParam(name).parser(pp).schema(schema).as(type).orElse(null);
+ if (pt == FORMDATA)
+ return
getFormParam(name).parser(pp).schema(schema).as(type).orElse(null);
+ if (pt == HEADER)
+ return
getHeaderParam(name).parser(pp).schema(schema).as(type).orElse(null);
+ if (pt == PATH)
+ return
getPathParam(name).parser(pp).schema(schema).as(type).orElse(null);
+ }
+ return null;
+ });
} catch (Exception e) {
throw asRuntimeException(e);
}
@@ -1551,11 +1551,7 @@ public final class RestRequest extends
HttpServletRequestWrapper {
/* Called by RestSession.finish() */
void close() {
if (config != null) {
- try {
- config.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
+ config.close();
}
}