]> git.basschouten.com Git - openhab-addons.git/commitdiff
[io] Use Java 17 features (#15485)
authorHolger Friedrich <holgerfriedrich@users.noreply.github.com>
Thu, 24 Aug 2023 04:44:56 +0000 (06:44 +0200)
committerGitHub <noreply@github.com>
Thu, 24 Aug 2023 04:44:56 +0000 (06:44 +0200)
* instanceof matching and multiline strings
* use Map/Set/List.of instead of Collections

Signed-off-by: Holger Friedrich <mail@holger-friedrich.de>
16 files changed:
bundles/org.openhab.io.homekit/src/main/java/org/openhab/io/homekit/internal/accessories/HomekitTelevisionSpeakerImpl.java
bundles/org.openhab.io.hueemulation/src/main/java/org/openhab/io/hueemulation/internal/NetworkUtils.java
bundles/org.openhab.io.hueemulation/src/main/java/org/openhab/io/hueemulation/internal/rest/ConfigurationAccess.java
bundles/org.openhab.io.hueemulation/src/main/java/org/openhab/io/hueemulation/internal/rest/Scenes.java
bundles/org.openhab.io.hueemulation/src/main/java/org/openhab/io/hueemulation/internal/rest/UserManagement.java
bundles/org.openhab.io.hueemulation/src/test/java/org/openhab/io/hueemulation/internal/rest/CommonSetup.java
bundles/org.openhab.io.hueemulation/src/test/java/org/openhab/io/hueemulation/internal/rest/ItemUIDtoHueIDMappingTests.java
bundles/org.openhab.io.hueemulation/src/test/java/org/openhab/io/hueemulation/internal/rest/ScheduleTests.java
bundles/org.openhab.io.neeo/src/main/java/org/openhab/io/neeo/NeeoService.java
bundles/org.openhab.io.neeo/src/main/java/org/openhab/io/neeo/internal/NeeoItemValueConverter.java
bundles/org.openhab.io.neeo/src/main/java/org/openhab/io/neeo/internal/serialization/NeeoBrainDeviceSerializer.java
bundles/org.openhab.io.neeo/src/main/java/org/openhab/io/neeo/internal/serialization/NeeoDeviceChannelSerializer.java
bundles/org.openhab.io.neeo/src/main/java/org/openhab/io/neeo/internal/servletservices/NeeoBrainService.java
bundles/org.openhab.io.openhabcloud/src/main/java/org/openhab/io/openhabcloud/internal/CloudClient.java
bundles/org.openhab.io.openhabcloud/src/main/java/org/openhab/io/openhabcloud/internal/CloudService.java
bundles/org.openhab.io.openhabcloud/src/main/java/org/openhab/io/openhabcloud/internal/actions/NotificationModuleHandlerFactory.java

index db4ccc7426327309d60927d0dafdad253e09297a..885d319a37cdf32465aa9d11c863b6614344aaa2 100644 (file)
@@ -61,7 +61,7 @@ public class HomekitTelevisionSpeakerImpl extends AbstractHomekitAccessoryImpl {
         var volumeCharacteristic = getCharacteristic(VolumeCharacteristic.class);
         var volumeSelectorCharacteristic = getCharacteristic(VolumeSelectorCharacteristic.class);
 
-        if (!volumeControlTypeCharacteristic.isPresent()) {
+        if (volumeControlTypeCharacteristic.isEmpty()) {
             VolumeControlTypeEnum type;
             if (volumeCharacteristic.isPresent()) {
                 type = VolumeControlTypeEnum.ABSOLUTE;
index f2c42fcd2c6f9ba6cc66f72d5e15225cc0f6f954..bc99d6b6e74bea989d68553b50cddffb020d1ec6 100644 (file)
@@ -17,8 +17,8 @@ import java.net.NetworkInterface;
 import java.net.SocketException;
 import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
-import java.util.Collections;
 import java.util.List;
+import java.util.Set;
 
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.Response.ResponseBuilder;
@@ -95,7 +95,7 @@ public class NetworkUtils {
     public static Response singleError(Gson gson, UriInfo uri, int type, @Nullable String message) {
         HueResponse e = new HueResponse(
                 new HueErrorMessage(type, uri.getPath().replace("/api", ""), message != null ? message : ""));
-        String str = gson.toJson(Collections.singleton(e), new TypeToken<List<?>>() {
+        String str = gson.toJson(Set.of(e), new TypeToken<List<?>>() {
         }.getType());
         int httpCode = 500;
         switch (type) {
index bace57fedfa2fa27dc909aec094e9eba0f32e0d7..392b9bda99b525e1f614f568f404bec73fb6dd3c 100644 (file)
@@ -12,8 +12,8 @@
  */
 package org.openhab.io.hueemulation.internal.rest;
 
-import java.util.Collections;
 import java.util.List;
+import java.util.Set;
 
 import javax.ws.rs.GET;
 import javax.ws.rs.PUT;
@@ -132,7 +132,7 @@ public class ConfigurationAccess {
     public Response catchAll(@Context UriInfo uri) {
         HueResponse e = new HueResponse(
                 new HueErrorMessage(HueResponse.INVALID_JSON, uri.getPath().replace("/api", ""), "Invalid request: "));
-        String str = cs.gson.toJson(Collections.singleton(e), new TypeToken<List<?>>() {
+        String str = cs.gson.toJson(Set.of(e), new TypeToken<List<?>>() {
         }.getType());
         return Response.status(404).entity(str).build();
     }
index 7f72a6b3f01a491397858521ae6ae87a18c61304..2081e4a190250f69d1f14459cbb54475971b67db 100644 (file)
@@ -14,7 +14,6 @@ package org.openhab.io.hueemulation.internal.rest;
 
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.Collections;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
@@ -358,8 +357,7 @@ public class Scenes implements RegistryChangeListener<Rule> {
             if (groupItem == null) {
                 return NetworkUtils.singleError(cs.gson, uri, HueResponse.ARGUMENTS_INVALID, "Group does not exist!");
             }
-            List<Action> actions = Collections
-                    .singletonList(actionFromState(cs.mapItemUIDtoHueID(groupItem), groupItem.getState()));
+            List<Action> actions = List.of(actionFromState(cs.mapItemUIDtoHueID(groupItem), groupItem.getState()));
             builder.withActions(actions);
         }
 
index 750116f78d8e538de0447502309c63621d9f826c..29e973c5065ae4e8cc418db6d6fd90a2e74d9067 100644 (file)
@@ -14,8 +14,8 @@ package org.openhab.io.hueemulation.internal.rest;
 
 import java.time.LocalDateTime;
 import java.time.format.DateTimeFormatter;
-import java.util.Collections;
 import java.util.List;
+import java.util.Set;
 import java.util.UUID;
 
 import javax.ws.rs.DELETE;
@@ -172,7 +172,7 @@ public class UserManagement extends DefaultAbstractManagedProvider<HueUserAuthWi
         String clientKey = UUID.randomUUID().toString();
         addUser(apiKey, clientKey, userRequest.devicetype);
         HueSuccessResponseCreateUser h = new HueSuccessResponseCreateUser(apiKey, clientKey);
-        String result = cs.gson.toJson(Collections.singleton(new HueResponse(h)), new TypeToken<List<?>>() {
+        String result = cs.gson.toJson(Set.of(new HueResponse(h)), new TypeToken<List<?>>() {
         }.getType());
 
         return Response.ok(result).build();
index 5a62abdf8becb26e503cf456b467f236375e51bf..4b85990353c446c099e30d5bd217b50469662295 100644 (file)
@@ -19,9 +19,10 @@ import java.io.IOException;
 import java.net.InetSocketAddress;
 import java.net.ServerSocket;
 import java.net.URI;
-import java.util.Collections;
 import java.util.Dictionary;
 import java.util.Hashtable;
+import java.util.Map;
+import java.util.Set;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeoutException;
@@ -126,10 +127,10 @@ public class CommonSetup {
         } else {
             cs = new ConfigStoreWithoutMetadata(networkAddressService, configAdmin, scheduler);
         }
-        cs.activate(Collections.singletonMap("uuid", "a668dc9b-7172-49c3-832f-acb07dda2a20"));
-        cs.switchFilter = Collections.singleton("Switchable");
-        cs.whiteFilter = Collections.singleton("Switchable");
-        cs.colorFilter = Collections.singleton("ColorLighting");
+        cs.activate(Map.of("uuid", "a668dc9b-7172-49c3-832f-acb07dda2a20"));
+        cs.switchFilter = Set.of("Switchable");
+        cs.whiteFilter = Set.of("Switchable");
+        cs.colorFilter = Set.of("ColorLighting");
 
         userManagement = Mockito.spy(new UserManagement(storageService, cs));
 
index baf73902ae4916d1d3398076949dcd70cb5e51c2..74de2c9118f75ce332f5e4c9a59ecffcc0abe5d9 100644 (file)
@@ -17,7 +17,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
 import static org.mockito.Mockito.mock;
 
 import java.io.IOException;
-import java.util.Collections;
+import java.util.Map;
 import java.util.concurrent.ScheduledExecutorService;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
@@ -73,7 +73,7 @@ public class ItemUIDtoHueIDMappingTests {
 
         // Pretend there is a metadata entry for the imaginary item "demo1" with hueid 10
         commonSetup.metadataRegistry.add(new Metadata(new MetadataKey(ConfigStore.METAKEY, "demo1"), "10", null));
-        cs.activate(Collections.singletonMap("uuid", "demouuid"));
+        cs.activate(Map.of("uuid", "demouuid"));
 
         assertThat(cs.getHighestAssignedHueID(), CoreMatchers.is(10));
     }
index 4f06c214d6591f9fc1638ae9a9d75d271fbafaad..5cfb89df8a4a8cb0849e0da929b139774a6dc762 100644 (file)
@@ -20,7 +20,7 @@ import static org.mockito.Mockito.*;
 
 import java.io.IOException;
 import java.lang.reflect.Type;
-import java.util.Collections;
+import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Random;
@@ -341,7 +341,7 @@ public class ScheduleTests {
         configuration.put("time", "12:12:00");
         trigger = TriggerBuilder.create().withId("absolutetrigger").withTypeUID("timer.AbsoluteDateTimeTrigger")
                 .withConfiguration(configuration).build();
-        timeString = RuleUtils.timeStringFromTrigger(Collections.singletonList(trigger));
+        timeString = RuleUtils.timeStringFromTrigger(List.of(trigger));
 
         assertThat(timeString, is("2020-02-01T12:12:00"));
 
@@ -352,7 +352,7 @@ public class ScheduleTests {
         configuration.put("randomizeTime", "14:12:34");
         trigger = TriggerBuilder.create().withId("absolutetrigger").withTypeUID("timer.AbsoluteDateTimeTrigger")
                 .withConfiguration(configuration).build();
-        timeString = RuleUtils.timeStringFromTrigger(Collections.singletonList(trigger));
+        timeString = RuleUtils.timeStringFromTrigger(List.of(trigger));
 
         assertThat(timeString, is("2020-02-01T12:12:00A14:12:34"));
 
@@ -362,7 +362,7 @@ public class ScheduleTests {
         configuration.put("cronExpression", "15 12 * * 6,7");
         trigger = TriggerBuilder.create().withId("crontrigger").withTypeUID("timer.GenericCronTrigger")
                 .withConfiguration(configuration).build();
-        timeString = RuleUtils.timeStringFromTrigger(Collections.singletonList(trigger));
+        timeString = RuleUtils.timeStringFromTrigger(List.of(trigger));
 
         assertThat(timeString, is("W3/T12:15:00"));
 
@@ -371,7 +371,7 @@ public class ScheduleTests {
         configuration.put("cronExpression", "15 14 * * 1,2,3,4,5,6,7");
         trigger = TriggerBuilder.create().withId("crontrigger").withTypeUID("timer.GenericCronTrigger")
                 .withConfiguration(configuration).build();
-        timeString = RuleUtils.timeStringFromTrigger(Collections.singletonList(trigger));
+        timeString = RuleUtils.timeStringFromTrigger(List.of(trigger));
 
         assertThat(timeString, is("W127/T14:15:00"));
 
@@ -380,7 +380,7 @@ public class ScheduleTests {
         configuration.put("time", "12:12:00");
         trigger = TriggerBuilder.create().withId("timertrigger").withTypeUID("timer.TimerTrigger")
                 .withConfiguration(configuration).build();
-        timeString = RuleUtils.timeStringFromTrigger(Collections.singletonList(trigger));
+        timeString = RuleUtils.timeStringFromTrigger(List.of(trigger));
 
         assertThat(timeString, is("PT12:12:00"));
 
@@ -390,7 +390,7 @@ public class ScheduleTests {
         configuration.put("randomizeTime", "14:12:34");
         trigger = TriggerBuilder.create().withId("timertrigger").withTypeUID("timer.TimerTrigger")
                 .withConfiguration(configuration).build();
-        timeString = RuleUtils.timeStringFromTrigger(Collections.singletonList(trigger));
+        timeString = RuleUtils.timeStringFromTrigger(List.of(trigger));
 
         assertThat(timeString, is("PT12:12:00A14:12:34"));
 
@@ -400,7 +400,7 @@ public class ScheduleTests {
         configuration.put("repeat", -1);
         trigger = TriggerBuilder.create().withId("timertrigger").withTypeUID("timer.TimerTrigger")
                 .withConfiguration(configuration).build();
-        timeString = RuleUtils.timeStringFromTrigger(Collections.singletonList(trigger));
+        timeString = RuleUtils.timeStringFromTrigger(List.of(trigger));
 
         assertThat(timeString, is("R/PT12:12:00"));
 
@@ -411,7 +411,7 @@ public class ScheduleTests {
         configuration.put("repeat", 12);
         trigger = TriggerBuilder.create().withId("timertrigger").withTypeUID("timer.TimerTrigger")
                 .withConfiguration(configuration).build();
-        timeString = RuleUtils.timeStringFromTrigger(Collections.singletonList(trigger));
+        timeString = RuleUtils.timeStringFromTrigger(List.of(trigger));
 
         assertThat(timeString, is("R12/PT12:12:00A14:12:34"));
     }
index 92cefbdc4790fa2673f1b09286bc9a84a4f48596..d50e03e1ccdbe6ad50883879f173e72b6412dd6b 100644 (file)
@@ -407,7 +407,7 @@ public class NeeoService implements EventSubscriber, NetworkAddressChangeListene
      */
     @Override
     public Set<String> getSubscribedEventTypes() {
-        return Collections.singleton(ItemStateChangedEvent.TYPE);
+        return Set.of(ItemStateChangedEvent.TYPE);
     }
 
     @Override
index 45267d9fac79410ad282ed8336377d1ed6c01f56..d5d6c9408371ab97efc8612d03c0e1188a1eb1cd 100644 (file)
@@ -80,8 +80,7 @@ public class NeeoItemValueConverter {
         final String format = channel.getValue();
 
         // HSBType must be done before the others since it inherits from DecimalType
-        if (state instanceof HSBType) {
-            final HSBType hsb = (HSBType) state;
+        if (state instanceof HSBType hsb) {
             switch (channel.getSubType()) {
                 case HUE:
                     return new NeeoItemValue(hsb.getHue().toBigDecimal());
@@ -106,8 +105,8 @@ public class NeeoItemValueConverter {
                 convertedState = UnDefType.UNDEF;
                 break;
             case SLIDER:
-                if (state instanceof PercentType) {
-                    convertedState = new DecimalType(((PercentType) state).toBigDecimal());
+                if (state instanceof PercentType type) {
+                    convertedState = new DecimalType(type.toBigDecimal());
                 } else {
                     convertedState = state.as(DecimalType.class);
                 }
@@ -136,9 +135,9 @@ public class NeeoItemValueConverter {
         } else if (convertedState instanceof UpDownType) {
             return new NeeoItemValue(convertedState == UpDownType.UP);
 
-        } else if (convertedState instanceof DecimalType) {
+        } else if (convertedState instanceof DecimalType type) {
             if (format == null || format.isEmpty() || channel.getType() == NeeoCapabilityType.SLIDER) {
-                return new NeeoItemValue(((DecimalType) convertedState).toBigDecimal());
+                return new NeeoItemValue(type.toBigDecimal());
             }
         } else if (convertedState instanceof UnDefType) {
             return new NeeoItemValue("-");
index 7896b3782dc5ee40a892b2c748d38e25974e7337..35aef7ba01b6516ba1efae007fd6fec18860ee86 100644 (file)
@@ -203,8 +203,7 @@ public class NeeoBrainDeviceSerializer implements JsonSerializer<NeeoDevice> {
                         compPath + "/textlabel/actor", new JsonPrimitive(sensorItemName));
 
                 capObj.addProperty("isLabelVisible",
-                        channel instanceof NeeoDeviceChannelText ? ((NeeoDeviceChannelText) channel).isLabelVisible()
-                                : true);
+                        channel instanceof NeeoDeviceChannelText ndct ? ndct.isLabelVisible() : true);
 
                 capabilities.add(capObj);
 
index c7c043860f7154e1f288053e76294fbce5b9d2ca..50b5a06333beca746ce55e46dc7617ef0b6e0363 100644 (file)
@@ -153,10 +153,10 @@ public class NeeoDeviceChannelSerializer
 
         }
 
-        if (chnl instanceof NeeoDeviceChannelText) {
-            jo.addProperty("labelVisible", ((NeeoDeviceChannelText) chnl).isLabelVisible());
-        } else if (chnl instanceof NeeoDeviceChannelDirectory) {
-            jo.add("listItems", jsonContext.serialize(((NeeoDeviceChannelDirectory) chnl).getListItems()));
+        if (chnl instanceof NeeoDeviceChannelText text) {
+            jo.addProperty("labelVisible", text.isLabelVisible());
+        } else if (chnl instanceof NeeoDeviceChannelDirectory directory) {
+            jo.add("listItems", jsonContext.serialize(directory.getListItems()));
         }
 
         return jo;
index fc2fb908b288a42af91f24016d53b5b97c2d9803..4c01e9ac89625c53fb431bae998e5e3b19105336 100644 (file)
@@ -404,10 +404,9 @@ public class NeeoBrainService extends DefaultServletService {
                 }
 
             } else {
-                if (channel instanceof NeeoDeviceChannelDirectory) {
+                if (channel instanceof NeeoDeviceChannelDirectory directoryChannel) {
                     final NeeoDirectoryRequest discoveryRequest = gson.fromJson(req.getReader(),
                             NeeoDirectoryRequest.class);
-                    final NeeoDeviceChannelDirectory directoryChannel = (NeeoDeviceChannelDirectory) channel;
                     NeeoUtil.write(resp, gson.toJson(new NeeoDirectoryResult(discoveryRequest, directoryChannel)));
                 } else {
                     logger.debug("Channel definition for '{}' not found to directory set value ({})",
index 6e2fbc63d805511d4aee868f0512adeb56d768d4..9afe895fe2ff48fbbd7c640447fb770982ddd752 100644 (file)
@@ -237,8 +237,7 @@ public class CloudClient {
                 })//
                 .on(Manager.EVENT_CONNECT_ERROR, args -> {
                     if (args.length > 0) {
-                        if (args[0] instanceof Exception) {
-                            Exception e = (Exception) args[0];
+                        if (args[0] instanceof Exception e) {
                             logger.debug(
                                     "Error connecting to the openHAB Cloud instance: {} {}. Should reconnect automatically.",
                                     e.getClass().getSimpleName(), e.getMessage());
@@ -256,8 +255,8 @@ public class CloudClient {
                 .on(Manager.EVENT_PACKET, args -> {
                     int packetTypeIndex = -1;
                     String type = "<unexpected packet type>";
-                    if (args.length == 1 && args[0] instanceof Packet<?>) {
-                        packetTypeIndex = ((Packet<?>) args[0]).type;
+                    if (args.length == 1 && args[0] instanceof Packet<?> packet) {
+                        packetTypeIndex = packet.type;
 
                         if (packetTypeIndex < Parser.types.length) {
                             type = Parser.types[packetTypeIndex];
@@ -282,8 +281,7 @@ public class CloudClient {
                 .on(Socket.EVENT_RECONNECT,
                         args -> logger.debug("Socket.IO re-connected successfully (attempt {})", args[0]))//
                 .on(Socket.EVENT_RECONNECT_ERROR, args -> {
-                    if (args[0] instanceof Exception) {
-                        Exception e = (Exception) args[0];
+                    if (args[0] instanceof Exception e) {
                         logger.debug("Socket.IO re-connect attempt error: {} {}", e.getClass().getSimpleName(),
                                 e.getMessage());
                     } else {
@@ -308,8 +306,7 @@ public class CloudClient {
                 .on(Socket.EVENT_ERROR, args -> {
                     if (CloudClient.this.socket.connected()) {
                         if (args.length > 0) {
-                            if (args[0] instanceof Exception) {
-                                Exception e = (Exception) args[0];
+                            if (args[0] instanceof Exception e) {
                                 logger.warn("Error during communication: {} {}", e.getClass().getSimpleName(),
                                         e.getMessage());
                             } else {
@@ -335,8 +332,7 @@ public class CloudClient {
                         long delay = reconnectBackoff.duration();
                         // Try reconnecting on connection errors
                         if (args.length > 0) {
-                            if (args[0] instanceof Exception) {
-                                Exception e = (Exception) args[0];
+                            if (args[0] instanceof Exception e) {
                                 logger.warn(
                                         "Error connecting to the openHAB Cloud instance: {} {}. Reconnecting after {} ms.",
                                         e.getClass().getSimpleName(), e.getMessage(), delay);
index 5114ff8bb7802ac24cd2b00c99bb5652bdd82de1..31804eadd29227dfc21a6650fdf75a4cbf6387d6 100644 (file)
@@ -211,8 +211,7 @@ public class CloudService implements ActionService, CloudClientListener, EventSu
 
         exposedItems = new HashSet<>();
         Object expCfg = config.get(CFG_EXPOSE);
-        if (expCfg instanceof String) {
-            String value = (String) expCfg;
+        if (expCfg instanceof String value) {
             while (value.startsWith("[")) {
                 value = value.substring(1);
             }
@@ -222,8 +221,8 @@ public class CloudService implements ActionService, CloudClientListener, EventSu
             for (String itemName : Arrays.asList((value).split(","))) {
                 exposedItems.add(itemName.trim());
             }
-        } else if (expCfg instanceof Iterable) {
-            for (Object entry : ((Iterable<?>) expCfg)) {
+        } else if (expCfg instanceof Iterable iterable) {
+            for (Object entry : iterable) {
                 exposedItems.add(entry.toString());
             }
         }
index 9bff96a831bde460fb8416e80185e8d279a63925..76f329064e3d198c19d63a3439ec5dac656742a9 100644 (file)
@@ -62,17 +62,17 @@ public class NotificationModuleHandlerFactory extends BaseModuleHandlerFactory {
 
     @Override
     protected @Nullable ModuleHandler internalCreate(Module module, String ruleUID) {
-        if (module instanceof Action) {
+        if (module instanceof Action action) {
             switch (module.getTypeUID()) {
                 case SendNotificationActionHandler.TYPE_ID:
                 case SendNotificationActionHandler.EXTENDED_TYPE_ID:
-                    return new SendNotificationActionHandler((Action) module, cloudService);
+                    return new SendNotificationActionHandler(action, cloudService);
                 case SendBroadcastNotificationActionHandler.TYPE_ID:
                 case SendBroadcastNotificationActionHandler.EXTENDED_TYPE_ID:
-                    return new SendBroadcastNotificationActionHandler((Action) module, cloudService);
+                    return new SendBroadcastNotificationActionHandler(action, cloudService);
                 case SendLogNotificationActionHandler.TYPE_ID:
                 case SendLogNotificationActionHandler.EXTENDED_TYPE_ID:
-                    return new SendLogNotificationActionHandler((Action) module, cloudService);
+                    return new SendLogNotificationActionHandler(action, cloudService);
                 default:
                     break;
             }