]> git.basschouten.com Git - openhab-addons.git/commitdiff
[automation] Use Java 17 features (#15484)
authorHolger Friedrich <holgerfriedrich@users.noreply.github.com>
Wed, 23 Aug 2023 15:27:40 +0000 (17:27 +0200)
committerGitHub <noreply@github.com>
Wed, 23 Aug 2023 15:27:40 +0000 (17:27 +0200)
* [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>
bundles/org.openhab.automation.jrubyscripting/src/main/java/org/openhab/automation/jrubyscripting/internal/JRubyScriptEngineFactory.java
bundles/org.openhab.automation.jsscripting/src/main/java/org/openhab/automation/jsscripting/internal/OpenhabGraalJSScriptEngine.java
bundles/org.openhab.automation.jsscripting/src/main/java/org/openhab/automation/jsscripting/internal/ScriptExtensionModuleProvider.java
bundles/org.openhab.automation.jsscripting/src/main/java/org/openhab/automation/jsscripting/internal/scope/AbstractScriptExtensionProvider.java
bundles/org.openhab.automation.jsscripting/src/main/java/org/openhab/automation/jsscripting/internal/scope/ScriptDisposalAwareScriptExtensionProvider.java
bundles/org.openhab.automation.jsscripting/src/main/java/org/openhab/automation/jsscripting/internal/threading/ThreadsafeWrappingScriptedAutomationManagerDelegate.java
bundles/org.openhab.automation.pidcontroller/src/main/java/org/openhab/automation/pidcontroller/internal/handler/PIDControllerTriggerHandler.java
bundles/org.openhab.automation.pwm/src/main/java/org/openhab/automation/pwm/internal/handler/PWMTriggerHandler.java
bundles/org.openhab.automation.pwm/src/main/java/org/openhab/automation/pwm/internal/template/PWMRuleTemplate.java
bundles/org.openhab.automation.pwm/src/main/java/org/openhab/automation/pwm/internal/type/PWMTriggerType.java

index 6c79729dbb33e360d407dd5e4072bb94be3dfeca..ad7b08497f3c806b98636c0d837942665cdd6d88 100644 (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.
index 5efdc81992d26f526233ac2c24cfaf37f6ef3b38..432a3a2c284993b181910e1a00d2b244fe7eb682 100644 (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);
                             }
index 040bc98c427f559013b44ce4185c5c39b2138357..e22552e441fd133b2e62f70f6a4dfab6383fc59e 100644 (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);
         }
index 89d12fb8aef0424593c52540d05b5fad410c32f3..1494f10f24e4ceb710a66b7da2f4599cba9ff612 100644 (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
index 1f3a02c277787fd25bd20302bd6746bc6ac85ca1..9f73e3916efe5888c64e3a1f38dd194bbb8a52b1 100644 (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);
                 }
             }
         }
index 3d23ae082d80749bfe17a06c9282a3eefc902e8a..e8be9de31bc812ad32299478141b5c4ed574b50b 100644 (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);
index 6c90ac261a45efe2993ff48434881db5c117daf4..d36fe8c13aee2a4b80a5a54f40b7be1196d3834f 100644 (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);
index 335d9641d21ac7e9e7a51992342d4a52b316b83a..2e532910ebcbb2056e4ba05be1d4e0bdaf5a8bdd 100644 (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());
index c68772c210e64ac5d260338228c089f34650c348..78ebbb472eb60e3b018d4cc3612d593db8eae6e7 100644 (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>();
index 73df39b31a0e5935930c8fd472f1f4408fcc4926..b02c229bb713d44f8daf070e1a53696ad97fe82d 100644 (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);