[automation] Use Java 17 features (#15484)

* [automation] Code optimization for Java17: instanceof matching and multiline strings

Signed-off-by: Holger Friedrich <mail@holger-friedrich.de>

* [automation] Make use of Java17 features

Use Map/Set/List.of instead of Collections.

Signed-off-by: Holger Friedrich <mail@holger-friedrich.de>

* review comment

Signed-off-by: Holger Friedrich <mail@holger-friedrich.de>

---------

Signed-off-by: Holger Friedrich <mail@holger-friedrich.de>
This commit is contained in:
Holger Friedrich 2023-08-23 17:27:40 +02:00 committed by GitHub
parent 626c6bde4a
commit 7b90fbe162
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 35 additions and 31 deletions

View File

@ -123,8 +123,8 @@ public class JRubyScriptEngineFactory extends AbstractScriptEngineFactory {
importClassesToRuby(scriptEngine, partitionedMap.getOrDefault(true, new HashMap<>()));
Object scriptExtension = scopeValues.get("scriptExtension");
if (scriptExtension instanceof ScriptExtensionManagerWrapper && configuration.enableDependencyTracking()) {
ScriptExtensionManagerWrapper wrapper = (ScriptExtensionManagerWrapper) scriptExtension;
if (scriptExtension instanceof ScriptExtensionManagerWrapper wrapper
&& configuration.enableDependencyTracking()) {
// we inject like this instead of using the script context, because
// this is executed _before_ the dependency tracker is added to the script
// context.

View File

@ -30,7 +30,6 @@ import java.nio.file.attribute.FileAttribute;
import java.time.Duration;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;
@ -209,7 +208,7 @@ public class OpenhabGraalJSScriptEngine
public Map<String, Object> readAttributes(Path path, String attributes,
LinkOption... options) throws IOException {
if (isRootNodePath(path)) {
return Collections.singletonMap("isRegularFile", true);
return Map.of("isRegularFile", true);
}
return super.readAttributes(path, attributes, options);
}

View File

@ -78,10 +78,15 @@ public class ScriptExtensionModuleProvider {
private Value toValue(Context ctx, Map<String, Object> map) {
try {
return ctx.eval(Source.newBuilder( // convert to Map to JS Object
"js",
"(function (mapOfValues) {\n" + "let rv = {};\n" + "for (var key in mapOfValues) {\n"
+ " rv[key] = mapOfValues.get(key);\n" + "}\n" + "return rv;\n" + "})",
"<generated>").build()).execute(map);
"js", """
(function (mapOfValues) {
let rv = {};
for (var key in mapOfValues) {
rv[key] = mapOfValues.get(key);
}
return rv;
})\
""", "<generated>").build()).execute(map);
} catch (IOException e) {
throw new IllegalArgumentException("Failed to generate exports", e);
}

View File

@ -18,6 +18,7 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
@ -56,7 +57,7 @@ public abstract class AbstractScriptExtensionProvider implements ScriptExtension
@Override
public Collection<String> getPresets() {
return Collections.singleton(getPresetName());
return Set.of(getPresetName());
}
@Override

View File

@ -18,6 +18,7 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
@ -57,7 +58,7 @@ public abstract class ScriptDisposalAwareScriptExtensionProvider
@Override
public Collection<String> getPresets() {
return Collections.singleton(getPresetName());
return Set.of(getPresetName());
}
@Override
@ -92,8 +93,8 @@ public abstract class ScriptDisposalAwareScriptExtensionProvider
if (forScript != null) {
for (Object o : forScript.values()) {
if (o instanceof ScriptDisposalAware) {
((ScriptDisposalAware) o).unload(scriptIdentifier);
if (o instanceof ScriptDisposalAware script) {
script.unload(scriptIdentifier);
}
}
}

View File

@ -65,8 +65,8 @@ public class ThreadsafeWrappingScriptedAutomationManagerDelegate {
public Rule addRule(Rule element) {
// wrap in a threadsafe version, safe per context
if (element instanceof SimpleRule) {
element = new ThreadsafeSimpleRuleDelegate(lock, (SimpleRule) element);
if (element instanceof SimpleRule rule) {
element = new ThreadsafeSimpleRuleDelegate(lock, rule);
}
return delegate.addRule(element);

View File

@ -206,8 +206,8 @@ public class PIDControllerTriggerHandler extends BaseTriggerModuleHandler implem
private TriggerHandlerCallback getCallback() {
ModuleHandlerCallback localCallback = callback;
if (localCallback != null && localCallback instanceof TriggerHandlerCallback) {
return (TriggerHandlerCallback) localCallback;
if (localCallback != null && localCallback instanceof TriggerHandlerCallback handlerCallback) {
return handlerCallback;
}
throw new IllegalStateException("The module callback is not set");
@ -236,8 +236,8 @@ public class PIDControllerTriggerHandler extends BaseTriggerModuleHandler implem
private double getItemValueAsNumber(Item item) throws PIDException {
State setpointState = item.getState();
if (setpointState instanceof Number) {
double doubleValue = ((Number) setpointState).doubleValue();
if (setpointState instanceof Number number) {
double doubleValue = number.doubleValue();
if (Double.isFinite(doubleValue) && !Double.isNaN(doubleValue)) {
return doubleValue;
@ -254,9 +254,8 @@ public class PIDControllerTriggerHandler extends BaseTriggerModuleHandler implem
@Override
public void receive(Event event) {
if (event instanceof ItemStateChangedEvent) {
if (event instanceof ItemStateChangedEvent changedEvent) {
if (commandTopic.isPresent() && event.getTopic().equals(commandTopic.get())) {
ItemStateChangedEvent changedEvent = (ItemStateChangedEvent) event;
if ("RESET".equals(changedEvent.getItemState().toString())) {
controller.setIntegralResult(0);
controller.setDerivativeResult(0);

View File

@ -15,7 +15,7 @@ package org.openhab.automation.pwm.internal.handler;
import static org.openhab.automation.pwm.internal.PWMConstants.*;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
@ -115,8 +115,8 @@ public class PWMTriggerHandler extends BaseTriggerModuleHandler implements Event
private Optional<Double> getOptionalDoubleFromConfig(Configuration config, String key) {
Object o = config.get(key);
if (o instanceof BigDecimal) {
return Optional.of(((BigDecimal) o).doubleValue());
if (o instanceof BigDecimal decimal) {
return Optional.of(decimal.doubleValue());
}
return Optional.empty();
@ -202,21 +202,21 @@ public class PWMTriggerHandler extends BaseTriggerModuleHandler implements Event
}
private void setOutput(boolean enable) {
getCallback().triggered(module, Collections.singletonMap(OUTPUT, OnOffType.from(enable)));
getCallback().triggered(module, Map.of(OUTPUT, OnOffType.from(enable)));
}
private TriggerHandlerCallback getCallback() {
ModuleHandlerCallback localCallback = callback;
if (localCallback != null && localCallback instanceof TriggerHandlerCallback) {
return (TriggerHandlerCallback) localCallback;
if (localCallback != null && localCallback instanceof TriggerHandlerCallback handlerCallback) {
return handlerCallback;
}
throw new IllegalStateException();
}
private double getDutyCycleValueInPercent(State state) throws PWMException {
if (state instanceof DecimalType) {
return ((DecimalType) state).doubleValue();
if (state instanceof DecimalType decimal) {
return decimal.doubleValue();
} else if (state instanceof StringType) {
try {
return Integer.parseInt(state.toString());

View File

@ -43,7 +43,7 @@ public class PWMRuleTemplate extends RuleTemplate {
public static PWMRuleTemplate initialize() {
final String triggerId = UUID.randomUUID().toString();
final List<Trigger> triggers = Collections.singletonList(ModuleBuilder.createTrigger().withId(triggerId)
final List<Trigger> triggers = List.of(ModuleBuilder.createTrigger().withId(triggerId)
.withTypeUID(PWMTriggerType.UID).withLabel("PWM Trigger").build());
final Map<String, String> actionInputs = new HashMap<String, String>();

View File

@ -16,7 +16,6 @@ import static org.openhab.automation.pwm.internal.PWMConstants.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
@ -97,7 +96,7 @@ public class PWMTriggerType extends TriggerType {
"If the duty cycle Item is not updated within this time (in ms), the output is switched off")
.build());
List<Output> outputs = Collections.singletonList(new Output(OUTPUT, OnOffType.class.getName(), "Output",
List<Output> outputs = List.of(new Output(OUTPUT, OnOffType.class.getName(), "Output",
"Output value of the PWM module", Set.of("command"), null, null));
return new PWMTriggerType(configDescriptions, outputs);