diff --git a/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/OpenAPIUtils.java b/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/OpenAPIUtils.java index 04a597b70..8cf00f440 100644 --- a/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/OpenAPIUtils.java +++ b/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/OpenAPIUtils.java @@ -79,9 +79,7 @@ public class OpenAPIUtils { } try { - URI requestURI = new URI(HttpScheme.HTTP.asString(), (String) null, address, port, path, query, - (String) null); - return requestURI; + return new URI(HttpScheme.HTTP.asString(), (String) null, address, port, path, query, (String) null); } catch (URISyntaxException var8) { LOGGER.warn("URI could not be parsed with path {}", path); throw new NanoleafException("Wrong URI format for API request"); @@ -115,8 +113,8 @@ public class OpenAPIUtils { } } catch (ExecutionException ee) { Throwable cause = ee.getCause(); - if (cause != null && cause instanceof HttpResponseException - && ((HttpResponseException) cause).getResponse().getStatus() == HttpStatus.UNAUTHORIZED_401) { + if (cause instanceof HttpResponseException httpResponseException + && httpResponseException.getResponse().getStatus() == HttpStatus.UNAUTHORIZED_401) { LOGGER.debug("OpenAPI request unauthorized. Invalid authorization token."); throw new NanoleafUnauthorizedException("Invalid authorization token"); } else { diff --git a/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/command/NanoleafCommandExtension.java b/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/command/NanoleafCommandExtension.java index 1ac5e72cd..92a6235ef 100644 --- a/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/command/NanoleafCommandExtension.java +++ b/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/command/NanoleafCommandExtension.java @@ -57,8 +57,7 @@ public class NanoleafCommandExtension extends AbstractConsoleCommandExtension { thingRegistry.getAll().forEach(thing -> { if (thing.getUID().getBindingId().equals(NanoleafBindingConstants.BINDING_ID)) { ThingHandler handler = thing.getHandler(); - if (handler instanceof NanoleafControllerHandler) { - NanoleafControllerHandler nanoleafControllerHandler = (NanoleafControllerHandler) handler; + if (handler instanceof NanoleafControllerHandler nanoleafControllerHandler) { if (!handler.getThing().isEnabled()) { console.println( "The following Nanoleaf is NOT enabled as a Thing. Enable it first to view its layout."); @@ -76,16 +75,15 @@ public class NanoleafCommandExtension extends AbstractConsoleCommandExtension { Thing thing = thingRegistry.get(new ThingUID(uid)); if (thing != null) { ThingHandler handler = thing.getHandler(); - if (handler instanceof NanoleafControllerHandler) { - NanoleafControllerHandler nanoleafControllerHandler = (NanoleafControllerHandler) handler; + if (handler instanceof NanoleafControllerHandler nanoleafControllerHandler) { String layout = nanoleafControllerHandler.getLayout(); console.println(layout); } else { - console.println("Thing with UID '" + uid.toString() - + "' is not an initialized Nanoleaf controller."); + console.println( + "Thing with UID '" + uid + "' is not an initialized Nanoleaf controller."); } } else { - console.println("Thing with UID '" + uid.toString() + "' does not exist."); + console.println("Thing with UID '" + uid + "' does not exist."); } } else { printUsage(console); diff --git a/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/discovery/NanoleafMDNSDiscoveryParticipant.java b/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/discovery/NanoleafMDNSDiscoveryParticipant.java index 02e563588..b4d6e82b2 100644 --- a/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/discovery/NanoleafMDNSDiscoveryParticipant.java +++ b/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/discovery/NanoleafMDNSDiscoveryParticipant.java @@ -86,10 +86,8 @@ public class NanoleafMDNSDiscoveryParticipant implements MDNSDiscoveryParticipan MODEL_ID_LIGHTPANELS.equals(modelId) ? API_MIN_FW_VER_LIGHTPANELS : API_MIN_FW_VER_CANVAS); } - final DiscoveryResult result = DiscoveryResultBuilder.create(uid).withThingType(getThingType(service)) - .withProperties(properties).withLabel(service.getName()).withRepresentationProperty(CONFIG_ADDRESS) - .build(); - return result; + return DiscoveryResultBuilder.create(uid).withThingType(getThingType(service)).withProperties(properties) + .withLabel(service.getName()).withRepresentationProperty(CONFIG_ADDRESS).build(); } @Override diff --git a/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/handler/NanoleafPanelHandler.java b/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/handler/NanoleafPanelHandler.java index 676011174..36b241909 100644 --- a/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/handler/NanoleafPanelHandler.java +++ b/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/handler/NanoleafPanelHandler.java @@ -137,8 +137,8 @@ public class NanoleafPanelHandler extends BaseThingHandler implements NanoleafPa Bridge bridge = getBridge(); if (bridge != null) { ThingHandler handler = bridge.getHandler(); - if (handler instanceof NanoleafControllerHandler) { - ((NanoleafControllerHandler) handler).getColorInformation().unregisterChangeListener(getPanelID()); + if (handler instanceof NanoleafControllerHandler controllerHandler) { + controllerHandler.getColorInformation().unregisterChangeListener(getPanelID()); } } @@ -174,8 +174,8 @@ public class NanoleafPanelHandler extends BaseThingHandler implements NanoleafPa Bridge bridge = getBridge(); if (bridge != null) { ThingHandler handler = bridge.getHandler(); - if (handler instanceof NanoleafControllerHandler) { - ((NanoleafControllerHandler) handler).getColorInformation().registerChangeListener(getPanelID(), this); + if (handler instanceof NanoleafControllerHandler controllerHandler) { + controllerHandler.getColorInformation().registerChangeListener(getPanelID(), this); } } } @@ -185,8 +185,8 @@ public class NanoleafPanelHandler extends BaseThingHandler implements NanoleafPa logger.debug("currentPanelColor: {}", currentPanelColor); HSBType newPanelColor = new HSBType(); - if (command instanceof HSBType) { - newPanelColor = (HSBType) command; + if (command instanceof HSBType hsbCommand) { + newPanelColor = hsbCommand; } else if (command instanceof OnOffType) { if (OnOffType.ON.equals(command)) { newPanelColor = new HSBType(currentPanelColor.getHue(), currentPanelColor.getSaturation(), @@ -195,9 +195,8 @@ public class NanoleafPanelHandler extends BaseThingHandler implements NanoleafPa newPanelColor = new HSBType(currentPanelColor.getHue(), currentPanelColor.getSaturation(), MIN_PANEL_BRIGHTNESS); } - } else if (command instanceof PercentType) { - PercentType brightness = new PercentType( - Math.max(MIN_PANEL_BRIGHTNESS.intValue(), ((PercentType) command).intValue())); + } else if (command instanceof PercentType type) { + PercentType brightness = new PercentType(Math.max(MIN_PANEL_BRIGHTNESS.intValue(), type.intValue())); newPanelColor = new HSBType(currentPanelColor.getHue(), currentPanelColor.getSaturation(), brightness); } else if (command instanceof IncreaseDecreaseType) { int brightness = currentPanelColor.getBrightness().intValue(); @@ -281,8 +280,8 @@ public class NanoleafPanelHandler extends BaseThingHandler implements NanoleafPa Object panelId = getThing().getConfiguration().get(CONFIG_PANEL_ID); if (panelId instanceof Integer) { return (Integer) panelId; - } else if (panelId instanceof Number) { - return ((Number) panelId).intValue(); + } else if (panelId instanceof Number numberValue) { + return numberValue.intValue(); } else { // Fall back to parsing string representation of panel if it is not returning an integer String stringPanelId = panelId.toString(); @@ -300,8 +299,8 @@ public class NanoleafPanelHandler extends BaseThingHandler implements NanoleafPa Bridge bridge = getBridge(); if (bridge != null) { ThingHandler handler = bridge.getHandler(); - if (handler instanceof NanoleafControllerHandler) { - ((NanoleafControllerHandler) handler).getColorInformation().setPanelColor(panelId, color); + if (handler instanceof NanoleafControllerHandler controllerHandler) { + controllerHandler.getColorInformation().setPanelColor(panelId, color); } else { logger.debug("Couldn't find handler for panel {}", panelId); } diff --git a/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/layout/DrawingAlgorithm.java b/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/layout/DrawingAlgorithm.java index 10f852bb4..1bce9eedb 100644 --- a/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/layout/DrawingAlgorithm.java +++ b/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/layout/DrawingAlgorithm.java @@ -26,5 +26,5 @@ public enum DrawingAlgorithm { TRIANGLE, HEXAGON, CORNER, - LINE; + LINE } diff --git a/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/layout/DrawingSettings.java b/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/layout/DrawingSettings.java index 5ec5c3725..f7737a1bf 100644 --- a/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/layout/DrawingSettings.java +++ b/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/layout/DrawingSettings.java @@ -77,10 +77,8 @@ public class DrawingSettings { private static ImagePoint2D toPictureLayout(Point2D original, int imageHeight, ImagePoint2D min, double rotationRadians) { Point2D rotated = original.rotate(rotationRadians); - ImagePoint2D translated = new ImagePoint2D( - NanoleafBindingConstants.LAYOUT_BORDER_WIDTH + rotated.getX() - min.getX(), + return new ImagePoint2D(NanoleafBindingConstants.LAYOUT_BORDER_WIDTH + rotated.getX() - min.getX(), imageHeight - NanoleafBindingConstants.LAYOUT_BORDER_WIDTH - rotated.getY() + min.getY()); - return translated; } private static List toPictureLayout(List originals, int imageHeight, ImagePoint2D min, diff --git a/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/layout/NanoleafLayout.java b/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/layout/NanoleafLayout.java index 9bded7f5e..a147915f2 100644 --- a/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/layout/NanoleafLayout.java +++ b/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/layout/NanoleafLayout.java @@ -64,7 +64,7 @@ public class NanoleafLayout { return new byte[] {}; } - ImagePoint2D size[] = findSize(positionDatums, rotationRadians); + ImagePoint2D[] size = findSize(positionDatums, rotationRadians); final ImagePoint2D min = size[0]; final ImagePoint2D max = size[1]; diff --git a/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/model/State.java b/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/model/State.java index 5cf5dad22..c121b5596 100644 --- a/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/model/State.java +++ b/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/model/State.java @@ -90,20 +90,20 @@ public class State { } public void setState(IntegerState value) { - if (value instanceof Brightness) { - this.setBrightness((Brightness) value); - } else if (value instanceof Hue) { - this.setHue((Hue) value); - } else if (value instanceof Sat) { - this.setSaturation((Sat) value); - } else if (value instanceof Ct) { - this.setColorTemperature((Ct) value); + if (value instanceof Brightness brightnessState) { + this.setBrightness(brightnessState); + } else if (value instanceof Hue hueState) { + this.setHue(hueState); + } else if (value instanceof Sat satState) { + this.setSaturation(satState); + } else if (value instanceof Ct ctState) { + this.setColorTemperature(ctState); } } public void setState(BooleanState value) { - if (value instanceof On) { - this.setOn((On) value); + if (value instanceof On onState) { + this.setOn(onState); } } } diff --git a/bundles/org.openhab.binding.nanoleaf/src/test/java/org/openhab/binding/nanoleaf/internal/layout/NanoleafLayoutTest.java b/bundles/org.openhab.binding.nanoleaf/src/test/java/org/openhab/binding/nanoleaf/internal/layout/NanoleafLayoutTest.java index ea917af99..25d992260 100644 --- a/bundles/org.openhab.binding.nanoleaf/src/test/java/org/openhab/binding/nanoleaf/internal/layout/NanoleafLayoutTest.java +++ b/bundles/org.openhab.binding.nanoleaf/src/test/java/org/openhab/binding/nanoleaf/internal/layout/NanoleafLayoutTest.java @@ -70,7 +70,7 @@ public class NanoleafLayoutTest { } private class TestPanelState implements PanelState { - private final HSBType testColors[] = { HSBType.fromRGB(160, 120, 40), HSBType.fromRGB(80, 60, 20), + private final HSBType[] testColors = { HSBType.fromRGB(160, 120, 40), HSBType.fromRGB(80, 60, 20), HSBType.fromRGB(120, 90, 30), HSBType.fromRGB(200, 150, 60) }; @Override diff --git a/bundles/org.openhab.binding.neato/src/main/java/org/openhab/binding/neato/internal/NeatoHandlerFactory.java b/bundles/org.openhab.binding.neato/src/main/java/org/openhab/binding/neato/internal/NeatoHandlerFactory.java index d1f7b22c0..ce2fa1798 100644 --- a/bundles/org.openhab.binding.neato/src/main/java/org/openhab/binding/neato/internal/NeatoHandlerFactory.java +++ b/bundles/org.openhab.binding.neato/src/main/java/org/openhab/binding/neato/internal/NeatoHandlerFactory.java @@ -49,8 +49,7 @@ public class NeatoHandlerFactory extends BaseThingHandlerFactory { public static final Set SUPPORTED_THING_TYPE_UIDS = Collections .unmodifiableSet(Stream.of(BRIDGE_TYPE_NEATOACCOUNT, THING_TYPE_VACUUMCLEANER).collect(Collectors.toSet())); - public static final Set DISCOVERABLE_THING_TYPE_UIDS = Collections - .singleton(THING_TYPE_VACUUMCLEANER); + public static final Set DISCOVERABLE_THING_TYPE_UIDS = Set.of(THING_TYPE_VACUUMCLEANER); private Map> discoveryServiceRegistrations = new HashMap<>(); diff --git a/bundles/org.openhab.binding.neato/src/main/java/org/openhab/binding/neato/internal/NeatoRobot.java b/bundles/org.openhab.binding.neato/src/main/java/org/openhab/binding/neato/internal/NeatoRobot.java index be031f191..b1084a9a7 100644 --- a/bundles/org.openhab.binding.neato/src/main/java/org/openhab/binding/neato/internal/NeatoRobot.java +++ b/bundles/org.openhab.binding.neato/src/main/java/org/openhab/binding/neato/internal/NeatoRobot.java @@ -112,7 +112,6 @@ public class NeatoRobot { return HttpUtil.executeUrl("POST", "https://nucleo.neatocloud.com:4443/vendors/neato/robots/" + this.serialNumber + "/messages", headers, stream, "text/html; charset=ISO-8859-1", 20000); - } catch (IOException | NoSuchAlgorithmException | InvalidKeyException e) { throw new NeatoCommunicationException(e); } diff --git a/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/discovery/NeeoBrainDiscovery.java b/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/discovery/NeeoBrainDiscovery.java index 982d69b69..d324c8770 100644 --- a/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/discovery/NeeoBrainDiscovery.java +++ b/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/discovery/NeeoBrainDiscovery.java @@ -16,7 +16,6 @@ import static org.openhab.binding.neeo.internal.NeeoConstants.BRIDGE_TYPE_BRAIN; import java.net.InetAddress; import java.net.UnknownHostException; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; @@ -50,7 +49,7 @@ public class NeeoBrainDiscovery implements MDNSDiscoveryParticipant { @Override public Set<@Nullable ThingTypeUID> getSupportedThingTypeUIDs() { - return Collections.singleton(BRIDGE_TYPE_BRAIN); + return Set.of(BRIDGE_TYPE_BRAIN); } @Override diff --git a/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/discovery/NeeoDeviceDiscoveryService.java b/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/discovery/NeeoDeviceDiscoveryService.java index 7b79b5001..fbc60526a 100644 --- a/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/discovery/NeeoDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/discovery/NeeoDeviceDiscoveryService.java @@ -13,7 +13,6 @@ package org.openhab.binding.neeo.internal.discovery; import java.io.IOException; -import java.util.Collections; import java.util.Objects; import java.util.Set; @@ -46,8 +45,7 @@ public class NeeoDeviceDiscoveryService extends AbstractDiscoveryService { private final Logger logger = LoggerFactory.getLogger(NeeoDeviceDiscoveryService.class); /** The device thing type we support */ - private static final Set DISCOVERABLE_THING_TYPES_UIDS = Collections - .singleton(NeeoConstants.THING_TYPE_DEVICE); + private static final Set DISCOVERABLE_THING_TYPES_UIDS = Set.of(NeeoConstants.THING_TYPE_DEVICE); /** The timeout (in seconds) for searching the room */ private static final int SEARCH_TIME = 10; diff --git a/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/discovery/NeeoRoomDiscoveryService.java b/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/discovery/NeeoRoomDiscoveryService.java index 4d108e79e..3ccdadddd 100644 --- a/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/discovery/NeeoRoomDiscoveryService.java +++ b/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/discovery/NeeoRoomDiscoveryService.java @@ -13,7 +13,6 @@ package org.openhab.binding.neeo.internal.discovery; import java.io.IOException; -import java.util.Collections; import java.util.Objects; import java.util.Set; @@ -44,8 +43,7 @@ public class NeeoRoomDiscoveryService extends AbstractDiscoveryService { private final Logger logger = LoggerFactory.getLogger(NeeoRoomDiscoveryService.class); /** The room bridge type we support */ - private static final Set DISCOVERABLE_THING_TYPES_UIDS = Collections - .singleton(NeeoConstants.BRIDGE_TYPE_ROOM); + private static final Set DISCOVERABLE_THING_TYPES_UIDS = Set.of(NeeoConstants.BRIDGE_TYPE_ROOM); /** The timeout (in seconds) for searching the brain */ private static final int SEARCH_TIME = 10; diff --git a/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/handler/NeeoDeviceHandler.java b/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/handler/NeeoDeviceHandler.java index 56dc785f0..5ce26ae65 100644 --- a/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/handler/NeeoDeviceHandler.java +++ b/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/handler/NeeoDeviceHandler.java @@ -339,8 +339,8 @@ public class NeeoDeviceHandler extends BaseThingHandler { final Bridge parent = getBridge(); if (parent != null) { final BridgeHandler handler = parent.getHandler(); - if (handler instanceof NeeoRoomHandler) { - return ((NeeoRoomHandler) handler); + if (handler instanceof NeeoRoomHandler roomHandler) { + return roomHandler; } } return null; diff --git a/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/handler/NeeoRoomHandler.java b/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/handler/NeeoRoomHandler.java index 24436f594..18b4cf263 100644 --- a/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/handler/NeeoRoomHandler.java +++ b/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/handler/NeeoRoomHandler.java @@ -317,8 +317,8 @@ public class NeeoRoomHandler extends BaseBridgeHandler { final Bridge parent = getBridge(); if (parent != null) { final BridgeHandler handler = parent.getHandler(); - if (handler instanceof NeeoBrainHandler) { - return ((NeeoBrainHandler) handler); + if (handler instanceof NeeoBrainHandler brainHandler) { + return brainHandler; } } return null; diff --git a/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/models/NeeoDevicesDeserializer.java b/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/models/NeeoDevicesDeserializer.java index 945bb58b5..2465bbf72 100644 --- a/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/models/NeeoDevicesDeserializer.java +++ b/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/models/NeeoDevicesDeserializer.java @@ -41,9 +41,9 @@ public class NeeoDevicesDeserializer implements JsonDeserializer<@Nullable NeeoD Objects.requireNonNull(jsonElement, "jsonElement cannot be null"); Objects.requireNonNull(context, "context cannot be null"); - if (jsonElement instanceof JsonObject) { + if (jsonElement instanceof JsonObject jsonObject) { final List scenarios = new ArrayList<>(); - for (Map.Entry entry : ((JsonObject) jsonElement).entrySet()) { + for (Map.Entry entry : jsonObject.entrySet()) { final NeeoDevice device = context.deserialize(entry.getValue(), NeeoDevice.class); scenarios.add(device); } diff --git a/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/models/NeeoMacrosDeserializer.java b/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/models/NeeoMacrosDeserializer.java index 045af48ea..09c0ae0c9 100644 --- a/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/models/NeeoMacrosDeserializer.java +++ b/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/models/NeeoMacrosDeserializer.java @@ -41,9 +41,9 @@ public class NeeoMacrosDeserializer implements JsonDeserializer<@Nullable NeeoMa Objects.requireNonNull(jsonElement, "jsonElement cannot be null"); Objects.requireNonNull(context, "context cannot be null"); - if (jsonElement instanceof JsonObject) { + if (jsonElement instanceof JsonObject jsonObject) { final List scenarios = new ArrayList<>(); - for (Map.Entry entry : ((JsonObject) jsonElement).entrySet()) { + for (Map.Entry entry : jsonObject.entrySet()) { final NeeoMacro macro = context.deserialize(entry.getValue(), NeeoMacro.class); scenarios.add(macro); } diff --git a/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/models/NeeoRecipesDeserializer.java b/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/models/NeeoRecipesDeserializer.java index b2c2955e4..dea4c3d49 100644 --- a/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/models/NeeoRecipesDeserializer.java +++ b/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/models/NeeoRecipesDeserializer.java @@ -41,9 +41,9 @@ public class NeeoRecipesDeserializer implements JsonDeserializer<@Nullable NeeoR Objects.requireNonNull(jsonElement, "jsonElement cannot be null"); Objects.requireNonNull(context, "context cannot be null"); - if (jsonElement instanceof JsonObject) { + if (jsonElement instanceof JsonObject jsonObject) { final List recipes = new ArrayList<>(); - for (Map.Entry entry : ((JsonObject) jsonElement).entrySet()) { + for (Map.Entry entry : jsonObject.entrySet()) { final NeeoRecipe recipe = context.deserialize(entry.getValue(), NeeoRecipe.class); recipes.add(recipe); } diff --git a/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/models/NeeoRoomsDeserializer.java b/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/models/NeeoRoomsDeserializer.java index 1a776ab8f..0850113d6 100644 --- a/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/models/NeeoRoomsDeserializer.java +++ b/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/models/NeeoRoomsDeserializer.java @@ -40,9 +40,9 @@ public class NeeoRoomsDeserializer implements JsonDeserializer<@Nullable NeeoRoo @Nullable JsonDeserializationContext context) throws JsonParseException { Objects.requireNonNull(jsonElement, "jsonElement cannot be null"); Objects.requireNonNull(context, "context cannot be null"); - if (jsonElement instanceof JsonObject) { + if (jsonElement instanceof JsonObject jsonObject) { final List recipes = new ArrayList<>(); - for (Map.Entry entry : ((JsonObject) jsonElement).entrySet()) { + for (Map.Entry entry : jsonObject.entrySet()) { final NeeoRoom room = context.deserialize(entry.getValue(), NeeoRoom.class); recipes.add(room); } diff --git a/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/models/NeeoScenariosDeserializer.java b/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/models/NeeoScenariosDeserializer.java index bb9118363..ea9cbdca5 100644 --- a/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/models/NeeoScenariosDeserializer.java +++ b/bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/models/NeeoScenariosDeserializer.java @@ -40,9 +40,9 @@ public class NeeoScenariosDeserializer implements JsonDeserializer<@Nullable Nee @Nullable JsonDeserializationContext context) throws JsonParseException { Objects.requireNonNull(jsonElement, "jsonElement cannot be null"); Objects.requireNonNull(context, "context cannot be null"); - if (jsonElement instanceof JsonObject) { + if (jsonElement instanceof JsonObject jsonObject) { final List scenarios = new ArrayList<>(); - for (Map.Entry entry : ((JsonObject) jsonElement).entrySet()) { + for (Map.Entry entry : jsonObject.entrySet()) { final NeeoScenario scenario = context.deserialize(entry.getValue(), NeeoScenario.class); scenarios.add(scenario); } diff --git a/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoBaseHandler.java b/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoBaseHandler.java index c774e27da..4193e7cd2 100644 --- a/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoBaseHandler.java +++ b/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoBaseHandler.java @@ -29,7 +29,6 @@ import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingStatusDetail; import org.openhab.core.thing.binding.BaseThingHandler; -import org.openhab.core.thing.binding.BridgeHandler; import org.openhab.core.types.Command; import org.openhab.core.types.RefreshType; import org.openhab.core.types.State; @@ -166,8 +165,7 @@ public class NeoBaseHandler extends BaseThingHandler { if (channel != null) { Configuration config = channel.getConfiguration(); Object holdOnlineState = config.get(PARAM_HOLD_ONLINE_STATE); - if (holdOnlineState != null && (holdOnlineState instanceof Boolean) - && ((Boolean) holdOnlineState).booleanValue()) { + if (holdOnlineState instanceof Boolean booleanValue && booleanValue.booleanValue()) { /* * the Configuration Parameter "holdOnlineState" is True so do NOT send a * state update to OpenHAB @@ -236,11 +234,9 @@ public class NeoBaseHandler extends BaseThingHandler { protected @Nullable NeoHubHandler getNeoHub() { @Nullable Bridge b; - @Nullable - BridgeHandler h; - if ((b = getBridge()) != null && (h = b.getHandler()) != null && h instanceof NeoHubHandler) { - return (NeoHubHandler) h; + if ((b = getBridge()) != null && (b.getHandler() instanceof NeoHubHandler neoHubHandler)) { + return neoHubHandler; } return null; diff --git a/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoHubBindingConstants.java b/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoHubBindingConstants.java index 9e6db469f..d19693b37 100644 --- a/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoHubBindingConstants.java +++ b/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoHubBindingConstants.java @@ -110,7 +110,7 @@ public class NeoHubBindingConstants { /* * enumerator for results of method calls */ - public static enum NeoHubReturnResult { + public enum NeoHubReturnResult { SUCCEEDED, ERR_COMMUNICATION, ERR_INITIALIZATION diff --git a/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoHubDiscoveryParticipant.java b/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoHubDiscoveryParticipant.java index e983dbfc5..8f3ec0efa 100644 --- a/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoHubDiscoveryParticipant.java +++ b/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoHubDiscoveryParticipant.java @@ -13,7 +13,6 @@ package org.openhab.binding.neohub.internal; import java.net.Inet4Address; -import java.util.Collections; import java.util.Set; import javax.jmdns.ServiceInfo; @@ -47,8 +46,7 @@ public class NeoHubDiscoveryParticipant implements MDNSDiscoveryParticipant { private String getIpAddressIfValidNeoHub(ServiceInfo serviceInfo) { if (serviceInfo.getName().contains(HEATMISER_NEO_HUB)) { for (Inet4Address ipAddr : serviceInfo.getInet4Addresses()) { - String ipStr = ipAddr.getHostAddress(); - return ipStr; + return ipAddr.getHostAddress(); } } return ""; @@ -56,7 +54,7 @@ public class NeoHubDiscoveryParticipant implements MDNSDiscoveryParticipant { @Override public Set getSupportedThingTypeUIDs() { - return Collections.singleton(NeoHubBindingConstants.THING_TYPE_NEOHUB); + return Set.of(NeoHubBindingConstants.THING_TYPE_NEOHUB); } @Override @@ -69,11 +67,9 @@ public class NeoHubDiscoveryParticipant implements MDNSDiscoveryParticipant { String ipStr = getIpAddressIfValidNeoHub(serviceInfo); if (!ipStr.isEmpty()) { ThingUID thingUID = new ThingUID(NeoHubBindingConstants.THING_TYPE_NEOHUB, ipStr.replace('.', '_')); - DiscoveryResult hub = DiscoveryResultBuilder.create(thingUID) - .withProperty(NeoHubConfiguration.HOST_NAME, ipStr) + return DiscoveryResultBuilder.create(thingUID).withProperty(NeoHubConfiguration.HOST_NAME, ipStr) .withRepresentationProperty(NeoHubConfiguration.HOST_NAME).withLabel("NeoHub (" + ipStr + ")") .build(); - return hub; } return null; } diff --git a/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoHubDiscoveryService.java b/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoHubDiscoveryService.java index 282f07b86..900f7e8bf 100644 --- a/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoHubDiscoveryService.java +++ b/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoHubDiscoveryService.java @@ -111,18 +111,18 @@ public class NeoHubDiscoveryService extends AbstractDiscoveryService { for (AbstractRecord deviceRecord : deviceRecords) { // the record came from the legacy API (deviceType included) - if (deviceRecord instanceof InfoRecord) { - deviceType = ((InfoRecord) deviceRecord).getDeviceType(); + if (deviceRecord instanceof InfoRecord infoRecord) { + deviceType = infoRecord.getDeviceType(); publishDevice(deviceRecord, deviceType); continue; } // the record came from the new API (deviceType NOT included) - if (deviceRecord instanceof LiveDataRecord) { + if (deviceRecord instanceof LiveDataRecord liveDataRecord) { if (engineerData == null) { break; } - String deviceName = ((LiveDataRecord) deviceRecord).getDeviceName(); + String deviceName = liveDataRecord.getDeviceName(); // exclude repeater nodes from being discovered if (MATCHER_HEATMISER_REPEATER.matcher(deviceName).matches()) { continue; diff --git a/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoHubHandler.java b/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoHubHandler.java index 40715180f..2e9e42722 100644 --- a/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoHubHandler.java +++ b/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoHubHandler.java @@ -314,14 +314,14 @@ public class NeoHubHandler extends BaseBridgeHandler { // check if we also need to discard and update systemData NeoHubReadDcbResponse systemData = this.systemData; if (systemData != null) { - if (deviceData instanceof NeoHubLiveDeviceData) { + if (deviceData instanceof NeoHubLiveDeviceData liveDeviceData) { /* * note: time-stamps are measured in seconds from 1970-01-01T00:00:00Z * * new API: discard systemData if its time-stamp is older than the system * time-stamp on the hub */ - if (systemData.timeStamp < ((NeoHubLiveDeviceData) deviceData).getTimestampSystem()) { + if (systemData.timeStamp < liveDeviceData.getTimestampSystem()) { this.systemData = null; } } else { @@ -416,8 +416,8 @@ public class NeoHubHandler extends BaseBridgeHandler { List children = getThing().getThings(); for (Thing child : children) { ThingHandler device = child.getHandler(); - if (device instanceof NeoBaseHandler) { - ((NeoBaseHandler) device).toBaseSendPollResponse(deviceData); + if (device instanceof NeoBaseHandler neoBaseHandler) { + neoBaseHandler.toBaseSendPollResponse(deviceData); } } diff --git a/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoHubHandlerFactory.java b/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoHubHandlerFactory.java index cc90d6fc8..f543d5ebd 100644 --- a/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoHubHandlerFactory.java +++ b/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoHubHandlerFactory.java @@ -14,10 +14,7 @@ package org.openhab.binding.neohub.internal; import static org.openhab.binding.neohub.internal.NeoHubBindingConstants.*; -import java.util.Arrays; -import java.util.Collections; import java.util.HashMap; -import java.util.HashSet; import java.util.Hashtable; import java.util.Map; import java.util.Set; @@ -47,9 +44,8 @@ import org.osgi.service.component.annotations.Reference; @Component(configurationPid = "binding.neohub", service = ThingHandlerFactory.class) public class NeoHubHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections - .unmodifiableSet(new HashSet<>(Arrays.asList(THING_TYPE_NEOHUB, THING_TYPE_NEOSTAT, THING_TYPE_NEOPLUG, - THING_TYPE_NEOCONTACT, THING_TYPE_NEOTEMPERATURESENSOR))); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_NEOHUB, THING_TYPE_NEOSTAT, + THING_TYPE_NEOPLUG, THING_TYPE_NEOCONTACT, THING_TYPE_NEOTEMPERATURESENSOR); private final WebSocketFactory webSocketFactory; private final Map> discoServices = new HashMap<>(); @@ -68,8 +64,8 @@ public class NeoHubHandlerFactory extends BaseThingHandlerFactory { protected @Nullable ThingHandler createHandler(Thing thing) { ThingTypeUID thingTypeUID = thing.getThingTypeUID(); - if ((thingTypeUID.equals(THING_TYPE_NEOHUB)) && (thing instanceof Bridge)) { - NeoHubHandler handler = new NeoHubHandler((Bridge) thing, webSocketFactory); + if ((thingTypeUID.equals(THING_TYPE_NEOHUB)) && (thing instanceof Bridge bridge)) { + NeoHubHandler handler = new NeoHubHandler(bridge, webSocketFactory); createDiscoveryService(handler); return handler; } @@ -95,8 +91,8 @@ public class NeoHubHandlerFactory extends BaseThingHandlerFactory { @Override protected synchronized void removeHandler(ThingHandler handler) { - if (handler instanceof NeoHubHandler) { - destroyDiscoveryService((NeoHubHandler) handler); + if (handler instanceof NeoHubHandler neoHubHandler) { + destroyDiscoveryService(neoHubHandler); } } diff --git a/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoPlugHandler.java b/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoPlugHandler.java index e36f2fbc8..c1acd4a20 100644 --- a/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoPlugHandler.java +++ b/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoPlugHandler.java @@ -39,11 +39,11 @@ public class NeoPlugHandler extends NeoBaseHandler { protected String toNeoHubBuildCommandString(String channelId, Command command) { NeoBaseConfiguration config = this.config; if (config != null) { - if (command instanceof OnOffType && channelId.equals(CHAN_PLUG_OUTPUT_STATE)) { - return String.format(CMD_CODE_TIMER, ((OnOffType) command).toString(), config.deviceNameInHub); + if (command instanceof OnOffType onOffCommand && channelId.equals(CHAN_PLUG_OUTPUT_STATE)) { + return String.format(CMD_CODE_TIMER, onOffCommand.toString(), config.deviceNameInHub); } - if (command instanceof OnOffType && channelId.equals(CHAN_PLUG_AUTO_MODE)) { - return String.format(CMD_CODE_MANUAL, invert((OnOffType) command).toString(), config.deviceNameInHub); + if (command instanceof OnOffType onOffCommand && channelId.equals(CHAN_PLUG_AUTO_MODE)) { + return String.format(CMD_CODE_MANUAL, invert(onOffCommand).toString(), config.deviceNameInHub); } } return ""; diff --git a/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoStatHandler.java b/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoStatHandler.java index 7989ee766..38d4c0787 100644 --- a/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoStatHandler.java +++ b/bundles/org.openhab.binding.neohub/src/main/java/org/openhab/binding/neohub/internal/NeoStatHandler.java @@ -41,9 +41,9 @@ public class NeoStatHandler extends NeoBaseHandler { protected String toNeoHubBuildCommandString(String channelId, Command command) { NeoBaseConfiguration config = this.config; if (config != null) { - if (command instanceof QuantityType && channelId.equals(CHAN_TARGET_TEMP)) { + if (command instanceof QuantityType quantityCommand && channelId.equals(CHAN_TARGET_TEMP)) { Command doCommand = command; - QuantityType temp = ((QuantityType) command).toUnit(getTemperatureUnit()); + QuantityType temp = quantityCommand.toUnit(getTemperatureUnit()); if (temp != null) { doCommand = temp; } @@ -51,8 +51,8 @@ public class NeoStatHandler extends NeoBaseHandler { config.deviceNameInHub); } - if (command instanceof OnOffType && channelId.equals(CHAN_OCC_MODE_PRESENT)) { - return String.format(CMD_CODE_AWAY, invert((OnOffType) command).toString(), config.deviceNameInHub); + if (command instanceof OnOffType onOffCommand && channelId.equals(CHAN_OCC_MODE_PRESENT)) { + return String.format(CMD_CODE_AWAY, invert(onOffCommand).toString(), config.deviceNameInHub); } } return ""; diff --git a/bundles/org.openhab.binding.neohub/src/test/java/org/openhab/binding/neohub/test/NeoHubJsonTests.java b/bundles/org.openhab.binding.neohub/src/test/java/org/openhab/binding/neohub/test/NeoHubJsonTests.java index 6fb298ff7..87f670051 100644 --- a/bundles/org.openhab.binding.neohub/src/test/java/org/openhab/binding/neohub/test/NeoHubJsonTests.java +++ b/bundles/org.openhab.binding.neohub/src/test/java/org/openhab/binding/neohub/test/NeoHubJsonTests.java @@ -437,30 +437,30 @@ public class NeoHubJsonTests { jsonElement = JsonParser.parseString(load("dcb_celsius")); assertTrue(jsonElement.isJsonObject()); - assertTrue(((JsonObject) jsonElement).keySet().size() > 0); + assertTrue(!((JsonObject) jsonElement).keySet().isEmpty()); jsonElement = JsonParser.parseString(load("live_data")); assertTrue(jsonElement.isJsonObject()); - assertTrue(((JsonObject) jsonElement).keySet().size() > 0); + assertTrue(!((JsonObject) jsonElement).keySet().isEmpty()); jsonElement = JsonParser.parseString(load("engineers")); assertTrue(jsonElement.isJsonObject()); - assertTrue(((JsonObject) jsonElement).keySet().size() > 0); + assertTrue(!((JsonObject) jsonElement).keySet().isEmpty()); jsonElement = JsonParser.parseString(load("info_new")); assertTrue(jsonElement.isJsonObject()); - assertTrue(((JsonObject) jsonElement).keySet().size() > 0); + assertTrue(!((JsonObject) jsonElement).keySet().isEmpty()); jsonElement = JsonParser.parseString(load("info_old")); assertTrue(jsonElement.isJsonObject()); - assertTrue(((JsonObject) jsonElement).keySet().size() > 0); + assertTrue(!((JsonObject) jsonElement).keySet().isEmpty()); jsonElement = JsonParser.parseString(load("system")); assertTrue(jsonElement.isJsonObject()); - assertTrue(((JsonObject) jsonElement).keySet().size() > 0); + assertTrue(!((JsonObject) jsonElement).keySet().isEmpty()); jsonElement = JsonParser.parseString(load("info_sensors_closed")); assertTrue(jsonElement.isJsonObject()); - assertTrue(((JsonObject) jsonElement).keySet().size() > 0); + assertTrue(!((JsonObject) jsonElement).keySet().isEmpty()); } } diff --git a/bundles/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/sdm/api/PubSubAPI.java b/bundles/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/sdm/api/PubSubAPI.java index 8dbda72da..08e61bdfe 100644 --- a/bundles/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/sdm/api/PubSubAPI.java +++ b/bundles/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/sdm/api/PubSubAPI.java @@ -214,8 +214,8 @@ public class PubSubAPI { listeners.remove(listener); if (listeners.isEmpty()) { subscriptionListeners.remove(subscriptionId); - scheduler.getQueue().removeIf(runnable -> runnable instanceof Subscriber - && ((Subscriber) runnable).subscriptionId.equals(subscriptionId)); + scheduler.getQueue().removeIf( + runnable -> runnable instanceof Subscriber s && s.subscriptionId.equals(subscriptionId)); } } } diff --git a/bundles/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/sdm/discovery/SDMDiscoveryService.java b/bundles/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/sdm/discovery/SDMDiscoveryService.java index 0d6bfebbc..fab8d5573 100644 --- a/bundles/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/sdm/discovery/SDMDiscoveryService.java +++ b/bundles/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/sdm/discovery/SDMDiscoveryService.java @@ -73,8 +73,8 @@ public class SDMDiscoveryService extends AbstractDiscoveryService implements Thi @Override public void setThingHandler(ThingHandler handler) { - if (handler instanceof SDMAccountHandler) { - accountHandler = (SDMAccountHandler) handler; + if (handler instanceof SDMAccountHandler sdmAccountHandler) { + accountHandler = sdmAccountHandler; } } diff --git a/bundles/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/sdm/dto/SDMCommands.java b/bundles/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/sdm/dto/SDMCommands.java index 19d639a2a..48becd653 100644 --- a/bundles/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/sdm/dto/SDMCommands.java +++ b/bundles/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/sdm/dto/SDMCommands.java @@ -231,7 +231,7 @@ public class SDMCommands { */ public SDMSetFanTimerRequest(SDMFanTimerMode timerMode, Duration duration) { super("sdm.devices.commands.Fan.SetTimer", entry("timerMode", timerMode.name()), - entry("duration", String.valueOf(duration.toSeconds()) + "s")); + entry("duration", duration.toSeconds() + "s")); } } diff --git a/bundles/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/sdm/dto/SDMTraits.java b/bundles/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/sdm/dto/SDMTraits.java index dc479924d..2e9ba77ea 100644 --- a/bundles/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/sdm/dto/SDMTraits.java +++ b/bundles/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/sdm/dto/SDMTraits.java @@ -211,7 +211,7 @@ public class SDMTraits { public enum SDMTemperatureScale { CELSIUS, - FAHRENHEIT; + FAHRENHEIT } /** diff --git a/bundles/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/sdm/handler/SDMThermostatHandler.java b/bundles/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/sdm/handler/SDMThermostatHandler.java index 34b6a9150..aa3a94d45 100644 --- a/bundles/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/sdm/handler/SDMThermostatHandler.java +++ b/bundles/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/sdm/handler/SDMThermostatHandler.java @@ -98,8 +98,8 @@ public class SDMThermostatHandler extends SDMBaseHandler { delayedRefresh(); } } else if (CHANNEL_FAN_TIMER_MODE.equals(channelUID.getId())) { - if (command instanceof OnOffType) { - if ((OnOffType) command == OnOffType.ON) { + if (command instanceof OnOffType onOffCommand) { + if (onOffCommand == OnOffType.ON) { executeDeviceCommand(new SDMSetFanTimerRequest(SDMFanTimerMode.ON, getFanTimerDuration())); } else { executeDeviceCommand(new SDMSetFanTimerRequest(SDMFanTimerMode.OFF)); @@ -107,9 +107,8 @@ public class SDMThermostatHandler extends SDMBaseHandler { delayedRefresh(); } } else if (CHANNEL_FAN_TIMER_TIMEOUT.equals(channelUID.getId())) { - if (command instanceof DateTimeType) { - Duration duration = Duration.between(ZonedDateTime.now(), - ((DateTimeType) command).getZonedDateTime()); + if (command instanceof DateTimeType dateTimeCommand) { + Duration duration = Duration.between(ZonedDateTime.now(), dateTimeCommand.getZonedDateTime()); executeDeviceCommand(new SDMSetFanTimerRequest(SDMFanTimerMode.ON, duration)); delayedRefresh(); } @@ -202,8 +201,8 @@ public class SDMThermostatHandler extends SDMBaseHandler { if (channel != null) { Configuration configuration = channel.getConfiguration(); Object fanTimerDuration = configuration.get(SDMBindingConstants.CONFIG_PROPERTY_FAN_TIMER_DURATION); - if (fanTimerDuration instanceof BigDecimal) { - seconds = ((BigDecimal) fanTimerDuration).longValue(); + if (fanTimerDuration instanceof BigDecimal decimalValue) { + seconds = decimalValue.longValue(); } } diff --git a/bundles/org.openhab.binding.nest/src/test/java/org/openhab/binding/nest/internal/sdm/dto/SDMDataUtil.java b/bundles/org.openhab.binding.nest/src/test/java/org/openhab/binding/nest/internal/sdm/dto/SDMDataUtil.java index c3c0b9637..9fa00ea12 100644 --- a/bundles/org.openhab.binding.nest/src/test/java/org/openhab/binding/nest/internal/sdm/dto/SDMDataUtil.java +++ b/bundles/org.openhab.binding.nest/src/test/java/org/openhab/binding/nest/internal/sdm/dto/SDMDataUtil.java @@ -38,7 +38,7 @@ import com.google.gson.stream.JsonWriter; public class SDMDataUtil { public static Reader openDataReader(String fileName) throws FileNotFoundException { - String packagePath = (SDMDataUtil.class.getPackage().getName()).replaceAll("\\.", "/"); + String packagePath = (SDMDataUtil.class.getPackage().getName()).replace(".", "/"); String filePath = "src/test/resources/" + packagePath + "/" + fileName; InputStream inputStream = new FileInputStream(filePath); diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/action/RoomActions.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/action/RoomActions.java index ac773acd5..45cbbef30 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/action/RoomActions.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/action/RoomActions.java @@ -57,8 +57,7 @@ public class RoomActions implements ThingActions { @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof CommonInterface) { - CommonInterface commonHandler = (CommonInterface) handler; + if (handler instanceof CommonInterface commonHandler) { this.handler = commonHandler; } } diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/api/RestManager.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/api/RestManager.java index 2cd431e47..5f2b7f608 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/api/RestManager.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/api/RestManager.java @@ -64,7 +64,7 @@ public abstract class RestManager { @Nullable String payload, @Nullable String contentType) throws NetatmoException { URI uri = uriBuilder.build(); T response = apiBridge.executeUri(uri, method, clazz, payload, contentType, 3); - if (response instanceof ApiResponse.Ok && ((ApiResponse.Ok) response).failed()) { + if (response instanceof ApiResponse.Ok apiResponseOk && apiResponseOk.failed()) { throw new NetatmoException("Command failed : %s for uri : %s", response.getStatus(), uri.toString()); } return response; diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/api/WeatherApi.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/api/WeatherApi.java index ee205c88c..afb26963a 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/api/WeatherApi.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/api/WeatherApi.java @@ -58,8 +58,7 @@ public class WeatherApi extends RestManager { throws NetatmoException { UriBuilder uriBuilder = getApiUriBuilder(SUB_PATH_GET_STATION, PARAM_DEVICE_ID, deviceId, // PARAM_FAVORITES, getFavorites); - StationDataResponse response = get(uriBuilder, StationDataResponse.class); - return response; + return get(uriBuilder, StationDataResponse.class); } /** diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/api/data/NetatmoConstants.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/api/data/NetatmoConstants.java index 485af4f67..38de0898c 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/api/data/NetatmoConstants.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/api/data/NetatmoConstants.java @@ -54,7 +54,7 @@ public class NetatmoConstants { this.minValue = minValue; this.maxValue = maxValue; this.unit = unit; - String[] splitter = Double.valueOf(precision).toString().split("\\."); + String[] splitter = Double.toString(precision).split("\\."); if (splitter.length > 1) { int dec = Integer.parseInt(splitter[1]); this.scale = dec > 0 ? Integer.toString(dec).length() : 0; @@ -169,7 +169,7 @@ public class NetatmoConstants { public static final int THERM_MAX_SETPOINT = 30; // Token scopes - public static enum Scope { + public enum Scope { @SerializedName("read_station") READ_STATION, @SerializedName("read_thermostat") @@ -200,7 +200,7 @@ public class NetatmoConstants { ACCESS_DOORBELL, @SerializedName("read_carbonmonoxidedetector") READ_CARBONMONOXIDEDETECTOR, - UNKNOWN; + UNKNOWN } private static final Scope[] SMOKE_SCOPES = { Scope.READ_SMOKEDETECTOR }; @@ -212,7 +212,7 @@ public class NetatmoConstants { private static final Scope[] DOORBELL_SCOPES = { Scope.READ_DOORBELL, Scope.WRITE_DOORBELL, Scope.ACCESS_DOORBELL }; private static final Scope[] PRESENCE_SCOPES = { Scope.READ_PRESENCE, Scope.WRITE_PRESENCE, Scope.ACCESS_PRESENCE }; - public static enum FeatureArea { + public enum FeatureArea { AIR_CARE(AIR_CARE_SCOPES), WEATHER(WEATHER_SCOPES), ENERGY(THERMOSTAT_SCOPES), @@ -234,7 +234,7 @@ public class NetatmoConstants { static final int[] RADIO_SIGNAL_LEVELS = new int[] { 90, 80, 70, 60 }; // Resp : low, medium, high, full // Thermostat definitions - public static enum SetpointMode { + public enum SetpointMode { @SerializedName("program") PROGRAM("program"), @SerializedName("away") @@ -259,7 +259,7 @@ public class NetatmoConstants { } } - public static enum ThermostatZoneType { + public enum ThermostatZoneType { @SerializedName("0") DAY("0"), @SerializedName("1") @@ -290,7 +290,7 @@ public class NetatmoConstants { OFF, @SerializedName("auto") AUTO, - UNKNOWN; + UNKNOWN } public enum EventCategory { @@ -300,7 +300,7 @@ public class NetatmoConstants { ANIMAL, @SerializedName("vehicle") VEHICLE, - UNKNOWN; + UNKNOWN } public enum TrendDescription { @@ -310,7 +310,7 @@ public class NetatmoConstants { STABLE, @SerializedName("down") DOWN, - UNKNOWN; + UNKNOWN } public enum VideoStatus { @@ -320,7 +320,7 @@ public class NetatmoConstants { AVAILABLE, @SerializedName("deleted") DELETED, - UNKNOWN; + UNKNOWN } public enum SdCardStatus { @@ -338,7 +338,7 @@ public class NetatmoConstants { SD_CARD_INCOMPATIBLE_SPEED, @SerializedName("7") SD_CARD_INSUFFICIENT_SPACE, - UNKNOWN; + UNKNOWN } public enum AlimentationStatus { @@ -346,7 +346,7 @@ public class NetatmoConstants { ALIM_INCORRECT_POWER, @SerializedName("2") ALIM_CORRECT_POWER, - UNKNOWN; + UNKNOWN } public enum SirenStatus { @@ -429,6 +429,6 @@ public class NetatmoConstants { @SerializedName("40") JSON_GIVEN_HAS_AN_INVALID_ENCODING, @SerializedName("41") - DEVICE_IS_UNREACHABLE; + DEVICE_IS_UNREACHABLE } } diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/console/NetatmoCommandExtension.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/console/NetatmoCommandExtension.java index 91d7471a4..0a1ae833f 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/console/NetatmoCommandExtension.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/console/NetatmoCommandExtension.java @@ -63,9 +63,9 @@ public class NetatmoCommandExtension extends AbstractConsoleCommandExtension imp this.console = console; for (Thing thing : thingRegistry.getAll()) { ThingHandler thingHandler = thing.getHandler(); - if (thingHandler instanceof ApiBridgeHandler) { + if (thingHandler instanceof ApiBridgeHandler bridgeHandler) { console.println("Account bridge: " + thing.getLabel()); - ((ApiBridgeHandler) thingHandler).identifyAllModulesAndApplyAction(this::printThing); + bridgeHandler.identifyAllModulesAndApplyAction(this::printThing); } } } else { diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/deserialization/NAObjectMapDeserializer.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/deserialization/NAObjectMapDeserializer.java index 8ccef5f80..1700fcda7 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/deserialization/NAObjectMapDeserializer.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/deserialization/NAObjectMapDeserializer.java @@ -38,10 +38,10 @@ class NAObjectMapDeserializer implements JsonDeserializer> { throws JsonParseException { ParameterizedType parameterized = (ParameterizedType) clazz; Type[] typeArguments = parameterized.getActualTypeArguments(); - if (typeArguments.length > 0 && json instanceof JsonArray) { + if (typeArguments.length > 0 && json instanceof JsonArray jsonArray) { Type objectType = typeArguments[0]; NAObjectMap result = new NAObjectMap<>(); - ((JsonArray) json).forEach(item -> { + jsonArray.forEach(item -> { result.put(context.deserialize(item, objectType)); }); return result; diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/discovery/NetatmoDiscoveryService.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/discovery/NetatmoDiscoveryService.java index ab775ebc0..728644064 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/discovery/NetatmoDiscoveryService.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/discovery/NetatmoDiscoveryService.java @@ -79,8 +79,8 @@ public class NetatmoDiscoveryService extends AbstractDiscoveryService implements @Override public void setThingHandler(ThingHandler handler) { - if (handler instanceof ApiBridgeHandler) { - this.handler = (ApiBridgeHandler) handler; + if (handler instanceof ApiBridgeHandler bridgeHandler) { + this.handler = bridgeHandler; } } diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/CommonInterface.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/CommonInterface.java index d552d77c5..1a6c97369 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/CommonInterface.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/CommonInterface.java @@ -130,8 +130,8 @@ public interface CommonInterface { default List getActiveChildren() { Thing thing = getThing(); - if (thing instanceof Bridge) { - return ((Bridge) thing).getThings().stream().filter(Thing::isEnabled) + if (thing instanceof Bridge bridge) { + return bridge.getThings().stream().filter(Thing::isEnabled) .filter(th -> th.getStatusInfo().getStatusDetail() != ThingStatusDetail.BRIDGE_OFFLINE) .map(Thing::getHandler).filter(Objects::nonNull).map(CommonInterface.class::cast).toList(); } @@ -148,8 +148,7 @@ public interface CommonInterface { } default void setNewData(NAObject newData) { - if (newData instanceof NAThing) { - NAThing thingData = (NAThing) newData; + if (newData instanceof NAThing thingData) { if (getId().equals(thingData.getBridge())) { getActiveChildren().stream().filter(child -> child.getId().equals(thingData.getId())).findFirst() .ifPresent(child -> child.setNewData(thingData)); diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/capability/MeasureCapability.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/capability/MeasureCapability.java index c053956d9..9e1c3b2b5 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/capability/MeasureCapability.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/capability/MeasureCapability.java @@ -82,7 +82,7 @@ public class MeasureCapability extends RestCapability { MeasureClass.AS_SET.stream().filter(mc -> mc.apiDescriptor.equals(descriptor)) .reduce((first, second) -> second) .ifPresent(mc -> measures.put(channel.getUID().getIdWithoutGroup(), - result instanceof ZonedDateTime ? toDateTimeType((ZonedDateTime) result) + result instanceof ZonedDateTime zonedDateTime ? toDateTimeType(zonedDateTime) : result instanceof Double ? toQuantityType((Double) result, mc) : UnDefType.UNDEF)); } catch (NetatmoException e) { diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/BatteryChannelHelper.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/BatteryChannelHelper.java index e70194e44..1e3e4eab8 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/BatteryChannelHelper.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/BatteryChannelHelper.java @@ -45,12 +45,12 @@ public class BatteryChannelHelper extends ChannelHelper { protected @Nullable State internalGetProperty(String channelId, NAThing naThing, Configuration config) { int percent = -1; BatteryState batteryState = BatteryState.UNKNOWN; - if (naThing instanceof Module) { - percent = ((Module) naThing).getBatteryPercent(); - batteryState = ((Module) naThing).getBatteryState(); - } else if (naThing instanceof HomeStatusModule) { - percent = ((HomeStatusModule) naThing).getBatteryState().level; - batteryState = ((HomeStatusModule) naThing).getBatteryState(); + if (naThing instanceof Module module) { + percent = module.getBatteryPercent(); + batteryState = module.getBatteryState(); + } else if (naThing instanceof HomeStatusModule homeStatusModule) { + percent = homeStatusModule.getBatteryState().level; + batteryState = homeStatusModule.getBatteryState(); } else { return null; } diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/CameraChannelHelper.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/CameraChannelHelper.java index 00223eca4..66b667088 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/CameraChannelHelper.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/CameraChannelHelper.java @@ -56,8 +56,7 @@ public class CameraChannelHelper extends ChannelHelper { @Override protected @Nullable State internalGetProperty(String channelId, NAThing naThing, Configuration config) { - if (naThing instanceof HomeStatusModule) { - HomeStatusModule camera = (HomeStatusModule) naThing; + if (naThing instanceof HomeStatusModule camera) { boolean isMonitoring = OnOffType.ON.equals(camera.getMonitoring()); switch (channelId) { case CHANNEL_MONITORING: diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/ChannelHelper.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/ChannelHelper.java index b3f167ef6..93b3cd971 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/ChannelHelper.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/ChannelHelper.java @@ -48,20 +48,19 @@ public abstract class ChannelHelper { State result = null; if (channelGroups.isEmpty() || (groupId != null && channelGroups.contains(groupId))) { NAObject localData = data; - if (localData instanceof HomeEvent) { - result = internalGetHomeEvent(channelId, groupId, (HomeEvent) localData); + if (localData instanceof HomeEvent homeEvent) { + result = internalGetHomeEvent(channelId, groupId, homeEvent); if (result != null) { return result; } } - if (localData instanceof Event) { - result = internalGetEvent(channelId, (Event) localData); + if (localData instanceof Event event) { + result = internalGetEvent(channelId, event); if (result != null) { return result; } } - if (localData instanceof NAThing) { - NAThing naThing = (NAThing) localData; + if (localData instanceof NAThing naThing) { result = internalGetProperty(channelId, naThing, config); if (result != null) { return result; diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/DoorTagChannelHelper.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/DoorTagChannelHelper.java index 49f76672d..42ae704ec 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/DoorTagChannelHelper.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/DoorTagChannelHelper.java @@ -40,8 +40,7 @@ public class DoorTagChannelHelper extends ChannelHelper { @Override protected @Nullable State internalGetProperty(String channelId, NAThing naThing, Configuration config) { - if (naThing instanceof HomeStatusModule) { - HomeStatusModule doorTag = (HomeStatusModule) naThing; + if (naThing instanceof HomeStatusModule doorTag) { if (CHANNEL_STATUS.equalsIgnoreCase(channelId)) { return doorTag.getStatus().map(status -> (State) OpenClosedType.valueOf(status.toUpperCase())) .orElse(UnDefType.UNDEF); diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/EventChannelHelper.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/EventChannelHelper.java index 95066ee4b..b8afdd8a8 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/EventChannelHelper.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/EventChannelHelper.java @@ -56,8 +56,7 @@ public class EventChannelHelper extends ChannelHelper { @Override public void setNewData(@Nullable NAObject data) { - if (data instanceof Event) { - Event event = (Event) data; + if (data instanceof Event event) { if (!event.getEventType().validFor(moduleType)) { return; } diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/LocationChannelHelper.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/LocationChannelHelper.java index 9545ee08e..10538b5c4 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/LocationChannelHelper.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/LocationChannelHelper.java @@ -42,10 +42,10 @@ public class LocationChannelHelper extends ChannelHelper { protected @Nullable State internalGetProperty(String channelId, NAThing naThing, Configuration config) { if (CHANNEL_VALUE.equals(channelId)) { State point = UnDefType.UNDEF; - if (naThing instanceof Home) { - point = ((Home) naThing).getLocation(); - } else if (naThing instanceof Device) { - point = ((Device) naThing).getPlace().map(place -> place.getLocation()).orElse(point); + if (naThing instanceof Home home) { + point = home.getLocation(); + } else if (naThing instanceof Device device) { + point = device.getPlace().map(place -> place.getLocation()).orElse(point); } return point; } diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/PersonChannelHelper.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/PersonChannelHelper.java index 6ad930277..f94fb0c28 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/PersonChannelHelper.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/PersonChannelHelper.java @@ -41,8 +41,7 @@ public class PersonChannelHelper extends ChannelHelper { @Override protected @Nullable State internalGetProperty(String channelId, NAThing naThing, Configuration config) { - if (naThing instanceof HomeDataPerson) { - HomeDataPerson person = (HomeDataPerson) naThing; + if (naThing instanceof HomeDataPerson person) { switch (channelId) { case CHANNEL_PERSON_AVATAR_URL: return toStringType(person.getUrl().orElse(null)); @@ -50,8 +49,7 @@ public class PersonChannelHelper extends ChannelHelper { return toRawType(person.getUrl().orElse(null)); } } - if (naThing instanceof HomeStatusPerson) { - HomeStatusPerson person = (HomeStatusPerson) naThing; + if (naThing instanceof HomeStatusPerson person) { switch (channelId) { case CHANNEL_PERSON_AT_HOME: return OnOffType.from(person.atHome()); diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/RoomChannelHelper.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/RoomChannelHelper.java index 38e36b142..be01a675f 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/RoomChannelHelper.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/RoomChannelHelper.java @@ -40,8 +40,7 @@ public class RoomChannelHelper extends ChannelHelper { @Override protected @Nullable State internalGetObject(String channelId, NAObject naObject) { - if (naObject instanceof Room) { - Room room = (Room) naObject; + if (naObject instanceof Room room) { switch (channelId) { case CHANNEL_ROOM_WINDOW_OPEN: return room.hasOpenedWindows(); diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/SetpointChannelHelper.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/SetpointChannelHelper.java index 37b05ace3..7d180146e 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/SetpointChannelHelper.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/SetpointChannelHelper.java @@ -40,8 +40,7 @@ public class SetpointChannelHelper extends ChannelHelper { @Override protected @Nullable State internalGetObject(String channelId, NAObject naObject) { - if (naObject instanceof Room) { - Room room = (Room) naObject; + if (naObject instanceof Room room) { switch (channelId) { case CHANNEL_SETPOINT_MODE: return toStringType(room.getSetpointMode().name()); diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/Therm1ChannelHelper.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/Therm1ChannelHelper.java index 6333e4e4e..17b65a8dd 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/Therm1ChannelHelper.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/Therm1ChannelHelper.java @@ -38,8 +38,8 @@ public class Therm1ChannelHelper extends ChannelHelper { @Override protected @Nullable State internalGetProperty(String channelId, NAThing naThing, Configuration config) { - return (naThing instanceof HomeStatusModule && CHANNEL_THERM_RELAY.equals(channelId)) - ? ((HomeStatusModule) naThing).getBoilerStatus() + return (naThing instanceof HomeStatusModule homeStatusModule && CHANNEL_THERM_RELAY.equals(channelId)) + ? homeStatusModule.getBoilerStatus() : null; } } diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/utils/ChannelTypeUtils.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/utils/ChannelTypeUtils.java index 8869b3e79..40b56700b 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/utils/ChannelTypeUtils.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/utils/ChannelTypeUtils.java @@ -44,8 +44,8 @@ public class ChannelTypeUtils { public static @Nullable QuantityType commandToQuantity(Command command, MeasureClass measureClass) { Measure measureDef = measureClass.measureDefinition; - if (command instanceof QuantityType) { - return ((QuantityType) command).toUnit(measureDef.unit); + if (command instanceof QuantityType quantityCommand) { + return quantityCommand.toUnit(measureDef.unit); } try { double value = Double.parseDouble(command.toString()); diff --git a/bundles/org.openhab.binding.netatmo/src/test/java/org/openhab/binding/netatmo/internal/api/dto/NAObjectTest.java b/bundles/org.openhab.binding.netatmo/src/test/java/org/openhab/binding/netatmo/internal/api/dto/NAObjectTest.java index 233214303..d654d74bd 100644 --- a/bundles/org.openhab.binding.netatmo/src/test/java/org/openhab/binding/netatmo/internal/api/dto/NAObjectTest.java +++ b/bundles/org.openhab.binding.netatmo/src/test/java/org/openhab/binding/netatmo/internal/api/dto/NAObjectTest.java @@ -48,24 +48,34 @@ public class NAObjectTest { @Test public void testWebHookEvent() throws NetatmoException { - String event = "{" + " \"user_id\": \"5c810xxxxxxx45f4\"," + " \"snapshot_id\": \"5d19bxxxxxx6380342\"," - + " \"snapshot_key\": \"f0134210ff83fxxxxxxxf770090a423d9a5\"," - + " \"snapshot_url\": \"https://netatmocameraimage.blob.core.windows.net/production/5d1xxxa5\"," - + " \"event_type\": \"movement\"," + " \"camera_id\": \"70:exxxxxdd:a7\"," - + " \"device_id\": \"70:exxxxdd:a7\"," + " \"home_id\": \"5c5d79xxxx08cd594\"," - + " \"home_name\": \"Boulogne Billan.\"," + " \"event_id\": \"5d19baae369359e896380341\"," - + " \"message\": \"Boulogne Billan: Movement detected by Indoor Camera\"," - + " \"push_type\": \"NACamera-movement\"" + "}"; + String event = """ + {\ + "user_id": "5c810xxxxxxx45f4",\ + "snapshot_id": "5d19bxxxxxx6380342",\ + "snapshot_key": "f0134210ff83fxxxxxxxf770090a423d9a5",\ + "snapshot_url": "https://netatmocameraimage.blob.core.windows.net/production/5d1xxxa5",\ + "event_type": "movement",\ + "camera_id": "70:exxxxxdd:a7",\ + "device_id": "70:exxxxdd:a7",\ + "home_id": "5c5d79xxxx08cd594",\ + "home_name": "Boulogne Billan.",\ + "event_id": "5d19baae369359e896380341",\ + "message": "Boulogne Billan: Movement detected by Indoor Camera",\ + "push_type": "NACamera-movement"\ + }\ + """; WebhookEvent object = gson.deserialize(WebhookEvent.class, event); assertEquals(object.getEventType(), EventType.MOVEMENT); } @Test public void testDashboardData() throws NetatmoException { - String dashboard = "{time_utc:1623160336,Temperature:22.1,CO2:511," - + "Humidity:66,Noise:36,Pressure:1026.1,AbsolutePressure:1009.3," - + "min_temp:20,max_temp:22.4,date_max_temp:1623147932," - + "Sdate_min_temp:1623125249,pressure_trend:\"nonexistent\",temp_trend:\"stable\"}"; + String dashboard = """ + {time_utc:1623160336,Temperature:22.1,CO2:511,\ + Humidity:66,Noise:36,Pressure:1026.1,AbsolutePressure:1009.3,\ + min_temp:20,max_temp:22.4,date_max_temp:1623147932,\ + Sdate_min_temp:1623125249,pressure_trend:"nonexistent",temp_trend:"stable"}\ + """; Dashboard object = gson.deserialize(Dashboard.class, dashboard); assertEquals(511, object.getCo2(), 0); assertEquals(TrendDescription.UNKNOWN, object.getPressureTrend()); diff --git a/bundles/org.openhab.binding.network/src/main/java/org/openhab/binding/network/internal/action/NetworkActions.java b/bundles/org.openhab.binding.network/src/main/java/org/openhab/binding/network/internal/action/NetworkActions.java index d31d7ec33..56a635de6 100644 --- a/bundles/org.openhab.binding.network/src/main/java/org/openhab/binding/network/internal/action/NetworkActions.java +++ b/bundles/org.openhab.binding.network/src/main/java/org/openhab/binding/network/internal/action/NetworkActions.java @@ -37,8 +37,8 @@ public class NetworkActions implements ThingActions { @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof NetworkHandler) { - this.handler = (NetworkHandler) handler; + if (handler instanceof NetworkHandler networkHandler) { + this.handler = networkHandler; } } diff --git a/bundles/org.openhab.binding.network/src/main/java/org/openhab/binding/network/internal/discovery/NetworkDiscoveryService.java b/bundles/org.openhab.binding.network/src/main/java/org/openhab/binding/network/internal/discovery/NetworkDiscoveryService.java index 28b7e24df..08ab9c3a9 100644 --- a/bundles/org.openhab.binding.network/src/main/java/org/openhab/binding/network/internal/discovery/NetworkDiscoveryService.java +++ b/bundles/org.openhab.binding.network/src/main/java/org/openhab/binding/network/internal/discovery/NetworkDiscoveryService.java @@ -181,7 +181,7 @@ public class NetworkDiscoveryService extends AbstractDiscoveryService implements public static ThingUID createServiceUID(String ip, int tcpPort) { // uid must not contains dots - return new ThingUID(SERVICE_DEVICE, ip.replace('.', '_') + "_" + String.valueOf(tcpPort)); + return new ThingUID(SERVICE_DEVICE, ip.replace('.', '_') + "_" + tcpPort); } /** diff --git a/bundles/org.openhab.binding.network/src/main/java/org/openhab/binding/network/internal/handler/NetworkHandler.java b/bundles/org.openhab.binding.network/src/main/java/org/openhab/binding/network/internal/handler/NetworkHandler.java index c6b004164..4151ec3a6 100644 --- a/bundles/org.openhab.binding.network/src/main/java/org/openhab/binding/network/internal/handler/NetworkHandler.java +++ b/bundles/org.openhab.binding.network/src/main/java/org/openhab/binding/network/internal/handler/NetworkHandler.java @@ -17,8 +17,9 @@ import static org.openhab.binding.network.internal.NetworkBindingConstants.*; import java.time.Instant; import java.time.ZonedDateTime; import java.util.Collection; -import java.util.Collections; +import java.util.List; import java.util.Map; +import java.util.Set; import java.util.TimeZone; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -181,7 +182,7 @@ public class NetworkHandler extends BaseThingHandler updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "No port configured!"); return; } - presenceDetection.setServicePorts(Collections.singleton(port)); + presenceDetection.setServicePorts(Set.of(port)); } else { // It does not harm to send an additional UDP packet to a device, // therefore we assume all ping devices are iOS devices. If this @@ -239,7 +240,7 @@ public class NetworkHandler extends BaseThingHandler @Override public Collection> getServices() { - return Collections.singletonList(NetworkActions.class); + return List.of(NetworkActions.class); } public void sendWakeOnLanPacketViaIp() { diff --git a/bundles/org.openhab.binding.network/src/main/java/org/openhab/binding/network/internal/utils/NetworkUtils.java b/bundles/org.openhab.binding.network/src/main/java/org/openhab/binding/network/internal/utils/NetworkUtils.java index cf23c1e57..fe696b759 100644 --- a/bundles/org.openhab.binding.network/src/main/java/org/openhab/binding/network/internal/utils/NetworkUtils.java +++ b/bundles/org.openhab.binding.network/src/main/java/org/openhab/binding/network/internal/utils/NetworkUtils.java @@ -208,11 +208,11 @@ public class NetworkUtils { return IpPingMethodEnum.JAVA_PING; } else { os = os.toLowerCase(); - if (os.indexOf("win") >= 0) { + if (os.contains("win")) { method = IpPingMethodEnum.WINDOWS_PING; - } else if (os.indexOf("mac") >= 0) { + } else if (os.contains("mac")) { method = IpPingMethodEnum.MAC_OS_PING; - } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") >= 0) { + } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) { method = IpPingMethodEnum.IPUTILS_LINUX_PING; } else { // We cannot estimate the command line for any other operating system and just return false diff --git a/bundles/org.openhab.binding.network/src/test/java/org/openhab/binding/network/internal/PresenceDetectionTest.java b/bundles/org.openhab.binding.network/src/test/java/org/openhab/binding/network/internal/PresenceDetectionTest.java index 5bada538f..afae3f261 100644 --- a/bundles/org.openhab.binding.network/src/test/java/org/openhab/binding/network/internal/PresenceDetectionTest.java +++ b/bundles/org.openhab.binding.network/src/test/java/org/openhab/binding/network/internal/PresenceDetectionTest.java @@ -20,8 +20,8 @@ import static org.mockito.Mockito.*; import java.io.IOException; import java.net.UnknownHostException; -import java.util.Collections; import java.util.Optional; +import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; @@ -62,7 +62,7 @@ public class PresenceDetectionTest { @BeforeEach public void setUp() throws UnknownHostException { // Mock an interface - when(networkUtils.getInterfaceNames()).thenReturn(Collections.singleton("TESTinterface")); + when(networkUtils.getInterfaceNames()).thenReturn(Set.of("TESTinterface")); doReturn(ArpPingUtilEnum.IPUTILS_ARPING).when(networkUtils).determineNativeARPpingMethod(anyString()); doReturn(IpPingMethodEnum.WINDOWS_PING).when(networkUtils).determinePingMethod(); @@ -77,7 +77,7 @@ public class PresenceDetectionTest { subject.setTimeout(300); subject.setUseDhcpSniffing(false); subject.setIOSDevice(true); - subject.setServicePorts(Collections.singleton(1010)); + subject.setServicePorts(Set.of(1010)); subject.setUseArpPing(true, "arping", ArpPingUtilEnum.IPUTILS_ARPING); subject.setUseIcmpPing(true); diff --git a/bundles/org.openhab.binding.network/src/test/java/org/openhab/binding/network/internal/discovery/DiscoveryTest.java b/bundles/org.openhab.binding.network/src/test/java/org/openhab/binding/network/internal/discovery/DiscoveryTest.java index 7e90cd17a..a50e270fc 100644 --- a/bundles/org.openhab.binding.network/src/test/java/org/openhab/binding/network/internal/discovery/DiscoveryTest.java +++ b/bundles/org.openhab.binding.network/src/test/java/org/openhab/binding/network/internal/discovery/DiscoveryTest.java @@ -17,7 +17,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; -import java.util.Collections; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -80,7 +80,7 @@ public class DiscoveryTest { // TCP device when(value.isPingReachable()).thenReturn(false); when(value.isTCPServiceReachable()).thenReturn(true); - when(value.getReachableTCPports()).thenReturn(Collections.singletonList(1010)); + when(value.getReachableTCPports()).thenReturn(List.of(1010)); d.partialDetectionResult(value); verify(listener).thingDiscovered(any(), result.capture()); DiscoveryResult dresult = result.getValue(); diff --git a/bundles/org.openhab.binding.networkupstools/src/main/java/org/openhab/binding/networkupstools/internal/NUTChannelTypeProvider.java b/bundles/org.openhab.binding.networkupstools/src/main/java/org/openhab/binding/networkupstools/internal/NUTChannelTypeProvider.java index 59df392a2..10c77b571 100644 --- a/bundles/org.openhab.binding.networkupstools/src/main/java/org/openhab/binding/networkupstools/internal/NUTChannelTypeProvider.java +++ b/bundles/org.openhab.binding.networkupstools/src/main/java/org/openhab/binding/networkupstools/internal/NUTChannelTypeProvider.java @@ -58,9 +58,9 @@ public class NUTChannelTypeProvider implements ChannelTypeProvider, ThingHandler @Override public void setThingHandler(@Nullable final ThingHandler handler) { - if (handler instanceof NUTHandler) { + if (handler instanceof NUTHandler nutHandler) { this.handler = handler; - ((NUTHandler) handler).setChannelTypeProvider(this); + nutHandler.setChannelTypeProvider(this); } } diff --git a/bundles/org.openhab.binding.networkupstools/src/main/java/org/openhab/binding/networkupstools/internal/NUTHandler.java b/bundles/org.openhab.binding.networkupstools/src/main/java/org/openhab/binding/networkupstools/internal/NUTHandler.java index 221d11102..f06f628e5 100644 --- a/bundles/org.openhab.binding.networkupstools/src/main/java/org/openhab/binding/networkupstools/internal/NUTHandler.java +++ b/bundles/org.openhab.binding.networkupstools/src/main/java/org/openhab/binding/networkupstools/internal/NUTHandler.java @@ -15,10 +15,10 @@ package org.openhab.binding.networkupstools.internal; import java.time.Duration; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -112,7 +112,7 @@ public class NUTHandler extends BaseThingHandler { @Override public Collection> getServices() { - return Collections.singleton(NUTChannelTypeProvider.class); + return Set.of(NUTChannelTypeProvider.class); } public void setChannelTypeProvider(final NUTChannelTypeProvider channelTypeProvider) { diff --git a/bundles/org.openhab.binding.networkupstools/src/main/java/org/openhab/binding/networkupstools/internal/NUTHandlerFactory.java b/bundles/org.openhab.binding.networkupstools/src/main/java/org/openhab/binding/networkupstools/internal/NUTHandlerFactory.java index a3dccbbdf..bbcb5333e 100644 --- a/bundles/org.openhab.binding.networkupstools/src/main/java/org/openhab/binding/networkupstools/internal/NUTHandlerFactory.java +++ b/bundles/org.openhab.binding.networkupstools/src/main/java/org/openhab/binding/networkupstools/internal/NUTHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.networkupstools.internal; import static org.openhab.binding.networkupstools.internal.NUTBindingConstants.THING_TYPE_UPS; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -35,7 +34,7 @@ import org.osgi.service.component.annotations.Component; @Component(configurationPid = "binding.networkupstools", service = ThingHandlerFactory.class) public class NUTHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_UPS); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_UPS); @Override public boolean supportsThingType(final ThingTypeUID thingTypeUID) { diff --git a/bundles/org.openhab.binding.nibeheatpump/src/main/java/org/openhab/binding/nibeheatpump/internal/connection/SerialConnector.java b/bundles/org.openhab.binding.nibeheatpump/src/main/java/org/openhab/binding/nibeheatpump/internal/connection/SerialConnector.java index 4d12dc7fb..614d2a27c 100644 --- a/bundles/org.openhab.binding.nibeheatpump/src/main/java/org/openhab/binding/nibeheatpump/internal/connection/SerialConnector.java +++ b/bundles/org.openhab.binding.nibeheatpump/src/main/java/org/openhab/binding/nibeheatpump/internal/connection/SerialConnector.java @@ -278,7 +278,7 @@ public class SerialConnector extends NibeHeatPumpBaseConnector { int b; // wait first byte (blocking) if ((b = in.read()) > -1) { - byte d[] = new byte[] { (byte) b }; + byte[] d = new byte[] { (byte) b }; os.write(d); // read rest of the available bytes diff --git a/bundles/org.openhab.binding.nibeheatpump/src/main/java/org/openhab/binding/nibeheatpump/internal/connection/SimulatorConnector.java b/bundles/org.openhab.binding.nibeheatpump/src/main/java/org/openhab/binding/nibeheatpump/internal/connection/SimulatorConnector.java index b3dc935ab..40dcbd5c2 100644 --- a/bundles/org.openhab.binding.nibeheatpump/src/main/java/org/openhab/binding/nibeheatpump/internal/connection/SimulatorConnector.java +++ b/bundles/org.openhab.binding.nibeheatpump/src/main/java/org/openhab/binding/nibeheatpump/internal/connection/SimulatorConnector.java @@ -195,7 +195,6 @@ public class SimulatorConnector extends NibeHeatPumpBaseConnector { logger.debug("Read queue: {}, Write queue: {}", readQueue.size(), writeQueue.size()); } Thread.sleep(800); - } catch (InterruptedException e) { } } diff --git a/bundles/org.openhab.binding.nibeheatpump/src/main/java/org/openhab/binding/nibeheatpump/internal/connection/UDPConnector.java b/bundles/org.openhab.binding.nibeheatpump/src/main/java/org/openhab/binding/nibeheatpump/internal/connection/UDPConnector.java index 66cdb7d1e..b3b8c6506 100644 --- a/bundles/org.openhab.binding.nibeheatpump/src/main/java/org/openhab/binding/nibeheatpump/internal/connection/UDPConnector.java +++ b/bundles/org.openhab.binding.nibeheatpump/src/main/java/org/openhab/binding/nibeheatpump/internal/connection/UDPConnector.java @@ -98,7 +98,7 @@ public class UDPConnector extends NibeHeatPumpBaseConnector { public void sendDatagram(NibeHeatPumpMessage msg) throws NibeHeatPumpException { logger.debug("Sending request: {}", msg.toHexString()); - byte data[] = msg.decodeMessage(); + byte[] data = msg.decodeMessage(); int port = -1; if (msg instanceof ModbusWriteRequestMessage) { diff --git a/bundles/org.openhab.binding.nibeheatpump/src/main/java/org/openhab/binding/nibeheatpump/internal/handler/NibeHeatPumpHandler.java b/bundles/org.openhab.binding.nibeheatpump/src/main/java/org/openhab/binding/nibeheatpump/internal/handler/NibeHeatPumpHandler.java index ec112a0df..a2b5b94af 100644 --- a/bundles/org.openhab.binding.nibeheatpump/src/main/java/org/openhab/binding/nibeheatpump/internal/handler/NibeHeatPumpHandler.java +++ b/bundles/org.openhab.binding.nibeheatpump/src/main/java/org/openhab/binding/nibeheatpump/internal/handler/NibeHeatPumpHandler.java @@ -377,10 +377,10 @@ public class NibeHeatPumpHandler extends BaseThingHandler implements NibeHeatPum if (command instanceof DecimalType || command instanceof QuantityType || command instanceof StringType) { BigDecimal v; - if (command instanceof DecimalType) { - v = ((DecimalType) command).toBigDecimal(); - } else if (command instanceof QuantityType) { - v = ((QuantityType) command).toBigDecimal(); + if (command instanceof DecimalType decimalCommand) { + v = decimalCommand.toBigDecimal(); + } else if (command instanceof QuantityType quantityCommand) { + v = quantityCommand.toBigDecimal(); } else { v = new BigDecimal(command.toString()); } @@ -491,12 +491,12 @@ public class NibeHeatPumpHandler extends BaseThingHandler implements NibeHeatPum updateStatus(ThingStatus.ONLINE); - if (msg instanceof ModbusReadResponseMessage) { - handleReadResponseMessage((ModbusReadResponseMessage) msg); - } else if (msg instanceof ModbusWriteResponseMessage) { - handleWriteResponseMessage((ModbusWriteResponseMessage) msg); - } else if (msg instanceof ModbusDataReadOutMessage) { - handleDataReadOutMessage((ModbusDataReadOutMessage) msg); + if (msg instanceof ModbusReadResponseMessage readResponseMessage) { + handleReadResponseMessage(readResponseMessage); + } else if (msg instanceof ModbusWriteResponseMessage writeResponseMessage) { + handleWriteResponseMessage(writeResponseMessage); + } else if (msg instanceof ModbusDataReadOutMessage dataReadOutMessage) { + handleDataReadOutMessage(dataReadOutMessage); } else { logger.debug("Received unknown message: {}", msg.toString()); } @@ -567,7 +567,7 @@ public class NibeHeatPumpHandler extends BaseThingHandler implements NibeHeatPum logger.trace("Value did not change, ignoring update"); } else { final String channelPrefix = (variableInfo.type == Type.SETTING ? "setting#" : "sensor#"); - final String channelId = channelPrefix + String.valueOf(coilAddress); + final String channelId = channelPrefix + coilAddress; final String acceptedItemType = thing.getChannel(channelId).getAcceptedItemType(); logger.trace("AcceptedItemType for channel {} = {}", channelId, acceptedItemType); diff --git a/bundles/org.openhab.binding.nibeheatpump/src/test/java/org/openhab/binding/nibeheatpump/internal/message/NibeHeatPumpProtocolTest.java b/bundles/org.openhab.binding.nibeheatpump/src/test/java/org/openhab/binding/nibeheatpump/internal/message/NibeHeatPumpProtocolTest.java index 7d516e87b..c6f726e32 100644 --- a/bundles/org.openhab.binding.nibeheatpump/src/test/java/org/openhab/binding/nibeheatpump/internal/message/NibeHeatPumpProtocolTest.java +++ b/bundles/org.openhab.binding.nibeheatpump/src/test/java/org/openhab/binding/nibeheatpump/internal/message/NibeHeatPumpProtocolTest.java @@ -81,37 +81,24 @@ public class NibeHeatPumpProtocolTest { //@formatter:off final String strTestData = // RMU40 message, acknowledge should be send - "5C001962189600E1010200000000800000000000020914340001000005B8" - // RMU40 message, CRC failure, negative acknowledge should be send - + "5C001962189600E1010200000000800000000000020914340001000005B9" - // MODBUS40 write request - + "5C00206B004B" - // nonsense - + "3EAABB" - // MODBUS40 read request - + "5C0020690049" - // nonsense - + "F0561939F6" - // MODBUS40 data read out, acknowledge should be send - + "5C00206850449C9600489C88014C9C2D014E9CCF004D9CE0014F9C3200509C0400519C8201529C6B02569C3E00C9AF000001A8F600FDA77E02FAA90F0098A9DC27FFFF0000A0A93A04FFFF00009CA9FD19FFFF000081" - // nonsense - + "F0349823" - // MODBUS40 data read out, CRC failure, negative acknowledge should be send - + "5C00206850449C9600489C88014C9C2D014E9CCF004D9CE0014F9C3200509C0400519C8201529C6B02569C3E00C9AF000001A8F600FDA77E02FAA90F0098A9DC27FFFF0000A0A93A04FFFF00009CA9FD19FFFF000080" - // RMU40 message, acknowledge should be send - + "5C001962189600DF01020000000080000000000002091434000100000586" - // nonsense - + "123490" - // unknown RMU40 message, acknowledge should be send - + "5C0019600079" - // MODBUS40 data read out, special len, acknowledge should be send - + "5C00206851449C2500489CFC004C9CF1004E9CC7014D9C0B024F9C2500509C3300519C0B01529C5C5C01569C3100C9AF000001A80C01FDA716FAFAA9070098A91B1BFFFF0000A0A9CA02FFFF00009CA99212FFFF0000BE" - // MODBUS40 data read out, special len, acknowledge should be send - + "5C00206852449C2500489CFE004C9CF2004E9CD4014D9CFB014F9C2500509C3700519C0D01529C5C5C01569C3200C9AF000001A80C01FDA712FAFAA9070098A95C5C1BFFFF0000A0A9D102FFFF00009CA9B412FFFF00007F" - // MODBUS40 data read out, special checksum, acknowledge should be send - + "5C00206850449C2600489CF6004C9CF1004E9CD6014D9C0C024F9C4500509C3F00519CF100529C0401569CD500C9AF000001A80C01FDA799FAFAA9020098A91A1BFFFF0000A0A9CA02FFFF00009CA99212FFFF0000C5" - // 16-bit address (e.g. model F2120 heatpumps), acknowledge should be send - + "5C41C9F7007F"; + """ + 5C001962189600E1010200000000800000000000020914340001000005B8\ + 5C001962189600E1010200000000800000000000020914340001000005B9\ + 5C00206B004B\ + 3EAABB\ + 5C0020690049\ + F0561939F6\ + 5C00206850449C9600489C88014C9C2D014E9CCF004D9CE0014F9C3200509C0400519C8201529C6B02569C3E00C9AF000001A8F600FDA77E02FAA90F0098A9DC27FFFF0000A0A93A04FFFF00009CA9FD19FFFF000081\ + F0349823\ + 5C00206850449C9600489C88014C9C2D014E9CCF004D9CE0014F9C3200509C0400519C8201529C6B02569C3E00C9AF000001A8F600FDA77E02FAA90F0098A9DC27FFFF0000A0A93A04FFFF00009CA9FD19FFFF000080\ + 5C001962189600DF01020000000080000000000002091434000100000586\ + 123490\ + 5C0019600079\ + 5C00206851449C2500489CFC004C9CF1004E9CC7014D9C0B024F9C2500509C3300519C0B01529C5C5C01569C3100C9AF000001A80C01FDA716FAFAA9070098A91B1BFFFF0000A0A9CA02FFFF00009CA99212FFFF0000BE\ + 5C00206852449C2500489CFE004C9CF2004E9CD4014D9CFB014F9C2500509C3700519C0D01529C5C5C01569C3200C9AF000001A80C01FDA712FAFAA9070098A95C5C1BFFFF0000A0A9D102FFFF00009CA9B412FFFF00007F\ + 5C00206850449C2600489CF6004C9CF1004E9CD6014D9C0C024F9C4500509C3F00519CF100529C0401569CD500C9AF000001A80C01FDA799FAFAA9020098A91A1BFFFF0000A0A9CA02FFFF00009CA99212FFFF0000C5\ + 5C41C9F7007F\ + """; //@formatter:on // create byte data from hex string diff --git a/bundles/org.openhab.binding.nibeuplink/src/main/java/org/openhab/binding/nibeuplink/internal/command/UpdateSetting.java b/bundles/org.openhab.binding.nibeuplink/src/main/java/org/openhab/binding/nibeuplink/internal/command/UpdateSetting.java index dfed831ef..71a50b82e 100644 --- a/bundles/org.openhab.binding.nibeuplink/src/main/java/org/openhab/binding/nibeuplink/internal/command/UpdateSetting.java +++ b/bundles/org.openhab.binding.nibeuplink/src/main/java/org/openhab/binding/nibeuplink/internal/command/UpdateSetting.java @@ -56,10 +56,10 @@ public class UpdateSetting extends AbstractUplinkCommandCallback implements Nibe private String extractValue(Command command) { // this is necessary because we must not send the unit to the nibe backend - if (command instanceof QuantityType) { - return String.valueOf(((QuantityType) command).doubleValue()); - } else if (command instanceof OnOffType) { - return ChannelUtil.mapValue(channel, (OnOffType) command); + if (command instanceof QuantityType quantityCommand) { + return String.valueOf(quantityCommand.doubleValue()); + } else if (command instanceof OnOffType onOffCommand) { + return ChannelUtil.mapValue(channel, onOffCommand); } else { return command.toString(); } diff --git a/bundles/org.openhab.binding.nikobus/src/main/java/org/openhab/binding/nikobus/internal/discovery/NikobusDiscoveryService.java b/bundles/org.openhab.binding.nikobus/src/main/java/org/openhab/binding/nikobus/internal/discovery/NikobusDiscoveryService.java index b8e8047e3..9fe78ef92 100644 --- a/bundles/org.openhab.binding.nikobus/src/main/java/org/openhab/binding/nikobus/internal/discovery/NikobusDiscoveryService.java +++ b/bundles/org.openhab.binding.nikobus/src/main/java/org/openhab/binding/nikobus/internal/discovery/NikobusDiscoveryService.java @@ -14,9 +14,9 @@ package org.openhab.binding.nikobus.internal.discovery; import static org.openhab.binding.nikobus.internal.NikobusBindingConstants.*; -import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; @@ -44,7 +44,7 @@ public class NikobusDiscoveryService extends AbstractDiscoveryService implements private @Nullable NikobusPcLinkHandler bridgeHandler; public NikobusDiscoveryService() throws IllegalArgumentException { - super(Collections.singleton(THING_TYPE_PUSH_BUTTON), 0); + super(Set.of(THING_TYPE_PUSH_BUTTON), 0); } @Override @@ -92,8 +92,8 @@ public class NikobusDiscoveryService extends AbstractDiscoveryService implements @Override public void setThingHandler(ThingHandler handler) { - if (handler instanceof NikobusPcLinkHandler) { - bridgeHandler = (NikobusPcLinkHandler) handler; + if (handler instanceof NikobusPcLinkHandler pcLinkHandler) { + bridgeHandler = pcLinkHandler; } } diff --git a/bundles/org.openhab.binding.nikobus/src/main/java/org/openhab/binding/nikobus/internal/handler/NikobusDimmerModuleHandler.java b/bundles/org.openhab.binding.nikobus/src/main/java/org/openhab/binding/nikobus/internal/handler/NikobusDimmerModuleHandler.java index f143ef16a..967b34a84 100644 --- a/bundles/org.openhab.binding.nikobus/src/main/java/org/openhab/binding/nikobus/internal/handler/NikobusDimmerModuleHandler.java +++ b/bundles/org.openhab.binding.nikobus/src/main/java/org/openhab/binding/nikobus/internal/handler/NikobusDimmerModuleHandler.java @@ -54,8 +54,8 @@ public class NikobusDimmerModuleHandler extends NikobusSwitchModuleHandler { @Override protected int valueFromCommand(String channelId, Command command) { - if (command instanceof PercentType) { - return Math.round(((PercentType) command).floatValue() / 100f * 255f); + if (command instanceof PercentType percentCommand) { + return Math.round(percentCommand.floatValue() / 100f * 255f); } return super.valueFromCommand(channelId, command); diff --git a/bundles/org.openhab.binding.nikobus/src/main/java/org/openhab/binding/nikobus/internal/handler/NikobusPcLinkHandler.java b/bundles/org.openhab.binding.nikobus/src/main/java/org/openhab/binding/nikobus/internal/handler/NikobusPcLinkHandler.java index 3a021c386..af25d49d3 100644 --- a/bundles/org.openhab.binding.nikobus/src/main/java/org/openhab/binding/nikobus/internal/handler/NikobusPcLinkHandler.java +++ b/bundles/org.openhab.binding.nikobus/src/main/java/org/openhab/binding/nikobus/internal/handler/NikobusPcLinkHandler.java @@ -22,6 +22,7 @@ import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; @@ -120,7 +121,7 @@ public class NikobusPcLinkHandler extends BaseBridgeHandler { @Override public Collection> getServices() { - return Collections.singleton(NikobusDiscoveryService.class); + return Set.of(NikobusDiscoveryService.class); } private void processReceivedValue(byte value) { diff --git a/bundles/org.openhab.binding.nikobus/src/main/java/org/openhab/binding/nikobus/internal/handler/NikobusPushButtonHandler.java b/bundles/org.openhab.binding.nikobus/src/main/java/org/openhab/binding/nikobus/internal/handler/NikobusPushButtonHandler.java index 1b5895143..d03283ebe 100644 --- a/bundles/org.openhab.binding.nikobus/src/main/java/org/openhab/binding/nikobus/internal/handler/NikobusPushButtonHandler.java +++ b/bundles/org.openhab.binding.nikobus/src/main/java/org/openhab/binding/nikobus/internal/handler/NikobusPushButtonHandler.java @@ -195,8 +195,8 @@ public class NikobusPushButtonHandler extends NikobusBaseThingHandler { } ThingHandler thingHandler = thing.getHandler(); - if (thingHandler instanceof NikobusModuleHandler) { - return (NikobusModuleHandler) thingHandler; + if (thingHandler instanceof NikobusModuleHandler nikobusModuleHandler) { + return nikobusModuleHandler; } return null; } @@ -256,10 +256,10 @@ public class NikobusPushButtonHandler extends NikobusBaseThingHandler { } SwitchModuleGroup getGroup() { - if (getSegment(2).equals("1")) { + if ("1".equals(getSegment(2))) { return FIRST; } - if (getSegment(2).equals("2")) { + if ("2".equals(getSegment(2))) { return SECOND; } throw new IllegalArgumentException("Unexpected group found " + getSegment(2)); diff --git a/bundles/org.openhab.binding.nikobus/src/main/java/org/openhab/binding/nikobus/internal/handler/NikobusRollershutterModuleHandler.java b/bundles/org.openhab.binding.nikobus/src/main/java/org/openhab/binding/nikobus/internal/handler/NikobusRollershutterModuleHandler.java index a33e43dd9..7e10de7ac 100644 --- a/bundles/org.openhab.binding.nikobus/src/main/java/org/openhab/binding/nikobus/internal/handler/NikobusRollershutterModuleHandler.java +++ b/bundles/org.openhab.binding.nikobus/src/main/java/org/openhab/binding/nikobus/internal/handler/NikobusRollershutterModuleHandler.java @@ -87,13 +87,12 @@ public class NikobusRollershutterModuleHandler extends NikobusModuleHandler { @Override protected int valueFromCommand(String channelId, Command command) { Optional positionEstimator = getPositionEstimator(channelId); - if (command instanceof DecimalType) { - return positionEstimator.map(estimator -> { - return estimator.processSetPosition(((DecimalType) command).intValue()); - }).orElseThrow(() -> { - throw new IllegalArgumentException( - "Received position request but no estimation configured for channel " + channelId); - }); + if (command instanceof DecimalType decimalCommand) { + return positionEstimator.map(estimator -> estimator.processSetPosition(decimalCommand.intValue())) + .orElseThrow(() -> { + throw new IllegalArgumentException( + "Received position request but no estimation configured for channel " + channelId); + }); } int result = convertCommandToValue(channelId, command); positionEstimator.ifPresent(PositionEstimator::cancelStopMovement); diff --git a/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/discovery/NikoHomeControlDiscoveryService.java b/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/discovery/NikoHomeControlDiscoveryService.java index 57361398c..7ecd9167d 100644 --- a/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/discovery/NikoHomeControlDiscoveryService.java +++ b/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/discovery/NikoHomeControlDiscoveryService.java @@ -201,8 +201,8 @@ public class NikoHomeControlDiscoveryService extends AbstractDiscoveryService im @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof NikoHomeControlBridgeHandler) { - this.handler = (NikoHomeControlBridgeHandler) handler; + if (handler instanceof NikoHomeControlBridgeHandler homeControlBridgeHandler) { + this.handler = homeControlBridgeHandler; bridgeUID = handler.getThing().getUID(); } } diff --git a/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/handler/NikoHomeControlActionHandler.java b/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/handler/NikoHomeControlActionHandler.java index 30f317afe..520d9a5e4 100644 --- a/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/handler/NikoHomeControlActionHandler.java +++ b/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/handler/NikoHomeControlActionHandler.java @@ -125,9 +125,8 @@ public class NikoHomeControlActionHandler extends BaseThingHandler implements Nh return; } - if (command instanceof OnOffType) { - OnOffType s = (OnOffType) command; - if (OnOffType.OFF.equals(s)) { + if (command instanceof OnOffType onOffCommand) { + if (OnOffType.OFF.equals(onOffCommand)) { nhcAction.execute(NHCOFF); } else { nhcAction.execute(NHCON); @@ -142,18 +141,16 @@ public class NikoHomeControlActionHandler extends BaseThingHandler implements Nh return; } - if (command instanceof OnOffType) { - OnOffType s = (OnOffType) command; - if (OnOffType.OFF.equals(s)) { + if (command instanceof OnOffType onOffCommand) { + if (OnOffType.OFF.equals(onOffCommand)) { nhcAction.execute(NHCOFF); } else { nhcAction.execute(NHCON); } - } else if (command instanceof IncreaseDecreaseType) { - IncreaseDecreaseType s = (IncreaseDecreaseType) command; + } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) { int currentValue = nhcAction.getState(); int newValue; - if (IncreaseDecreaseType.INCREASE.equals(s)) { + if (IncreaseDecreaseType.INCREASE.equals(increaseDecreaseCommand)) { newValue = currentValue + stepValue; // round down to step multiple newValue = newValue - newValue % stepValue; @@ -168,12 +165,11 @@ public class NikoHomeControlActionHandler extends BaseThingHandler implements Nh nhcAction.execute(Integer.toString(newValue)); } } - } else if (command instanceof PercentType) { - PercentType p = (PercentType) command; - if (PercentType.ZERO.equals(p)) { + } else if (command instanceof PercentType percentCommand) { + if (PercentType.ZERO.equals(percentCommand)) { nhcAction.execute(NHCOFF); } else { - nhcAction.execute(Integer.toString(p.intValue())); + nhcAction.execute(Integer.toString(percentCommand.intValue())); } } } @@ -185,18 +181,17 @@ public class NikoHomeControlActionHandler extends BaseThingHandler implements Nh return; } - if (command instanceof UpDownType) { - UpDownType s = (UpDownType) command; - if (UpDownType.UP.equals(s)) { + if (command instanceof UpDownType upDownCommand) { + if (UpDownType.UP.equals(upDownCommand)) { nhcAction.execute(!invert ? NHCUP : NHCDOWN); } else { nhcAction.execute(!invert ? NHCDOWN : NHCUP); } } else if (command instanceof StopMoveType) { nhcAction.execute(NHCSTOP); - } else if (command instanceof PercentType) { - PercentType p = (PercentType) command; - nhcAction.execute(!invert ? Integer.toString(100 - p.intValue()) : Integer.toString(p.intValue())); + } else if (command instanceof PercentType percentCommand) { + nhcAction.execute(!invert ? Integer.toString(100 - percentCommand.intValue()) + : Integer.toString(percentCommand.intValue())); } } @@ -300,8 +295,7 @@ public class NikoHomeControlActionHandler extends BaseThingHandler implements Nh properties.put("timeToClose", String.valueOf(nhcAction.getCloseTime())); } - if (nhcAction instanceof NhcAction2) { - NhcAction2 action = (NhcAction2) nhcAction; + if (nhcAction instanceof NhcAction2 action) { properties.put(PROPERTY_DEVICE_TYPE, action.getDeviceType()); properties.put(PROPERTY_DEVICE_TECHNOLOGY, action.getDeviceTechnology()); properties.put(PROPERTY_DEVICE_MODEL, action.getDeviceModel()); diff --git a/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/handler/NikoHomeControlEnergyMeterHandler.java b/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/handler/NikoHomeControlEnergyMeterHandler.java index 571715634..7849c65c8 100644 --- a/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/handler/NikoHomeControlEnergyMeterHandler.java +++ b/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/handler/NikoHomeControlEnergyMeterHandler.java @@ -163,8 +163,7 @@ public class NikoHomeControlEnergyMeterHandler extends BaseThingHandler implemen private void updateProperties(NhcEnergyMeter nhcEnergyMeter) { Map properties = new HashMap<>(); - if (nhcEnergyMeter instanceof NhcEnergyMeter2) { - NhcEnergyMeter2 energyMeter = (NhcEnergyMeter2) nhcEnergyMeter; + if (nhcEnergyMeter instanceof NhcEnergyMeter2 energyMeter) { properties.put(PROPERTY_DEVICE_TYPE, energyMeter.getDeviceType()); properties.put(PROPERTY_DEVICE_TECHNOLOGY, energyMeter.getDeviceTechnology()); properties.put(PROPERTY_DEVICE_MODEL, energyMeter.getDeviceModel()); diff --git a/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/handler/NikoHomeControlThermostatHandler.java b/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/handler/NikoHomeControlThermostatHandler.java index 8493da617..59fb5b078 100644 --- a/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/handler/NikoHomeControlThermostatHandler.java +++ b/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/handler/NikoHomeControlThermostatHandler.java @@ -110,8 +110,8 @@ public class NikoHomeControlThermostatHandler extends BaseThingHandler implement updateStatus(ThingStatus.ONLINE); break; case CHANNEL_MODE: - if (command instanceof DecimalType) { - nhcThermostat.executeMode(((DecimalType) command).intValue()); + if (command instanceof DecimalType decimalCommand) { + nhcThermostat.executeMode(decimalCommand.intValue()); } updateStatus(ThingStatus.ONLINE); break; @@ -128,20 +128,20 @@ public class NikoHomeControlThermostatHandler extends BaseThingHandler implement if (time <= 0) { time = overruleTime; } - if (command instanceof QuantityType) { - QuantityType setpoint = ((QuantityType) command).toUnit(CELSIUS); + if (command instanceof QuantityType quantityCommand) { + QuantityType setpoint = quantityCommand.toUnit(CELSIUS); if (setpoint != null) { nhcThermostat.executeOverrule(Math.round(setpoint.floatValue() * 10), time); } - } else if (command instanceof DecimalType) { - BigDecimal setpoint = ((DecimalType) command).toBigDecimal(); + } else if (command instanceof DecimalType decimalCommand) { + BigDecimal setpoint = decimalCommand.toBigDecimal(); nhcThermostat.executeOverrule(Math.round(setpoint.floatValue() * 10), time); } updateStatus(ThingStatus.ONLINE); break; case CHANNEL_OVERRULETIME: - if (command instanceof DecimalType) { - int overruletime = ((DecimalType) command).intValue(); + if (command instanceof DecimalType decimalCommand) { + int overruletime = decimalCommand.intValue(); int overrule = nhcThermostat.getOverrule(); if (overruletime <= 0) { overruletime = 0; @@ -244,8 +244,7 @@ public class NikoHomeControlThermostatHandler extends BaseThingHandler implement private void updateProperties(NhcThermostat nhcThermostat) { Map properties = new HashMap<>(); - if (nhcThermostat instanceof NhcThermostat2) { - NhcThermostat2 thermostat = (NhcThermostat2) nhcThermostat; + if (nhcThermostat instanceof NhcThermostat2 thermostat) { properties.put(PROPERTY_DEVICE_TYPE, thermostat.getDeviceType()); properties.put(PROPERTY_DEVICE_TECHNOLOGY, thermostat.getDeviceTechnology()); properties.put(PROPERTY_DEVICE_MODEL, thermostat.getDeviceModel()); diff --git a/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/protocol/NikoHomeControlConstants.java b/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/protocol/NikoHomeControlConstants.java index 1b2b4d2fb..6d2fa68e3 100644 --- a/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/protocol/NikoHomeControlConstants.java +++ b/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/protocol/NikoHomeControlConstants.java @@ -23,7 +23,7 @@ import org.eclipse.jdt.annotation.NonNullByDefault; public class NikoHomeControlConstants { // Action types abstracted from NhcI and NhcII action types - public static enum ActionType { + public enum ActionType { TRIGGER, RELAY, DIMMER, diff --git a/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/protocol/nhc2/NhcMqttConnection2.java b/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/protocol/nhc2/NhcMqttConnection2.java index ab4f6c57a..28bc58a04 100644 --- a/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/protocol/nhc2/NhcMqttConnection2.java +++ b/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/protocol/nhc2/NhcMqttConnection2.java @@ -62,7 +62,7 @@ public class NhcMqttConnection2 implements MqttActionCallback { private MqttMessageSubscriber messageSubscriber; private MqttConnectionObserver connectionObserver; - private TrustManager trustManagers[]; + private TrustManager[] trustManagers; private String clientId; private volatile String cocoAddress = ""; diff --git a/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/NoboHubBridgeHandler.java b/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/NoboHubBridgeHandler.java index 29df9e116..b87f7c6fc 100644 --- a/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/NoboHubBridgeHandler.java +++ b/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/NoboHubBridgeHandler.java @@ -99,11 +99,10 @@ public class NoboHubBridgeHandler extends BaseBridgeHandler { if (CHANNEL_HUB_ACTIVE_OVERRIDE_NAME.equals(channelUID.getId())) { if (ht != null && h != null) { - if (command instanceof StringType) { - StringType strCommand = (StringType) command; - logger.debug("Changing override for hub {} to {}", channelUID, strCommand); + if (command instanceof StringType stringCommand) { + logger.debug("Changing override for hub {} to {}", channelUID, stringCommand); try { - OverrideMode mode = OverrideMode.getByName(strCommand.toFullString()); + OverrideMode mode = OverrideMode.getByName(stringCommand.toFullString()); ht.getConnection().setOverride(h, mode); } catch (NoboCommunicationException nce) { logger.debug("Failed setting override mode", nce); diff --git a/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/NoboHubHandlerFactory.java b/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/NoboHubHandlerFactory.java index 969e060db..9398af4a1 100644 --- a/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/NoboHubHandlerFactory.java +++ b/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/NoboHubHandlerFactory.java @@ -92,8 +92,8 @@ public class NoboHubHandlerFactory extends BaseThingHandlerFactory { @Override protected void removeHandler(ThingHandler thingHandler) { - if (thingHandler instanceof NoboHubBridgeHandler) { - unregisterDiscoveryService((NoboHubBridgeHandler) thingHandler); + if (thingHandler instanceof NoboHubBridgeHandler bridgeHandler) { + unregisterDiscoveryService(bridgeHandler); } } diff --git a/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/ZoneHandler.java b/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/ZoneHandler.java index fc3dee948..5af6c6a1b 100644 --- a/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/ZoneHandler.java +++ b/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/ZoneHandler.java @@ -166,8 +166,7 @@ public class ZoneHandler extends BaseThingHandler { if (CHANNEL_ZONE_COMFORT_TEMPERATURE.equals(channelUID.getId())) { Zone zone = getZone(); if (zone != null) { - if (command instanceof DecimalType) { - DecimalType comfortTemp = (DecimalType) command; + if (command instanceof DecimalType comfortTemp) { logger.debug("Set comfort temp for zone {} to {}", zone.getName(), comfortTemp.doubleValue()); zone.setComfortTemperature(comfortTemp.intValue()); sendCommand(zone.generateCommandString("U00")); @@ -180,8 +179,7 @@ public class ZoneHandler extends BaseThingHandler { if (CHANNEL_ZONE_ECO_TEMPERATURE.equals(channelUID.getId())) { Zone zone = getZone(); if (zone != null) { - if (command instanceof DecimalType) { - DecimalType ecoTemp = (DecimalType) command; + if (command instanceof DecimalType ecoTemp) { logger.debug("Set eco temp for zone {} to {}", zone.getName(), ecoTemp.doubleValue()); zone.setEcoTemperature(ecoTemp.intValue()); sendCommand(zone.generateCommandString("U00")); @@ -193,8 +191,7 @@ public class ZoneHandler extends BaseThingHandler { if (CHANNEL_ZONE_ACTIVE_WEEK_PROFILE.equals(channelUID.getId())) { Zone zone = getZone(); if (zone != null) { - if (command instanceof DecimalType) { - DecimalType weekProfileId = (DecimalType) command; + if (command instanceof DecimalType weekProfileId) { logger.debug("Set week profile for zone {} to {}", zone.getName(), weekProfileId); zone.setWeekProfile(weekProfileId.intValue()); sendCommand(zone.generateCommandString("U00")); diff --git a/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/discovery/NoboHubDiscoveryService.java b/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/discovery/NoboHubDiscoveryService.java index 9c9594ffc..e534ef212 100644 --- a/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/discovery/NoboHubDiscoveryService.java +++ b/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/discovery/NoboHubDiscoveryService.java @@ -82,8 +82,8 @@ public class NoboHubDiscoveryService extends AbstractDiscoveryService implements @Override public void setThingHandler(ThingHandler thingHandler) { - if (thingHandler instanceof NoboHubBridgeHandler) { - this.hubBridgeHandler = (NoboHubBridgeHandler) thingHandler; + if (thingHandler instanceof NoboHubBridgeHandler bridgeHandler) { + this.hubBridgeHandler = bridgeHandler; } } diff --git a/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/model/Hub.java b/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/model/Hub.java index 463582afe..6beeb16c1 100644 --- a/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/model/Hub.java +++ b/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/model/Hub.java @@ -51,7 +51,7 @@ public class Hub { } public static Hub fromH05(String h05) throws NoboDataException { - String parts[] = h05.split(" ", 8); + String[] parts = h05.split(" ", 8); if (parts.length != 8) { throw new NoboDataException( diff --git a/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/model/Temperature.java b/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/model/Temperature.java index 952fa1e2a..57d6f99e4 100644 --- a/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/model/Temperature.java +++ b/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/model/Temperature.java @@ -31,7 +31,7 @@ public final class Temperature { } public static Temperature fromY02(String y02) throws NoboDataException { - String parts[] = y02.split(" ", 3); + String[] parts = y02.split(" ", 3); if (parts.length != 3) { throw new NoboDataException( String.format("Unexpected number of parts from hub on Y02 call: %d", parts.length)); diff --git a/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/model/Zone.java b/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/model/Zone.java index 53a89302c..f40fda15d 100644 --- a/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/model/Zone.java +++ b/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/model/Zone.java @@ -43,7 +43,7 @@ public final class Zone { } public static Zone fromH01(String h01) throws NoboDataException { - String parts[] = h01.split(" ", 8); + String[] parts = h01.split(" ", 8); if (parts.length != 8) { throw new NoboDataException( diff --git a/bundles/org.openhab.binding.novafinedust/src/main/java/org/openhab/binding/novafinedust/internal/NovaFineDustHandlerFactory.java b/bundles/org.openhab.binding.novafinedust/src/main/java/org/openhab/binding/novafinedust/internal/NovaFineDustHandlerFactory.java index daca57696..8e41d8d7c 100644 --- a/bundles/org.openhab.binding.novafinedust/src/main/java/org/openhab/binding/novafinedust/internal/NovaFineDustHandlerFactory.java +++ b/bundles/org.openhab.binding.novafinedust/src/main/java/org/openhab/binding/novafinedust/internal/NovaFineDustHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.novafinedust.internal; import static org.openhab.binding.novafinedust.internal.NovaFineDustBindingConstants.THING_TYPE_SDS011; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -39,7 +38,7 @@ import org.osgi.service.component.annotations.Reference; @Component(configurationPid = "binding.novafinedust", service = ThingHandlerFactory.class) public class NovaFineDustHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_SDS011); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_SDS011); private final SerialPortManager serialPortManager; diff --git a/bundles/org.openhab.binding.novafinedust/src/main/java/org/openhab/binding/novafinedust/internal/sds011protocol/SDS011Communicator.java b/bundles/org.openhab.binding.novafinedust/src/main/java/org/openhab/binding/novafinedust/internal/sds011protocol/SDS011Communicator.java index 77060d103..0383c165c 100644 --- a/bundles/org.openhab.binding.novafinedust/src/main/java/org/openhab/binding/novafinedust/internal/sds011protocol/SDS011Communicator.java +++ b/bundles/org.openhab.binding.novafinedust/src/main/java/org/openhab/binding/novafinedust/internal/sds011protocol/SDS011Communicator.java @@ -80,7 +80,6 @@ public class SDS011Communicator { */ public void initialize(WorkMode mode, Duration interval) throws PortInUseException, TooManyListenersException, IOException, UnsupportedCommOperationException { - logger.trace("Initializing with mode={}, interval={}", mode, interval); SerialPort localSerialPort = portId.open(thingHandler.getThing().getUID().toString(), 2000); @@ -246,8 +245,7 @@ public class SDS011Communicator { private boolean doRead() throws IOException { SensorReply reply = readReply(); logger.trace("doRead(): Read reply={}", reply); - if (reply instanceof SensorMeasuredDataReply) { - SensorMeasuredDataReply sensorData = (SensorMeasuredDataReply) reply; + if (reply instanceof SensorMeasuredDataReply sensorData) { logger.trace("We received sensor data"); if (sensorData.isValidData()) { logger.trace("Sensor data is valid => updating channels"); diff --git a/bundles/org.openhab.binding.novafinedust/src/main/java/org/openhab/binding/novafinedust/internal/sds011protocol/messages/SensorFirmwareReply.java b/bundles/org.openhab.binding.novafinedust/src/main/java/org/openhab/binding/novafinedust/internal/sds011protocol/messages/SensorFirmwareReply.java index 2a5beb5c8..afb5f65a2 100644 --- a/bundles/org.openhab.binding.novafinedust/src/main/java/org/openhab/binding/novafinedust/internal/sds011protocol/messages/SensorFirmwareReply.java +++ b/bundles/org.openhab.binding.novafinedust/src/main/java/org/openhab/binding/novafinedust/internal/sds011protocol/messages/SensorFirmwareReply.java @@ -40,8 +40,7 @@ public class SensorFirmwareReply extends SensorReply { * @return firmware of the sensor formatted as YY-MM-DD */ public String getFirmware() { - String firmware = year + "-" + month + "-" + day; - return firmware; + return year + "-" + month + "-" + day; } @Override diff --git a/bundles/org.openhab.binding.ntp/src/main/java/org/openhab/binding/ntp/internal/NtpBindingConstants.java b/bundles/org.openhab.binding.ntp/src/main/java/org/openhab/binding/ntp/internal/NtpBindingConstants.java index 4f36e1d28..a71e5fe01 100644 --- a/bundles/org.openhab.binding.ntp/src/main/java/org/openhab/binding/ntp/internal/NtpBindingConstants.java +++ b/bundles/org.openhab.binding.ntp/src/main/java/org/openhab/binding/ntp/internal/NtpBindingConstants.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.ntp.internal; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -46,5 +45,5 @@ public class NtpBindingConstants { public static final String PROPERTY_DATE_TIME_FORMAT = "DateTimeFormat"; public static final String PROPERTY_NTP_SERVER_PORT = "serverPort"; - public static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_NTP); + public static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_NTP); } diff --git a/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/NukiHandlerFactory.java b/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/NukiHandlerFactory.java index 12e9a1f1e..6bfe90a0c 100644 --- a/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/NukiHandlerFactory.java +++ b/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/NukiHandlerFactory.java @@ -101,8 +101,8 @@ public class NukiHandlerFactory extends BaseThingHandlerFactory { public void unregisterHandler(Thing thing) { super.unregisterHandler(thing); ThingHandler handler = thing.getHandler(); - if (handler instanceof NukiBridgeHandler) { - nukiApiServlet.remove((NukiBridgeHandler) handler); + if (handler instanceof NukiBridgeHandler bridgeHandler) { + nukiApiServlet.remove(bridgeHandler); } } diff --git a/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/constants/NukiBindingConstants.java b/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/constants/NukiBindingConstants.java index d441d7bc6..f3acb9afc 100644 --- a/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/constants/NukiBindingConstants.java +++ b/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/constants/NukiBindingConstants.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.nuki.internal.constants; -import java.util.Collections; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -38,9 +37,9 @@ public class NukiBindingConstants { public static final ThingTypeUID THING_TYPE_SMARTLOCK = new ThingTypeUID(BINDING_ID, "smartlock"); public static final ThingTypeUID THING_TYPE_OPENER = new ThingTypeUID(BINDING_ID, "opener"); - public static final Set THING_TYPE_BRIDGE_UIDS = Collections.singleton(THING_TYPE_BRIDGE); - public static final Set THING_TYPE_SMARTLOCK_UIDS = Collections.singleton(THING_TYPE_SMARTLOCK); - public static final Set THING_TYPE_OPENER_UIDS = Collections.singleton(THING_TYPE_OPENER); + public static final Set THING_TYPE_BRIDGE_UIDS = Set.of(THING_TYPE_BRIDGE); + public static final Set THING_TYPE_SMARTLOCK_UIDS = Set.of(THING_TYPE_SMARTLOCK); + public static final Set THING_TYPE_OPENER_UIDS = Set.of(THING_TYPE_OPENER); public static final Set SUPPORTED_THING_TYPES_UIDS = Stream .of(THING_TYPE_BRIDGE_UIDS, THING_TYPE_SMARTLOCK_UIDS, THING_TYPE_OPENER_UIDS).flatMap(Set::stream) diff --git a/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/dataexchange/NukiHttpClient.java b/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/dataexchange/NukiHttpClient.java index d66598e9c..fd31e33f7 100644 --- a/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/dataexchange/NukiHttpClient.java +++ b/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/dataexchange/NukiHttpClient.java @@ -73,8 +73,7 @@ public class NukiHttpClient { private NukiBaseResponse handleException(Exception e) { if (e instanceof ExecutionException) { Throwable cause = e.getCause(); - if (cause instanceof HttpResponseException) { - HttpResponseException causeException = (HttpResponseException) cause; + if (cause instanceof HttpResponseException causeException) { int status = causeException.getResponse().getStatus(); String reason = causeException.getResponse().getReason(); logger.debug("HTTP Response Exception! Status[{}] - Reason[{}]! Check your API Token!", status, reason); diff --git a/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/discovery/NukiBridgeDiscoveryService.java b/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/discovery/NukiBridgeDiscoveryService.java index 0e834f10d..5e6eb0f58 100644 --- a/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/discovery/NukiBridgeDiscoveryService.java +++ b/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/discovery/NukiBridgeDiscoveryService.java @@ -12,7 +12,7 @@ */ package org.openhab.binding.nuki.internal.discovery; -import java.util.Collections; +import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jetty.client.HttpClient; @@ -56,7 +56,7 @@ public class NukiBridgeDiscoveryService extends AbstractDiscoveryService { @Activate public NukiBridgeDiscoveryService(@Reference final HttpClientFactory httpClientFactory, @Reference final ThingRegistry thingRegistry) { - super(Collections.singleton(NukiBindingConstants.THING_TYPE_BRIDGE), 30, false); + super(Set.of(NukiBindingConstants.THING_TYPE_BRIDGE), 30, false); this.httpClient = httpClientFactory.getCommonHttpClient(); this.thingRegistry = thingRegistry; } diff --git a/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/discovery/NukiDeviceDiscoveryService.java b/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/discovery/NukiDeviceDiscoveryService.java index b3a23b1fb..acb176450 100644 --- a/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/discovery/NukiDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/discovery/NukiDeviceDiscoveryService.java @@ -103,8 +103,8 @@ public class NukiDeviceDiscoveryService extends AbstractDiscoveryService impleme @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof NukiBridgeHandler) { - bridge = (NukiBridgeHandler) handler; + if (handler instanceof NukiBridgeHandler bridgeHandler) { + bridge = bridgeHandler; } } diff --git a/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/handler/AbstractNukiDeviceHandler.java b/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/handler/AbstractNukiDeviceHandler.java index 7d0ec0d06..100f0951a 100644 --- a/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/handler/AbstractNukiDeviceHandler.java +++ b/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/handler/AbstractNukiDeviceHandler.java @@ -149,8 +149,7 @@ public abstract class AbstractNukiDeviceHandler { @@ -203,6 +202,7 @@ public abstract class AbstractNukiDeviceHandler handler.accept((NukiBridgeHandler) bridgeHandler)); + if (bridgeHandler instanceof NukiBridgeHandler nukiBridgeHandler) { + scheduler.execute(() -> handler.accept(nukiBridgeHandler)); } } } diff --git a/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/handler/NukiBridgeHandler.java b/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/handler/NukiBridgeHandler.java index 475fd1ec4..3db6e5b4d 100644 --- a/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/handler/NukiBridgeHandler.java +++ b/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/handler/NukiBridgeHandler.java @@ -16,6 +16,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; +import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; @@ -143,7 +144,7 @@ public class NukiBridgeHandler extends BaseBridgeHandler { @Override public Collection> getServices() { - return Collections.singleton(NukiDeviceDiscoveryService.class); + return Set.of(NukiDeviceDiscoveryService.class); } private synchronized void initializeHandler() { @@ -175,7 +176,6 @@ public class NukiBridgeHandler extends BaseBridgeHandler { public void checkBridgeOnline() { logger.debug("checkBridgeOnline():bridgeIp[{}] status[{}]", this.config.ip, getThing().getStatus()); if (getThing().getStatus().equals(ThingStatus.ONLINE)) { - withHttpClient(client -> { logger.debug("Requesting BridgeInfo to ensure Bridge[{}] is online.", this.config.ip); BridgeInfoResponse bridgeInfoResponse = client.getBridgeInfo(); diff --git a/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/handler/NukiOpenerHandler.java b/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/handler/NukiOpenerHandler.java index 29cd9e3f4..91b27fa77 100644 --- a/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/handler/NukiOpenerHandler.java +++ b/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/handler/NukiOpenerHandler.java @@ -66,8 +66,8 @@ public class NukiOpenerHandler extends AbstractNukiDeviceHandler { BridgeLockActionResponse response = client.getOpenerAction(configuration.nukiId, action); diff --git a/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/handler/NukiSmartLockHandler.java b/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/handler/NukiSmartLockHandler.java index b561e4604..effc3338d 100644 --- a/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/handler/NukiSmartLockHandler.java +++ b/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/handler/NukiSmartLockHandler.java @@ -82,9 +82,8 @@ public class NukiSmartLockHandler extends AbstractNukiDeviceHandler { BridgeLockActionResponse bridgeLockActionResponse = client diff --git a/bundles/org.openhab.binding.nuvo/src/main/java/org/openhab/binding/nuvo/internal/NuvoHandlerFactory.java b/bundles/org.openhab.binding.nuvo/src/main/java/org/openhab/binding/nuvo/internal/NuvoHandlerFactory.java index 893200f18..c31043f45 100644 --- a/bundles/org.openhab.binding.nuvo/src/main/java/org/openhab/binding/nuvo/internal/NuvoHandlerFactory.java +++ b/bundles/org.openhab.binding.nuvo/src/main/java/org/openhab/binding/nuvo/internal/NuvoHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.nuvo.internal; import static org.openhab.binding.nuvo.internal.NuvoBindingConstants.*; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -42,7 +41,7 @@ import org.osgi.service.component.annotations.Reference; @Component(configurationPid = "binding.nuvo", service = ThingHandlerFactory.class) public class NuvoHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_AMP); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_AMP); private final SerialPortManager serialPortManager; diff --git a/bundles/org.openhab.binding.nuvo/src/main/java/org/openhab/binding/nuvo/internal/handler/NuvoHandler.java b/bundles/org.openhab.binding.nuvo/src/main/java/org/openhab/binding/nuvo/internal/handler/NuvoHandler.java index c55ea48aa..d3ac3c1f2 100644 --- a/bundles/org.openhab.binding.nuvo/src/main/java/org/openhab/binding/nuvo/internal/handler/NuvoHandler.java +++ b/bundles/org.openhab.binding.nuvo/src/main/java/org/openhab/binding/nuvo/internal/handler/NuvoHandler.java @@ -22,7 +22,6 @@ import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Base64; import java.util.Collection; -import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; @@ -317,7 +316,7 @@ public class NuvoHandler extends BaseThingHandler implements NuvoMessageEventLis // Also add any openHAB NuvoNet source favorites to the list for (int src = 1; src <= MAX_SRC; src++) { - NuvoEnum source = NuvoEnum.valueOf(SOURCE + String.valueOf(src)); + NuvoEnum source = NuvoEnum.valueOf(SOURCE + src); String[] favorites = favoriteMap.get(source); if (favorites != null) { for (int fav = 0; fav < favorites.length; fav++) { @@ -388,7 +387,7 @@ public class NuvoHandler extends BaseThingHandler implements NuvoMessageEventLis @Override public Collection> getServices() { - return Collections.singletonList(NuvoThingActions.class); + return List.of(NuvoThingActions.class); } public void handleRawCommand(String command) { @@ -435,8 +434,8 @@ public class NuvoHandler extends BaseThingHandler implements NuvoMessageEventLis } break; case CHANNEL_TYPE_SOURCE: - if (command instanceof DecimalType) { - int value = ((DecimalType) command).intValue(); + if (command instanceof DecimalType decimalCommand) { + int value = decimalCommand.intValue(); if (value >= 1 && value <= MAX_SRC) { logger.debug("Got source command {} zone {}", value, target); connector.sendCommand(target, NuvoCommand.SOURCE, String.valueOf(value)); @@ -447,8 +446,8 @@ public class NuvoHandler extends BaseThingHandler implements NuvoMessageEventLis } break; case CHANNEL_TYPE_FAVORITE: - if (command instanceof DecimalType) { - int value = ((DecimalType) command).intValue(); + if (command instanceof DecimalType decimalCommand) { + int value = decimalCommand.intValue(); if (value >= 1 && value <= MAX_FAV) { logger.debug("Got favorite command {} zone {}", value, target); connector.sendCommand(target, NuvoCommand.FAVORITE, String.valueOf(value)); @@ -465,10 +464,9 @@ public class NuvoHandler extends BaseThingHandler implements NuvoMessageEventLis } break; case CHANNEL_TYPE_VOLUME: - if (command instanceof PercentType) { + if (command instanceof PercentType percentCommand) { int value = (MAX_VOLUME - - (int) Math.round( - ((PercentType) command).doubleValue() / 100.0 * (MAX_VOLUME - MIN_VOLUME)) + - (int) Math.round(percentCommand.doubleValue() / 100.0 * (MAX_VOLUME - MIN_VOLUME)) + MIN_VOLUME); logger.debug("Got volume command {} zone {}", value, target); connector.sendCommand(target, NuvoCommand.VOLUME, String.valueOf(value)); @@ -481,8 +479,8 @@ public class NuvoHandler extends BaseThingHandler implements NuvoMessageEventLis } break; case CHANNEL_TYPE_TREBLE: - if (command instanceof DecimalType) { - int value = ((DecimalType) command).intValue(); + if (command instanceof DecimalType decimalCommand) { + int value = decimalCommand.intValue(); if (value >= MIN_EQ && value <= MAX_EQ) { // device can only accept even values if (value % 2 == 1) { @@ -494,8 +492,8 @@ public class NuvoHandler extends BaseThingHandler implements NuvoMessageEventLis } break; case CHANNEL_TYPE_BASS: - if (command instanceof DecimalType) { - int value = ((DecimalType) command).intValue(); + if (command instanceof DecimalType decimalCommand) { + int value = decimalCommand.intValue(); if (value >= MIN_EQ && value <= MAX_EQ) { if (value % 2 == 1) { value++; @@ -506,8 +504,8 @@ public class NuvoHandler extends BaseThingHandler implements NuvoMessageEventLis } break; case CHANNEL_TYPE_BALANCE: - if (command instanceof DecimalType) { - int value = ((DecimalType) command).intValue(); + if (command instanceof DecimalType decimalCommand) { + int value = decimalCommand.intValue(); if (value >= MIN_EQ && value <= MAX_EQ) { if (value % 2 == 1) { value++; diff --git a/bundles/org.openhab.binding.nzwateralerts/src/main/java/org/openhab/binding/nzwateralerts/internal/handler/NZWaterAlertsHandlerFactory.java b/bundles/org.openhab.binding.nzwateralerts/src/main/java/org/openhab/binding/nzwateralerts/internal/handler/NZWaterAlertsHandlerFactory.java index 250c29018..3ff408f79 100644 --- a/bundles/org.openhab.binding.nzwateralerts/src/main/java/org/openhab/binding/nzwateralerts/internal/handler/NZWaterAlertsHandlerFactory.java +++ b/bundles/org.openhab.binding.nzwateralerts/src/main/java/org/openhab/binding/nzwateralerts/internal/handler/NZWaterAlertsHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.nzwateralerts.internal.handler; import static org.openhab.binding.nzwateralerts.internal.NZWaterAlertsBindingConstants.*; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -41,7 +40,7 @@ import org.osgi.service.component.annotations.Reference; public class NZWaterAlertsHandlerFactory extends BaseThingHandlerFactory { private final HttpClient httpClient; - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_WATERALERT); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_WATERALERT); @Activate public NZWaterAlertsHandlerFactory(final @Reference HttpClientFactory httpClientFactory) { diff --git a/bundles/org.openhab.binding.oceanic/src/main/java/org/openhab/binding/oceanic/internal/handler/NetworkOceanicThingHandler.java b/bundles/org.openhab.binding.oceanic/src/main/java/org/openhab/binding/oceanic/internal/handler/NetworkOceanicThingHandler.java index a2def1158..79e7cbd6a 100644 --- a/bundles/org.openhab.binding.oceanic/src/main/java/org/openhab/binding/oceanic/internal/handler/NetworkOceanicThingHandler.java +++ b/bundles/org.openhab.binding.oceanic/src/main/java/org/openhab/binding/oceanic/internal/handler/NetworkOceanicThingHandler.java @@ -200,7 +200,6 @@ public class NetworkOceanicThingHandler extends OceanicThingHandler { } } } - } } catch (IOException e) { logger.debug("An exception occurred while quering host {}:{} : '{}'", config.ipAddress, diff --git a/bundles/org.openhab.binding.oceanic/src/main/java/org/openhab/binding/oceanic/internal/handler/SerialOceanicThingHandler.java b/bundles/org.openhab.binding.oceanic/src/main/java/org/openhab/binding/oceanic/internal/handler/SerialOceanicThingHandler.java index 125747e2b..16280a828 100644 --- a/bundles/org.openhab.binding.oceanic/src/main/java/org/openhab/binding/oceanic/internal/handler/SerialOceanicThingHandler.java +++ b/bundles/org.openhab.binding.oceanic/src/main/java/org/openhab/binding/oceanic/internal/handler/SerialOceanicThingHandler.java @@ -67,7 +67,6 @@ public class SerialOceanicThingHandler extends OceanicThingHandler implements Se SerialOceanicBindingConfiguration config = getConfigAs(SerialOceanicBindingConfiguration.class); if (serialPort == null && config.port != null) { - SerialPortIdentifier portIdentifier = serialPortManager.getIdentifier(config.port); if (portIdentifier == null) { @@ -172,7 +171,7 @@ public class SerialOceanicThingHandler extends OceanicThingHandler implements Se } long timeStamp = System.currentTimeMillis(); - while (lastLineReceived.equals("")) { + while ("".equals(lastLineReceived)) { try { Thread.sleep(50); } catch (InterruptedException e) { diff --git a/bundles/org.openhab.binding.ojelectronics/src/main/java/org/openhab/binding/ojelectronics/internal/OJCloudHandlerFactory.java b/bundles/org.openhab.binding.ojelectronics/src/main/java/org/openhab/binding/ojelectronics/internal/OJCloudHandlerFactory.java index 718494f0f..7a610c52d 100644 --- a/bundles/org.openhab.binding.ojelectronics/src/main/java/org/openhab/binding/ojelectronics/internal/OJCloudHandlerFactory.java +++ b/bundles/org.openhab.binding.ojelectronics/src/main/java/org/openhab/binding/ojelectronics/internal/OJCloudHandlerFactory.java @@ -64,8 +64,7 @@ public class OJCloudHandlerFactory extends BaseThingHandlerFactory { @Override protected @Nullable ThingHandler createHandler(Thing thing) { if (SUPPORTED_THING_TYPES_UIDS.contains(thing.getThingTypeUID())) { - OJCloudHandler handler = new OJCloudHandler((Bridge) thing, httpClient); - return handler; + return new OJCloudHandler((Bridge) thing, httpClient); } return null; } diff --git a/bundles/org.openhab.binding.ojelectronics/src/main/java/org/openhab/binding/ojelectronics/internal/ThermostatHandler.java b/bundles/org.openhab.binding.ojelectronics/src/main/java/org/openhab/binding/ojelectronics/internal/ThermostatHandler.java index 2bcfec98f..95720a882 100644 --- a/bundles/org.openhab.binding.ojelectronics/src/main/java/org/openhab/binding/ojelectronics/internal/ThermostatHandler.java +++ b/bundles/org.openhab.binding.ojelectronics/src/main/java/org/openhab/binding/ojelectronics/internal/ThermostatHandler.java @@ -197,8 +197,8 @@ public class ThermostatHandler extends BaseThingHandler { } private void updateManualSetpoint(Command command) { - if (command instanceof QuantityType) { - getCurrentThermostat().manualModeSetpoint = (int) (((QuantityType) command).floatValue() * 100); + if (command instanceof QuantityType quantityCommand) { + getCurrentThermostat().manualModeSetpoint = (int) (quantityCommand.floatValue() * 100); } else { logger.warn("Unable to set value {}", command); } @@ -210,8 +210,8 @@ public class ThermostatHandler extends BaseThingHandler { } private void updateBoostEndTime(Command command) { - if (command instanceof DateTimeType) { - getCurrentThermostat().boostEndTime = Date.from(((DateTimeType) command).getZonedDateTime().toInstant()); + if (command instanceof DateTimeType dateTimeCommand) { + getCurrentThermostat().boostEndTime = Date.from(dateTimeCommand.getZonedDateTime().toInstant()); } else { logger.warn("Unable to set value {}", command); } @@ -223,9 +223,9 @@ public class ThermostatHandler extends BaseThingHandler { } private void updateComfortEndTime(Command command) { - if (command instanceof DateTimeType) { + if (command instanceof DateTimeType dateTimeCommand) { getCurrentThermostat().comfortEndTime = Objects - .requireNonNull(Date.from(((DateTimeType) command).getZonedDateTime().toInstant())); + .requireNonNull(Date.from(dateTimeCommand.getZonedDateTime().toInstant())); } else { logger.warn("Unable to set value {}", command); } @@ -237,8 +237,8 @@ public class ThermostatHandler extends BaseThingHandler { } private void updateComfortSetpoint(Command command) { - if (command instanceof QuantityType) { - getCurrentThermostat().comfortSetpoint = (int) (((QuantityType) command).floatValue() * 100); + if (command instanceof QuantityType quantityCommand) { + getCurrentThermostat().comfortSetpoint = (int) (quantityCommand.floatValue() * 100); } else { logger.warn("Unable to set value {}", command); } @@ -325,9 +325,9 @@ public class ThermostatHandler extends BaseThingHandler { } private void updateVacationBeginDay(Command command) { - if (command instanceof DateTimeType) { + if (command instanceof DateTimeType dateTimeCommand) { getCurrentThermostat().vacationBeginDay = Date - .from(((DateTimeType) command).getZonedDateTime().toInstant().truncatedTo(ChronoUnit.DAYS)); + .from(dateTimeCommand.getZonedDateTime().toInstant().truncatedTo(ChronoUnit.DAYS)); } else { logger.warn("Unable to set value {}", command); } @@ -341,9 +341,9 @@ public class ThermostatHandler extends BaseThingHandler { } private void updateVacationEndDay(Command command) { - if (command instanceof DateTimeType) { + if (command instanceof DateTimeType dateTimeCommand) { getCurrentThermostat().vacationEndDay = Date - .from(((DateTimeType) command).getZonedDateTime().toInstant().truncatedTo(ChronoUnit.DAYS)); + .from(dateTimeCommand.getZonedDateTime().toInstant().truncatedTo(ChronoUnit.DAYS)); } else { logger.warn("Unable to set value {}", command); } diff --git a/bundles/org.openhab.binding.ojelectronics/src/main/java/org/openhab/binding/ojelectronics/internal/services/OJDiscoveryService.java b/bundles/org.openhab.binding.ojelectronics/src/main/java/org/openhab/binding/ojelectronics/internal/services/OJDiscoveryService.java index d37334601..b19af92f5 100644 --- a/bundles/org.openhab.binding.ojelectronics/src/main/java/org/openhab/binding/ojelectronics/internal/services/OJDiscoveryService.java +++ b/bundles/org.openhab.binding.ojelectronics/src/main/java/org/openhab/binding/ojelectronics/internal/services/OJDiscoveryService.java @@ -73,8 +73,7 @@ public final class OJDiscoveryService extends AbstractDiscoveryService implement @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof OJCloudHandler) { - final OJCloudHandler bridgeHandler = (OJCloudHandler) handler; + if (handler instanceof OJCloudHandler bridgeHandler) { this.bridgeHandler = bridgeHandler; bridgeHandler.setDiscoveryService(this); } diff --git a/bundles/org.openhab.binding.ojelectronics/src/main/java/org/openhab/binding/ojelectronics/internal/services/RefreshService.java b/bundles/org.openhab.binding.ojelectronics/src/main/java/org/openhab/binding/ojelectronics/internal/services/RefreshService.java index 399307660..c1eec0517 100644 --- a/bundles/org.openhab.binding.ojelectronics/src/main/java/org/openhab/binding/ojelectronics/internal/services/RefreshService.java +++ b/bundles/org.openhab.binding.ojelectronics/src/main/java/org/openhab/binding/ojelectronics/internal/services/RefreshService.java @@ -196,9 +196,8 @@ public final class RefreshService implements AutoCloseable { } private Request createRequest() { - Request request = httpClient.newRequest(config.getRestApiUrl() + "/Group/GroupContents") - .param("sessionid", sessionId).param("apiKey", config.apiKey).method(HttpMethod.GET); - return request; + return httpClient.newRequest(config.getRestApiUrl() + "/Group/GroupContents").param("sessionid", sessionId) + .param("apiKey", config.apiKey).method(HttpMethod.GET); } private void initializationDone(String responseBody) { diff --git a/bundles/org.openhab.binding.ojelectronics/src/main/java/org/openhab/binding/ojelectronics/internal/services/SignInService.java b/bundles/org.openhab.binding.ojelectronics/src/main/java/org/openhab/binding/ojelectronics/internal/services/SignInService.java index 1a364c1d7..8b9615802 100644 --- a/bundles/org.openhab.binding.ojelectronics/src/main/java/org/openhab/binding/ojelectronics/internal/services/SignInService.java +++ b/bundles/org.openhab.binding.ojelectronics/src/main/java/org/openhab/binding/ojelectronics/internal/services/SignInService.java @@ -90,7 +90,7 @@ public class SignInService { if (result.getResponse().getStatus() == 200) { PostSignInResponseModel signInModel = Objects .requireNonNull(gson.fromJson(getContentAsString(), PostSignInResponseModel.class)); - if (signInModel.errorCode != 0 || signInModel.sessionId.equals("")) { + if (signInModel.errorCode != 0 || "".equals(signInModel.sessionId)) { unauthorized.run(); return; } diff --git a/bundles/org.openhab.binding.omnikinverter/src/main/java/org/openhab/binding/omnikinverter/internal/OmnikInverterHandlerFactory.java b/bundles/org.openhab.binding.omnikinverter/src/main/java/org/openhab/binding/omnikinverter/internal/OmnikInverterHandlerFactory.java index 5e671e481..0ffbf8993 100644 --- a/bundles/org.openhab.binding.omnikinverter/src/main/java/org/openhab/binding/omnikinverter/internal/OmnikInverterHandlerFactory.java +++ b/bundles/org.openhab.binding.omnikinverter/src/main/java/org/openhab/binding/omnikinverter/internal/OmnikInverterHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.omnikinverter.internal; import static org.openhab.binding.omnikinverter.internal.OmnikInverterBindingConstants.THING_TYPE_OMNIK; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -37,7 +36,7 @@ import org.osgi.service.component.annotations.Component; @Component(configurationPid = "binding.omnikinverter", service = ThingHandlerFactory.class) public class OmnikInverterHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_OMNIK); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_OMNIK); @Override public boolean supportsThingType(ThingTypeUID thingTypeUID) { diff --git a/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/action/OmnilinkActions.java b/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/action/OmnilinkActions.java index 4e7ab5b5a..2c1804864 100644 --- a/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/action/OmnilinkActions.java +++ b/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/action/OmnilinkActions.java @@ -42,8 +42,8 @@ public class OmnilinkActions implements ThingActions { @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof OmnilinkBridgeHandler) { - this.handler = (OmnilinkBridgeHandler) handler; + if (handler instanceof OmnilinkBridgeHandler bridgeHandler) { + this.handler = bridgeHandler; } } diff --git a/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/discovery/OmnilinkDiscoveryService.java b/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/discovery/OmnilinkDiscoveryService.java index 59c00dd12..b55f305cb 100644 --- a/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/discovery/OmnilinkDiscoveryService.java +++ b/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/discovery/OmnilinkDiscoveryService.java @@ -75,8 +75,8 @@ public class OmnilinkDiscoveryService extends AbstractDiscoveryService @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof OmnilinkBridgeHandler) { - bridgeHandler = (OmnilinkBridgeHandler) handler; + if (handler instanceof OmnilinkBridgeHandler omnilinkBridgeHandler) { + bridgeHandler = omnilinkBridgeHandler; } } diff --git a/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/handler/AbstractAreaHandler.java b/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/handler/AbstractAreaHandler.java index bce007996..75f3146dd 100644 --- a/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/handler/AbstractAreaHandler.java +++ b/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/handler/AbstractAreaHandler.java @@ -177,11 +177,11 @@ public abstract class AbstractAreaHandler extends AbstractOmnilinkStatusHandler< protected abstract EnumSet getAlarms(); private void handleKeypadEmergency(ChannelUID channelUID, Command command) { - if (command instanceof DecimalType) { + if (command instanceof DecimalType decimalCommand) { try { final OmnilinkBridgeHandler bridge = getOmnilinkBridgeHandler(); if (bridge != null) { - bridge.activateKeypadEmergency(thingID, ((DecimalType) command).intValue()); + bridge.activateKeypadEmergency(thingID, decimalCommand.intValue()); } else { logger.debug("Received null bridge while sending Keypad Emergency command!"); } diff --git a/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/handler/AudioSourceHandler.java b/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/handler/AudioSourceHandler.java index 30d999e42..7ba769038 100644 --- a/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/handler/AudioSourceHandler.java +++ b/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/handler/AudioSourceHandler.java @@ -118,8 +118,8 @@ public class AudioSourceHandler extends AbstractOmnilinkHandler { if (command instanceof RefreshType) { updateState(CHANNEL_AUDIO_SOURCE_POLLING, OnOffType.from((scheduledPolling != null && !scheduledPolling.isDone()))); - } else if (command instanceof OnOffType) { - handlePolling(channelUID, (OnOffType) command); + } else if (command instanceof OnOffType onOffCommand) { + handlePolling(channelUID, onOffCommand); } else { logger.debug("Invalid command: {}, must be RefreshType or OnOffType", command); } diff --git a/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/handler/AudioZoneHandler.java b/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/handler/AudioZoneHandler.java index 8d1b1f157..fd93b8a9d 100644 --- a/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/handler/AudioZoneHandler.java +++ b/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/handler/AudioZoneHandler.java @@ -111,26 +111,24 @@ public class AudioZoneHandler extends AbstractOmnilinkStatusHandler theThing = getUnitThing(unitNumber); theThing.map(Thing::getHandler) .ifPresent(theHandler -> ((UnitHandler) theHandler).handleStatus(unitStatus)); - } else if (status instanceof ExtendedZoneStatus) { - ExtendedZoneStatus zoneStatus = (ExtendedZoneStatus) status; + } else if (status instanceof ExtendedZoneStatus zoneStatus) { int zoneNumber = zoneStatus.getNumber(); logger.debug("Received status update for Zone: {}, status: {}", zoneNumber, zoneStatus); Optional theThing = getChildThing(THING_TYPE_ZONE, zoneNumber); theThing.map(Thing::getHandler) .ifPresent(theHandler -> ((ZoneHandler) theHandler).handleStatus(zoneStatus)); - } else if (status instanceof ExtendedAreaStatus) { - ExtendedAreaStatus areaStatus = (ExtendedAreaStatus) status; + } else if (status instanceof ExtendedAreaStatus areaStatus) { int areaNumber = areaStatus.getNumber(); logger.debug("Received status update for Area: {}, status: {}", areaNumber, areaStatus); @@ -321,16 +318,14 @@ public class OmnilinkBridgeHandler extends BaseBridgeHandler implements Notifica theThing.map(Thing::getHandler) .ifPresent(theHandler -> ((AbstractAreaHandler) theHandler).handleStatus(areaStatus)); }); - } else if (status instanceof ExtendedAccessControlReaderLockStatus) { - ExtendedAccessControlReaderLockStatus lockStatus = (ExtendedAccessControlReaderLockStatus) status; + } else if (status instanceof ExtendedAccessControlReaderLockStatus lockStatus) { int lockNumber = lockStatus.getNumber(); logger.debug("Received status update for Lock: {}, status: {}", lockNumber, lockStatus); Optional theThing = getChildThing(THING_TYPE_LOCK, lockNumber); theThing.map(Thing::getHandler) .ifPresent(theHandler -> ((LockHandler) theHandler).handleStatus(lockStatus)); - } else if (status instanceof ExtendedThermostatStatus) { - ExtendedThermostatStatus thermostatStatus = (ExtendedThermostatStatus) status; + } else if (status instanceof ExtendedThermostatStatus thermostatStatus) { int thermostatNumber = thermostatStatus.getNumber(); logger.debug("Received status update for Thermostat: {}, status: {}", thermostatNumber, @@ -338,8 +333,7 @@ public class OmnilinkBridgeHandler extends BaseBridgeHandler implements Notifica Optional theThing = getChildThing(THING_TYPE_THERMOSTAT, thermostatNumber); theThing.map(Thing::getHandler) .ifPresent(theHandler -> ((ThermostatHandler) theHandler).handleStatus(thermostatStatus)); - } else if (status instanceof ExtendedAudioZoneStatus) { - ExtendedAudioZoneStatus audioZoneStatus = (ExtendedAudioZoneStatus) status; + } else if (status instanceof ExtendedAudioZoneStatus audioZoneStatus) { int audioZoneNumber = audioZoneStatus.getNumber(); logger.debug("Received status update for Audio Zone: {}, status: {}", audioZoneNumber, @@ -347,8 +341,7 @@ public class OmnilinkBridgeHandler extends BaseBridgeHandler implements Notifica Optional theThing = getChildThing(THING_TYPE_AUDIO_ZONE, audioZoneNumber); theThing.map(Thing::getHandler) .ifPresent(theHandler -> ((AudioZoneHandler) theHandler).handleStatus(audioZoneStatus)); - } else if (status instanceof ExtendedAuxSensorStatus) { - ExtendedAuxSensorStatus auxSensorStatus = (ExtendedAuxSensorStatus) status; + } else if (status instanceof ExtendedAuxSensorStatus auxSensorStatus) { int auxSensorNumber = auxSensorStatus.getNumber(); // Aux Sensors can be either temperature or humidity, need to check both. diff --git a/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/handler/TempSensorHandler.java b/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/handler/TempSensorHandler.java index 97df80701..69cc15883 100644 --- a/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/handler/TempSensorHandler.java +++ b/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/handler/TempSensorHandler.java @@ -117,7 +117,7 @@ public class TempSensorHandler extends AbstractOmnilinkStatusHandler { piocRegister.set(PIOC_PE); diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/device/DS2423.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/device/DS2423.java index 6ee7d5439..160748df9 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/device/DS2423.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/device/DS2423.java @@ -52,7 +52,7 @@ public class DS2423 extends AbstractOwDevice { List states = bridgeHandler.readDecimalTypeArray(sensorId, counterParameter); if (states.size() != 2) { - throw new OwException("Expected exactly two values, got " + String.valueOf(states.size())); + throw new OwException("Expected exactly two values, got " + states.size()); } else { callback.postUpdate(CHANNEL_COUNTER + "0", states.get(0)); callback.postUpdate(CHANNEL_COUNTER + "1", states.get(1)); diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/device/DS2438.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/device/DS2438.java index caf92b18c..37fdb3b7b 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/device/DS2438.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/device/DS2438.java @@ -141,8 +141,8 @@ public class DS2438 extends AbstractOwDevice { if (enabledChannels.contains(CHANNEL_CURRENT)) { if (currentSensorType == CurrentSensorType.IBUTTONLINK) { State current = bridgeHandler.readDecimalType(sensorId, voltageParameter); - if (current instanceof DecimalType) { - double currentDouble = ((DecimalType) current).doubleValue(); + if (current instanceof DecimalType decimalCommand) { + double currentDouble = decimalCommand.doubleValue(); if (currentDouble >= 0.1 || currentDouble <= 3.78) { current = new QuantityType<>(currentDouble * 5.163 + 0.483, Units.AMPERE); } @@ -168,19 +168,17 @@ public class DS2438 extends AbstractOwDevice { switch (lightSensorType) { case ELABNET_V2: State light = bridgeHandler.readDecimalType(sensorId, currentParamater); - if (light instanceof DecimalType) { + if (light instanceof DecimalType decimalCommand) { light = new QuantityType<>( - Math.round(Math.pow(10, ((DecimalType) light).doubleValue() / 47 * 1000)), - Units.LUX); + Math.round(Math.pow(10, decimalCommand.doubleValue() / 47 * 1000)), Units.LUX); callback.postUpdate(CHANNEL_LIGHT, light); } break; case ELABNET_V1: light = bridgeHandler.readDecimalType(sensorId, currentParamater); - if (light instanceof DecimalType) { - light = new QuantityType<>(Math.round(Math - .exp(1.059 * Math.log(1000000 * ((DecimalType) light).doubleValue() / (4096 * 390)) - + 4.518) + if (light instanceof DecimalType decimalCommand) { + light = new QuantityType<>(Math.round(Math.exp( + 1.059 * Math.log(1000000 * decimalCommand.doubleValue() / (4096 * 390)) + 4.518) * 20000), Units.LUX); callback.postUpdate(CHANNEL_LIGHT, light); } diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/discovery/OwDiscoveryService.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/discovery/OwDiscoveryService.java index 0f6cac667..da245fb23 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/discovery/OwDiscoveryService.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/discovery/OwDiscoveryService.java @@ -142,8 +142,8 @@ public class OwDiscoveryService extends AbstractDiscoveryService implements Thin @Override public void setThingHandler(ThingHandler thingHandler) { - if (thingHandler instanceof OwserverBridgeHandler) { - this.bridgeHandler = (OwserverBridgeHandler) thingHandler; + if (thingHandler instanceof OwserverBridgeHandler serverBridgeHandler) { + this.bridgeHandler = serverBridgeHandler; } } diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/EDSSensorThingHandler.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/EDSSensorThingHandler.java index 122c29423..d3f3e13b0 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/EDSSensorThingHandler.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/EDSSensorThingHandler.java @@ -15,7 +15,6 @@ package org.openhab.binding.onewire.internal.handler; import static org.openhab.binding.onewire.internal.OwBindingConstants.*; import java.nio.charset.StandardCharsets; -import java.util.Collections; import java.util.Map; import java.util.Set; @@ -38,7 +37,7 @@ public class EDSSensorThingHandler extends OwBaseThingHandler { public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_EDS_ENV); public static final Set SUPPORTED_SENSOR_TYPES = Set.of(OwSensorType.EDS0064, OwSensorType.EDS0065, OwSensorType.EDS0066, OwSensorType.EDS0067, OwSensorType.EDS0068); - private static final Set REQUIRED_PROPERTIES = Collections.singleton(PROPERTY_HW_REVISION); + private static final Set REQUIRED_PROPERTIES = Set.of(PROPERTY_HW_REVISION); public EDSSensorThingHandler(Thing thing, OwDynamicStateDescriptionProvider dynamicStateDescriptionProvider) { super(thing, dynamicStateDescriptionProvider, SUPPORTED_SENSOR_TYPES, REQUIRED_PROPERTIES); @@ -78,7 +77,7 @@ public class EDSSensorThingHandler extends OwBaseThingHandler { properties.put(PROPERTY_MODELID, sensorType.name()); properties.put(PROPERTY_VENDOR, "Embedded Data Systems"); - properties.put(PROPERTY_HW_REVISION, String.valueOf(fwRevision)); + properties.put(PROPERTY_HW_REVISION, fwRevision); updateProperties(properties); } diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/OwserverBridgeHandler.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/OwserverBridgeHandler.java index 882760b7c..2f3eae8e1 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/OwserverBridgeHandler.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/OwserverBridgeHandler.java @@ -18,7 +18,6 @@ import java.math.BigDecimal; import java.util.ArrayList; import java.util.BitSet; import java.util.Collection; -import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Queue; @@ -62,7 +61,7 @@ import org.slf4j.LoggerFactory; */ @NonNullByDefault public class OwserverBridgeHandler extends BaseBridgeHandler { - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_OWSERVER); + public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_OWSERVER); private final Logger logger = LoggerFactory.getLogger(OwserverBridgeHandler.class); protected boolean refreshable = false; @@ -405,9 +404,9 @@ public class OwserverBridgeHandler extends BaseBridgeHandler { State value; try { synchronized (owserverConnection) { - if (channelConfig.acceptedItemType.equals("String")) { + if ("String".equals(channelConfig.acceptedItemType)) { value = new StringType(owserverConnection.readString(channelConfig.path)); - } else if (channelConfig.acceptedItemType.equals("Number")) { + } else if ("Number".equals(channelConfig.acceptedItemType)) { value = owserverConnection.readDecimalType(channelConfig.path); } else { logger.debug("mismatched configuration, itemType unknown for channel {}", diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/owserver/OwserverConnection.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/owserver/OwserverConnection.java index ed4326a17..f19fdbcc2 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/owserver/OwserverConnection.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/owserver/OwserverConnection.java @@ -303,7 +303,7 @@ public class OwserverConnection { } else { returnPacket = read(false); } - } while (returnPacket.isPingPacket() || !(returnPacket.hasPayload() == payloadExpected)); + } while (returnPacket.isPingPacket() || returnPacket.hasPayload() != payloadExpected); } catch (OwException e) { logger.debug("failed requesting {}->{} [{}]", requestPacket, returnPacket, e.getMessage()); diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/owserver/OwserverPacket.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/owserver/OwserverPacket.java index c4a2495b3..555ebcf8b 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/owserver/OwserverPacket.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/owserver/OwserverPacket.java @@ -42,7 +42,7 @@ public class OwserverPacket { protected int packetSize = 0; protected int payloadOffset = 0; - protected byte payload[] = new byte[0]; + protected byte[] payload = new byte[0]; /** * constructor for new packet diff --git a/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/internal/BasicThingHandlerTest.java b/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/internal/BasicThingHandlerTest.java index 7d1a4fa0b..2bb4cfe3f 100644 --- a/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/internal/BasicThingHandlerTest.java +++ b/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/internal/BasicThingHandlerTest.java @@ -83,9 +83,7 @@ public class BasicThingHandlerTest extends AbstractThingHandlerTest { return; } - Mockito.doAnswer(answer -> { - return OwSensorType.DS2401; - }).when(secondBridgeHandler).getType(any()); + Mockito.doAnswer(answer -> OwSensorType.DS2401).when(secondBridgeHandler).getType(any()); thingHandler.initialize(); @@ -101,9 +99,7 @@ public class BasicThingHandlerTest extends AbstractThingHandlerTest { return; } - Mockito.doAnswer(answer -> { - return OwSensorType.DS18B20; - }).when(secondBridgeHandler).getType(any()); + Mockito.doAnswer(answer -> OwSensorType.DS18B20).when(secondBridgeHandler).getType(any()); thingHandler.initialize(); waitForAssert(() -> assertEquals(ThingStatus.UNKNOWN, thingHandler.getThing().getStatusInfo().getStatus())); @@ -125,9 +121,7 @@ public class BasicThingHandlerTest extends AbstractThingHandlerTest { return; } - Mockito.doAnswer(answer -> { - return OwSensorType.DS2408; - }).when(secondBridgeHandler).getType(any()); + Mockito.doAnswer(answer -> OwSensorType.DS2408).when(secondBridgeHandler).getType(any()); thingHandler.initialize(); waitForAssert(() -> assertEquals(ThingStatus.UNKNOWN, thingHandler.getThing().getStatusInfo().getStatus())); diff --git a/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/internal/EDSSensorThingHandlerTest.java b/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/internal/EDSSensorThingHandlerTest.java index 8da6c6719..bd7778c20 100644 --- a/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/internal/EDSSensorThingHandlerTest.java +++ b/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/internal/EDSSensorThingHandlerTest.java @@ -87,9 +87,7 @@ public class EDSSensorThingHandlerTest extends AbstractThingHandlerTest { initializeHandlerMocks(); - Mockito.doAnswer(answer -> { - return new OwPageBuffer("EDS0065 ".getBytes()); - }).when(secondBridgeHandler).readPages(any()); + Mockito.doAnswer(answer -> new OwPageBuffer("EDS0065 ".getBytes())).when(secondBridgeHandler).readPages(any()); } @Test diff --git a/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/internal/MultisensorThingHandlerTest.java b/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/internal/MultisensorThingHandlerTest.java index c8cfde455..c0be6b89e 100644 --- a/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/internal/MultisensorThingHandlerTest.java +++ b/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/internal/MultisensorThingHandlerTest.java @@ -74,9 +74,7 @@ public class MultisensorThingHandlerTest extends AbstractThingHandlerTest { initializeHandlerMocks(); - Mockito.doAnswer(answer -> { - return OwSensorType.DS2438; - }).when(secondBridgeHandler).getType(any()); + Mockito.doAnswer(answer -> OwSensorType.DS2438).when(secondBridgeHandler).getType(any()); Mockito.doAnswer(answer -> { OwPageBuffer pageBuffer = new OwPageBuffer(8); diff --git a/bundles/org.openhab.binding.onewiregpio/src/main/java/org/openhab/binding/onewiregpio/internal/OneWireGPIOHandlerFactory.java b/bundles/org.openhab.binding.onewiregpio/src/main/java/org/openhab/binding/onewiregpio/internal/OneWireGPIOHandlerFactory.java index e2178b16b..026dfbafe 100644 --- a/bundles/org.openhab.binding.onewiregpio/src/main/java/org/openhab/binding/onewiregpio/internal/OneWireGPIOHandlerFactory.java +++ b/bundles/org.openhab.binding.onewiregpio/src/main/java/org/openhab/binding/onewiregpio/internal/OneWireGPIOHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.onewiregpio.internal; import static org.openhab.binding.onewiregpio.internal.OneWireGPIOBindingConstants.THING_TYPE; -import java.util.Collections; import java.util.Set; import org.openhab.binding.onewiregpio.internal.handler.OneWireGPIOHandler; @@ -34,7 +33,7 @@ import org.osgi.service.component.annotations.Component; @Component(service = ThingHandlerFactory.class, configurationPid = "binding.onewiregpio") public class OneWireGPIOHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE); @Override public boolean supportsThingType(ThingTypeUID thingTypeUID) { diff --git a/bundles/org.openhab.binding.onkyo/src/main/java/org/openhab/binding/onkyo/internal/automation/modules/OnkyoThingActions.java b/bundles/org.openhab.binding.onkyo/src/main/java/org/openhab/binding/onkyo/internal/automation/modules/OnkyoThingActions.java index b3ad248cc..458fb8fb8 100644 --- a/bundles/org.openhab.binding.onkyo/src/main/java/org/openhab/binding/onkyo/internal/automation/modules/OnkyoThingActions.java +++ b/bundles/org.openhab.binding.onkyo/src/main/java/org/openhab/binding/onkyo/internal/automation/modules/OnkyoThingActions.java @@ -54,8 +54,8 @@ public class OnkyoThingActions implements ThingActions { @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof OnkyoHandler) { - this.handler = (OnkyoHandler) handler; + if (handler instanceof OnkyoHandler onkyoHandler) { + this.handler = onkyoHandler; } } diff --git a/bundles/org.openhab.binding.onkyo/src/main/java/org/openhab/binding/onkyo/internal/eiscp/EiscpCommand.java b/bundles/org.openhab.binding.onkyo/src/main/java/org/openhab/binding/onkyo/internal/eiscp/EiscpCommand.java index c9bc37a51..250ba8ca3 100644 --- a/bundles/org.openhab.binding.onkyo/src/main/java/org/openhab/binding/onkyo/internal/eiscp/EiscpCommand.java +++ b/bundles/org.openhab.binding.onkyo/src/main/java/org/openhab/binding/onkyo/internal/eiscp/EiscpCommand.java @@ -162,7 +162,7 @@ public enum EiscpCommand { ZONE3_SOURCE_SET("SL3", "%02X"), ZONE3_SOURCE("SL3", ""); - public static enum Zone { + public enum Zone { MAIN, ZONE1, ZONE2, diff --git a/bundles/org.openhab.binding.onkyo/src/main/java/org/openhab/binding/onkyo/internal/eiscp/EiscpProtocol.java b/bundles/org.openhab.binding.onkyo/src/main/java/org/openhab/binding/onkyo/internal/eiscp/EiscpProtocol.java index 683bdba3c..f986e47df 100644 --- a/bundles/org.openhab.binding.onkyo/src/main/java/org/openhab/binding/onkyo/internal/eiscp/EiscpProtocol.java +++ b/bundles/org.openhab.binding.onkyo/src/main/java/org/openhab/binding/onkyo/internal/eiscp/EiscpProtocol.java @@ -137,7 +137,7 @@ public class EiscpProtocol { // version final byte versionChar = stream.readByte(); if (versionChar != 1) { - throw new EiscpException("Unsupported version " + String.valueOf(versionChar)); + throw new EiscpException("Unsupported version " + versionChar); } // skip 3 reserved bytes diff --git a/bundles/org.openhab.binding.onkyo/src/main/java/org/openhab/binding/onkyo/internal/handler/OnkyoHandler.java b/bundles/org.openhab.binding.onkyo/src/main/java/org/openhab/binding/onkyo/internal/handler/OnkyoHandler.java index e0dff912c..4b2570efc 100644 --- a/bundles/org.openhab.binding.onkyo/src/main/java/org/openhab/binding/onkyo/internal/handler/OnkyoHandler.java +++ b/bundles/org.openhab.binding.onkyo/src/main/java/org/openhab/binding/onkyo/internal/handler/OnkyoHandler.java @@ -18,7 +18,6 @@ import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.List; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -179,8 +178,8 @@ public class OnkyoHandler extends OnkyoUpnpHandler implements OnkyoEventListener handleVolumeSet(EiscpCommand.Zone.ZONE1, volumeLevelZone1, command); break; case CHANNEL_INPUT: - if (command instanceof DecimalType) { - selectInput(((DecimalType) command).intValue()); + if (command instanceof DecimalType decimalCommand) { + selectInput(decimalCommand.intValue()); } else if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.SOURCE_QUERY); } @@ -793,11 +792,11 @@ public class OnkyoHandler extends OnkyoUpnpHandler implements OnkyoEventListener } else if (command instanceof StringType) { val = String.format(valTemplate, command); - } else if (command instanceof DecimalType) { - val = String.format(valTemplate, ((DecimalType) command).intValue()); + } else if (command instanceof DecimalType decimalCommand) { + val = String.format(valTemplate, decimalCommand.intValue()); - } else if (command instanceof PercentType) { - val = String.format(valTemplate, ((DecimalType) command).intValue()); + } else if (command instanceof PercentType percentCommand) { + val = String.format(valTemplate, percentCommand.intValue()); } else { val = valTemplate; } @@ -857,12 +856,11 @@ public class OnkyoHandler extends OnkyoUpnpHandler implements OnkyoEventListener } private void handleVolumeSet(EiscpCommand.Zone zone, final State currentValue, final Command command) { - if (command instanceof PercentType) { - sendCommand(EiscpCommand.getCommandForZone(zone, EiscpCommand.VOLUME_SET), - downScaleVolume((PercentType) command)); + if (command instanceof PercentType percentCommand) { + sendCommand(EiscpCommand.getCommandForZone(zone, EiscpCommand.VOLUME_SET), downScaleVolume(percentCommand)); } else if (command.equals(IncreaseDecreaseType.INCREASE)) { - if (currentValue instanceof PercentType) { - if (((DecimalType) currentValue).intValue() < configuration.volumeLimit) { + if (currentValue instanceof PercentType percentCommand) { + if (percentCommand.intValue() < configuration.volumeLimit) { sendCommand(EiscpCommand.getCommandForZone(zone, EiscpCommand.VOLUME_UP)); } else { logger.info("Volume level is limited to {}, ignore volume up command.", configuration.volumeLimit); @@ -881,8 +879,8 @@ public class OnkyoHandler extends OnkyoUpnpHandler implements OnkyoEventListener } private State handleReceivedVolume(State volume) { - if (volume instanceof DecimalType) { - return upScaleVolume(((DecimalType) volume)); + if (volume instanceof DecimalType decimalCommand) { + return upScaleVolume(decimalCommand); } return volume; } @@ -921,8 +919,8 @@ public class OnkyoHandler extends OnkyoUpnpHandler implements OnkyoEventListener } public PercentType getVolume() throws IOException { - if (volumeLevelZone1 instanceof PercentType) { - return (PercentType) volumeLevelZone1; + if (volumeLevelZone1 instanceof PercentType percentCommand) { + return percentCommand; } throw new IOException(); @@ -944,6 +942,6 @@ public class OnkyoHandler extends OnkyoUpnpHandler implements OnkyoEventListener @Override public Collection> getServices() { - return Collections.singletonList(OnkyoThingActions.class); + return List.of(OnkyoThingActions.class); } } diff --git a/bundles/org.openhab.binding.onkyo/src/main/java/org/openhab/binding/onkyo/internal/handler/OnkyoUpnpHandler.java b/bundles/org.openhab.binding.onkyo/src/main/java/org/openhab/binding/onkyo/internal/handler/OnkyoUpnpHandler.java index c109edd72..08e266168 100644 --- a/bundles/org.openhab.binding.onkyo/src/main/java/org/openhab/binding/onkyo/internal/handler/OnkyoUpnpHandler.java +++ b/bundles/org.openhab.binding.onkyo/src/main/java/org/openhab/binding/onkyo/internal/handler/OnkyoUpnpHandler.java @@ -43,7 +43,7 @@ public abstract class OnkyoUpnpHandler extends BaseThingHandler implements UpnpI } protected void handlePlayUri(Command command) { - if (command != null && command instanceof StringType) { + if (command instanceof StringType) { try { playMedia(command.toString()); diff --git a/bundles/org.openhab.binding.opengarage/src/main/java/org/openhab/binding/opengarage/internal/OpenGarageBindingConstants.java b/bundles/org.openhab.binding.opengarage/src/main/java/org/openhab/binding/opengarage/internal/OpenGarageBindingConstants.java index 937a5fa66..02704100d 100644 --- a/bundles/org.openhab.binding.opengarage/src/main/java/org/openhab/binding/opengarage/internal/OpenGarageBindingConstants.java +++ b/bundles/org.openhab.binding.opengarage/src/main/java/org/openhab/binding/opengarage/internal/OpenGarageBindingConstants.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.opengarage.internal; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -41,5 +40,5 @@ public class OpenGarageBindingConstants { public static final String CHANNEL_OG_VEHICLE = "vehicle"; // now deprecated public static final String CHANNEL_OG_VEHICLE_STATUS = "vehicle-status"; - public static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(OPENGARAGE_THING); + public static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(OPENGARAGE_THING); } diff --git a/bundles/org.openhab.binding.opensprinkler/src/main/java/org/openhab/binding/opensprinkler/internal/OpenSprinklerState.java b/bundles/org.openhab.binding.opensprinkler/src/main/java/org/openhab/binding/opensprinkler/internal/OpenSprinklerState.java index 52263aa57..7deed6cd6 100644 --- a/bundles/org.openhab.binding.opensprinkler/src/main/java/org/openhab/binding/opensprinkler/internal/OpenSprinklerState.java +++ b/bundles/org.openhab.binding.opensprinkler/src/main/java/org/openhab/binding/opensprinkler/internal/OpenSprinklerState.java @@ -37,7 +37,7 @@ public class OpenSprinklerState { public List stations = new ArrayList<>(); public static class JsResponse { - public int sn[] = new int[8]; + public int[] sn = new int[8]; public int nstations = 8; } diff --git a/bundles/org.openhab.binding.opensprinkler/src/main/java/org/openhab/binding/opensprinkler/internal/discovery/OpenSprinklerDiscoveryService.java b/bundles/org.openhab.binding.opensprinkler/src/main/java/org/openhab/binding/opensprinkler/internal/discovery/OpenSprinklerDiscoveryService.java index 9c54d25e7..4851a9785 100644 --- a/bundles/org.openhab.binding.opensprinkler/src/main/java/org/openhab/binding/opensprinkler/internal/discovery/OpenSprinklerDiscoveryService.java +++ b/bundles/org.openhab.binding.opensprinkler/src/main/java/org/openhab/binding/opensprinkler/internal/discovery/OpenSprinklerDiscoveryService.java @@ -127,7 +127,7 @@ public class OpenSprinklerDiscoveryService extends AbstractDiscoveryService { InetAddress currentIP = InetAddress.getByAddress(ByteBuffer.allocate(4).putInt(i).array()); // Try to reach each IP with a timeout of 500ms which is enough for local network if (currentIP.isReachable(500)) { - String host = currentIP.getHostAddress().toString(); + String host = currentIP.getHostAddress(); logger.debug("Unknown device was found at: {}", host); discoverySearchPool.execute(new OpenSprinklerDiscoveryJob(this, host)); } diff --git a/bundles/org.openhab.binding.opensprinkler/src/main/java/org/openhab/binding/opensprinkler/internal/util/Hash.java b/bundles/org.openhab.binding.opensprinkler/src/main/java/org/openhab/binding/opensprinkler/internal/util/Hash.java index a614441a6..d49963a63 100644 --- a/bundles/org.openhab.binding.opensprinkler/src/main/java/org/openhab/binding/opensprinkler/internal/util/Hash.java +++ b/bundles/org.openhab.binding.opensprinkler/src/main/java/org/openhab/binding/opensprinkler/internal/util/Hash.java @@ -47,9 +47,7 @@ public class Hash { sb.append(String.format("%02x", b & 0xff)); } - String digest = sb.toString(); - - return digest; + return sb.toString(); } catch (Exception exp) { // Instead of null we return the unhashed password. return unhashed; diff --git a/bundles/org.openhab.binding.openthermgateway/src/main/java/org/openhab/binding/openthermgateway/handler/BaseDeviceHandler.java b/bundles/org.openhab.binding.openthermgateway/src/main/java/org/openhab/binding/openthermgateway/handler/BaseDeviceHandler.java index b4fcd9d92..fba16e343 100644 --- a/bundles/org.openhab.binding.openthermgateway/src/main/java/org/openhab/binding/openthermgateway/handler/BaseDeviceHandler.java +++ b/bundles/org.openhab.binding.openthermgateway/src/main/java/org/openhab/binding/openthermgateway/handler/BaseDeviceHandler.java @@ -85,11 +85,10 @@ public abstract class BaseDeviceHandler extends BaseThingHandler { } for (DataItem dataItem : dataItems) { - if (dataItem instanceof TspFhbSizeDataItem) { + if (dataItem instanceof TspFhbSizeDataItem sizeDataItem) { logger.debug("Received TSP or FHB size message {} ({})", message.getID(), dataItem.getSubject()); - verifyTspFhbChannels(((TspFhbSizeDataItem) dataItem).getValueId(), - message.getUInt(dataItem.getByteType())); + verifyTspFhbChannels(sizeDataItem.getValueId(), message.getUInt(dataItem.getByteType())); } else { String channelId = dataItem.getChannelId(message); diff --git a/bundles/org.openhab.binding.openthermgateway/src/main/java/org/openhab/binding/openthermgateway/handler/OpenThermGatewayHandler.java b/bundles/org.openhab.binding.openthermgateway/src/main/java/org/openhab/binding/openthermgateway/handler/OpenThermGatewayHandler.java index bb82111cb..a51534303 100644 --- a/bundles/org.openhab.binding.openthermgateway/src/main/java/org/openhab/binding/openthermgateway/handler/OpenThermGatewayHandler.java +++ b/bundles/org.openhab.binding.openthermgateway/src/main/java/org/openhab/binding/openthermgateway/handler/OpenThermGatewayHandler.java @@ -89,12 +89,11 @@ public class OpenThermGatewayHandler extends BaseBridgeHandler implements OpenTh GatewayCommand gatewayCommand = null; - if (command instanceof OnOffType) { - OnOffType onOff = (OnOffType) command; - gatewayCommand = GatewayCommand.parse(code, onOff == OnOffType.ON ? "1" : "0"); + if (command instanceof OnOffType onOffCommand) { + gatewayCommand = GatewayCommand.parse(code, onOffCommand == OnOffType.ON ? "1" : "0"); } - if (command instanceof QuantityType) { - QuantityType quantityType = ((QuantityType) command).toUnit(SIUnits.CELSIUS); + if (command instanceof QuantityType quantityCommand) { + QuantityType quantityType = quantityCommand.toUnit(SIUnits.CELSIUS); if (quantityType != null) { double value = quantityType.doubleValue(); @@ -109,19 +108,19 @@ public class OpenThermGatewayHandler extends BaseBridgeHandler implements OpenTh sendCommand(gatewayCommand); if (GatewayCommandCode.CONTROLSETPOINT.equals(code)) { - if (gatewayCommand.getMessage().equals("0.0")) { + if ("0.0".equals(gatewayCommand.getMessage())) { updateState(OpenThermGatewayBindingConstants.CHANNEL_OVERRIDE_CENTRAL_HEATING_WATER_SETPOINT, UnDefType.UNDEF); } updateState(OpenThermGatewayBindingConstants.CHANNEL_OVERRIDE_CENTRAL_HEATING_ENABLED, - OnOffType.from(!gatewayCommand.getMessage().equals("0.0"))); + OnOffType.from(!"0.0".equals(gatewayCommand.getMessage()))); } else if (GatewayCommandCode.CONTROLSETPOINT2.equals(code)) { - if (gatewayCommand.getMessage().equals("0.0")) { + if ("0.0".equals(gatewayCommand.getMessage())) { updateState(OpenThermGatewayBindingConstants.CHANNEL_OVERRIDE_CENTRAL_HEATING2_WATER_SETPOINT, UnDefType.UNDEF); } updateState(OpenThermGatewayBindingConstants.CHANNEL_OVERRIDE_CENTRAL_HEATING2_ENABLED, - OnOffType.from(!gatewayCommand.getMessage().equals("0.0"))); + OnOffType.from(!"0.0".equals(gatewayCommand.getMessage()))); } } } diff --git a/bundles/org.openhab.binding.openuv/src/main/java/org/openhab/binding/openuv/internal/json/OpenUVResult.java b/bundles/org.openhab.binding.openuv/src/main/java/org/openhab/binding/openuv/internal/json/OpenUVResult.java index 70a6cf6d3..fe4e0a545 100644 --- a/bundles/org.openhab.binding.openuv/src/main/java/org/openhab/binding/openuv/internal/json/OpenUVResult.java +++ b/bundles/org.openhab.binding.openuv/src/main/java/org/openhab/binding/openuv/internal/json/OpenUVResult.java @@ -45,7 +45,7 @@ public class OpenUVResult { @SerializedName("st5") V, // Fitzpatrick Skin Type V @SerializedName("st6") - VI;// Fitzpatrick Skin Type VI + VI// Fitzpatrick Skin Type VI } private double uv; diff --git a/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/actions/OpenWebNetCENActions.java b/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/actions/OpenWebNetCENActions.java index c062250f4..df066e136 100644 --- a/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/actions/OpenWebNetCENActions.java +++ b/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/actions/OpenWebNetCENActions.java @@ -84,8 +84,8 @@ public class OpenWebNetCENActions implements ThingActions { // legacy delegate methods public static void virtualPress(@Nullable ThingActions actions, @Nullable String press, int button) { - if (actions instanceof OpenWebNetCENActions) { - ((OpenWebNetCENActions) actions).virtualPress(press, button); + if (actions instanceof OpenWebNetCENActions openWebNetCENActions) { + openWebNetCENActions.virtualPress(press, button); } else { throw new IllegalArgumentException("Instance is not an OpenWebNetCENActions class."); } diff --git a/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/discovery/BusGatewayUpnpDiscovery.java b/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/discovery/BusGatewayUpnpDiscovery.java index e62431b21..d16613c15 100644 --- a/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/discovery/BusGatewayUpnpDiscovery.java +++ b/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/discovery/BusGatewayUpnpDiscovery.java @@ -13,7 +13,6 @@ package org.openhab.binding.openwebnet.internal.discovery; import java.util.Arrays; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; @@ -145,7 +144,7 @@ public class BusGatewayUpnpDiscovery implements UpnpDiscoveryParticipant { @Override public Set getSupportedThingTypeUIDs() { - return Collections.singleton(OpenWebNetBindingConstants.THING_TYPE_BUS_GATEWAY); + return Set.of(OpenWebNetBindingConstants.THING_TYPE_BUS_GATEWAY); } @Override diff --git a/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/discovery/OpenWebNetDeviceDiscoveryService.java b/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/discovery/OpenWebNetDeviceDiscoveryService.java index a4de4fb05..c7dc04aa0 100644 --- a/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/discovery/OpenWebNetDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/discovery/OpenWebNetDeviceDiscoveryService.java @@ -270,14 +270,14 @@ public class OpenWebNetDeviceDiscoveryService extends AbstractDiscoveryService whereConfig, properties.get(OpenWebNetBindingConstants.CONFIG_PROPERTY_STANDALONE)); } - if (w instanceof WhereZigBee && WhereZigBee.UNIT_02.equals(((WhereZigBee) w).getUnit())) { + if (w instanceof WhereZigBee whereZigBee && WhereZigBee.UNIT_02.equals(whereZigBee.getUnit())) { logger.debug("UNIT=02 found (WHERE={}) -> will remove previous result if exists", w); thingRemoved(thingUID); // remove previously discovered thing // re-create thingUID with new type thingTypeUID = OpenWebNetBindingConstants.THING_TYPE_ZB_ON_OFF_SWITCH_2UNITS; thingLabel = OpenWebNetBindingConstants.THING_LABEL_ZB_ON_OFF_SWITCH_2UNITS; thingUID = new ThingUID(thingTypeUID, bridgeUID, tId); - whereConfig = ((WhereZigBee) w).valueWithUnit(WhereZigBee.UNIT_ALL); // replace unit '02' with '00' + whereConfig = whereZigBee.valueWithUnit(WhereZigBee.UNIT_ALL); // replace unit '02' with '00' logger.debug("UNIT=02, switching type from {} to {}", OpenWebNetBindingConstants.THING_TYPE_ZB_ON_OFF_SWITCH, OpenWebNetBindingConstants.THING_TYPE_ZB_ON_OFF_SWITCH_2UNITS); @@ -302,9 +302,9 @@ public class OpenWebNetDeviceDiscoveryService extends AbstractDiscoveryService @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof OpenWebNetBridgeHandler) { + if (handler instanceof OpenWebNetBridgeHandler openWebNetBridgeHandler) { logger.debug("attaching {} to handler {} ", this, handler); - bridgeHandler = (OpenWebNetBridgeHandler) handler; + bridgeHandler = openWebNetBridgeHandler; bridgeHandler.deviceDiscoveryService = this; bridgeUID = bridgeHandler.getThing().getUID(); } diff --git a/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/discovery/UsbGatewayDiscoveryService.java b/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/discovery/UsbGatewayDiscoveryService.java index 48fb700c3..13a771ddd 100644 --- a/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/discovery/UsbGatewayDiscoveryService.java +++ b/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/discovery/UsbGatewayDiscoveryService.java @@ -12,9 +12,9 @@ */ package org.openhab.binding.openwebnet.internal.discovery; -import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -78,8 +78,7 @@ public class UsbGatewayDiscoveryService extends AbstractDiscoveryService impleme */ @Activate public UsbGatewayDiscoveryService(final @Reference SerialPortManager spm) { - super(Collections.singleton(OpenWebNetBindingConstants.THING_TYPE_ZB_GATEWAY), DISCOVERY_TIMEOUT_SECONDS, - false); + super(Set.of(OpenWebNetBindingConstants.THING_TYPE_ZB_GATEWAY), DISCOVERY_TIMEOUT_SECONDS, false); // Obtain the serial port manager service using an OSGi reference serialPortManager = spm; } diff --git a/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/handler/OpenWebNetAutomationHandler.java b/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/handler/OpenWebNetAutomationHandler.java index e5ba0561c..0618ee655 100644 --- a/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/handler/OpenWebNetAutomationHandler.java +++ b/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/handler/OpenWebNetAutomationHandler.java @@ -107,12 +107,12 @@ public class OpenWebNetAutomationHandler extends OpenWebNetThingHandler { if (shutterRunConfig == null) { shutterRunConfig = AUTO_CALIBRATION; logger.debug("shutterRun null --> default to AUTO"); - } else if (shutterRunConfig instanceof String) { - if (AUTO_CALIBRATION.equalsIgnoreCase(((String) shutterRunConfig))) { + } else if (shutterRunConfig instanceof String stringValue) { + if (AUTO_CALIBRATION.equalsIgnoreCase(stringValue)) { logger.debug("shutterRun set to AUTO via configuration"); shutterRun = SHUTTER_RUN_UNDEFINED; // reset shutterRun } else { // try to parse int>=1000 - int shutterRunInt = Integer.parseInt((String) shutterRunConfig); + int shutterRunInt = Integer.parseInt(stringValue); if (shutterRunInt < 1000) { throw new NumberFormatException(); } @@ -210,8 +210,8 @@ public class OpenWebNetAutomationHandler extends OpenWebNetThingHandler { } else { send(Automation.requestMoveDown(w.value())); } - } else if (command instanceof PercentType) { - handlePercentCommand((PercentType) command, w.value()); + } else if (command instanceof PercentType percentCommand) { + handlePercentCommand(percentCommand, w.value()); } } } else { diff --git a/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/handler/OpenWebNetBridgeHandler.java b/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/handler/OpenWebNetBridgeHandler.java index 6522eae33..05139bded 100644 --- a/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/handler/OpenWebNetBridgeHandler.java +++ b/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/handler/OpenWebNetBridgeHandler.java @@ -268,7 +268,7 @@ public class OpenWebNetBridgeHandler extends ConfigStatusBridgeHandler implement @Override public Collection> getServices() { - return Collections.singleton(OpenWebNetDeviceDiscoveryService.class); + return Set.of(OpenWebNetDeviceDiscoveryService.class); } /** @@ -505,8 +505,7 @@ public class OpenWebNetBridgeHandler extends ConfigStatusBridgeHandler implement return; // we ignore ACKS/NACKS } // GATEWAY MANAGEMENT - if (msg instanceof GatewayMgmt) { - GatewayMgmt gwMsg = (GatewayMgmt) msg; + if (msg instanceof GatewayMgmt gwMsg) { if (dateTimeSynch && GatewayMgmt.DimGatewayMgmt.DATETIME.equals(gwMsg.getDim())) { checkDateTimeDiff(gwMsg); } @@ -573,9 +572,9 @@ public class OpenWebNetBridgeHandler extends ConfigStatusBridgeHandler implement logger.warn("received onConnected() but gateway is null"); return; } - if (gw instanceof USBGateway) { + if (gw instanceof USBGateway usbGateway) { logger.info("---- CONNECTED to Zigbee USB gateway bridge '{}' (serialPort: {})", thing.getUID(), - ((USBGateway) gw).getSerialPortName()); + usbGateway.getSerialPortName()); } else { logger.info("---- CONNECTED to BUS gateway bridge '{}' ({}:{})", thing.getUID(), ((BUSGateway) gw).getHost(), ((BUSGateway) gw).getPort()); @@ -736,8 +735,8 @@ public class OpenWebNetBridgeHandler extends ConfigStatusBridgeHandler implement */ public String normalizeWhere(Where where) { String str = where.value(); - if (where instanceof WhereZigBee) { - str = ((WhereZigBee) where).valueWithUnit(WhereZigBee.UNIT_ALL); // 76543210X#9 --> 765432100#9 + if (where instanceof WhereZigBee whereZigBee) { + str = whereZigBee.valueWithUnit(WhereZigBee.UNIT_ALL); // 76543210X#9 --> 765432100#9 } else { if (str.indexOf("#4#") == -1) { // skip APL#4#bus case if (str.indexOf('#') == 0) { // Thermo central unit (#0) or zone via central unit (#Z, Z=[1-99]) --> Z, diff --git a/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/handler/OpenWebNetLightingHandler.java b/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/handler/OpenWebNetLightingHandler.java index 639b16eea..d00a3bb76 100644 --- a/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/handler/OpenWebNetLightingHandler.java +++ b/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/handler/OpenWebNetLightingHandler.java @@ -169,8 +169,8 @@ public class OpenWebNetLightingHandler extends OpenWebNetThingHandler { */ private void handleBrightnessCommand(Command command) { logger.debug("handleBrightnessCommand() command={}", command); - if (command instanceof PercentType) { - dimLightTo(((PercentType) command).intValue(), command); + if (command instanceof PercentType percentCommand) { + dimLightTo(percentCommand.intValue(), command); } else if (command instanceof IncreaseDecreaseType) { if (IncreaseDecreaseType.INCREASE.equals(command)) { dimLightTo(brightness + 10, command); diff --git a/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/handler/OpenWebNetScenarioHandler.java b/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/handler/OpenWebNetScenarioHandler.java index 8f8974728..e62342936 100644 --- a/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/handler/OpenWebNetScenarioHandler.java +++ b/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/handler/OpenWebNetScenarioHandler.java @@ -16,7 +16,6 @@ import static org.openhab.binding.openwebnet.internal.OpenWebNetBindingConstants import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.Optional; import java.util.Scanner; import java.util.Set; @@ -162,7 +161,7 @@ public class OpenWebNetScenarioHandler extends OpenWebNetThingHandler { @Override public Collection> getServices() { - return Collections.singleton(OpenWebNetCENActions.class); + return Set.of(OpenWebNetCENActions.class); } @Override diff --git a/bundles/org.openhab.binding.oppo/src/main/java/org/openhab/binding/oppo/internal/OppoHandlerFactory.java b/bundles/org.openhab.binding.oppo/src/main/java/org/openhab/binding/oppo/internal/OppoHandlerFactory.java index 10d2db5cf..d4ba57c25 100644 --- a/bundles/org.openhab.binding.oppo/src/main/java/org/openhab/binding/oppo/internal/OppoHandlerFactory.java +++ b/bundles/org.openhab.binding.oppo/src/main/java/org/openhab/binding/oppo/internal/OppoHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.oppo.internal; import static org.openhab.binding.oppo.internal.OppoBindingConstants.*; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -39,7 +38,7 @@ import org.osgi.service.component.annotations.Reference; @NonNullByDefault @Component(configurationPid = "binding.oppo", service = ThingHandlerFactory.class) public class OppoHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_PLAYER); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_PLAYER); private final SerialPortManager serialPortManager; @@ -62,9 +61,7 @@ public class OppoHandlerFactory extends BaseThingHandlerFactory { ThingTypeUID thingTypeUID = thing.getThingTypeUID(); if (SUPPORTED_THING_TYPES_UIDS.contains(thingTypeUID)) { - OppoHandler handler = new OppoHandler(thing, stateDescriptionProvider, serialPortManager); - - return handler; + return new OppoHandler(thing, stateDescriptionProvider, serialPortManager); } return null; } diff --git a/bundles/org.openhab.binding.oppo/src/main/java/org/openhab/binding/oppo/internal/discovery/OppoDiscoveryService.java b/bundles/org.openhab.binding.oppo/src/main/java/org/openhab/binding/oppo/internal/discovery/OppoDiscoveryService.java index 09d9961f8..998482d06 100644 --- a/bundles/org.openhab.binding.oppo/src/main/java/org/openhab/binding/oppo/internal/discovery/OppoDiscoveryService.java +++ b/bundles/org.openhab.binding.oppo/src/main/java/org/openhab/binding/oppo/internal/discovery/OppoDiscoveryService.java @@ -53,7 +53,7 @@ import org.slf4j.LoggerFactory; @NonNullByDefault @Component(service = DiscoveryService.class, configurationPid = "discovery.oppo") public class OppoDiscoveryService extends AbstractDiscoveryService { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_PLAYER); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_PLAYER); private final Logger logger = LoggerFactory.getLogger(OppoDiscoveryService.class); diff --git a/bundles/org.openhab.binding.oppo/src/main/java/org/openhab/binding/oppo/internal/handler/OppoHandler.java b/bundles/org.openhab.binding.oppo/src/main/java/org/openhab/binding/oppo/internal/handler/OppoHandler.java index 6030544a4..e7d5f24f0 100644 --- a/bundles/org.openhab.binding.oppo/src/main/java/org/openhab/binding/oppo/internal/handler/OppoHandler.java +++ b/bundles/org.openhab.binding.oppo/src/main/java/org/openhab/binding/oppo/internal/handler/OppoHandler.java @@ -268,8 +268,8 @@ public class OppoHandler extends BaseThingHandler implements OppoMessageEventLis } break; case CHANNEL_SOURCE: - if (command instanceof DecimalType) { - int value = ((DecimalType) command).intValue(); + if (command instanceof DecimalType decimalCommand) { + int value = decimalCommand.intValue(); connector.sendCommand(OppoCommand.SET_INPUT_SOURCE, String.valueOf(value)); } break; @@ -297,14 +297,14 @@ public class OppoHandler extends BaseThingHandler implements OppoMessageEventLis } break; case CHANNEL_SUB_SHIFT: - if (command instanceof DecimalType) { - int value = ((DecimalType) command).intValue(); + if (command instanceof DecimalType decimalCommand) { + int value = decimalCommand.intValue(); connector.sendCommand(OppoCommand.SET_SUBTITLE_SHIFT, String.valueOf(value)); } break; case CHANNEL_OSD_POSITION: - if (command instanceof DecimalType) { - int value = ((DecimalType) command).intValue(); + if (command instanceof DecimalType decimalCommand) { + int value = decimalCommand.intValue(); connector.sendCommand(OppoCommand.SET_OSD_POSITION, String.valueOf(value)); } break; @@ -843,7 +843,7 @@ public class OppoHandler extends BaseThingHandler implements OppoMessageEventLis if (model == MODEL83 || model == MODEL103 || model == MODEL105) { hdmiModeOptions.add(new StateOption("AUTO", "Auto")); hdmiModeOptions.add(new StateOption("SRC", "Source Direct")); - if (!(model == MODEL83)) { + if (model != MODEL83) { hdmiModeOptions.add(new StateOption("4K2K", "4K*2K")); } hdmiModeOptions.add(new StateOption("1080P", "1080P")); diff --git a/bundles/org.openhab.binding.orbitbhyve/src/main/java/org/openhab/binding/orbitbhyve/internal/discovery/OrbitBhyveDiscoveryService.java b/bundles/org.openhab.binding.orbitbhyve/src/main/java/org/openhab/binding/orbitbhyve/internal/discovery/OrbitBhyveDiscoveryService.java index 21dcdc79f..41a3992fb 100644 --- a/bundles/org.openhab.binding.orbitbhyve/src/main/java/org/openhab/binding/orbitbhyve/internal/discovery/OrbitBhyveDiscoveryService.java +++ b/bundles/org.openhab.binding.orbitbhyve/src/main/java/org/openhab/binding/orbitbhyve/internal/discovery/OrbitBhyveDiscoveryService.java @@ -14,7 +14,6 @@ package org.openhab.binding.orbitbhyve.internal.discovery; import static org.openhab.binding.orbitbhyve.internal.OrbitBhyveBindingConstants.THING_TYPE_SPRINKLER; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -79,8 +78,8 @@ public class OrbitBhyveDiscoveryService extends AbstractDiscoveryService @Override public void setThingHandler(@Nullable ThingHandler thingHandler) { - if (thingHandler instanceof OrbitBhyveBridgeHandler) { - bridgeHandler = (OrbitBhyveBridgeHandler) thingHandler; + if (thingHandler instanceof OrbitBhyveBridgeHandler bridgeHandler) { + this.bridgeHandler = bridgeHandler; } } @@ -145,6 +144,6 @@ public class OrbitBhyveDiscoveryService extends AbstractDiscoveryService @Override public Set getSupportedThingTypes() { - return Collections.singleton(THING_TYPE_SPRINKLER); + return Set.of(THING_TYPE_SPRINKLER); } } diff --git a/bundles/org.openhab.binding.orbitbhyve/src/main/java/org/openhab/binding/orbitbhyve/internal/handler/OrbitBhyveBridgeHandler.java b/bundles/org.openhab.binding.orbitbhyve/src/main/java/org/openhab/binding/orbitbhyve/internal/handler/OrbitBhyveBridgeHandler.java index 90b91d9fd..d0a7aadd7 100644 --- a/bundles/org.openhab.binding.orbitbhyve/src/main/java/org/openhab/binding/orbitbhyve/internal/handler/OrbitBhyveBridgeHandler.java +++ b/bundles/org.openhab.binding.orbitbhyve/src/main/java/org/openhab/binding/orbitbhyve/internal/handler/OrbitBhyveBridgeHandler.java @@ -23,6 +23,7 @@ import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; +import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.ScheduledFuture; @@ -109,7 +110,7 @@ public class OrbitBhyveBridgeHandler extends ConfigStatusBridgeHandler { @Override public Collection> getServices() { - return Collections.singleton(OrbitBhyveDiscoveryService.class); + return Set.of(OrbitBhyveDiscoveryService.class); } @Override @@ -230,8 +231,7 @@ public class OrbitBhyveBridgeHandler extends ConfigStatusBridgeHandler { if (logger.isTraceEnabled()) { logger.trace("Device response: {}", response.getContentAsString()); } - OrbitBhyveDevice device = gson.fromJson(response.getContentAsString(), OrbitBhyveDevice.class); - return device; + return gson.fromJson(response.getContentAsString(), OrbitBhyveDevice.class); } else { logger.debug("Returned status: {}", response.getStatus()); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, @@ -316,10 +316,10 @@ public class OrbitBhyveBridgeHandler extends ConfigStatusBridgeHandler { if (th.isEnabled()) { String deviceId = th.getUID().getId(); ThingHandler handler = th.getHandler(); - if (handler instanceof OrbitBhyveSprinklerHandler) { + if (handler instanceof OrbitBhyveSprinklerHandler sprinklerHandler) { for (OrbitBhyveDevice device : devices) { if (deviceId.equals(th.getUID().getId())) { - updateDeviceStatus(device, (OrbitBhyveSprinklerHandler) handler); + updateDeviceStatus(device, sprinklerHandler); } } } @@ -340,9 +340,9 @@ public class OrbitBhyveBridgeHandler extends ConfigStatusBridgeHandler { for (Thing th : getThing().getThings()) { if (deviceId.equals(th.getUID().getId())) { ThingHandler handler = th.getHandler(); - if (handler instanceof OrbitBhyveSprinklerHandler) { + if (handler instanceof OrbitBhyveSprinklerHandler sprinklerHandler) { OrbitBhyveDevice device = getDevice(deviceId); - updateDeviceStatus(device, (OrbitBhyveSprinklerHandler) handler); + updateDeviceStatus(device, sprinklerHandler); } } } @@ -352,8 +352,8 @@ public class OrbitBhyveBridgeHandler extends ConfigStatusBridgeHandler { for (Thing th : getThing().getThings()) { if (program.getDeviceId().equals(th.getUID().getId())) { ThingHandler handler = th.getHandler(); - if (handler instanceof OrbitBhyveSprinklerHandler) { - ((OrbitBhyveSprinklerHandler) handler).updateProgram(program); + if (handler instanceof OrbitBhyveSprinklerHandler sprinklerHandler) { + sprinklerHandler.updateProgram(program); } } } diff --git a/bundles/org.openhab.binding.orbitbhyve/src/main/java/org/openhab/binding/orbitbhyve/internal/handler/OrbitBhyveSprinklerHandler.java b/bundles/org.openhab.binding.orbitbhyve/src/main/java/org/openhab/binding/orbitbhyve/internal/handler/OrbitBhyveSprinklerHandler.java index d5bbba1c2..2f20e03b5 100644 --- a/bundles/org.openhab.binding.orbitbhyve/src/main/java/org/openhab/binding/orbitbhyve/internal/handler/OrbitBhyveSprinklerHandler.java +++ b/bundles/org.openhab.binding.orbitbhyve/src/main/java/org/openhab/binding/orbitbhyve/internal/handler/OrbitBhyveSprinklerHandler.java @@ -81,8 +81,8 @@ public class OrbitBhyveSprinklerHandler extends BaseThingHandler { handler.stopWatering(deviceId); return; } - if (CHANNEL_WATERING_TIME.equals(channelUID.getId()) && command instanceof QuantityType) { - final QuantityType value = ((QuantityType) command).toUnit(Units.MINUTE); + if (CHANNEL_WATERING_TIME.equals(channelUID.getId()) && command instanceof QuantityType quantityCommand) { + final QuantityType value = quantityCommand.toUnit(Units.MINUTE); if (value != null) { wateringTime = value.intValue(); } diff --git a/bundles/org.openhab.binding.orvibo/src/main/java/org/openhab/binding/orvibo/internal/OrviboHandlerFactory.java b/bundles/org.openhab.binding.orvibo/src/main/java/org/openhab/binding/orvibo/internal/OrviboHandlerFactory.java index 2a475339b..199f73a90 100644 --- a/bundles/org.openhab.binding.orvibo/src/main/java/org/openhab/binding/orvibo/internal/OrviboHandlerFactory.java +++ b/bundles/org.openhab.binding.orvibo/src/main/java/org/openhab/binding/orvibo/internal/OrviboHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.orvibo.internal; import static org.openhab.binding.orvibo.internal.OrviboBindingConstants.THING_TYPE_S20; -import java.util.Collections; import java.util.Set; import org.openhab.binding.orvibo.internal.handler.S20Handler; @@ -34,7 +33,7 @@ import org.osgi.service.component.annotations.Component; @Component(service = ThingHandlerFactory.class, configurationPid = "binding.orvibo") public class OrviboHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_S20); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_S20); @Override public boolean supportsThingType(ThingTypeUID thingTypeUID) { diff --git a/bundles/org.openhab.binding.orvibo/src/main/java/org/openhab/binding/orvibo/internal/discovery/SocketDiscoveryService.java b/bundles/org.openhab.binding.orvibo/src/main/java/org/openhab/binding/orvibo/internal/discovery/SocketDiscoveryService.java index 9e8eafd46..990fbec60 100644 --- a/bundles/org.openhab.binding.orvibo/src/main/java/org/openhab/binding/orvibo/internal/discovery/SocketDiscoveryService.java +++ b/bundles/org.openhab.binding.orvibo/src/main/java/org/openhab/binding/orvibo/internal/discovery/SocketDiscoveryService.java @@ -13,7 +13,6 @@ package org.openhab.binding.orvibo.internal.discovery; import java.net.SocketException; -import java.util.Collections; import java.util.Map; import java.util.Set; @@ -50,7 +49,7 @@ public class SocketDiscoveryService extends AbstractDiscoveryService implements } private static Set getSupportedThingTypeUIDs() { - return Collections.singleton(OrviboBindingConstants.THING_TYPE_S20); + return Set.of(OrviboBindingConstants.THING_TYPE_S20); } @Override @@ -109,8 +108,7 @@ public class SocketDiscoveryService extends AbstractDiscoveryService implements } private ThingUID getUID(Socket socket) { - ThingUID thingUID = new ThingUID(OrviboBindingConstants.THING_TYPE_S20, socket.getDeviceId()); - return thingUID; + return new ThingUID(OrviboBindingConstants.THING_TYPE_S20, socket.getDeviceId()); } private void doThingDiscovered(Socket socket) { diff --git a/bundles/org.openhab.binding.paradoxalarm/src/main/java/org/openhab/binding/paradoxalarm/internal/communication/CommunicationState.java b/bundles/org.openhab.binding.paradoxalarm/src/main/java/org/openhab/binding/paradoxalarm/internal/communication/CommunicationState.java index 56c8a367b..0e8bcc593 100644 --- a/bundles/org.openhab.binding.paradoxalarm/src/main/java/org/openhab/binding/paradoxalarm/internal/communication/CommunicationState.java +++ b/bundles/org.openhab.binding.paradoxalarm/src/main/java/org/openhab/binding/paradoxalarm/internal/communication/CommunicationState.java @@ -225,7 +225,7 @@ public enum CommunicationState implements IResponseReceiver { } private byte[] generateInitializationRequest(byte[] initializationMessage, byte[] pcPassword) { - byte[] message7 = new byte[] { + return new byte[] { // Initialization command 0x00, @@ -282,7 +282,6 @@ public enum CommunicationState implements IResponseReceiver { // Checksum 0x00 }; - return message7; } @Override @@ -290,11 +289,10 @@ public enum CommunicationState implements IResponseReceiver { // UGLY - this is the handling of ghost packet which appears after the logon sequence // Read ghost packet affter 300ms then continue with normal flow communicator.getScheduler().schedule(() -> { - if (communicator instanceof GenericCommunicator) { + if (communicator instanceof GenericCommunicator genericCommunicator) { try { - GenericCommunicator genCommunicator = (GenericCommunicator) communicator; byte[] value = new byte[256]; - int packetLength = genCommunicator.getRx().read(value); + int packetLength = genericCommunicator.getRx().read(value); logger.debug("Reading ghost packet with length={}", packetLength); ParadoxUtil.printPacket("Reading ghost packet", value); } catch (IOException e) { @@ -315,8 +313,7 @@ public enum CommunicationState implements IResponseReceiver { @Override protected void runPhase(IParadoxInitialLoginCommunicator communicator, Object... args) { - if (communicator instanceof IParadoxCommunicator) { - IParadoxCommunicator comm = (IParadoxCommunicator) communicator; + if (communicator instanceof IParadoxCommunicator comm) { comm.initializeData(); } nextState().runPhase(communicator); diff --git a/bundles/org.openhab.binding.paradoxalarm/src/main/java/org/openhab/binding/paradoxalarm/internal/communication/crypto/EncryptionHandler.java b/bundles/org.openhab.binding.paradoxalarm/src/main/java/org/openhab/binding/paradoxalarm/internal/communication/crypto/EncryptionHandler.java index a87bacd46..078ef7adf 100644 --- a/bundles/org.openhab.binding.paradoxalarm/src/main/java/org/openhab/binding/paradoxalarm/internal/communication/crypto/EncryptionHandler.java +++ b/bundles/org.openhab.binding.paradoxalarm/src/main/java/org/openhab/binding/paradoxalarm/internal/communication/crypto/EncryptionHandler.java @@ -163,8 +163,7 @@ public class EncryptionHandler { byteArray[i] = (byte) (keyBytes[i] & 0xFF); } - byte[] expandedArray = ParadoxUtil.extendArray(byteArray, KEY_ARRAY_LENGTH); - return expandedArray; + return ParadoxUtil.extendArray(byteArray, KEY_ARRAY_LENGTH); } private void expandKey(byte[] input) { diff --git a/bundles/org.openhab.binding.paradoxalarm/src/main/java/org/openhab/binding/paradoxalarm/internal/discovery/ParadoxDiscoveryService.java b/bundles/org.openhab.binding.paradoxalarm/src/main/java/org/openhab/binding/paradoxalarm/internal/discovery/ParadoxDiscoveryService.java index ba014c821..7359267b8 100644 --- a/bundles/org.openhab.binding.paradoxalarm/src/main/java/org/openhab/binding/paradoxalarm/internal/discovery/ParadoxDiscoveryService.java +++ b/bundles/org.openhab.binding.paradoxalarm/src/main/java/org/openhab/binding/paradoxalarm/internal/discovery/ParadoxDiscoveryService.java @@ -98,7 +98,7 @@ public class ParadoxDiscoveryService extends AbstractDiscoveryService { private void discoverZones(List zones) { zones.stream().forEach(zone -> { - String thingId = zone.getLabel().replaceAll(" ", "_"); + String thingId = zone.getLabel().replace(" ", "_"); String label = zone.getLabel(); ThingUID bridgeUid = ip150BridgeHandler.getThing().getUID(); diff --git a/bundles/org.openhab.binding.paradoxalarm/src/main/java/org/openhab/binding/paradoxalarm/internal/handlers/ParadoxPartitionHandler.java b/bundles/org.openhab.binding.paradoxalarm/src/main/java/org/openhab/binding/paradoxalarm/internal/handlers/ParadoxPartitionHandler.java index 99855a25f..bfdcd92f6 100644 --- a/bundles/org.openhab.binding.paradoxalarm/src/main/java/org/openhab/binding/paradoxalarm/internal/handlers/ParadoxPartitionHandler.java +++ b/bundles/org.openhab.binding.paradoxalarm/src/main/java/org/openhab/binding/paradoxalarm/internal/handlers/ParadoxPartitionHandler.java @@ -121,7 +121,6 @@ public class ParadoxPartitionHandler extends EntityBaseHandler { return null; } - Partition partition = partitions.get(index); - return partition; + return partitions.get(index); } } diff --git a/bundles/org.openhab.binding.paradoxalarm/src/main/java/org/openhab/binding/paradoxalarm/internal/handlers/ParadoxZoneHandler.java b/bundles/org.openhab.binding.paradoxalarm/src/main/java/org/openhab/binding/paradoxalarm/internal/handlers/ParadoxZoneHandler.java index c2ab9c150..b9e620216 100644 --- a/bundles/org.openhab.binding.paradoxalarm/src/main/java/org/openhab/binding/paradoxalarm/internal/handlers/ParadoxZoneHandler.java +++ b/bundles/org.openhab.binding.paradoxalarm/src/main/java/org/openhab/binding/paradoxalarm/internal/handlers/ParadoxZoneHandler.java @@ -131,8 +131,7 @@ public class ParadoxZoneHandler extends EntityBaseHandler { return null; } - Zone zone = zones.get(index); - return zone; + return zones.get(index); } private ParadoxIP150BridgeHandler getBridgeHandler() { diff --git a/bundles/org.openhab.binding.paradoxalarm/src/main/java/org/openhab/binding/paradoxalarm/internal/util/ParadoxUtil.java b/bundles/org.openhab.binding.paradoxalarm/src/main/java/org/openhab/binding/paradoxalarm/internal/util/ParadoxUtil.java index 1624b9d24..bad674aff 100644 --- a/bundles/org.openhab.binding.paradoxalarm/src/main/java/org/openhab/binding/paradoxalarm/internal/util/ParadoxUtil.java +++ b/bundles/org.openhab.binding.paradoxalarm/src/main/java/org/openhab/binding/paradoxalarm/internal/util/ParadoxUtil.java @@ -129,8 +129,7 @@ public class ParadoxUtil { for (byte[] array : arrays) { outputStream.write(array); } - byte[] byteArray = outputStream.toByteArray(); - return byteArray; + return outputStream.toByteArray(); } catch (IOException e) { LOGGER.warn("Exception merging arrays:", e); return new byte[0]; diff --git a/bundles/org.openhab.binding.pentair/src/main/java/org/openhab/binding/pentair/internal/handler/PentairBaseBridgeHandler.java b/bundles/org.openhab.binding.pentair/src/main/java/org/openhab/binding/pentair/internal/handler/PentairBaseBridgeHandler.java index ab3f0f84a..e3629a96c 100644 --- a/bundles/org.openhab.binding.pentair/src/main/java/org/openhab/binding/pentair/internal/handler/PentairBaseBridgeHandler.java +++ b/bundles/org.openhab.binding.pentair/src/main/java/org/openhab/binding/pentair/internal/handler/PentairBaseBridgeHandler.java @@ -246,7 +246,7 @@ public abstract class PentairBaseBridgeHandler extends BaseBridgeHandler { @Override public void run() { logger.debug("parser thread started"); - byte buf[] = new byte[40]; + byte[] buf = new byte[40]; int c; int chksum, i, length; Thing thing; diff --git a/bundles/org.openhab.binding.pentair/src/main/java/org/openhab/binding/pentair/internal/handler/PentairEasyTouchHandler.java b/bundles/org.openhab.binding.pentair/src/main/java/org/openhab/binding/pentair/internal/handler/PentairEasyTouchHandler.java index 12f753c69..cb0e47f97 100644 --- a/bundles/org.openhab.binding.pentair/src/main/java/org/openhab/binding/pentair/internal/handler/PentairEasyTouchHandler.java +++ b/bundles/org.openhab.binding.pentair/src/main/java/org/openhab/binding/pentair/internal/handler/PentairEasyTouchHandler.java @@ -98,8 +98,8 @@ public class PentairEasyTouchHandler extends PentairBaseThingHandler { return; } - if (command instanceof OnOffType) { - boolean state = ((OnOffType) command) == OnOffType.ON; + if (command instanceof OnOffType onOffCommand) { + boolean state = onOffCommand == OnOffType.ON; switch (channelUID.getId()) { case EASYTOUCH_POOL: @@ -154,8 +154,8 @@ public class PentairEasyTouchHandler extends PentairBaseThingHandler { circuitSwitch(18, state); break; } - } else if (command instanceof DecimalType) { - int sp = ((DecimalType) command).intValue(); + } else if (command instanceof DecimalType decimalCommand) { + int sp = decimalCommand.intValue(); switch (channelUID.getId()) { case EASYTOUCH_SPASETPOINT: diff --git a/bundles/org.openhab.binding.pentair/src/main/java/org/openhab/binding/pentair/internal/handler/PentairSerialBridgeHandler.java b/bundles/org.openhab.binding.pentair/src/main/java/org/openhab/binding/pentair/internal/handler/PentairSerialBridgeHandler.java index 7e9bc0a96..66f59b3b8 100644 --- a/bundles/org.openhab.binding.pentair/src/main/java/org/openhab/binding/pentair/internal/handler/PentairSerialBridgeHandler.java +++ b/bundles/org.openhab.binding.pentair/src/main/java/org/openhab/binding/pentair/internal/handler/PentairSerialBridgeHandler.java @@ -57,8 +57,8 @@ public class PentairSerialBridgeHandler extends PentairBaseBridgeHandler { throw new IllegalStateException("cannot open serial port!"); } - if (cp instanceof SerialPort) { - port = (SerialPort) cp; + if (cp instanceof SerialPort serialPort) { + port = serialPort; } else { throw new IllegalStateException("unknown port type"); } diff --git a/bundles/org.openhab.binding.phc/src/main/java/org/openhab/binding/phc/internal/PHCHelper.java b/bundles/org.openhab.binding.phc/src/main/java/org/openhab/binding/phc/internal/PHCHelper.java index 23058f613..ab02283e0 100644 --- a/bundles/org.openhab.binding.phc/src/main/java/org/openhab/binding/phc/internal/PHCHelper.java +++ b/bundles/org.openhab.binding.phc/src/main/java/org/openhab/binding/phc/internal/PHCHelper.java @@ -38,9 +38,7 @@ public class PHCHelper { String thingID = StringUtils.padLeft(Integer.toBinaryString(moduleAddr & 0xFF).trim(), 5, "0"); thingID = new StringBuilder(thingID).reverse().toString(); - ThingUID thingUID = new ThingUID(thingTypeUID, thingID); - - return thingUID; + return new ThingUID(thingTypeUID, thingID); } /** diff --git a/bundles/org.openhab.binding.phc/src/main/java/org/openhab/binding/phc/internal/handler/PHCBridgeHandler.java b/bundles/org.openhab.binding.phc/src/main/java/org/openhab/binding/phc/internal/handler/PHCBridgeHandler.java index f3b279aaf..534e3a220 100644 --- a/bundles/org.openhab.binding.phc/src/main/java/org/openhab/binding/phc/internal/handler/PHCBridgeHandler.java +++ b/bundles/org.openhab.binding.phc/src/main/java/org/openhab/binding/phc/internal/handler/PHCBridgeHandler.java @@ -77,9 +77,9 @@ public class PHCBridgeHandler extends BaseBridgeHandler implements SerialPortEve private final BlockingQueue sendQueue = new LinkedBlockingQueue<>(); private final ScheduledThreadPoolExecutor threadPoolExecutor = new ScheduledThreadPoolExecutor(3); - private final byte emLedOutputState[] = new byte[32]; - private final byte amOutputState[] = new byte[32]; - private final byte dmOutputState[] = new byte[32]; + private final byte[] emLedOutputState = new byte[32]; + private final byte[] amOutputState = new byte[32]; + private final byte[] dmOutputState = new byte[32]; private final List modules = new ArrayList<>(); @@ -570,7 +570,8 @@ public class PHCBridgeHandler extends BaseBridgeHandler implements SerialPortEve private void sendDim(byte moduleAddress, byte channel, Command command, short dimTime) { byte module = (byte) (moduleAddress | 0xA0); - byte[] cmd = new byte[(command instanceof PercentType && !(((PercentType) command).byteValue() == 0)) ? 3 : 1]; + byte[] cmd = new byte[(command instanceof PercentType percentCommand && percentCommand.byteValue() != 0) ? 3 + : 1]; cmd[0] = (byte) (channel << 5); diff --git a/bundles/org.openhab.binding.phc/src/main/java/org/openhab/binding/phc/internal/handler/PHCHandler.java b/bundles/org.openhab.binding.phc/src/main/java/org/openhab/binding/phc/internal/handler/PHCHandler.java index 5d940e66e..76106e5a4 100644 --- a/bundles/org.openhab.binding.phc/src/main/java/org/openhab/binding/phc/internal/handler/PHCHandler.java +++ b/bundles/org.openhab.binding.phc/src/main/java/org/openhab/binding/phc/internal/handler/PHCHandler.java @@ -157,8 +157,8 @@ public class PHCHandler extends BaseThingHandler { } ThingHandler handler = bridge.getHandler(); - if (handler instanceof PHCBridgeHandler) { - bridgeHandler = (PHCBridgeHandler) handler; + if (handler instanceof PHCBridgeHandler phcBridgeHandler) { + bridgeHandler = phcBridgeHandler; } else { logger.debug("No available bridge handler for {}.", bridge.getUID()); diff --git a/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/PilightConnector.java b/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/PilightConnector.java index b02deee8b..20c14d785 100644 --- a/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/PilightConnector.java +++ b/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/PilightConnector.java @@ -18,7 +18,7 @@ import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; -import java.util.Collections; +import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; @@ -111,11 +111,11 @@ public class PilightConnector implements Runnable, Closeable { callback.versionReceived(version); } else if (line.startsWith("{\"status\":")) { // currently unused - } else if (line.equals("1")) { + } else if ("1".equals(line)) { throw new IOException("Connection to pilight lost"); } else { final @Nullable Status status = inputMapper.readValue(line, Status.class); - callback.statusReceived(Collections.singletonList(status)); + callback.statusReceived(List.of(status)); } } diff --git a/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/discovery/PilightBridgeDiscoveryService.java b/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/discovery/PilightBridgeDiscoveryService.java index e79ac8e19..423c04cab 100644 --- a/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/discovery/PilightBridgeDiscoveryService.java +++ b/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/discovery/PilightBridgeDiscoveryService.java @@ -57,9 +57,14 @@ public class PilightBridgeDiscoveryService extends AbstractDiscoveryService { private static final int AUTODISCOVERY_SEARCH_TIME_SEC = 5; private static final int AUTODISCOVERY_BACKGROUND_SEARCH_INTERVAL_SEC = 60 * 10; - private static final String SSDP_DISCOVERY_REQUEST_MESSAGE = "M-SEARCH * HTTP/1.1\r\n" - + "Host:239.255.255.250:1900\r\n" + "ST:urn:schemas-upnp-org:service:pilight:1\r\n" - + "Man:\"ssdp:discover\"\r\n" + "MX:3\r\n\r\n"; + private static final String SSDP_DISCOVERY_REQUEST_MESSAGE = """ + M-SEARCH * HTTP/1.1 + Host:239.255.255.250:1900 + ST:urn:schemas-upnp-org:service:pilight:1 + Man:"ssdp:discover" + MX:3 + + """; public static final String SSDP_MULTICAST_ADDRESS = "239.255.255.250"; public static final int SSDP_PORT = 1900; public static final int SSDP_WAIT_TIMEOUT = 2000; // in milliseconds @@ -73,7 +78,7 @@ public class PilightBridgeDiscoveryService extends AbstractDiscoveryService { } public static Set getSupportedThingTypeUIDs() { - return Collections.singleton(PilightBindingConstants.THING_TYPE_BRIDGE); + return Set.of(PilightBindingConstants.THING_TYPE_BRIDGE); } @Override diff --git a/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/discovery/PilightDeviceDiscoveryService.java b/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/discovery/PilightDeviceDiscoveryService.java index e4f60da7f..fb14f9551 100644 --- a/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/discovery/PilightDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/discovery/PilightDeviceDiscoveryService.java @@ -165,12 +165,9 @@ public class PilightDeviceDiscoveryService extends AbstractDiscoveryService impl @Override public void setThingHandler(final ThingHandler handler) { - if (handler instanceof PilightBridgeHandler) { - this.pilightBridgeHandler = (PilightBridgeHandler) handler; - final @Nullable PilightBridgeHandler pilightBridgeHandler = this.pilightBridgeHandler; - if (pilightBridgeHandler != null) { - bridgeUID = pilightBridgeHandler.getThing().getUID(); - } + if (handler instanceof PilightBridgeHandler pilightBridgeHandler) { + this.pilightBridgeHandler = pilightBridgeHandler; + bridgeUID = pilightBridgeHandler.getThing().getUID(); } } diff --git a/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/handler/PilightBaseHandler.java b/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/handler/PilightBaseHandler.java index 2ac0bb970..c124d9935 100644 --- a/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/handler/PilightBaseHandler.java +++ b/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/handler/PilightBaseHandler.java @@ -121,8 +121,8 @@ public abstract class PilightBaseHandler extends BaseThingHandler { if (bridge != null) { @Nullable BridgeHandler handler = bridge.getHandler(); - if (handler instanceof PilightBridgeHandler) { - return (PilightBridgeHandler) handler; + if (handler instanceof PilightBridgeHandler bridgeHandler) { + return bridgeHandler; } } return null; diff --git a/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/handler/PilightBridgeHandler.java b/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/handler/PilightBridgeHandler.java index 24a46180c..d29d4f448 100644 --- a/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/handler/PilightBridgeHandler.java +++ b/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/handler/PilightBridgeHandler.java @@ -14,8 +14,8 @@ package org.openhab.binding.pilight.internal.handler; import java.util.Collection; -import java.util.Collections; import java.util.List; +import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledFuture; @@ -185,8 +185,8 @@ public class PilightBridgeHandler extends BaseBridgeHandler { if (!DeviceType.SERVER.equals(type)) { for (Thing thing : getThing().getThings()) { final @Nullable ThingHandler handler = thing.getHandler(); - if (handler instanceof PilightBaseHandler) { - ((PilightBaseHandler) handler).updateFromStatusIfMatches(status); + if (handler instanceof PilightBaseHandler baseHandler) { + baseHandler.updateFromStatusIfMatches(status); } } } @@ -194,7 +194,7 @@ public class PilightBridgeHandler extends BaseBridgeHandler { @Override public Collection> getServices() { - return Collections.singleton(PilightDeviceDiscoveryService.class); + return Set.of(PilightDeviceDiscoveryService.class); } /** @@ -228,8 +228,8 @@ public class PilightBridgeHandler extends BaseBridgeHandler { private void processConfig(Config config) { for (Thing thing : getThing().getThings()) { final @Nullable ThingHandler handler = thing.getHandler(); - if (handler instanceof PilightBaseHandler) { - ((PilightBaseHandler) handler).updateFromConfigIfMatches(config); + if (handler instanceof PilightBaseHandler baseHandler) { + baseHandler.updateFromConfigIfMatches(config); } } diff --git a/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/handler/PilightDimmerHandler.java b/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/handler/PilightDimmerHandler.java index ef2afd8d5..2be664af5 100644 --- a/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/handler/PilightDimmerHandler.java +++ b/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/handler/PilightDimmerHandler.java @@ -91,8 +91,8 @@ public class PilightDimmerHandler extends PilightBaseHandler { if (command instanceof OnOffType) { code.setState(command.equals(OnOffType.ON) ? Code.STATE_ON : Code.STATE_OFF); - } else if (command instanceof PercentType) { - setDimmerValue((PercentType) command, code); + } else if (command instanceof PercentType percentCommand) { + setDimmerValue(percentCommand, code); } else { logger.warn("Only OnOffType and PercentType are supported by a dimmer."); return null; diff --git a/bundles/org.openhab.binding.pioneeravr/src/main/java/org/openhab/binding/pioneeravr/internal/protocol/RequestResponseFactory.java b/bundles/org.openhab.binding.pioneeravr/src/main/java/org/openhab/binding/pioneeravr/internal/protocol/RequestResponseFactory.java index 5172b89ba..338073b7f 100644 --- a/bundles/org.openhab.binding.pioneeravr/src/main/java/org/openhab/binding/pioneeravr/internal/protocol/RequestResponseFactory.java +++ b/bundles/org.openhab.binding.pioneeravr/src/main/java/org/openhab/binding/pioneeravr/internal/protocol/RequestResponseFactory.java @@ -41,8 +41,7 @@ public final class RequestResponseFactory { * @return */ public static SimpleCommand getIpControlCommand(SimpleCommandType command) { - SimpleCommand result = new SimpleCommand(command); - return result; + return new SimpleCommand(command); } /** @@ -53,8 +52,7 @@ public final class RequestResponseFactory { * @return */ public static SimpleCommand getIpControlCommand(SimpleCommandType command, int zone) { - SimpleCommand result = new SimpleCommand(command, zone); - return result; + return new SimpleCommand(command, zone); } /** @@ -65,8 +63,7 @@ public final class RequestResponseFactory { * @return */ public static ParameterizedCommand getIpControlCommand(ParameterizedCommandType command) { - ParameterizedCommand result = new ParameterizedCommand(command); - return result; + return new ParameterizedCommand(command); } /** @@ -78,8 +75,7 @@ public final class RequestResponseFactory { * @return */ public static ParameterizedCommand getIpControlCommand(ParameterizedCommandType command, int zone) { - ParameterizedCommand result = new ParameterizedCommand(command, zone); - return result; + return new ParameterizedCommand(command, zone); } /** diff --git a/bundles/org.openhab.binding.pioneeravr/src/main/java/org/openhab/binding/pioneeravr/internal/protocol/SimpleCommand.java b/bundles/org.openhab.binding.pioneeravr/src/main/java/org/openhab/binding/pioneeravr/internal/protocol/SimpleCommand.java index 072762744..f6012349f 100644 --- a/bundles/org.openhab.binding.pioneeravr/src/main/java/org/openhab/binding/pioneeravr/internal/protocol/SimpleCommand.java +++ b/bundles/org.openhab.binding.pioneeravr/src/main/java/org/openhab/binding/pioneeravr/internal/protocol/SimpleCommand.java @@ -44,7 +44,7 @@ public class SimpleCommand implements AvrCommand { MCACC_MEMORY_CHANGE_CYCLIC("0MC"), MCACC_MEMORY_QUERY("?MC"); - private String zoneCommands[]; + private String[] zoneCommands; private SimpleCommandType(String... command) { this.zoneCommands = command; diff --git a/bundles/org.openhab.binding.pioneeravr/src/main/java/org/openhab/binding/pioneeravr/internal/protocol/StreamAvrConnection.java b/bundles/org.openhab.binding.pioneeravr/src/main/java/org/openhab/binding/pioneeravr/internal/protocol/StreamAvrConnection.java index bc46daaeb..8b511c462 100644 --- a/bundles/org.openhab.binding.pioneeravr/src/main/java/org/openhab/binding/pioneeravr/internal/protocol/StreamAvrConnection.java +++ b/bundles/org.openhab.binding.pioneeravr/src/main/java/org/openhab/binding/pioneeravr/internal/protocol/StreamAvrConnection.java @@ -240,14 +240,14 @@ public abstract class StreamAvrConnection implements AvrConnection { commandToSend = RequestResponseFactory.getIpControlCommand(SimpleCommandType.VOLUME_DOWN, zone); } else if (command == IncreaseDecreaseType.INCREASE) { commandToSend = RequestResponseFactory.getIpControlCommand(SimpleCommandType.VOLUME_UP, zone); - } else if (command instanceof PercentType) { + } else if (command instanceof PercentType percentCommand) { String ipControlVolume = VolumeConverter - .convertFromPercentToIpControlVolume(((PercentType) command).doubleValue(), zone); + .convertFromPercentToIpControlVolume(percentCommand.doubleValue(), zone); commandToSend = RequestResponseFactory.getIpControlCommand(ParameterizedCommandType.VOLUME_SET, zone) .setParameter(ipControlVolume); - } else if (command instanceof DecimalType) { - String ipControlVolume = VolumeConverter - .convertFromDbToIpControlVolume(((DecimalType) command).doubleValue(), zone); + } else if (command instanceof DecimalType decimalCommand) { + String ipControlVolume = VolumeConverter.convertFromDbToIpControlVolume(decimalCommand.doubleValue(), + zone); commandToSend = RequestResponseFactory.getIpControlCommand(ParameterizedCommandType.VOLUME_SET, zone) .setParameter(ipControlVolume); } else { @@ -267,8 +267,8 @@ public abstract class StreamAvrConnection implements AvrConnection { commandToSend = RequestResponseFactory.getIpControlCommand(SimpleCommandType.INPUT_CHANGE_CYCLIC, zone); } else if (command == IncreaseDecreaseType.DECREASE) { commandToSend = RequestResponseFactory.getIpControlCommand(SimpleCommandType.INPUT_CHANGE_REVERSE, zone); - } else if (command instanceof StringType) { - String inputSourceValue = ((StringType) command).toString(); + } else if (command instanceof StringType stringCommand) { + String inputSourceValue = stringCommand.toString(); commandToSend = RequestResponseFactory.getIpControlCommand(ParameterizedCommandType.INPUT_CHANNEL_SET, zone) .setParameter(inputSourceValue); } else { @@ -285,8 +285,8 @@ public abstract class StreamAvrConnection implements AvrConnection { if (command == IncreaseDecreaseType.INCREASE) { commandToSend = RequestResponseFactory.getIpControlCommand(SimpleCommandType.LISTENING_MODE_CHANGE_CYCLIC, zone); - } else if (command instanceof StringType) { - String listeningModeValue = ((StringType) command).toString(); + } else if (command instanceof StringType stringCommand) { + String listeningModeValue = stringCommand.toString(); commandToSend = RequestResponseFactory .getIpControlCommand(ParameterizedCommandType.LISTENING_MODE_SET, zone) .setParameter(listeningModeValue); @@ -318,8 +318,8 @@ public abstract class StreamAvrConnection implements AvrConnection { if (command == IncreaseDecreaseType.INCREASE) { commandToSend = RequestResponseFactory.getIpControlCommand(SimpleCommandType.MCACC_MEMORY_CHANGE_CYCLIC); - } else if (command instanceof StringType) { - String MCACCMemoryValue = ((StringType) command).toString(); + } else if (command instanceof StringType stringCommand) { + String MCACCMemoryValue = stringCommand.toString(); commandToSend = RequestResponseFactory.getIpControlCommand(ParameterizedCommandType.MCACC_MEMORY_SET) .setParameter(MCACCMemoryValue); } else { diff --git a/bundles/org.openhab.binding.pixometer/src/main/java/org/openhab/binding/pixometer/handler/AccountHandler.java b/bundles/org.openhab.binding.pixometer/src/main/java/org/openhab/binding/pixometer/handler/AccountHandler.java index c7280a6d2..e5979212f 100644 --- a/bundles/org.openhab.binding.pixometer/src/main/java/org/openhab/binding/pixometer/handler/AccountHandler.java +++ b/bundles/org.openhab.binding.pixometer/src/main/java/org/openhab/binding/pixometer/handler/AccountHandler.java @@ -120,7 +120,7 @@ public class AccountHandler extends BaseBridgeHandler { int expiresIn = Integer.parseInt(responseJson.get("expires_in").toString()); setTokenExpiryDate(TimeUnit.SECONDS.toNanos(expiresIn)); - setAuthToken(responseJson.get(AUTH_TOKEN).toString().replaceAll("\"", "")); + setAuthToken(responseJson.get(AUTH_TOKEN).toString().replace("\"", "")); updateStatus(ThingStatus.ONLINE); return; diff --git a/bundles/org.openhab.binding.pixometer/src/main/java/org/openhab/binding/pixometer/internal/PixometerBindingConstants.java b/bundles/org.openhab.binding.pixometer/src/main/java/org/openhab/binding/pixometer/internal/PixometerBindingConstants.java index b939bd4da..fa59c837b 100644 --- a/bundles/org.openhab.binding.pixometer/src/main/java/org/openhab/binding/pixometer/internal/PixometerBindingConstants.java +++ b/bundles/org.openhab.binding.pixometer/src/main/java/org/openhab/binding/pixometer/internal/PixometerBindingConstants.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.pixometer.internal; -import java.util.Collections; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -40,7 +39,7 @@ public class PixometerBindingConstants { public static final ThingTypeUID THING_TYPE_GASMETER = new ThingTypeUID(BINDING_ID, "gasmeter"); public static final ThingTypeUID THING_TYPE_WATERMETER = new ThingTypeUID(BINDING_ID, "watermeter"); - public static final Set BRIDGE_THING_TYPES_UIDS = Collections.singleton(BRIDGE_THING_TYPE); + public static final Set BRIDGE_THING_TYPES_UIDS = Set.of(BRIDGE_THING_TYPE); public static final Set SUPPORTED_THING_TYPES_UIDS = Stream .of(THING_TYPE_ENERGYMETER, THING_TYPE_GASMETER, THING_TYPE_WATERMETER).collect(Collectors.toSet()); diff --git a/bundles/org.openhab.binding.pixometer/src/main/java/org/openhab/binding/pixometer/internal/serializer/CustomReadingInstanceDeserializer.java b/bundles/org.openhab.binding.pixometer/src/main/java/org/openhab/binding/pixometer/internal/serializer/CustomReadingInstanceDeserializer.java index f56ef2816..33b1b2e8e 100644 --- a/bundles/org.openhab.binding.pixometer/src/main/java/org/openhab/binding/pixometer/internal/serializer/CustomReadingInstanceDeserializer.java +++ b/bundles/org.openhab.binding.pixometer/src/main/java/org/openhab/binding/pixometer/internal/serializer/CustomReadingInstanceDeserializer.java @@ -96,7 +96,7 @@ public class CustomReadingInstanceDeserializer implements JsonDeserializer SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_PJLINK); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_PJLINK); @Activate public PJLinkDeviceHandlerFactory(@Reference InputChannelStateDescriptionProvider provider) { diff --git a/bundles/org.openhab.binding.pjlinkdevice/src/main/java/org/openhab/binding/pjlinkdevice/internal/device/PJLinkDevice.java b/bundles/org.openhab.binding.pjlinkdevice/src/main/java/org/openhab/binding/pjlinkdevice/internal/device/PJLinkDevice.java index fdbf3444a..f4233e7b0 100644 --- a/bundles/org.openhab.binding.pjlinkdevice/src/main/java/org/openhab/binding/pjlinkdevice/internal/device/PJLinkDevice.java +++ b/bundles/org.openhab.binding.pjlinkdevice/src/main/java/org/openhab/binding/pjlinkdevice/internal/device/PJLinkDevice.java @@ -171,9 +171,6 @@ public class PJLinkDevice { } else { try { authenticate(rawHeader.substring("PJLINK 1 ".length())); - } catch (AuthenticationException e) { - // propagate AuthenticationException - throw e; } catch (ResponseException e) { // maybe only the test command is broken on the device // as long as we don't get an AuthenticationException, we'll just ignore it for now @@ -236,16 +233,16 @@ public class PJLinkDevice { String response = null; while ((response = getReader().readLine()) != null && preprocessResponse(response).isEmpty()) { logger.debug("Got empty string response for request '{}' from {}, waiting for another line", response, - fullCommand.replaceAll("\r", "\\\\r")); + fullCommand.replace("\r", "\\\\r")); } if (response == null) { - throw new ResponseException(MessageFormat.format("Response to request ''{0}'' was null", - fullCommand.replaceAll("\r", "\\\\r"))); + throw new ResponseException( + MessageFormat.format("Response to request ''{0}'' was null", fullCommand.replace("\r", "\\\\r"))); } if (logger.isDebugEnabled()) { logger.debug("Got response '{}' ({}) for request '{}' from {}", response, - Arrays.toString(response.getBytes()), fullCommand.replaceAll("\r", "\\\\r"), ipAddress); + Arrays.toString(response.getBytes()), fullCommand.replace("\r", "\\\\r"), ipAddress); } return preprocessResponse(response); } diff --git a/bundles/org.openhab.binding.pjlinkdevice/src/main/java/org/openhab/binding/pjlinkdevice/internal/device/command/CachedCommand.java b/bundles/org.openhab.binding.pjlinkdevice/src/main/java/org/openhab/binding/pjlinkdevice/internal/device/command/CachedCommand.java index b869f2317..84a0f75ed 100644 --- a/bundles/org.openhab.binding.pjlinkdevice/src/main/java/org/openhab/binding/pjlinkdevice/internal/device/command/CachedCommand.java +++ b/bundles/org.openhab.binding.pjlinkdevice/src/main/java/org/openhab/binding/pjlinkdevice/internal/device/command/CachedCommand.java @@ -59,14 +59,14 @@ public class CachedCommand> implements Command< } catch (CacheException e) { // try to unwrap RuntimeException thrown in ExpiringCache Throwable cause = e.getCause(); - if (cause instanceof ResponseException) { - throw (ResponseException) cause; + if (cause instanceof ResponseException responseException) { + throw responseException; } - if (cause instanceof IOException) { - throw (IOException) cause; + if (cause instanceof IOException ioException) { + throw ioException; } - if (cause instanceof AuthenticationException) { - throw (AuthenticationException) cause; + if (cause instanceof AuthenticationException authenticationException) { + throw authenticationException; } throw e; } diff --git a/bundles/org.openhab.binding.pjlinkdevice/src/main/java/org/openhab/binding/pjlinkdevice/internal/device/command/lampstatus/LampStatesResponse.java b/bundles/org.openhab.binding.pjlinkdevice/src/main/java/org/openhab/binding/pjlinkdevice/internal/device/command/lampstatus/LampStatesResponse.java index fd7f6871e..b649c2ad5 100644 --- a/bundles/org.openhab.binding.pjlinkdevice/src/main/java/org/openhab/binding/pjlinkdevice/internal/device/command/lampstatus/LampStatesResponse.java +++ b/bundles/org.openhab.binding.pjlinkdevice/src/main/java/org/openhab/binding/pjlinkdevice/internal/device/command/lampstatus/LampStatesResponse.java @@ -69,7 +69,7 @@ public class LampStatesResponse extends PrefixedResponse login()); } break; diff --git a/bundles/org.openhab.binding.playstation/src/main/java/org/openhab/binding/playstation/internal/discovery/PlayStationDiscovery.java b/bundles/org.openhab.binding.playstation/src/main/java/org/openhab/binding/playstation/internal/discovery/PlayStationDiscovery.java index 16ca4e0a6..cfcf1cd5c 100644 --- a/bundles/org.openhab.binding.playstation/src/main/java/org/openhab/binding/playstation/internal/discovery/PlayStationDiscovery.java +++ b/bundles/org.openhab.binding.playstation/src/main/java/org/openhab/binding/playstation/internal/discovery/PlayStationDiscovery.java @@ -254,7 +254,7 @@ public class PlayStationDiscovery extends AbstractDiscoveryService { properties.put(Thing.PROPERTY_HARDWARE_VERSION, hwVersion); properties.put(Thing.PROPERTY_FIRMWARE_VERSION, formatPS4Version(systemVersion)); properties.put(Thing.PROPERTY_MAC_ADDRESS, hostIdToMacAddress(hostId)); - ThingUID uid = hostType.equalsIgnoreCase("PS5") ? new ThingUID(THING_TYPE_PS5, hostId) + ThingUID uid = "PS5".equalsIgnoreCase(hostType) ? new ThingUID(THING_TYPE_PS5, hostId) : new ThingUID(THING_TYPE_PS4, hostId); DiscoveryResult result = DiscoveryResultBuilder.create(uid).withProperties(properties).withLabel(hostName) @@ -408,10 +408,10 @@ public class PlayStationDiscovery extends AbstractDiscoveryService { hwVersion = PS4HW_CUH1000; break; case "bc60a7": // Ethernet - if (ethId.equals("7b")) { + if ("7b".equals(ethId)) { hwVersion = PS4HW_CUH2000; } - if (ethId.equals("8f")) { + if ("8f".equals(ethId)) { hwVersion = PS4HW_CUH7000; } break; @@ -423,10 +423,10 @@ public class PlayStationDiscovery extends AbstractDiscoveryService { break; case "40490f": // WiFi case "5c9656": // WiFi - if (ethId.equals("07")) { + if ("07".equals(ethId)) { hwVersion = PS4HW_CUH2000; } - if (ethId.equals("da")) { + if ("da".equals(ethId)) { hwVersion = PS4HW_CUH7000; } break; diff --git a/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/PLCLogoClient.java b/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/PLCLogoClient.java index 5a9a8d92b..097cba7e1 100644 --- a/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/PLCLogoClient.java +++ b/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/PLCLogoClient.java @@ -102,7 +102,7 @@ public class PLCLogoClient extends S7Client { // read first portion directly to data result = super.ReadArea(Area, DBNumber, Start, packet, WordLength, Data); while ((result == 0) && (offset < Amount)) { - byte buffer[] = new byte[Math.min(Amount - offset, packet)]; + byte[] buffer = new byte[Math.min(Amount - offset, packet)]; result = super.ReadArea(Area, DBNumber, offset, buffer.length, WordLength, buffer); System.arraycopy(buffer, 0, Data, offset, buffer.length); offset = offset + buffer.length; diff --git a/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/PLCLogoHandlerFactory.java b/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/PLCLogoHandlerFactory.java index 5222fff5c..4351f2e72 100644 --- a/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/PLCLogoHandlerFactory.java +++ b/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/PLCLogoHandlerFactory.java @@ -69,8 +69,8 @@ public class PLCLogoHandlerFactory extends BaseThingHandlerFactory { @Override protected @Nullable ThingHandler createHandler(Thing thing) { - if (THING_TYPE_DEVICE.equals(thing.getThingTypeUID()) && (thing instanceof Bridge)) { - return new PLCBridgeHandler((Bridge) thing); + if (THING_TYPE_DEVICE.equals(thing.getThingTypeUID()) && (thing instanceof Bridge bridge)) { + return new PLCBridgeHandler(bridge); } else if (THING_TYPE_ANALOG.equals(thing.getThingTypeUID())) { return new PLCAnalogHandler(thing); } else if (THING_TYPE_DIGITAL.equals(thing.getThingTypeUID())) { diff --git a/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/discovery/PLCDiscoveryService.java b/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/discovery/PLCDiscoveryService.java index 93de7e246..938bd3dcd 100644 --- a/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/discovery/PLCDiscoveryService.java +++ b/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/discovery/PLCDiscoveryService.java @@ -21,7 +21,6 @@ import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Arrays; -import java.util.Collections; import java.util.Enumeration; import java.util.Set; import java.util.TreeSet; @@ -55,7 +54,7 @@ import org.slf4j.LoggerFactory; public class PLCDiscoveryService extends AbstractDiscoveryService { private final Logger logger = LoggerFactory.getLogger(PLCDiscoveryService.class); - private static final Set THING_TYPES_UIDS = Collections.singleton(THING_TYPE_DEVICE); + private static final Set THING_TYPES_UIDS = Set.of(THING_TYPE_DEVICE); private static final String LOGO_HOST = "address"; private static final int LOGO_PORT = 102; diff --git a/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCAnalogHandler.java b/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCAnalogHandler.java index dba7a9d7a..a38e996e5 100644 --- a/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCAnalogHandler.java +++ b/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCAnalogHandler.java @@ -53,7 +53,7 @@ import Moka7.S7Client; @NonNullByDefault public class PLCAnalogHandler extends PLCCommonHandler { - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_ANALOG); + public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_ANALOG); private final Logger logger = LoggerFactory.getLogger(PLCAnalogHandler.class); private AtomicReference config = new AtomicReference<>(); @@ -118,11 +118,11 @@ public class PLCAnalogHandler extends PLCCommonHandler { } else { logger.debug("Can not read data from LOGO!: {}.", S7Client.ErrorText(result)); } - } else if (command instanceof DecimalType) { + } else if (command instanceof DecimalType decimalCommand) { byte[] buffer = new byte[2]; String type = channel.getAcceptedItemType(); if (ANALOG_ITEM.equalsIgnoreCase(type)) { - S7.SetShortAt(buffer, 0, ((DecimalType) command).intValue()); + S7.SetShortAt(buffer, 0, decimalCommand.intValue()); } else { logger.debug("Channel {} will not accept {} items.", channelUID, type); } @@ -262,7 +262,7 @@ public class PLCAnalogHandler extends PLCCommonHandler { cBuilder.withType(new ChannelTypeUID(BINDING_ID, type.toLowerCase())); cBuilder.withLabel(name); cBuilder.withDescription("Analog " + text + " block " + name); - cBuilder.withProperties(Collections.singletonMap(BLOCK_PROPERTY, name)); + cBuilder.withProperties(Map.of(BLOCK_PROPERTY, name)); tBuilder.withChannel(cBuilder.build()); setOldValue(name, null); } diff --git a/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCBridgeHandler.java b/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCBridgeHandler.java index 626cd1a49..5c430d717 100644 --- a/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCBridgeHandler.java +++ b/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCBridgeHandler.java @@ -17,7 +17,6 @@ import static org.openhab.binding.plclogo.internal.PLCLogoBindingConstants.*; import java.time.DateTimeException; import java.time.ZonedDateTime; import java.util.Arrays; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -61,7 +60,7 @@ import Moka7.S7Client; @NonNullByDefault public class PLCBridgeHandler extends BaseBridgeHandler { - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_DEVICE); + public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_DEVICE); private final Logger logger = LoggerFactory.getLogger(PLCBridgeHandler.class); @@ -281,11 +280,10 @@ public class PLCBridgeHandler extends BaseBridgeHandler { @Override public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) { super.childHandlerInitialized(childHandler, childThing); - if (childHandler instanceof PLCCommonHandler) { - PLCCommonHandler handler = (PLCCommonHandler) childHandler; + if (childHandler instanceof PLCCommonHandler plcCommonHandler) { synchronized (handlers) { - if (!handlers.contains(handler)) { - handlers.add(handler); + if (!handlers.contains(plcCommonHandler)) { + handlers.add(plcCommonHandler); } } } @@ -293,11 +291,10 @@ public class PLCBridgeHandler extends BaseBridgeHandler { @Override public void childHandlerDisposed(ThingHandler childHandler, Thing childThing) { - if (childHandler instanceof PLCCommonHandler) { - PLCCommonHandler handler = (PLCCommonHandler) childHandler; + if (childHandler instanceof PLCCommonHandler plcCommonHandler) { synchronized (handlers) { - if (handlers.contains(handler)) { - handlers.remove(handler); + if (handlers.contains(plcCommonHandler)) { + handlers.remove(plcCommonHandler); } } } diff --git a/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCCommonHandler.java b/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCCommonHandler.java index 892b472fc..4753d2b1d 100644 --- a/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCCommonHandler.java +++ b/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCCommonHandler.java @@ -243,8 +243,8 @@ public abstract class PLCCommonHandler extends BaseThingHandler { Bridge bridge = getBridge(); if (bridge != null) { BridgeHandler handler = bridge.getHandler(); - if ((handler != null) && (handler instanceof PLCBridgeHandler)) { - return (PLCBridgeHandler) handler; + if (handler instanceof PLCBridgeHandler bridgeHandler) { + return bridgeHandler; } } return null; diff --git a/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCDateTimeHandler.java b/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCDateTimeHandler.java index 4f205c37a..cfee712a0 100644 --- a/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCDateTimeHandler.java +++ b/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCDateTimeHandler.java @@ -15,8 +15,8 @@ package org.openhab.binding.plclogo.internal.handler; import static org.openhab.binding.plclogo.internal.PLCLogoBindingConstants.*; import java.time.ZonedDateTime; -import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; @@ -53,7 +53,7 @@ import Moka7.S7Client; @NonNullByDefault public class PLCDateTimeHandler extends PLCCommonHandler { - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_DATETIME); + public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_DATETIME); private final Logger logger = LoggerFactory.getLogger(PLCDateTimeHandler.class); private AtomicReference config = new AtomicReference<>(); @@ -89,11 +89,11 @@ public class PLCDateTimeHandler extends PLCCommonHandler { } else { logger.debug("Can not read data from LOGO!: {}.", S7Client.ErrorText(result)); } - } else if (command instanceof DateTimeType) { + } else if (command instanceof DateTimeType dateTimeCommand) { byte[] buffer = new byte[2]; String type = channel.getAcceptedItemType(); if (DATE_TIME_ITEM.equalsIgnoreCase(type)) { - ZonedDateTime datetime = ((DateTimeType) command).getZonedDateTime(); + ZonedDateTime datetime = dateTimeCommand.getZonedDateTime(); if ("Time".equalsIgnoreCase(channelUID.getId())) { buffer[0] = S7.ByteToBCD(datetime.getHour()); buffer[1] = S7.ByteToBCD(datetime.getMinute()); @@ -216,14 +216,14 @@ public class PLCDateTimeHandler extends PLCCommonHandler { cBuilder.withType(new ChannelTypeUID(BINDING_ID, type.toLowerCase())); cBuilder.withLabel(name); cBuilder.withDescription(text + " block parameter " + name); - cBuilder.withProperties(Collections.singletonMap(BLOCK_PROPERTY, name)); + cBuilder.withProperties(Map.of(BLOCK_PROPERTY, name)); tBuilder.withChannel(cBuilder.build()); cBuilder = ChannelBuilder.create(new ChannelUID(thing.getUID(), VALUE_CHANNEL), ANALOG_ITEM); cBuilder.withType(new ChannelTypeUID(BINDING_ID, ANALOG_ITEM.toLowerCase())); cBuilder.withLabel(name); cBuilder.withDescription(text + " block parameter " + name); - cBuilder.withProperties(Collections.singletonMap(BLOCK_PROPERTY, name)); + cBuilder.withProperties(Map.of(BLOCK_PROPERTY, name)); tBuilder.withChannel(cBuilder.build()); setOldValue(name, null); diff --git a/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCDigitalHandler.java b/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCDigitalHandler.java index 250df8973..f7fbe1f80 100644 --- a/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCDigitalHandler.java +++ b/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCDigitalHandler.java @@ -55,7 +55,7 @@ import Moka7.S7Client; @NonNullByDefault public class PLCDigitalHandler extends PLCCommonHandler { - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_DIGITAL); + public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_DIGITAL); private final Logger logger = LoggerFactory.getLogger(PLCDigitalHandler.class); private AtomicReference config = new AtomicReference<>(); @@ -187,9 +187,8 @@ public class PLCDigitalHandler extends PLCCommonHandler { protected void updateState(ChannelUID channelUID, State state) { super.updateState(channelUID, state); DecimalType value = state.as(DecimalType.class); - if (state instanceof OpenClosedType) { - OpenClosedType type = (OpenClosedType) state; - value = new DecimalType(type == OpenClosedType.CLOSED ? 1 : 0); + if (state instanceof OpenClosedType openClosedState) { + value = new DecimalType(openClosedState == OpenClosedType.CLOSED ? 1 : 0); } Channel channel = thing.getChannel(channelUID.getId()); @@ -272,7 +271,7 @@ public class PLCDigitalHandler extends PLCCommonHandler { cBuilder.withType(new ChannelTypeUID(BINDING_ID, type.toLowerCase())); cBuilder.withLabel(name); cBuilder.withDescription("Digital " + text + " block " + name); - cBuilder.withProperties(Collections.singletonMap(BLOCK_PROPERTY, name)); + cBuilder.withProperties(Map.of(BLOCK_PROPERTY, name)); tBuilder.withChannel(cBuilder.build()); setOldValue(name, null); } diff --git a/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCMemoryHandler.java b/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCMemoryHandler.java index 553f805f7..be4b9c85a 100644 --- a/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCMemoryHandler.java +++ b/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCMemoryHandler.java @@ -14,8 +14,8 @@ package org.openhab.binding.plclogo.internal.handler; import static org.openhab.binding.plclogo.internal.PLCLogoBindingConstants.*; -import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; @@ -52,7 +52,7 @@ import Moka7.S7Client; @NonNullByDefault public class PLCMemoryHandler extends PLCCommonHandler { - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_MEMORY); + public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_MEMORY); private final Logger logger = LoggerFactory.getLogger(PLCMemoryHandler.class); private AtomicReference config = new AtomicReference<>(); @@ -108,15 +108,15 @@ public class PLCMemoryHandler extends PLCCommonHandler { } else { logger.debug("Can not read data from LOGO!: {}.", S7Client.ErrorText(result)); } - } else if (command instanceof DecimalType) { + } else if (command instanceof DecimalType decimalCommand) { int length = MEMORY_BYTE.equalsIgnoreCase(kind) ? 1 : 2; byte[] buffer = new byte[MEMORY_DWORD.equalsIgnoreCase(kind) ? 4 : length]; if (ANALOG_ITEM.equalsIgnoreCase(type) && MEMORY_BYTE.equalsIgnoreCase(kind)) { - buffer[0] = ((DecimalType) command).byteValue(); + buffer[0] = decimalCommand.byteValue(); } else if (ANALOG_ITEM.equalsIgnoreCase(type) && MEMORY_WORD.equalsIgnoreCase(kind)) { - S7.SetShortAt(buffer, 0, ((DecimalType) command).intValue()); + S7.SetShortAt(buffer, 0, decimalCommand.intValue()); } else if (ANALOG_ITEM.equalsIgnoreCase(type) && MEMORY_DWORD.equalsIgnoreCase(kind)) { - S7.SetDIntAt(buffer, 0, ((DecimalType) command).intValue()); + S7.SetDIntAt(buffer, 0, decimalCommand.intValue()); } else { logger.debug("Channel {} will not accept {} items.", channelUID, type); } @@ -124,10 +124,10 @@ public class PLCMemoryHandler extends PLCCommonHandler { if (result != 0) { logger.debug("Can not write data to LOGO!: {}.", S7Client.ErrorText(result)); } - } else if (command instanceof OnOffType) { + } else if (command instanceof OnOffType onOffCommand) { byte[] buffer = new byte[1]; if (DIGITAL_OUTPUT_ITEM.equalsIgnoreCase(type) && MEMORY_BYTE.equalsIgnoreCase(kind)) { - S7.SetBitAt(buffer, 0, 0, ((OnOffType) command) == OnOffType.ON); + S7.SetBitAt(buffer, 0, 0, onOffCommand == OnOffType.ON); } else { logger.debug("Channel {} will not accept {} items.", channelUID, type); } @@ -291,7 +291,7 @@ public class PLCMemoryHandler extends PLCCommonHandler { cBuilder.withType(new ChannelTypeUID(BINDING_ID, type.toLowerCase())); cBuilder.withLabel(name); cBuilder.withDescription(text + " in/output block " + name); - cBuilder.withProperties(Collections.singletonMap(BLOCK_PROPERTY, name)); + cBuilder.withProperties(Map.of(BLOCK_PROPERTY, name)); tBuilder.withChannel(cBuilder.build()); setOldValue(name, null); diff --git a/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCPulseHandler.java b/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCPulseHandler.java index 32064f085..46cb2cd41 100644 --- a/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCPulseHandler.java +++ b/bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCPulseHandler.java @@ -14,8 +14,8 @@ package org.openhab.binding.plclogo.internal.handler; import static org.openhab.binding.plclogo.internal.PLCLogoBindingConstants.*; -import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; @@ -55,7 +55,7 @@ import Moka7.S7Client; @NonNullByDefault public class PLCPulseHandler extends PLCCommonHandler { - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_PULSE); + public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_PULSE); private final Logger logger = LoggerFactory.getLogger(PLCPulseHandler.class); private AtomicReference config = new AtomicReference<>(); @@ -191,9 +191,8 @@ public class PLCPulseHandler extends PLCCommonHandler { protected void updateState(ChannelUID channelUID, State state) { super.updateState(channelUID, state); DecimalType value = state.as(DecimalType.class); - if (state instanceof OpenClosedType) { - OpenClosedType type = (OpenClosedType) state; - value = new DecimalType(type == OpenClosedType.CLOSED ? 1 : 0); + if (state instanceof OpenClosedType openClosedState) { + value = new DecimalType(openClosedState == OpenClosedType.CLOSED ? 1 : 0); } setOldValue(channelUID.getId(), value); @@ -272,7 +271,7 @@ public class PLCPulseHandler extends PLCCommonHandler { cBuilder.withType(new ChannelTypeUID(BINDING_ID, bType.toLowerCase())); cBuilder.withLabel(bName); cBuilder.withDescription("Control block " + bName); - cBuilder.withProperties(Collections.singletonMap(BLOCK_PROPERTY, bName)); + cBuilder.withProperties(Map.of(BLOCK_PROPERTY, bName)); tBuilder.withChannel(cBuilder.build()); setOldValue(STATE_CHANNEL, null); @@ -282,7 +281,7 @@ public class PLCPulseHandler extends PLCCommonHandler { cBuilder.withType(new ChannelTypeUID(BINDING_ID, oType.toLowerCase())); cBuilder.withLabel(oName); cBuilder.withDescription("Observed block " + oName); - cBuilder.withProperties(Collections.singletonMap(BLOCK_PROPERTY, oName)); + cBuilder.withProperties(Map.of(BLOCK_PROPERTY, oName)); tBuilder.withChannel(cBuilder.build()); setOldValue(OBSERVE_CHANNEL, null); diff --git a/bundles/org.openhab.binding.plex/src/main/java/org/openhab/binding/plex/internal/handler/PlexApiConnector.java b/bundles/org.openhab.binding.plex/src/main/java/org/openhab/binding/plex/internal/handler/PlexApiConnector.java index 7a95ece6e..9d6adb82b 100644 --- a/bundles/org.openhab.binding.plex/src/main/java/org/openhab/binding/plex/internal/handler/PlexApiConnector.java +++ b/bundles/org.openhab.binding.plex/src/main/java/org/openhab/binding/plex/internal/handler/PlexApiConnector.java @@ -133,11 +133,9 @@ public class PlexApiConnector { */ public @Nullable MediaContainer getSessionData() { try { - String url = "https://" + host + ":" + String.valueOf(port) + "/status/sessions" + "?X-Plex-Token=" + token; + String url = "https://" + host + ":" + port + "/status/sessions" + "?X-Plex-Token=" + token; logger.debug("Getting session data '{}'", url); - MediaContainer mediaContainer = getFromXml(doHttpRequest("GET", url, getClientHeaders(), false), - MediaContainer.class); - return mediaContainer; + return getFromXml(doHttpRequest("GET", url, getClientHeaders(), false), MediaContainer.class); } catch (IOException | InterruptedException | TimeoutException | ExecutionException e) { logger.debug("An exception occurred while polling the PLEX Server: '{}'", e.getMessage()); return null; @@ -151,8 +149,7 @@ public class PlexApiConnector { * @return the completed url that will be usable */ public String getURL(String url) { - String artURL = scheme + "://" + host + ":" + String.valueOf(port + url + "?X-Plex-Token=" + token); - return artURL; + return scheme + "://" + host + ":" + port + url + "?X-Plex-Token=" + token; } /** @@ -355,7 +352,7 @@ public class PlexApiConnector { NotificationContainer notification = gson.fromJson(msg, NotificationContainer.class); if (notification != null) { PlexUpdateListener listenerLocal = listener; - if (listenerLocal != null && notification.getNotificationContainer().getType().equals("playing")) { + if (listenerLocal != null && "playing".equals(notification.getNotificationContainer().getType())) { listenerLocal.onItemStatusUpdate( notification.getNotificationContainer().getPlaySessionStateNotification().get(0) .getSessionKey(), @@ -413,7 +410,7 @@ public class PlexApiConnector { if (commandPath != null) { try { - String url = "https://" + host + ":" + String.valueOf(port) + commandPath; + String url = "https://" + host + ":" + port + commandPath; Properties headers = getClientHeaders(); headers.put("X-Plex-Target-Client-Identifier", playerID); doHttpRequest("GET", url, headers, false); diff --git a/bundles/org.openhab.binding.plex/src/main/java/org/openhab/binding/plex/internal/handler/PlexServerHandler.java b/bundles/org.openhab.binding.plex/src/main/java/org/openhab/binding/plex/internal/handler/PlexServerHandler.java index 16423c07f..6f86e2b8c 100644 --- a/bundles/org.openhab.binding.plex/src/main/java/org/openhab/binding/plex/internal/handler/PlexServerHandler.java +++ b/bundles/org.openhab.binding.plex/src/main/java/org/openhab/binding/plex/internal/handler/PlexServerHandler.java @@ -245,10 +245,10 @@ public class PlexServerHandler extends BaseBridgeHandler implements PlexUpdateLi // configured, update // it tmpMeta.setArt(plexAPIConnector.getURL(tmpMeta.getArt())); - if (tmpMeta.getType().equals("episode")) { + if ("episode".equals(tmpMeta.getType())) { tmpMeta.setThumb(plexAPIConnector.getURL(tmpMeta.getGrandparentThumb())); tmpMeta.setTitle(tmpMeta.getGrandparentTitle() + " : " + tmpMeta.getTitle()); - } else if (tmpMeta.getType().equals("track")) { + } else if ("track".equals(tmpMeta.getType())) { tmpMeta.setThumb(plexAPIConnector.getURL(tmpMeta.getThumb())); tmpMeta.setTitle(tmpMeta.getGrandparentTitle() + " - " + tmpMeta.getParentTitle() + " - " + tmpMeta.getTitle()); @@ -304,8 +304,8 @@ public class PlexServerHandler extends BaseBridgeHandler implements PlexUpdateLi } refreshAllPlayers(); } catch (Exception e) { - updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, String - .format("An exception occurred while polling the PLEX Server: '%s'", e.getMessage()).toString()); + updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, + String.format("An exception occurred while polling the PLEX Server: '%s'", e.getMessage())); } }; diff --git a/bundles/org.openhab.binding.plugwise/src/main/java/org/openhab/binding/plugwise/internal/PlugwiseMessageProcessor.java b/bundles/org.openhab.binding.plugwise/src/main/java/org/openhab/binding/plugwise/internal/PlugwiseMessageProcessor.java index e46c99272..93362e040 100644 --- a/bundles/org.openhab.binding.plugwise/src/main/java/org/openhab/binding/plugwise/internal/PlugwiseMessageProcessor.java +++ b/bundles/org.openhab.binding.plugwise/src/main/java/org/openhab/binding/plugwise/internal/PlugwiseMessageProcessor.java @@ -94,7 +94,7 @@ public class PlugwiseMessageProcessor implements SerialPortEventListener { */ private void parseAndQueue(ByteBuffer readBuffer) { String response = new String(readBuffer.array(), 0, readBuffer.limit()); - response = response.replaceAll("\r", "").replaceAll("\n", ""); + response = response.replace("\r", "").replace("\n", ""); Matcher matcher = RESPONSE_PATTERN.matcher(response); @@ -123,10 +123,10 @@ public class PlugwiseMessageProcessor implements SerialPortEventListener { try { Message message = messageFactory.createMessage(messageType, sequenceNumber, payload); - if (message instanceof AcknowledgementMessage - && !((AcknowledgementMessage) message).isExtended()) { + if (message instanceof AcknowledgementMessage acknowledgementMessage + && !acknowledgementMessage.isExtended()) { logger.debug("Adding to acknowledgedQueue: {}", message); - context.getAcknowledgedQueue().put((AcknowledgementMessage) message); + context.getAcknowledgedQueue().put(acknowledgementMessage); } else { logger.debug("Adding to receivedQueue: {}", message); context.getReceivedQueue().put(message); diff --git a/bundles/org.openhab.binding.plugwise/src/main/java/org/openhab/binding/plugwise/internal/PlugwiseThingDiscoveryService.java b/bundles/org.openhab.binding.plugwise/src/main/java/org/openhab/binding/plugwise/internal/PlugwiseThingDiscoveryService.java index 7cc1d5a53..fddac119a 100644 --- a/bundles/org.openhab.binding.plugwise/src/main/java/org/openhab/binding/plugwise/internal/PlugwiseThingDiscoveryService.java +++ b/bundles/org.openhab.binding.plugwise/src/main/java/org/openhab/binding/plugwise/internal/PlugwiseThingDiscoveryService.java @@ -289,8 +289,8 @@ public class PlugwiseThingDiscoveryService extends AbstractDiscoveryService @Override public void setThingHandler(ThingHandler handler) { - if (handler instanceof PlugwiseStickHandler) { - stickHandler = (PlugwiseStickHandler) handler; + if (handler instanceof PlugwiseStickHandler plugwiseStickHandler) { + stickHandler = plugwiseStickHandler; stickHandler.addStickStatusListener(this); } } diff --git a/bundles/org.openhab.binding.plugwise/src/main/java/org/openhab/binding/plugwise/internal/handler/PlugwiseRelayDeviceHandler.java b/bundles/org.openhab.binding.plugwise/src/main/java/org/openhab/binding/plugwise/internal/handler/PlugwiseRelayDeviceHandler.java index 03a5621af..567b90600 100644 --- a/bundles/org.openhab.binding.plugwise/src/main/java/org/openhab/binding/plugwise/internal/handler/PlugwiseRelayDeviceHandler.java +++ b/bundles/org.openhab.binding.plugwise/src/main/java/org/openhab/binding/plugwise/internal/handler/PlugwiseRelayDeviceHandler.java @@ -353,11 +353,10 @@ public class PlugwiseRelayDeviceHandler extends AbstractPlugwiseThingHandler { public void handleCommand(ChannelUID channelUID, Command command) { logger.debug("Handling command '{}' for {} ({}) channel '{}'", command, deviceType, macAddress, channelUID.getId()); - if (CHANNEL_STATE.equals(channelUID.getId()) && (command instanceof OnOffType)) { + if (CHANNEL_STATE.equals(channelUID.getId()) && (command instanceof OnOffType onOffCommand)) { if (configuration.getPowerStateChanging() == PowerStateChanging.COMMAND_SWITCHING) { - OnOffType onOff = (OnOffType) command; - pendingPowerStateChange = new PendingPowerStateChange(onOff); - handleOnOffCommand(onOff); + pendingPowerStateChange = new PendingPowerStateChange(onOffCommand); + handleOnOffCommand(onOffCommand); } else { OnOffType onOff = configuration.getPowerStateChanging() == PowerStateChanging.ALWAYS_ON ? OnOffType.ON : OnOffType.OFF; diff --git a/bundles/org.openhab.binding.plugwise/src/main/java/org/openhab/binding/plugwise/internal/protocol/BroadcastGroupSwitchResponseMessage.java b/bundles/org.openhab.binding.plugwise/src/main/java/org/openhab/binding/plugwise/internal/protocol/BroadcastGroupSwitchResponseMessage.java index b0aec94ff..ab72c4fea 100644 --- a/bundles/org.openhab.binding.plugwise/src/main/java/org/openhab/binding/plugwise/internal/protocol/BroadcastGroupSwitchResponseMessage.java +++ b/bundles/org.openhab.binding.plugwise/src/main/java/org/openhab/binding/plugwise/internal/protocol/BroadcastGroupSwitchResponseMessage.java @@ -50,7 +50,7 @@ public class BroadcastGroupSwitchResponseMessage extends Message { if (matcher.matches()) { macAddress = new MACAddress(matcher.group(1)); portMask = Integer.parseInt(matcher.group(2)); - powerState = (matcher.group(3).equals("01")); + powerState = ("01".equals(matcher.group(3))); } else { throw new PlugwisePayloadMismatchException(BROADCAST_GROUP_SWITCH_RESPONSE, PAYLOAD_PATTERN, payload); } diff --git a/bundles/org.openhab.binding.plugwise/src/main/java/org/openhab/binding/plugwise/internal/protocol/InformationResponseMessage.java b/bundles/org.openhab.binding.plugwise/src/main/java/org/openhab/binding/plugwise/internal/protocol/InformationResponseMessage.java index 21fe711f8..712a6cd34 100644 --- a/bundles/org.openhab.binding.plugwise/src/main/java/org/openhab/binding/plugwise/internal/protocol/InformationResponseMessage.java +++ b/bundles/org.openhab.binding.plugwise/src/main/java/org/openhab/binding/plugwise/internal/protocol/InformationResponseMessage.java @@ -113,7 +113,7 @@ public class InformationResponseMessage extends Message { month = Integer.parseInt(matcher.group(3), 16); minutes = Integer.parseInt(matcher.group(4), 16); logAddress = (Integer.parseInt(matcher.group(5), 16) - 278528) / 32; - powerState = (matcher.group(6).equals("01")); + powerState = ("01".equals(matcher.group(6))); hertz = Integer.parseInt(matcher.group(7), 16); hardwareVersion = matcher.group(8).substring(0, 4) + "-" + matcher.group(8).substring(4, 8) + "-" + matcher.group(8).substring(8, 12); diff --git a/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/api/model/PlugwiseHAController.java b/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/api/model/PlugwiseHAController.java index 1e751fd98..689293065 100644 --- a/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/api/model/PlugwiseHAController.java +++ b/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/api/model/PlugwiseHAController.java @@ -158,7 +158,7 @@ public class PlugwiseHAController { DomainObjects domainObjects = executeRequest(request); this.gatewayUpdateDateTime = ZonedDateTime.parse(request.getServerDateTime(), PlugwiseHAController.FORMAT); int size = 0; - if (!(domainObjects.getAppliances() == null)) { + if (domainObjects.getAppliances() != null) { size = domainObjects.getAppliances().size(); } this.logger.debug("Found {} Plugwise Home Automation appliance(s)", size); @@ -201,7 +201,7 @@ public class PlugwiseHAController { DomainObjects domainObjects = executeRequest(request); this.gatewayUpdateDateTime = ZonedDateTime.parse(request.getServerDateTime(), PlugwiseHAController.FORMAT); int size = 0; - if (!(domainObjects.getLocations() == null)) { + if (domainObjects.getLocations() != null) { size = domainObjects.getLocations().size(); } this.logger.debug("Found {} Plugwise Home Automation Zone(s)", size); diff --git a/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/api/model/converter/DateTimeConverter.java b/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/api/model/converter/DateTimeConverter.java index 900aeca39..b60061dbd 100644 --- a/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/api/model/converter/DateTimeConverter.java +++ b/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/api/model/converter/DateTimeConverter.java @@ -51,8 +51,7 @@ public class DateTimeConverter extends AbstractSingleValueConverter { } try { - ZonedDateTime dateTime = ZonedDateTime.parse(str, DateTimeConverter.FORMAT); - return dateTime; + return ZonedDateTime.parse(str, DateTimeConverter.FORMAT); } catch (DateTimeParseException e) { logger.debug("Invalid datetime format in {}", str); return null; diff --git a/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/api/model/dto/ActuatorFunctionality.java b/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/api/model/dto/ActuatorFunctionality.java index 5ae6f92de..24a3e15b8 100644 --- a/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/api/model/dto/ActuatorFunctionality.java +++ b/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/api/model/dto/ActuatorFunctionality.java @@ -77,6 +77,7 @@ public class ActuatorFunctionality extends PlugwiseBaseModel implements Plugwise return upperBound; } + @Override public ZonedDateTime getUpdatedDate() { return updatedDate; } diff --git a/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/api/model/dto/Appliance.java b/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/api/model/dto/Appliance.java index 0642275f4..b8a3d2360 100644 --- a/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/api/model/dto/Appliance.java +++ b/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/api/model/dto/Appliance.java @@ -230,7 +230,7 @@ public class Appliance extends PlugwiseBaseModel implements PlugwiseComparableDa public boolean isBatteryOperated() { if (this.zigbeeNode instanceof ZigBeeNode) { - return this.zigbeeNode.getPowerSource().equals("battery") && this.getBatteryLevel().isPresent(); + return "battery".equals(this.zigbeeNode.getPowerSource()) && this.getBatteryLevel().isPresent(); } else { return false; } diff --git a/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/api/model/dto/Log.java b/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/api/model/dto/Log.java index cad7b95a4..d0c512854 100644 --- a/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/api/model/dto/Log.java +++ b/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/api/model/dto/Log.java @@ -83,6 +83,7 @@ public class Log extends PlugwiseBaseModel implements PlugwiseComparableDate unit = entity.getOffsetTemperatureUnit().orElse(UNIT_CELSIUS).equals(UNIT_CELSIUS) ? SIUnits.CELSIUS : ImperialUnits.FAHRENHEIT; - QuantityType state = ((QuantityType) command).toUnit(unit); + QuantityType state = quantityCommand.toUnit(unit); if (state != null) { try { @@ -167,19 +165,19 @@ public class PlugwiseHAApplianceHandler extends PlugwiseHABaseHandler unit = entity.getSetpointTemperatureUnit().orElse(UNIT_CELSIUS) .equals(UNIT_CELSIUS) ? SIUnits.CELSIUS : ImperialUnits.FAHRENHEIT; - QuantityType state = ((QuantityType) command).toUnit(unit); + QuantityType state = quantityCommand.toUnit(unit); if (state != null) { try { diff --git a/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/handler/PlugwiseHABridgeHandler.java b/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/handler/PlugwiseHABridgeHandler.java index 108e5b974..68dbbf7c5 100644 --- a/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/handler/PlugwiseHABridgeHandler.java +++ b/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/handler/PlugwiseHABridgeHandler.java @@ -18,8 +18,8 @@ import static org.openhab.core.thing.ThingStatus.ONLINE; import static org.openhab.core.thing.ThingStatusDetail.*; import java.util.Collection; -import java.util.Collections; import java.util.Map; +import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -108,7 +108,7 @@ public class PlugwiseHABridgeHandler extends BaseBridgeHandler { @Override public Collection> getServices() { - return Collections.singleton(PlugwiseHADiscoveryService.class); + return Set.of(PlugwiseHADiscoveryService.class); } @Override diff --git a/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/handler/PlugwiseHAZoneHandler.java b/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/handler/PlugwiseHAZoneHandler.java index cd24e7442..aba491865 100644 --- a/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/handler/PlugwiseHAZoneHandler.java +++ b/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/handler/PlugwiseHAZoneHandler.java @@ -105,9 +105,7 @@ public class PlugwiseHAZoneHandler extends PlugwiseHABaseHandler unit = entity.getSetpointTemperatureUnit().orElse(UNIT_CELSIUS) .equals(UNIT_CELSIUS) ? SIUnits.CELSIUS : ImperialUnits.FAHRENHEIT; - QuantityType state = ((QuantityType) command).toUnit(unit); + QuantityType state = quantityCommand.toUnit(unit); if (state != null) { try { controller.setLocationThermostat(entity, state.doubleValue()); @@ -144,31 +142,31 @@ public class PlugwiseHAZoneHandler extends PlugwiseHABaseHandler> getServices() { - return Collections.singleton(PowermaxDiscoveryService.class); + return Set.of(PowermaxDiscoveryService.class); } public @Nullable PowermaxState getCurrentState() { @@ -628,8 +628,7 @@ public class PowermaxBridgeHandler extends BaseBridgeHandler implements Powermax continue; } ThingHandler thingHandler = thing.getHandler(); - if (thingHandler instanceof PowermaxThingHandler) { - PowermaxThingHandler handler = (PowermaxThingHandler) thingHandler; + if (thingHandler instanceof PowermaxThingHandler powermaxThingHandler) { if (thing.getThingTypeUID().equals(THING_TYPE_ZONE)) { // All of the zone state objects will have the same list of values. // The use of getZone(1) here is just to get any PowermaxZoneState @@ -638,12 +637,12 @@ public class PowermaxBridgeHandler extends BaseBridgeHandler implements Powermax for (Value value : state.getZone(1).getValues()) { String channelId = value.getChannel(); if ((channel == null) || channel.equals(channelId)) { - handler.updateChannelFromAlarmState(channelId, state); + powermaxThingHandler.updateChannelFromAlarmState(channelId, state); } } } else if (thing.getThingTypeUID().equals(THING_TYPE_X10)) { if ((channel == null) || channel.equals(X10_STATUS)) { - handler.updateChannelFromAlarmState(X10_STATUS, state); + powermaxThingHandler.updateChannelFromAlarmState(X10_STATUS, state); } } } diff --git a/bundles/org.openhab.binding.powermax/src/main/java/org/openhab/binding/powermax/internal/message/PowermaxMessageConstants.java b/bundles/org.openhab.binding.powermax/src/main/java/org/openhab/binding/powermax/internal/message/PowermaxMessageConstants.java index c55e4836f..9a2318049 100644 --- a/bundles/org.openhab.binding.powermax/src/main/java/org/openhab/binding/powermax/internal/message/PowermaxMessageConstants.java +++ b/bundles/org.openhab.binding.powermax/src/main/java/org/openhab/binding/powermax/internal/message/PowermaxMessageConstants.java @@ -31,7 +31,7 @@ public class PowermaxMessageConstants { // System events - public static enum PowermaxSysEventType { + public enum PowermaxSysEventType { NONE, ALARM, SILENT_ALARM, @@ -41,7 +41,7 @@ public class PowermaxMessageConstants { RESTORE, GENERAL_RESTORE, CANCEL, - RESET; + RESET } public static class PowermaxSysEvent { diff --git a/bundles/org.openhab.binding.powermax/src/main/java/org/openhab/binding/powermax/internal/message/PowermaxStatusMessage.java b/bundles/org.openhab.binding.powermax/src/main/java/org/openhab/binding/powermax/internal/message/PowermaxStatusMessage.java index 0c460bb5e..962c4b501 100644 --- a/bundles/org.openhab.binding.powermax/src/main/java/org/openhab/binding/powermax/internal/message/PowermaxStatusMessage.java +++ b/bundles/org.openhab.binding.powermax/src/main/java/org/openhab/binding/powermax/internal/message/PowermaxStatusMessage.java @@ -181,7 +181,7 @@ public class PowermaxStatusMessage extends PowermaxBaseMessage { } else if (zoneEType == 0x05) { // Violated (Motion) PowermaxZoneSettings zone = panelSettings.getZoneSettings(eventZone); - if ((zone != null) && zone.getSensorType().equalsIgnoreCase("unknown")) { + if ((zone != null) && "unknown".equalsIgnoreCase(zone.getSensorType())) { zone.setSensorType(PowermaxSensorType.MOTION_SENSOR_1.getLabel()); } updatedState.getZone(eventZone).tripped.setValue(true); @@ -276,11 +276,11 @@ public class PowermaxStatusMessage extends PowermaxBaseMessage { // the sensor type always triggers an alarm // or the system is armed away // or the system is armed home and the zone is not interior(-follow) - boolean armed = (!zone.getType().equalsIgnoreCase("Non-Alarm") + boolean armed = (!"Non-Alarm".equalsIgnoreCase(zone.getType()) && (zone.isAlwaysInAlarm() || (mode == PowermaxArmMode.ARMED_AWAY.getCode()) || ((mode == PowermaxArmMode.ARMED_HOME.getCode()) - && !zone.getType().equalsIgnoreCase("Interior-Follow") - && !zone.getType().equalsIgnoreCase("Interior")))); + && !"Interior-Follow".equalsIgnoreCase(zone.getType()) + && !"Interior".equalsIgnoreCase(zone.getType())))); updatedState.getZone(i).armed.setValue(armed); } }); diff --git a/bundles/org.openhab.binding.powermax/src/main/java/org/openhab/binding/powermax/internal/state/PowermaxZoneState.java b/bundles/org.openhab.binding.powermax/src/main/java/org/openhab/binding/powermax/internal/state/PowermaxZoneState.java index 3961edd8b..d38b6e7d3 100644 --- a/bundles/org.openhab.binding.powermax/src/main/java/org/openhab/binding/powermax/internal/state/PowermaxZoneState.java +++ b/bundles/org.openhab.binding.powermax/src/main/java/org/openhab/binding/powermax/internal/state/PowermaxZoneState.java @@ -39,9 +39,7 @@ public class PowermaxZoneState extends PowermaxStateContainer { public StringValue lastMessage = new StringValue(this, ZONE_LAST_MESSAGE); public DateTimeValue lastMessageTime = new DateTimeValue(this, ZONE_LAST_MESSAGE_TIME); - public DynamicValue locked = new DynamicValue<>(this, LOCKED, () -> { - return armed.getValue(); - }, () -> { + public DynamicValue locked = new DynamicValue<>(this, LOCKED, () -> armed.getValue(), () -> { Boolean isArmed = armed.getValue(); if (isArmed == null) { return UnDefType.NULL; diff --git a/bundles/org.openhab.binding.prowl/src/main/java/org/openhab/binding/prowl/internal/ProwlHandler.java b/bundles/org.openhab.binding.prowl/src/main/java/org/openhab/binding/prowl/internal/ProwlHandler.java index 962b5e438..9a869eaeb 100644 --- a/bundles/org.openhab.binding.prowl/src/main/java/org/openhab/binding/prowl/internal/ProwlHandler.java +++ b/bundles/org.openhab.binding.prowl/src/main/java/org/openhab/binding/prowl/internal/ProwlHandler.java @@ -15,7 +15,7 @@ package org.openhab.binding.prowl.internal; import static org.openhab.binding.prowl.internal.ProwlBindingConstants.*; import java.util.Collection; -import java.util.Collections; +import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -113,7 +113,7 @@ public class ProwlHandler extends BaseThingHandler { @Override public Collection> getServices() { - return Collections.singletonList(ProwlActions.class); + return List.of(ProwlActions.class); } public void pushNotification(@Nullable String event, @Nullable String description) { diff --git a/bundles/org.openhab.binding.prowl/src/main/java/org/openhab/binding/prowl/internal/action/ProwlActions.java b/bundles/org.openhab.binding.prowl/src/main/java/org/openhab/binding/prowl/internal/action/ProwlActions.java index 6846eb4b1..003103c86 100644 --- a/bundles/org.openhab.binding.prowl/src/main/java/org/openhab/binding/prowl/internal/action/ProwlActions.java +++ b/bundles/org.openhab.binding.prowl/src/main/java/org/openhab/binding/prowl/internal/action/ProwlActions.java @@ -78,8 +78,8 @@ public class ProwlActions implements ThingActions { public static void pushNotification(@Nullable ThingActions actions, @Nullable String event, @Nullable String description, int priority) { - if (actions instanceof ProwlActions) { - ((ProwlActions) actions).pushNotification(event, description, priority); + if (actions instanceof ProwlActions prowlActions) { + prowlActions.pushNotification(event, description, priority); } else { throw new IllegalArgumentException("Instance is not a ProwlActions class."); } diff --git a/bundles/org.openhab.binding.publictransportswitzerland/src/main/java/org/openhab/binding/publictransportswitzerland/internal/PublicTransportSwitzerlandHandlerFactory.java b/bundles/org.openhab.binding.publictransportswitzerland/src/main/java/org/openhab/binding/publictransportswitzerland/internal/PublicTransportSwitzerlandHandlerFactory.java index 6973e1cc9..a20c3db59 100644 --- a/bundles/org.openhab.binding.publictransportswitzerland/src/main/java/org/openhab/binding/publictransportswitzerland/internal/PublicTransportSwitzerlandHandlerFactory.java +++ b/bundles/org.openhab.binding.publictransportswitzerland/src/main/java/org/openhab/binding/publictransportswitzerland/internal/PublicTransportSwitzerlandHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.publictransportswitzerland.internal; import static org.openhab.binding.publictransportswitzerland.internal.PublicTransportSwitzerlandBindingConstants.*; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -37,7 +36,7 @@ import org.osgi.service.component.annotations.Component; @Component(configurationPid = "binding.publictransportswitzerland", service = ThingHandlerFactory.class) public class PublicTransportSwitzerlandHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_STATIONBOARD); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_STATIONBOARD); @Override public boolean supportsThingType(ThingTypeUID thingTypeUID) { diff --git a/bundles/org.openhab.binding.publictransportswitzerland/src/main/java/org/openhab/binding/publictransportswitzerland/internal/stationboard/PublicTransportSwitzerlandStationboardHandler.java b/bundles/org.openhab.binding.publictransportswitzerland/src/main/java/org/openhab/binding/publictransportswitzerland/internal/stationboard/PublicTransportSwitzerlandStationboardHandler.java index 9b924401b..c0eda20e7 100644 --- a/bundles/org.openhab.binding.publictransportswitzerland/src/main/java/org/openhab/binding/publictransportswitzerland/internal/stationboard/PublicTransportSwitzerlandStationboardHandler.java +++ b/bundles/org.openhab.binding.publictransportswitzerland/src/main/java/org/openhab/binding/publictransportswitzerland/internal/stationboard/PublicTransportSwitzerlandStationboardHandler.java @@ -236,9 +236,10 @@ public class PublicTransportSwitzerlandStationboardHandler extends BaseThingHand if (categoryElement == null || numberElement == null || destinationElement == null || departureTimeElement == null) { - logger.warn("Skipping stationboard item." - + "One of the following is null: category: {}, number: {}, destination: {}, departureTime: {}", - categoryElement, numberElement, destinationElement, departureTimeElement); + logger.warn(""" + Skipping stationboard item.\ + One of the following is null: category: {}, number: {}, destination: {}, departureTime: {}\ + """, categoryElement, numberElement, destinationElement, departureTimeElement); continue; } diff --git a/bundles/org.openhab.binding.pulseaudio/src/main/java/org/openhab/binding/pulseaudio/internal/PulseaudioClient.java b/bundles/org.openhab.binding.pulseaudio/src/main/java/org/openhab/binding/pulseaudio/internal/PulseaudioClient.java index eeab4962b..a0729193c 100644 --- a/bundles/org.openhab.binding.pulseaudio/src/main/java/org/openhab/binding/pulseaudio/internal/PulseaudioClient.java +++ b/bundles/org.openhab.binding.pulseaudio/src/main/java/org/openhab/binding/pulseaudio/internal/PulseaudioClient.java @@ -225,8 +225,8 @@ public class PulseaudioClient { */ public @Nullable Sink getSink(String name) { for (AbstractAudioDeviceConfig item : items) { - if (item.getPaName().equalsIgnoreCase(name) && item instanceof Sink) { - return (Sink) item; + if (item.getPaName().equalsIgnoreCase(name) && item instanceof Sink sink) { + return sink; } } return null; @@ -239,8 +239,8 @@ public class PulseaudioClient { */ public @Nullable Sink getSink(int id) { for (AbstractAudioDeviceConfig item : items) { - if (item.getId() == id && item instanceof Sink) { - return (Sink) item; + if (item.getId() == id && item instanceof Sink sink) { + return sink; } } return null; @@ -253,8 +253,8 @@ public class PulseaudioClient { */ public @Nullable Source getSource(int id) { for (AbstractAudioDeviceConfig item : items) { - if (item.getId() == id && item instanceof Source) { - return (Source) item; + if (item.getId() == id && item instanceof Source source) { + return source; } } return null; @@ -362,8 +362,10 @@ public class PulseaudioClient { currentTry++; } while (currentTry < 3); - logger.warn("The pulseaudio binding tried 3 times to load the module-simple-protocol-tcp" - + " on random port on the pulseaudio server and give up trying"); + logger.warn(""" + The pulseaudio binding tried 3 times to load the module-simple-protocol-tcp\ + on random port on the pulseaudio server and give up trying\ + """); return Optional.empty(); } diff --git a/bundles/org.openhab.binding.pulseaudio/src/main/java/org/openhab/binding/pulseaudio/internal/discovery/PulseaudioDeviceDiscoveryService.java b/bundles/org.openhab.binding.pulseaudio/src/main/java/org/openhab/binding/pulseaudio/internal/discovery/PulseaudioDeviceDiscoveryService.java index 915f59645..d529eb68e 100644 --- a/bundles/org.openhab.binding.pulseaudio/src/main/java/org/openhab/binding/pulseaudio/internal/discovery/PulseaudioDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.pulseaudio/src/main/java/org/openhab/binding/pulseaudio/internal/discovery/PulseaudioDeviceDiscoveryService.java @@ -83,8 +83,8 @@ public class PulseaudioDeviceDiscoveryService extends AbstractDiscoveryService i Map properties = new HashMap<>(); // All devices need this parameter properties.put(PulseaudioBindingConstants.DEVICE_PARAMETER_NAME_OR_DESCRIPTION, uidName); - if (device instanceof Sink) { - if (((Sink) device).isCombinedSink()) { + if (device instanceof Sink sink) { + if (sink.isCombinedSink()) { thingType = PulseaudioBindingConstants.COMBINED_SINK_THING_TYPE; } else { thingType = PulseaudioBindingConstants.SINK_THING_TYPE; diff --git a/bundles/org.openhab.binding.pulseaudio/src/main/java/org/openhab/binding/pulseaudio/internal/handler/PulseaudioBridgeHandler.java b/bundles/org.openhab.binding.pulseaudio/src/main/java/org/openhab/binding/pulseaudio/internal/handler/PulseaudioBridgeHandler.java index 56367d4a4..e6a327505 100644 --- a/bundles/org.openhab.binding.pulseaudio/src/main/java/org/openhab/binding/pulseaudio/internal/handler/PulseaudioBridgeHandler.java +++ b/bundles/org.openhab.binding.pulseaudio/src/main/java/org/openhab/binding/pulseaudio/internal/handler/PulseaudioBridgeHandler.java @@ -16,7 +16,6 @@ import static org.openhab.binding.pulseaudio.internal.PulseaudioBindingConstants import java.io.IOException; import java.math.BigDecimal; -import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -57,8 +56,8 @@ import org.slf4j.LoggerFactory; public class PulseaudioBridgeHandler extends BaseBridgeHandler implements PulseAudioBindingConfigurationListener { private final Logger logger = LoggerFactory.getLogger(PulseaudioBridgeHandler.class); - public static final Set SUPPORTED_THING_TYPES_UIDS = Collections - .singleton(PulseaudioBindingConstants.BRIDGE_THING_TYPE); + public static final Set SUPPORTED_THING_TYPES_UIDS = Set + .of(PulseaudioBindingConstants.BRIDGE_THING_TYPE); public String host = "localhost"; public int port = 4712; @@ -215,8 +214,8 @@ public class PulseaudioBridgeHandler extends BaseBridgeHandler implements PulseA @Override public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) { - if (childHandler instanceof PulseaudioHandler) { - this.childHandlersInitialized.add((PulseaudioHandler) childHandler); + if (childHandler instanceof PulseaudioHandler pulsaudioHandler) { + this.childHandlersInitialized.add(pulsaudioHandler); } else { logger.error("This bridge can only support PulseaudioHandler child"); } diff --git a/bundles/org.openhab.binding.pulseaudio/src/main/java/org/openhab/binding/pulseaudio/internal/handler/PulseaudioHandler.java b/bundles/org.openhab.binding.pulseaudio/src/main/java/org/openhab/binding/pulseaudio/internal/handler/PulseaudioHandler.java index 9658e5741..72a10ce50 100644 --- a/bundles/org.openhab.binding.pulseaudio/src/main/java/org/openhab/binding/pulseaudio/internal/handler/PulseaudioHandler.java +++ b/bundles/org.openhab.binding.pulseaudio/src/main/java/org/openhab/binding/pulseaudio/internal/handler/PulseaudioHandler.java @@ -252,8 +252,8 @@ public class PulseaudioHandler extends BaseThingHandler { return null; } ThingHandler handler = bridge.getHandler(); - if (handler instanceof PulseaudioBridgeHandler) { - return (PulseaudioBridgeHandler) handler; + if (handler instanceof PulseaudioBridgeHandler pulseaudioBridgeHandler) { + return pulseaudioBridgeHandler; } else { logger.debug("No available bridge handler found for device {} bridge {} .", safeGetDeviceNameOrDescription(), bridge.getUID()); @@ -300,25 +300,22 @@ public class PulseaudioHandler extends BaseThingHandler { briHandler.getClient().setVolumePercent(device, newVolume); updateState = new PercentType(newVolume); savedVolume = newVolume; - } else if (command instanceof PercentType) { - DecimalType volume = (DecimalType) command; + } else if (command instanceof PercentType volume) { briHandler.getClient().setVolumePercent(device, volume.intValue()); - updateState = (PercentType) command; + updateState = volume; savedVolume = volume.intValue(); - } else if (command instanceof DecimalType) { - // set volume - DecimalType volume = (DecimalType) command; + } else if (command instanceof DecimalType volume) { briHandler.getClient().setVolume(device, volume.intValue()); - updateState = (DecimalType) command; + updateState = volume; savedVolume = volume.intValue(); } } else if (channelUID.getId().equals(MUTE_CHANNEL)) { - if (command instanceof OnOffType) { + if (command instanceof OnOffType onOffCommand) { briHandler.getClient().setMute(device, OnOffType.ON.equals(command)); - updateState = (OnOffType) command; + updateState = onOffCommand; } } else if (channelUID.getId().equals(SLAVES_CHANNEL)) { - if (device instanceof Sink && ((Sink) device).isCombinedSink()) { + if (device instanceof Sink sink && sink.isCombinedSink()) { if (command instanceof StringType) { List slaves = new ArrayList<>(); for (String slaveName : command.toString().split(",")) { @@ -335,16 +332,16 @@ public class PulseaudioHandler extends BaseThingHandler { logger.warn("{} is no combined sink", device); } } else if (channelUID.getId().equals(ROUTE_TO_SINK_CHANNEL)) { - if (device instanceof SinkInput) { + if (device instanceof SinkInput input) { Sink newSink = null; - if (command instanceof DecimalType) { - newSink = briHandler.getClient().getSink(((DecimalType) command).intValue()); + if (command instanceof DecimalType decimalCommand) { + newSink = briHandler.getClient().getSink(decimalCommand.intValue()); } else { newSink = briHandler.getClient().getSink(command.toString()); } if (newSink != null) { logger.debug("rerouting {} to {}", device, newSink); - briHandler.getClient().moveSinkInput(((SinkInput) device), newSink); + briHandler.getClient().moveSinkInput(input, newSink); updateState = new StringType(newSink.getPaName()); } else { logger.warn("no sink {} found", command.toString()); @@ -405,12 +402,12 @@ public class PulseaudioHandler extends BaseThingHandler { updateState(MUTE_CHANNEL, OnOffType.from(device.isMuted())); org.openhab.binding.pulseaudio.internal.items.AbstractAudioDeviceConfig.State state = device.getState(); updateState(STATE_CHANNEL, state != null ? new StringType(state.toString()) : new StringType("-")); - if (device instanceof SinkInput) { - updateState(ROUTE_TO_SINK_CHANNEL, new StringType( - Optional.ofNullable(((SinkInput) device).getSink()).map(Sink::getPaName).orElse("-"))); + if (device instanceof SinkInput input) { + updateState(ROUTE_TO_SINK_CHANNEL, + new StringType(Optional.ofNullable(input.getSink()).map(Sink::getPaName).orElse("-"))); } - if (device instanceof Sink && ((Sink) device).isCombinedSink()) { - updateState(SLAVES_CHANNEL, new StringType(String.join(",", ((Sink) device).getCombinedSinkNames()))); + if (device instanceof Sink sink && sink.isCombinedSink()) { + updateState(SLAVES_CHANNEL, new StringType(String.join(",", sink.getCombinedSinkNames()))); } audioSinkSetup(); audioSourceSetup(); diff --git a/bundles/org.openhab.binding.pushbullet/src/main/java/org/openhab/binding/pushbullet/internal/PushbulletBindingConstants.java b/bundles/org.openhab.binding.pushbullet/src/main/java/org/openhab/binding/pushbullet/internal/PushbulletBindingConstants.java index c3267b3b5..c6ffa7ccb 100644 --- a/bundles/org.openhab.binding.pushbullet/src/main/java/org/openhab/binding/pushbullet/internal/PushbulletBindingConstants.java +++ b/bundles/org.openhab.binding.pushbullet/src/main/java/org/openhab/binding/pushbullet/internal/PushbulletBindingConstants.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.pushbullet.internal; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -32,7 +31,7 @@ public class PushbulletBindingConstants { // List of all Thing Type UIDs public static final ThingTypeUID THING_TYPE_BOT = new ThingTypeUID(BINDING_ID, "bot"); - public static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_BOT); + public static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_BOT); // List of all Channel ids public static final String RECIPIENT = "recipient"; diff --git a/bundles/org.openhab.binding.pushbullet/src/main/java/org/openhab/binding/pushbullet/internal/handler/PushbulletHandler.java b/bundles/org.openhab.binding.pushbullet/src/main/java/org/openhab/binding/pushbullet/internal/handler/PushbulletHandler.java index 85996ced7..b74d72570 100644 --- a/bundles/org.openhab.binding.pushbullet/src/main/java/org/openhab/binding/pushbullet/internal/handler/PushbulletHandler.java +++ b/bundles/org.openhab.binding.pushbullet/src/main/java/org/openhab/binding/pushbullet/internal/handler/PushbulletHandler.java @@ -19,8 +19,8 @@ import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Collection; -import java.util.Collections; import java.util.Properties; +import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -97,7 +97,7 @@ public class PushbulletHandler extends BaseThingHandler { @Override public Collection> getServices() { - return Collections.singleton(PushbulletActions.class); + return Set.of(PushbulletActions.class); } public boolean sendPush(@Nullable String recipient, @Nullable String message, String type) { @@ -129,8 +129,6 @@ public class PushbulletHandler extends BaseThingHandler { logger.debug("Unpacked Response: {}", response); - stream.close(); - if ((null != response) && (null == response.getPushError())) { result = true; } diff --git a/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/QbusBindingConstants.java b/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/QbusBindingConstants.java index c75346564..b666bc556 100644 --- a/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/QbusBindingConstants.java +++ b/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/QbusBindingConstants.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.qbus.internal; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -31,7 +30,7 @@ public class QbusBindingConstants { // bridge public static final ThingTypeUID BRIDGE_THING_TYPE = new ThingTypeUID(BINDING_ID, "bridge"); - public static final Set BRIDGE_THING_TYPES_UIDS = Collections.singleton(BRIDGE_THING_TYPE); + public static final Set BRIDGE_THING_TYPES_UIDS = Set.of(BRIDGE_THING_TYPE); // Bridge config properties public static final String CONFIG_HOST_NAME = "addr"; public static final String CONFIG_PORT = "port"; diff --git a/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/QbusBridgeHandler.java b/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/QbusBridgeHandler.java index 8f1c7ec39..713c3c480 100644 --- a/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/QbusBridgeHandler.java +++ b/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/QbusBridgeHandler.java @@ -274,8 +274,7 @@ public class QbusBridgeHandler extends BaseBridgeHandler { */ public ThingStatusDetail getStatusDetails() { ThingStatusInfo status = thing.getStatusInfo(); - ThingStatusDetail detail = status.getStatusDetail(); - return detail; + return status.getStatusDetail(); } /** diff --git a/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/QbusHandlerFactory.java b/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/QbusHandlerFactory.java index b05774678..f3ae79af9 100644 --- a/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/QbusHandlerFactory.java +++ b/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/QbusHandlerFactory.java @@ -49,8 +49,7 @@ public class QbusHandlerFactory extends BaseThingHandlerFactory { @Override protected @Nullable ThingHandler createHandler(Thing thing) { if (BRIDGE_THING_TYPES_UIDS.contains(thing.getThingTypeUID())) { - QbusBridgeHandler handler = new QbusBridgeHandler((Bridge) thing); - return handler; + return new QbusBridgeHandler((Bridge) thing); } else if (SCENE_THING_TYPES_UIDS.contains(thing.getThingTypeUID())) { return new QbusSceneHandler(thing); } else if (BISTABIEL_THING_TYPES_UIDS.contains(thing.getThingTypeUID())) { diff --git a/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/handler/QbusDimmerHandler.java b/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/handler/QbusDimmerHandler.java index b28ae70a5..3daa280be 100644 --- a/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/handler/QbusDimmerHandler.java +++ b/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/handler/QbusDimmerHandler.java @@ -242,8 +242,8 @@ public class QbusDimmerHandler extends QbusGlobalHandler { qDimmer.execute(sendvalue, snr); } } - } else if (command instanceof PercentType) { - int percentToInt = ((PercentType) command).intValue(); + } else if (command instanceof PercentType percentCommand) { + int percentToInt = percentCommand.intValue(); if (PercentType.ZERO.equals(command)) { qDimmer.execute(0, snr); } else { diff --git a/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/handler/QbusGlobalHandler.java b/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/handler/QbusGlobalHandler.java index 0e1be2f89..717625842 100644 --- a/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/handler/QbusGlobalHandler.java +++ b/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/handler/QbusGlobalHandler.java @@ -55,8 +55,7 @@ public abstract class QbusGlobalHandler extends BaseThingHandler { "No bridge handler initialized for " + type + " with id " + globalId + "."); return null; } - QbusCommunication qComm = qBridgeHandler.getCommunication(); - return qComm; + return qBridgeHandler.getCommunication(); } /** @@ -73,8 +72,7 @@ public abstract class QbusGlobalHandler extends BaseThingHandler { "No bridge initialized for " + type + " with ID " + globalId); return null; } - QbusBridgeHandler qBridgeHandler = (QbusBridgeHandler) qBridge.getHandler(); - return qBridgeHandler; + return (QbusBridgeHandler) qBridge.getHandler(); } /** diff --git a/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/handler/QbusRolHandler.java b/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/handler/QbusRolHandler.java index d03a1ca7e..b8a7c9723 100644 --- a/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/handler/QbusRolHandler.java +++ b/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/handler/QbusRolHandler.java @@ -187,21 +187,19 @@ public class QbusRolHandler extends QbusGlobalHandler { private void handleScreenposCommand(QbusRol qRol, Command command) throws InterruptedException, IOException { String snr = getSN(); if (snr != null) { - if (command instanceof UpDownType) { - UpDownType upDown = (UpDownType) command; - if (upDown == DOWN) { + if (command instanceof UpDownType upDownCommand) { + if (upDownCommand == DOWN) { qRol.execute(0, snr); } else { qRol.execute(100, snr); } - } else if (command instanceof IncreaseDecreaseType) { - IncreaseDecreaseType inc = (IncreaseDecreaseType) command; + } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) { int stepValue = ((Number) getConfig().get(CONFIG_STEP_VALUE)).intValue(); Integer currentValue = qRol.getState(); int newValue; int sendValue; if (currentValue != null) { - if (inc == IncreaseDecreaseType.INCREASE) { + if (increaseDecreaseCommand == increaseDecreaseCommand.INCREASE) { newValue = currentValue + stepValue; // round down to step multiple newValue = newValue - newValue % stepValue; @@ -215,10 +213,9 @@ public class QbusRolHandler extends QbusGlobalHandler { qRol.execute(sendValue, snr); } } - } else if (command instanceof PercentType) { - PercentType p = (PercentType) command; - int pp = p.intValue(); - if (PercentType.ZERO.equals(p)) { + } else if (command instanceof PercentType percentCommand) { + int pp = percentCommand.intValue(); + if (PercentType.ZERO.equals(percentCommand)) { qRol.execute(0, snr); } else { qRol.execute(pp, snr); @@ -262,8 +259,8 @@ public class QbusRolHandler extends QbusGlobalHandler { qRol.executeSlats(sendValue, snr); } } - } else if (command instanceof PercentType) { - int percentToInt = ((PercentType) command).intValue(); + } else if (command instanceof PercentType percentCommand) { + int percentToInt = percentCommand.intValue(); if (PercentType.ZERO.equals(command)) { qRol.executeSlats(0, snr); } else { diff --git a/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/handler/QbusThermostatHandler.java b/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/handler/QbusThermostatHandler.java index 4bfe677f1..d6376ea8d 100644 --- a/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/handler/QbusThermostatHandler.java +++ b/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/handler/QbusThermostatHandler.java @@ -194,8 +194,8 @@ public class QbusThermostatHandler extends QbusGlobalHandler { throws InterruptedException, IOException { String snr = getSN(); if (snr != null) { - if (command instanceof DecimalType) { - int mode = ((DecimalType) command).intValue(); + if (command instanceof DecimalType decimalCommand) { + int mode = decimalCommand.intValue(); qThermostat.executeMode(mode, snr); } } @@ -214,10 +214,9 @@ public class QbusThermostatHandler extends QbusGlobalHandler { throws InterruptedException, IOException { String snr = getSN(); if (snr != null) { - if (command instanceof QuantityType) { - QuantityType s = (QuantityType) command; - double sp = s.doubleValue(); - QuantityType spCelcius = s.toUnit(CELSIUS); + if (command instanceof QuantityType quantityCommand) { + double sp = quantityCommand.doubleValue(); + QuantityType spCelcius = quantityCommand.toUnit(CELSIUS); if (spCelcius != null) { qThermostat.executeSetpoint(sp, snr); diff --git a/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/protocol/QbusCommunication.java b/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/protocol/QbusCommunication.java index 900c85ab3..2e96edff3 100644 --- a/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/protocol/QbusCommunication.java +++ b/bundles/org.openhab.binding.qbus/src/main/java/org/openhab/binding/qbus/internal/protocol/QbusCommunication.java @@ -410,7 +410,7 @@ public final class QbusCommunication extends BaseThingHandler { } if (ctdState != null) { - if (ctdType.equals("bistabiel")) { + if ("bistabiel".equals(ctdType)) { QbusBistabiel output = new QbusBistabiel(ctdId); if (!bistabiel.containsKey(ctdId)) { output.setQComm(this); @@ -419,7 +419,7 @@ public final class QbusCommunication extends BaseThingHandler { } else { output.updateState(ctdStateI); } - } else if (ctdType.equals("dimmer")) { + } else if ("dimmer".equals(ctdType)) { QbusDimmer output = new QbusDimmer(ctdId); if (!dimmer.containsKey(ctdId)) { output.setQComm(this); @@ -428,7 +428,7 @@ public final class QbusCommunication extends BaseThingHandler { } else { output.updateState(ctdStateI); } - } else if (ctdType.equals("CO2")) { + } else if ("CO2".equals(ctdType)) { QbusCO2 output = new QbusCO2(); if (!co2.containsKey(ctdId)) { output.updateState(ctdStateI); @@ -436,13 +436,13 @@ public final class QbusCommunication extends BaseThingHandler { } else { output.updateState(ctdStateI); } - } else if (ctdType.equals("scene")) { + } else if ("scene".equals(ctdType)) { QbusScene output = new QbusScene(ctdId); if (!scene.containsKey(ctdId)) { output.setQComm(this); scene.put(ctdId, output); } - } else if (ctdType.equals("rol")) { + } else if ("rol".equals(ctdType)) { QbusRol output = new QbusRol(ctdId); if (!rol.containsKey(ctdId)) { output.setQComm(this); @@ -459,7 +459,7 @@ public final class QbusCommunication extends BaseThingHandler { } } } else if (ctdMeasuredD != null && ctdSetpointD != null && ctdMmodeI != null) { - if (ctdType.equals("thermostat")) { + if ("thermostat".equals(ctdType)) { QbusThermostat output = new QbusThermostat(ctdId); if (!thermostat.containsKey(ctdId)) { output.setQComm(this); diff --git a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/action/ArmingActionType.java b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/action/ArmingActionType.java index f83b7da90..a51f5ec8e 100644 --- a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/action/ArmingActionType.java +++ b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/action/ArmingActionType.java @@ -20,5 +20,5 @@ package org.openhab.binding.qolsysiq.internal.client.dto.action; public enum ArmingActionType { ARM_AWAY, ARM_STAY, - DISARM; + DISARM } diff --git a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/event/EventType.java b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/event/EventType.java index 0934fb43d..0265104e9 100644 --- a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/event/EventType.java +++ b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/event/EventType.java @@ -22,5 +22,5 @@ public enum EventType { ARMING, ERROR, INFO, - ZONE_EVENT; + ZONE_EVENT } diff --git a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/event/InfoEventType.java b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/event/InfoEventType.java index 48f39eece..f2c58f401 100644 --- a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/event/InfoEventType.java +++ b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/event/InfoEventType.java @@ -19,5 +19,5 @@ package org.openhab.binding.qolsysiq.internal.client.dto.event; */ public enum InfoEventType { SUMMARY, - SECURE_ARM; + SECURE_ARM } diff --git a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/event/ZoneEventType.java b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/event/ZoneEventType.java index 67eafa9e9..9be16c021 100644 --- a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/event/ZoneEventType.java +++ b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/event/ZoneEventType.java @@ -20,5 +20,5 @@ package org.openhab.binding.qolsysiq.internal.client.dto.event; public enum ZoneEventType { ZONE_ACTIVE, ZONE_ADD, - ZONE_UPDATE; + ZONE_UPDATE } diff --git a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/model/AlarmType.java b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/model/AlarmType.java index 061008ee9..c45e2ba36 100644 --- a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/model/AlarmType.java +++ b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/model/AlarmType.java @@ -25,5 +25,5 @@ public enum AlarmType { POLICE, @SerializedName("") ZONEOPEN, - NONE; + NONE } diff --git a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/model/PartitionStatus.java b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/model/PartitionStatus.java index 801f4a20a..aaeb99ccc 100644 --- a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/model/PartitionStatus.java +++ b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/model/PartitionStatus.java @@ -23,5 +23,5 @@ public enum PartitionStatus { ARM_STAY, DISARM, ENTRY_DELAY, - EXIT_DELAY; + EXIT_DELAY } diff --git a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/model/ZoneStatus.java b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/model/ZoneStatus.java index 8b9c80a87..c0e802e56 100644 --- a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/model/ZoneStatus.java +++ b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/model/ZoneStatus.java @@ -31,5 +31,5 @@ public enum ZoneStatus { @SerializedName("Idle") IDlE, @SerializedName("Tamper") - TAMPER; + TAMPER } diff --git a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/model/ZoneType.java b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/model/ZoneType.java index f5bfa4306..f3a48c3e5 100644 --- a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/model/ZoneType.java +++ b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/client/dto/model/ZoneType.java @@ -115,5 +115,5 @@ public enum ZoneType { @SerializedName("120") ZWAVE_SIREN, @SerializedName("121") - COUNT; + COUNT } diff --git a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/discovery/QolsysIQChildDiscoveryService.java b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/discovery/QolsysIQChildDiscoveryService.java index 20c21eb2b..78cfbd73b 100644 --- a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/discovery/QolsysIQChildDiscoveryService.java +++ b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/discovery/QolsysIQChildDiscoveryService.java @@ -51,8 +51,8 @@ public class QolsysIQChildDiscoveryService extends AbstractDiscoveryService @Override public void setThingHandler(ThingHandler handler) { - if (handler instanceof QolsysIQChildDiscoveryHandler) { - ((QolsysIQChildDiscoveryHandler) handler).setDiscoveryService(this); + if (handler instanceof QolsysIQChildDiscoveryHandler childDiscoveryHandler) { + childDiscoveryHandler.setDiscoveryService(this); this.thingHandler = handler; } } diff --git a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/handler/QolsysIQPanelHandler.java b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/handler/QolsysIQPanelHandler.java index 7939ebd88..37bb1ecc9 100644 --- a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/handler/QolsysIQPanelHandler.java +++ b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/handler/QolsysIQPanelHandler.java @@ -17,6 +17,7 @@ import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; +import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -100,7 +101,7 @@ public class QolsysIQPanelHandler extends BaseBridgeHandler @Override public Collection> getServices() { - return Collections.singleton(QolsysIQChildDiscoveryService.class); + return Set.of(QolsysIQChildDiscoveryService.class); } @Override @@ -316,9 +317,9 @@ public class QolsysIQPanelHandler extends BaseBridgeHandler private @Nullable QolsysIQPartitionHandler partitionHandler(int partitionId) { for (Thing thing : getThing().getThings()) { ThingHandler handler = thing.getHandler(); - if (handler instanceof QolsysIQPartitionHandler) { - if (((QolsysIQPartitionHandler) handler).getPartitionId() == partitionId) { - return (QolsysIQPartitionHandler) handler; + if (handler instanceof QolsysIQPartitionHandler partitionHandler) { + if (partitionHandler.getPartitionId() == partitionId) { + return partitionHandler; } } } diff --git a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/handler/QolsysIQPartitionHandler.java b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/handler/QolsysIQPartitionHandler.java index 702193a4e..12483d91a 100644 --- a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/handler/QolsysIQPartitionHandler.java +++ b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/handler/QolsysIQPartitionHandler.java @@ -18,6 +18,7 @@ import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -156,7 +157,7 @@ public class QolsysIQPartitionHandler extends BaseBridgeHandler implements Qolsy @Override public Collection> getServices() { - return Collections.singleton(QolsysIQChildDiscoveryService.class); + return Set.of(QolsysIQChildDiscoveryService.class); } @Override @@ -347,9 +348,9 @@ public class QolsysIQPartitionHandler extends BaseBridgeHandler implements Qolsy private @Nullable QolsysIQZoneHandler zoneHandler(int zoneId) { for (Thing thing : getThing().getThings()) { ThingHandler handler = thing.getHandler(); - if (handler instanceof QolsysIQZoneHandler) { - if (((QolsysIQZoneHandler) handler).getZoneId() == zoneId) { - return (QolsysIQZoneHandler) handler; + if (handler instanceof QolsysIQZoneHandler zoneHandler) { + if (zoneHandler.getZoneId() == zoneId) { + return zoneHandler; } } } @@ -360,8 +361,8 @@ public class QolsysIQPartitionHandler extends BaseBridgeHandler implements Qolsy Bridge bridge = getBridge(); if (bridge != null) { BridgeHandler handler = bridge.getHandler(); - if (handler instanceof QolsysIQPanelHandler) { - return (QolsysIQPanelHandler) handler; + if (handler instanceof QolsysIQPanelHandler panelHandler) { + return panelHandler; } } return null; diff --git a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/handler/QolsysIQZoneHandler.java b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/handler/QolsysIQZoneHandler.java index 361378ad9..f4d513a7c 100644 --- a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/handler/QolsysIQZoneHandler.java +++ b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/handler/QolsysIQZoneHandler.java @@ -105,12 +105,12 @@ public class QolsysIQZoneHandler extends BaseThingHandler { private void initializeZone() { Bridge bridge = getBridge(); BridgeHandler handler = bridge == null ? null : bridge.getHandler(); - if (bridge != null && handler instanceof QolsysIQPartitionHandler) { + if (bridge != null && handler instanceof QolsysIQPartitionHandler partitionHandler) { if (handler.getThing().getStatus() != ThingStatus.ONLINE) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE); return; } - Zone z = ((QolsysIQPartitionHandler) handler).getZone(getZoneId()); + Zone z = partitionHandler.getZone(getZoneId()); if (z == null) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Zone not found in partition"); return; diff --git a/bundles/org.openhab.binding.radiothermostat/src/main/java/org/openhab/binding/radiothermostat/internal/RadioThermostatHandlerFactory.java b/bundles/org.openhab.binding.radiothermostat/src/main/java/org/openhab/binding/radiothermostat/internal/RadioThermostatHandlerFactory.java index 227ee7eb5..069ab3118 100644 --- a/bundles/org.openhab.binding.radiothermostat/src/main/java/org/openhab/binding/radiothermostat/internal/RadioThermostatHandlerFactory.java +++ b/bundles/org.openhab.binding.radiothermostat/src/main/java/org/openhab/binding/radiothermostat/internal/RadioThermostatHandlerFactory.java @@ -61,8 +61,7 @@ public class RadioThermostatHandlerFactory extends BaseThingHandlerFactory { ThingTypeUID thingTypeUID = thing.getThingTypeUID(); if (thingTypeUID.equals(THING_TYPE_RTHERM)) { - RadioThermostatHandler handler = new RadioThermostatHandler(thing, stateDescriptionProvider, httpClient); - return handler; + return new RadioThermostatHandler(thing, stateDescriptionProvider, httpClient); } return null; diff --git a/bundles/org.openhab.binding.radiothermostat/src/main/java/org/openhab/binding/radiothermostat/internal/handler/RadioThermostatHandler.java b/bundles/org.openhab.binding.radiothermostat/src/main/java/org/openhab/binding/radiothermostat/internal/handler/RadioThermostatHandler.java index 26c6569d5..819da52cd 100644 --- a/bundles/org.openhab.binding.radiothermostat/src/main/java/org/openhab/binding/radiothermostat/internal/handler/RadioThermostatHandler.java +++ b/bundles/org.openhab.binding.radiothermostat/src/main/java/org/openhab/binding/radiothermostat/internal/handler/RadioThermostatHandler.java @@ -136,7 +136,7 @@ public class RadioThermostatHandler extends BaseThingHandler implements RadioThe // The setpoint mode is controlled by the name of setpoint attribute sent to the thermostat. // Temporary mode uses setpoint names prefixed with "t_" while absolute mode uses "a_" - if (config.setpointMode.equals("absolute")) { + if ("absolute".equals(config.setpointMode)) { this.setpointCmdKeyPrefix = "a_"; } @@ -479,18 +479,18 @@ public class RadioThermostatHandler extends BaseThingHandler implements RadioThe State state = null; if (value == null) { state = UnDefType.UNDEF; - } else if (value instanceof PointType) { - state = (PointType) value; - } else if (value instanceof ZonedDateTime) { - state = new DateTimeType((ZonedDateTime) value); - } else if (value instanceof QuantityType) { - state = (QuantityType) value; - } else if (value instanceof Number) { - state = new DecimalType((Number) value); + } else if (value instanceof PointType pointCommand) { + state = pointCommand; + } else if (value instanceof ZonedDateTime zonedDateTimeCommand) { + state = new DateTimeType(zonedDateTimeCommand); + } else if (value instanceof QuantityType quantityCommand) { + state = quantityCommand; + } else if (value instanceof Number numberCommand) { + state = new DecimalType(numberCommand); } else if (value instanceof String) { state = new StringType(value.toString()); - } else if (value instanceof OnOffType) { - state = (OnOffType) value; + } else if (value instanceof OnOffType onOffCommand) { + state = onOffCommand; } else { logger.warn("Update channel {}: Unsupported value type {}", channelId, value.getClass().getSimpleName()); diff --git a/bundles/org.openhab.binding.remoteopenhab/src/main/java/org/openhab/binding/remoteopenhab/internal/RemoteopenhabBindingConstants.java b/bundles/org.openhab.binding.remoteopenhab/src/main/java/org/openhab/binding/remoteopenhab/internal/RemoteopenhabBindingConstants.java index 8c64b878f..2b0686cc2 100644 --- a/bundles/org.openhab.binding.remoteopenhab/src/main/java/org/openhab/binding/remoteopenhab/internal/RemoteopenhabBindingConstants.java +++ b/bundles/org.openhab.binding.remoteopenhab/src/main/java/org/openhab/binding/remoteopenhab/internal/RemoteopenhabBindingConstants.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.remoteopenhab.internal; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -34,10 +33,10 @@ public class RemoteopenhabBindingConstants { public static final ThingTypeUID THING_TYPE_THING = new ThingTypeUID(BINDING_ID, "thing"); // All supported Bridge types - public static final Set SUPPORTED_BRIDGE_TYPES_UIDS = Collections.singleton(BRIDGE_TYPE_SERVER); + public static final Set SUPPORTED_BRIDGE_TYPES_UIDS = Set.of(BRIDGE_TYPE_SERVER); // All supported Thing types - public static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_THING); + public static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_THING); // List of all channel types public static final String CHANNEL_TYPE_TRIGGER = "trigger"; diff --git a/bundles/org.openhab.binding.remoteopenhab/src/main/java/org/openhab/binding/remoteopenhab/internal/discovery/RemoteopenhabDiscoveryService.java b/bundles/org.openhab.binding.remoteopenhab/src/main/java/org/openhab/binding/remoteopenhab/internal/discovery/RemoteopenhabDiscoveryService.java index 54fa055b5..d76711728 100644 --- a/bundles/org.openhab.binding.remoteopenhab/src/main/java/org/openhab/binding/remoteopenhab/internal/discovery/RemoteopenhabDiscoveryService.java +++ b/bundles/org.openhab.binding.remoteopenhab/src/main/java/org/openhab/binding/remoteopenhab/internal/discovery/RemoteopenhabDiscoveryService.java @@ -59,8 +59,8 @@ public class RemoteopenhabDiscoveryService extends AbstractDiscoveryService @Override public void setThingHandler(ThingHandler handler) { - if (handler instanceof RemoteopenhabBridgeHandler) { - this.bridgeHandler = (RemoteopenhabBridgeHandler) handler; + if (handler instanceof RemoteopenhabBridgeHandler remoteopenhabBridgeHandler) { + this.bridgeHandler = remoteopenhabBridgeHandler; this.restClient = bridgeHandler.gestRestClient(); } } diff --git a/bundles/org.openhab.binding.remoteopenhab/src/main/java/org/openhab/binding/remoteopenhab/internal/handler/RemoteopenhabBridgeHandler.java b/bundles/org.openhab.binding.remoteopenhab/src/main/java/org/openhab/binding/remoteopenhab/internal/handler/RemoteopenhabBridgeHandler.java index fbeab2ee2..88eacc09c 100644 --- a/bundles/org.openhab.binding.remoteopenhab/src/main/java/org/openhab/binding/remoteopenhab/internal/handler/RemoteopenhabBridgeHandler.java +++ b/bundles/org.openhab.binding.remoteopenhab/src/main/java/org/openhab/binding/remoteopenhab/internal/handler/RemoteopenhabBridgeHandler.java @@ -19,10 +19,10 @@ import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -552,7 +552,7 @@ public class RemoteopenhabBridgeHandler extends BaseBridgeHandler } else if (acceptedItemType.startsWith(CoreItemFactory.NUMBER + ":")) { // Item type Number with dimension if (stateType == null || "Quantity".equals(stateType)) { - List> stateTypes = Collections.singletonList(QuantityType.class); + List> stateTypes = List.of(QuantityType.class); channelState = TypeParser.parseState(stateTypes, state); } else if ("Decimal".equals(stateType)) { channelState = new DecimalType(state); @@ -661,6 +661,6 @@ public class RemoteopenhabBridgeHandler extends BaseBridgeHandler @Override public Collection> getServices() { - return Collections.singleton(RemoteopenhabDiscoveryService.class); + return Set.of(RemoteopenhabDiscoveryService.class); } } diff --git a/bundles/org.openhab.binding.remoteopenhab/src/main/java/org/openhab/binding/remoteopenhab/internal/rest/RemoteopenhabRestClient.java b/bundles/org.openhab.binding.remoteopenhab/src/main/java/org/openhab/binding/remoteopenhab/internal/rest/RemoteopenhabRestClient.java index 0d257c399..81d8acf6c 100644 --- a/bundles/org.openhab.binding.remoteopenhab/src/main/java/org/openhab/binding/remoteopenhab/internal/rest/RemoteopenhabRestClient.java +++ b/bundles/org.openhab.binding.remoteopenhab/src/main/java/org/openhab/binding/remoteopenhab/internal/rest/RemoteopenhabRestClient.java @@ -621,12 +621,10 @@ public class RemoteopenhabRestClient { String statusLine = statusCode + " " + response.getReason(); throw new RemoteopenhabException("@text/exception.http-call-failed", statusLine); } - String encoding = response.getEncoding() != null ? response.getEncoding().replaceAll("\"", "").trim() + String encoding = response.getEncoding() != null ? response.getEncoding().replace("\"", "").trim() : StandardCharsets.UTF_8.name(); return new String(response.getContent(), encoding); } - } catch (RemoteopenhabException e) { - throw e; } catch (ExecutionException e) { // After a long network outage, the first HTTP request will fail with an EOFException exception. // We retry the request a second time in this case. diff --git a/bundles/org.openhab.binding.renault/src/main/java/org/openhab/binding/renault/internal/api/Car.java b/bundles/org.openhab.binding.renault/src/main/java/org/openhab/binding/renault/internal/api/Car.java index 8231be38d..1ead79e93 100644 --- a/bundles/org.openhab.binding.renault/src/main/java/org/openhab/binding/renault/internal/api/Car.java +++ b/bundles/org.openhab.binding.renault/src/main/java/org/openhab/binding/renault/internal/api/Car.java @@ -141,7 +141,7 @@ public class Car { JsonObject attributes = getAttributes(responseJson); if (attributes != null) { if (attributes.get("hvacStatus") != null) { - hvacstatus = attributes.get("hvacStatus").getAsString().equals("on"); + hvacstatus = "on".equals(attributes.get("hvacStatus").getAsString()); } if (attributes.get("externalTemperature") != null) { externalTemperature = attributes.get("externalTemperature").getAsDouble(); @@ -207,13 +207,12 @@ public class Car { String url = null; for (JsonElement asset : assetsJson) { if (asset.getAsJsonObject().get("assetType") != null - && asset.getAsJsonObject().get("assetType").getAsString().equals("PICTURE")) { + && "PICTURE".equals(asset.getAsJsonObject().get("assetType").getAsString())) { if (asset.getAsJsonObject().get("renditions") != null) { JsonArray renditions = asset.getAsJsonObject().get("renditions").getAsJsonArray(); for (JsonElement rendition : renditions) { - if (rendition.getAsJsonObject().get("resolutionType") != null - && rendition.getAsJsonObject().get("resolutionType").getAsString() - .equals("ONE_MYRENAULT_SMALL")) { + if (rendition.getAsJsonObject().get("resolutionType") != null && "ONE_MYRENAULT_SMALL" + .equals(rendition.getAsJsonObject().get("resolutionType").getAsString())) { url = rendition.getAsJsonObject().get("url").getAsString(); break; } diff --git a/bundles/org.openhab.binding.renault/src/main/java/org/openhab/binding/renault/internal/api/MyRenaultHttpSession.java b/bundles/org.openhab.binding.renault/src/main/java/org/openhab/binding/renault/internal/api/MyRenaultHttpSession.java index e70756b90..55bf3c0fc 100644 --- a/bundles/org.openhab.binding.renault/src/main/java/org/openhab/binding/renault/internal/api/MyRenaultHttpSession.java +++ b/bundles/org.openhab.binding.renault/src/main/java/org/openhab/binding/renault/internal/api/MyRenaultHttpSession.java @@ -277,7 +277,6 @@ public class MyRenaultHttpSession { public void actionPause(boolean mode) throws RenaultForbiddenException, RenaultNotImplementedException, RenaultActionException, RenaultAPIGatewayException { - final String apiMode = mode ? "pause" : "resume"; final String path = "/commerce/v1/accounts/" + kamereonaccountId + "/kamereon/kcm/v1/vehicles/" + config.vin + "/charge/pause-resume?country=" + getCountry(config); diff --git a/bundles/org.openhab.binding.renault/src/main/java/org/openhab/binding/renault/internal/handler/RenaultHandler.java b/bundles/org.openhab.binding.renault/src/main/java/org/openhab/binding/renault/internal/handler/RenaultHandler.java index bfc76b719..ad0dc7525 100644 --- a/bundles/org.openhab.binding.renault/src/main/java/org/openhab/binding/renault/internal/handler/RenaultHandler.java +++ b/bundles/org.openhab.binding.renault/src/main/java/org/openhab/binding/renault/internal/handler/RenaultHandler.java @@ -123,15 +123,14 @@ public class RenaultHandler extends BaseThingHandler { @Override public void handleCommand(ChannelUID channelUID, Command command) { - switch (channelUID.getId()) { case RenaultBindingConstants.CHANNEL_HVAC_TARGET_TEMPERATURE: if (!car.isDisableHvac()) { if (command instanceof RefreshType) { updateState(CHANNEL_HVAC_TARGET_TEMPERATURE, new QuantityType(car.getHvacTargetTemperature(), SIUnits.CELSIUS)); - } else if (command instanceof DecimalType) { - car.setHvacTargetTemperature(((DecimalType) command).doubleValue()); + } else if (command instanceof DecimalType decimalCommand) { + car.setHvacTargetTemperature(decimalCommand.doubleValue()); updateState(CHANNEL_HVAC_TARGET_TEMPERATURE, new QuantityType(car.getHvacTargetTemperature(), SIUnits.CELSIUS)); } else if (command instanceof QuantityType) { diff --git a/bundles/org.openhab.binding.resol/src/main/java/org/openhab/binding/resol/handler/ResolBridgeHandler.java b/bundles/org.openhab.binding.resol/src/main/java/org/openhab/binding/resol/handler/ResolBridgeHandler.java index 1779f8a8d..0cb587d11 100644 --- a/bundles/org.openhab.binding.resol/src/main/java/org/openhab/binding/resol/handler/ResolBridgeHandler.java +++ b/bundles/org.openhab.binding.resol/src/main/java/org/openhab/binding/resol/handler/ResolBridgeHandler.java @@ -15,9 +15,9 @@ package org.openhab.binding.resol.handler; import java.io.IOException; import java.net.InetAddress; import java.util.Collection; -import java.util.Collections; import java.util.Locale; import java.util.Objects; +import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -102,7 +102,7 @@ public class ResolBridgeHandler extends BaseBridgeHandler { @Override public Collection> getServices() { - return Collections.singleton(ResolDeviceDiscoveryService.class); + return Set.of(ResolDeviceDiscoveryService.class); } public void registerResolThingListener(ResolEmuEMThingHandler resolEmuEMThingHandler) { @@ -125,8 +125,8 @@ public class ResolBridgeHandler extends BaseBridgeHandler { getThing().getThings().stream().forEach(thing -> { ThingHandler th = thing.getHandler(); - if (th instanceof ResolEmuEMThingHandler) { - ((ResolEmuEMThingHandler) th).stop(); + if (th instanceof ResolEmuEMThingHandler resolEmuEMThingHandler) { + resolEmuEMThingHandler.stop(); } }); @@ -175,8 +175,8 @@ public class ResolBridgeHandler extends BaseBridgeHandler { getThing().getThings().stream().forEach(thing -> { ThingHandler th = thing.getHandler(); - if (th instanceof ResolEmuEMThingHandler) { - ((ResolEmuEMThingHandler) th).useConnection(c); + if (th instanceof ResolEmuEMThingHandler resolEmuEMThingHandler) { + resolEmuEMThingHandler.useConnection(c); } }); } catch (IOException e) { @@ -235,11 +235,10 @@ public class ResolBridgeHandler extends BaseBridgeHandler { connection.disconnect(); getThing().getThings().stream().forEach(thing -> { ThingHandler th = thing.getHandler(); - if (th instanceof ResolEmuEMThingHandler) { - ((ResolEmuEMThingHandler) th).stop(); + if (th instanceof ResolEmuEMThingHandler resolEmuEMThingHandler) { + resolEmuEMThingHandler.stop(); } }); - } } catch (IOException ioe) { // we don't care about exceptions on disconnect in dispose diff --git a/bundles/org.openhab.binding.resol/src/main/java/org/openhab/binding/resol/handler/ResolEmuEMThingHandler.java b/bundles/org.openhab.binding.resol/src/main/java/org/openhab/binding/resol/handler/ResolEmuEMThingHandler.java index b95c5c0cf..4fd285b23 100644 --- a/bundles/org.openhab.binding.resol/src/main/java/org/openhab/binding/resol/handler/ResolEmuEMThingHandler.java +++ b/bundles/org.openhab.binding.resol/src/main/java/org/openhab/binding/resol/handler/ResolEmuEMThingHandler.java @@ -136,8 +136,8 @@ public class ResolEmuEMThingHandler extends ResolBaseThingHandler implements Pro ResolBridgeHandler bridgeHandler = null; ThingHandler handler = bridge.getHandler(); - if (handler instanceof ResolBridgeHandler) { - bridgeHandler = (ResolBridgeHandler) handler; + if (handler instanceof ResolBridgeHandler resolBridgeHandler) { + bridgeHandler = resolBridgeHandler; } else { logger.debug("No available bridge handler found yet. Bridge: {} .", bridge.getUID()); } @@ -190,13 +190,13 @@ public class ResolEmuEMThingHandler extends ResolBaseThingHandler implements Pro float value = 0; int intValue = 0; - if (command instanceof QuantityType) { - value = Objects.requireNonNullElse(((QuantityType) command).toUnit(SIUnits.CELSIUS), + if (command instanceof QuantityType quantityCommand) { + value = Objects.requireNonNullElse(quantityCommand.toUnit(SIUnits.CELSIUS), new QuantityType<>(888.8, SIUnits.CELSIUS)).floatValue(); - } else if (command instanceof OnOffType) { - intValue = ((OnOffType) command).equals(OnOffType.ON) ? 1 : 0; - } else if (command instanceof DecimalType) { - intValue = ((DecimalType) command).intValue(); + } else if (command instanceof OnOffType onOffCommand) { + intValue = onOffCommand.equals(OnOffType.ON) ? 1 : 0; + } else if (command instanceof DecimalType decimalCommand) { + intValue = decimalCommand.intValue(); value = intValue; } else { /* nothing to do */ diff --git a/bundles/org.openhab.binding.resol/src/main/java/org/openhab/binding/resol/handler/ResolThingHandler.java b/bundles/org.openhab.binding.resol/src/main/java/org/openhab/binding/resol/handler/ResolThingHandler.java index 20dff6490..21a1e354b 100644 --- a/bundles/org.openhab.binding.resol/src/main/java/org/openhab/binding/resol/handler/ResolThingHandler.java +++ b/bundles/org.openhab.binding.resol/src/main/java/org/openhab/binding/resol/handler/ResolThingHandler.java @@ -113,8 +113,8 @@ public class ResolThingHandler extends ResolBaseThingHandler { ResolBridgeHandler bridgeHandler = null; ThingHandler handler = bridge.getHandler(); - if (handler instanceof ResolBridgeHandler) { - bridgeHandler = (ResolBridgeHandler) handler; + if (handler instanceof ResolBridgeHandler resolBridgeHandler) { + bridgeHandler = resolBridgeHandler; } else { logger.debug("No available bridge handler found yet. Bridge: {} .", bridge.getUID()); } diff --git a/bundles/org.openhab.binding.resol/src/main/java/org/openhab/binding/resol/internal/discovery/ResolDeviceDiscoveryService.java b/bundles/org.openhab.binding.resol/src/main/java/org/openhab/binding/resol/internal/discovery/ResolDeviceDiscoveryService.java index dad172f2a..2687804ea 100644 --- a/bundles/org.openhab.binding.resol/src/main/java/org/openhab/binding/resol/internal/discovery/ResolDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.resol/src/main/java/org/openhab/binding/resol/internal/discovery/ResolDeviceDiscoveryService.java @@ -110,8 +110,8 @@ public class ResolDeviceDiscoveryService extends AbstractDiscoveryService @Override public void setThingHandler(ThingHandler handler) { - if (handler instanceof ResolBridgeHandler) { - resolBridgeHandler = (ResolBridgeHandler) handler; + if (handler instanceof ResolBridgeHandler resolBridgeHandler) { + this.resolBridgeHandler = resolBridgeHandler; } } diff --git a/bundles/org.openhab.binding.revogi/src/main/java/org/openhab/binding/revogi/internal/RevogiSmartStripControlHandlerFactory.java b/bundles/org.openhab.binding.revogi/src/main/java/org/openhab/binding/revogi/internal/RevogiSmartStripControlHandlerFactory.java index 89face499..a98e2e546 100644 --- a/bundles/org.openhab.binding.revogi/src/main/java/org/openhab/binding/revogi/internal/RevogiSmartStripControlHandlerFactory.java +++ b/bundles/org.openhab.binding.revogi/src/main/java/org/openhab/binding/revogi/internal/RevogiSmartStripControlHandlerFactory.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.revogi.internal; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -34,8 +33,8 @@ import org.osgi.service.component.annotations.Component; @Component(configurationPid = "binding.revogi", service = ThingHandlerFactory.class) public class RevogiSmartStripControlHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections - .singleton(RevogiSmartStripControlBindingConstants.SMART_STRIP_THING_TYPE); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set + .of(RevogiSmartStripControlBindingConstants.SMART_STRIP_THING_TYPE); @Override public boolean supportsThingType(ThingTypeUID thingTypeUID) { diff --git a/bundles/org.openhab.binding.revogi/src/main/java/org/openhab/binding/revogi/internal/RevogiSmartStripDiscoveryService.java b/bundles/org.openhab.binding.revogi/src/main/java/org/openhab/binding/revogi/internal/RevogiSmartStripDiscoveryService.java index b42626457..fe10af9e0 100644 --- a/bundles/org.openhab.binding.revogi/src/main/java/org/openhab/binding/revogi/internal/RevogiSmartStripDiscoveryService.java +++ b/bundles/org.openhab.binding.revogi/src/main/java/org/openhab/binding/revogi/internal/RevogiSmartStripDiscoveryService.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.revogi.internal; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -43,8 +42,8 @@ import org.osgi.service.component.annotations.Component; @Component(service = DiscoveryService.class, configurationPid = "discovery.revogi") @NonNullByDefault public class RevogiSmartStripDiscoveryService extends AbstractDiscoveryService { - public static final Set SUPPORTED_THING_TYPES = Collections - .singleton(RevogiSmartStripControlBindingConstants.SMART_STRIP_THING_TYPE); + public static final Set SUPPORTED_THING_TYPES = Set + .of(RevogiSmartStripControlBindingConstants.SMART_STRIP_THING_TYPE); private final RevogiDiscoveryService revogiDiscoveryService; diff --git a/bundles/org.openhab.binding.revogi/src/test/java/org/openhab/binding/revogi/internal/api/RevogiDiscoveryServiceTest.java b/bundles/org.openhab.binding.revogi/src/test/java/org/openhab/binding/revogi/internal/api/RevogiDiscoveryServiceTest.java index 27e154763..032f2645b 100644 --- a/bundles/org.openhab.binding.revogi/src/test/java/org/openhab/binding/revogi/internal/api/RevogiDiscoveryServiceTest.java +++ b/bundles/org.openhab.binding.revogi/src/test/java/org/openhab/binding/revogi/internal/api/RevogiDiscoveryServiceTest.java @@ -41,7 +41,7 @@ public class RevogiDiscoveryServiceTest { public void discoverSmartStripSuccesfully() { // given DiscoveryResponseDTO discoveryResponse = new DiscoveryResponseDTO("1234", "reg", "sak", "Strip", "mac", "5.11"); - List discoveryString = Collections.singletonList(new UdpResponseDTO( + List discoveryString = List.of(new UdpResponseDTO( "{\"response\":0,\"data\":{\"sn\":\"1234\",\"regid\":\"reg\",\"sak\":\"sak\",\"name\":\"Strip\",\"mac\":\"mac\",\"ver\":\"5.11\"}}", "127.0.0.1")); when(udpSenderService.broadcastUdpDatagram("00sw=all,,,;")) @@ -61,8 +61,7 @@ public class RevogiDiscoveryServiceTest { @Test public void invalidUdpResponse() throws ExecutionException, InterruptedException { // given - List discoveryString = Collections - .singletonList(new UdpResponseDTO("something invalid", "12345")); + List discoveryString = List.of(new UdpResponseDTO("something invalid", "12345")); when(udpSenderService.broadcastUdpDatagram("00sw=all,,,;")) .thenReturn(CompletableFuture.completedFuture(discoveryString)); diff --git a/bundles/org.openhab.binding.revogi/src/test/java/org/openhab/binding/revogi/internal/api/StatusServiceTest.java b/bundles/org.openhab.binding.revogi/src/test/java/org/openhab/binding/revogi/internal/api/StatusServiceTest.java index fab4aae7e..086301e45 100644 --- a/bundles/org.openhab.binding.revogi/src/test/java/org/openhab/binding/revogi/internal/api/StatusServiceTest.java +++ b/bundles/org.openhab.binding.revogi/src/test/java/org/openhab/binding/revogi/internal/api/StatusServiceTest.java @@ -17,7 +17,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; @@ -40,7 +39,7 @@ public class StatusServiceTest { // given StatusDTO status = new StatusDTO(true, 200, Arrays.asList(0, 0, 0, 0, 0, 0), Arrays.asList(0, 0, 0, 0, 0, 0), Arrays.asList(0, 0, 0, 0, 0, 0)); - List statusString = Collections.singletonList(new UdpResponseDTO( + List statusString = List.of(new UdpResponseDTO( "V3{\"response\":90,\"code\":200,\"data\":{\"switch\":[0,0,0,0,0,0],\"watt\":[0,0,0,0,0,0],\"amp\":[0,0,0,0,0,0]}}", "127.0.0.1")); when(udpSenderService.sendMessage("V3{\"sn\":\"serial\", \"cmd\": 90}", "127.0.0.1")) @@ -56,7 +55,7 @@ public class StatusServiceTest { @Test public void invalidUdpResponse() { // given - List statusString = Collections.singletonList(new UdpResponseDTO("something invalid", "12345")); + List statusString = List.of(new UdpResponseDTO("something invalid", "12345")); when(udpSenderService.sendMessage("V3{\"sn\":\"serial\", \"cmd\": 90}", "127.0.0.1")) .thenReturn(CompletableFuture.completedFuture(statusString)); diff --git a/bundles/org.openhab.binding.revogi/src/test/java/org/openhab/binding/revogi/internal/api/SwitchServiceTest.java b/bundles/org.openhab.binding.revogi/src/test/java/org/openhab/binding/revogi/internal/api/SwitchServiceTest.java index cc94ac246..6122a130f 100644 --- a/bundles/org.openhab.binding.revogi/src/test/java/org/openhab/binding/revogi/internal/api/SwitchServiceTest.java +++ b/bundles/org.openhab.binding.revogi/src/test/java/org/openhab/binding/revogi/internal/api/SwitchServiceTest.java @@ -17,7 +17,6 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; @@ -39,8 +38,7 @@ public class SwitchServiceTest { @Test public void getStatusSuccesfully() { // given - List response = Collections - .singletonList(new UdpResponseDTO("V3{\"response\":20,\"code\":200}", "127.0.0.1")); + List response = List.of(new UdpResponseDTO("V3{\"response\":20,\"code\":200}", "127.0.0.1")); when(udpSenderService.sendMessage("V3{\"sn\":\"serial\", \"cmd\": 20, \"port\": 1, \"state\": 1}", "127.0.0.1")) .thenReturn(CompletableFuture.completedFuture(response)); @@ -54,8 +52,7 @@ public class SwitchServiceTest { @Test public void getStatusSuccesfullyWithBroadcast() { // given - List response = Collections - .singletonList(new UdpResponseDTO("V3{\"response\":20,\"code\":200}", "127.0.0.1")); + List response = List.of(new UdpResponseDTO("V3{\"response\":20,\"code\":200}", "127.0.0.1")); when(udpSenderService.broadcastUdpDatagram("V3{\"sn\":\"serial\", \"cmd\": 20, \"port\": 1, \"state\": 1}")) .thenReturn(CompletableFuture.completedFuture(response)); @@ -69,7 +66,7 @@ public class SwitchServiceTest { @Test public void invalidUdpResponse() { // given - List response = Collections.singletonList(new UdpResponseDTO("something invalid", "12345")); + List response = List.of(new UdpResponseDTO("something invalid", "12345")); when(udpSenderService.sendMessage("V3{\"sn\":\"serial\", \"cmd\": 20, \"port\": 1, \"state\": 1}", "127.0.0.1")) .thenReturn(CompletableFuture.completedFuture(response)); diff --git a/bundles/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/internal/discovery/RFXComBridgeDiscovery.java b/bundles/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/internal/discovery/RFXComBridgeDiscovery.java index d7d4720e2..5226b6f1d 100644 --- a/bundles/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/internal/discovery/RFXComBridgeDiscovery.java +++ b/bundles/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/internal/discovery/RFXComBridgeDiscovery.java @@ -116,7 +116,6 @@ public class RFXComBridgeDiscovery extends AbstractDiscoveryService { } logger.debug("Discovery done"); - } catch (IOException e) { logger.error("Error occurred during discovery", e); } catch (UnsatisfiedLinkError e) { diff --git a/bundles/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/internal/discovery/RFXComDeviceDiscoveryService.java b/bundles/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/internal/discovery/RFXComDeviceDiscoveryService.java index 7a49db4e1..f0ff9eeca 100644 --- a/bundles/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/internal/discovery/RFXComDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/internal/discovery/RFXComDeviceDiscoveryService.java @@ -53,8 +53,8 @@ public class RFXComDeviceDiscoveryService extends AbstractDiscoveryService @Override public void setThingHandler(ThingHandler handler) { - if (handler instanceof RFXComBridgeHandler) { - bridgeHandler = (RFXComBridgeHandler) handler; + if (handler instanceof RFXComBridgeHandler rfxComBridgeHandler) { + bridgeHandler = rfxComBridgeHandler; } } diff --git a/bundles/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/internal/handler/RFXComBridgeHandler.java b/bundles/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/internal/handler/RFXComBridgeHandler.java index b06d90706..4f216049c 100644 --- a/bundles/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/internal/handler/RFXComBridgeHandler.java +++ b/bundles/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/internal/handler/RFXComBridgeHandler.java @@ -14,9 +14,9 @@ package org.openhab.binding.rfxcom.internal.handler; import java.io.IOException; import java.util.Collection; -import java.util.Collections; import java.util.List; import java.util.Queue; +import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledFuture; @@ -133,7 +133,7 @@ public class RFXComBridgeHandler extends BaseBridgeHandler { @Override public Collection> getServices() { - return Collections.singleton(RFXComDeviceDiscoveryService.class); + return Set.of(RFXComDeviceDiscoveryService.class); } @Override @@ -226,11 +226,14 @@ public class RFXComBridgeHandler extends BaseBridgeHandler { logger.error("Connection to RFXCOM transceiver failed", e); if ("device not opened (3)".equalsIgnoreCase(e.getMessage())) { if (connector instanceof RFXComJD2XXConnector) { - logger.info("Automatically Discovered RFXCOM bridges use FTDI chip driver (D2XX)." - + " Reason for this error normally is related to operating system native FTDI drivers," - + " which prevent D2XX driver to open device." - + " To solve this problem, uninstall OS FTDI native drivers or add manually universal bridge 'RFXCOM USB Transceiver'," - + " which use normal serial port driver rather than D2XX."); + logger.info( + """ + Automatically Discovered RFXCOM bridges use FTDI chip driver (D2XX).\ + Reason for this error normally is related to operating system native FTDI drivers,\ + which prevent D2XX driver to open device.\ + To solve this problem, uninstall OS FTDI native drivers or add manually universal bridge 'RFXCOM USB Transceiver',\ + which use normal serial port driver rather than D2XX.\ + """); } } } catch (Exception e) { @@ -259,8 +262,7 @@ public class RFXComBridgeHandler extends BaseBridgeHandler { RFXComMessage message = messageFactory.createMessage(packet); logger.debug("Message received: {}", message); - if (message instanceof RFXComInterfaceMessage) { - RFXComInterfaceMessage msg = (RFXComInterfaceMessage) message; + if (message instanceof RFXComInterfaceMessage msg) { if (msg.subType == SubType.RESPONSE) { if (msg.command == Commands.GET_STATUS) { logger.debug("RFXCOM transceiver/receiver type: {}, hw version: {}.{}, fw version: {}", @@ -322,25 +324,24 @@ public class RFXComBridgeHandler extends BaseBridgeHandler { logger.debug("Interface response received: {}", msg); transmitQueue.sendNext(); } - } else if (message instanceof RFXComTransmitterMessage) { - RFXComTransmitterMessage resp = (RFXComTransmitterMessage) message; - + } else if (message instanceof RFXComTransmitterMessage resp) { logger.debug("Transmitter response received: {}", resp); transmitQueue.sendNext(); - } else if (message instanceof RFXComDeviceMessage) { + } else if (message instanceof RFXComDeviceMessage deviceMessage) { for (DeviceMessageListener deviceStatusListener : deviceStatusListeners) { try { - deviceStatusListener.onDeviceMessageReceived(getThing().getUID(), - (RFXComDeviceMessage) message); + deviceStatusListener.onDeviceMessageReceived(getThing().getUID(), deviceMessage); } catch (Exception e) { // catch all exceptions give all handlers a fair chance of handling the messages logger.error("An exception occurred while calling the DeviceStatusListener", e); } } } else { - logger.warn("The received message cannot be processed, please create an " - + "issue at the relevant tracker. Received message: {}", message); + logger.warn(""" + The received message cannot be processed, please create an \ + issue at the relevant tracker. Received message: {}\ + """, message); } } catch (RFXComMessageNotImplementedException e) { logger.debug("Message not supported, data: {}", HexUtils.bytesToHex(packet)); diff --git a/bundles/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/internal/messages/RFXComChimeMessage.java b/bundles/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/internal/messages/RFXComChimeMessage.java index 0601c0eb7..75da2f7fc 100644 --- a/bundles/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/internal/messages/RFXComChimeMessage.java +++ b/bundles/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/internal/messages/RFXComChimeMessage.java @@ -160,8 +160,8 @@ public class RFXComChimeMessage extends RFXComDeviceMessageImpl SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_MANAGER); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_MANAGER); private final SerialPortManager serialPortManager; diff --git a/bundles/org.openhab.binding.rme/src/main/java/org/openhab/binding/rme/internal/handler/RMEThingHandler.java b/bundles/org.openhab.binding.rme/src/main/java/org/openhab/binding/rme/internal/handler/RMEThingHandler.java index 58e1a8778..b50c15526 100644 --- a/bundles/org.openhab.binding.rme/src/main/java/org/openhab/binding/rme/internal/handler/RMEThingHandler.java +++ b/bundles/org.openhab.binding.rme/src/main/java/org/openhab/binding/rme/internal/handler/RMEThingHandler.java @@ -102,9 +102,9 @@ public class RMEThingHandler extends SerialThingHandler { } case MODE: { StringType stringType = null; - if (matcher.group(i).equals("0")) { + if ("0".equals(matcher.group(i))) { stringType = MANUAL; - } else if (matcher.group(i).equals("1")) { + } else if ("1".equals(matcher.group(i))) { stringType = AUTOMATIC; } if (stringType != null) { @@ -115,9 +115,9 @@ public class RMEThingHandler extends SerialThingHandler { } case SOURCE: { StringType stringType = null; - if (matcher.group(i).equals("0")) { + if ("0".equals(matcher.group(i))) { stringType = RAIN; - } else if (matcher.group(i).equals("1")) { + } else if ("1".equals(matcher.group(i))) { stringType = CITY; } if (stringType != null) { @@ -127,10 +127,10 @@ public class RMEThingHandler extends SerialThingHandler { break; } default: - if (matcher.group(i).equals("0")) { + if ("0".equals(matcher.group(i))) { updateState(new ChannelUID(getThing().getUID(), DataField.get(i).channelID()), OnOffType.OFF); - } else if (matcher.group(i).equals("1")) { + } else if ("1".equals(matcher.group(i))) { updateState(new ChannelUID(getThing().getUID(), DataField.get(i).channelID()), OnOffType.ON); } diff --git a/bundles/org.openhab.binding.robonect/src/main/java/org/openhab/binding/robonect/internal/handler/RobonectHandler.java b/bundles/org.openhab.binding.robonect/src/main/java/org/openhab/binding/robonect/internal/handler/RobonectHandler.java index ebf18a9d4..ceb0da5d0 100644 --- a/bundles/org.openhab.binding.robonect/src/main/java/org/openhab/binding/robonect/internal/handler/RobonectHandler.java +++ b/bundles/org.openhab.binding.robonect/src/main/java/org/openhab/binding/robonect/internal/handler/RobonectHandler.java @@ -107,8 +107,8 @@ public class RobonectHandler extends BaseThingHandler { private void sendCommand(ChannelUID channelUID, Command command) { switch (channelUID.getId()) { case CHANNEL_MOWER_NAME: - if (command instanceof StringType) { - updateName((StringType) command); + if (command instanceof StringType stringCommand) { + updateName(stringCommand); } else { logger.debug("Got name update of type {} but StringType is expected.", command.getClass().getName()); @@ -125,8 +125,8 @@ public class RobonectHandler extends BaseThingHandler { break; case CHANNEL_MOWER_START: - if (command instanceof OnOffType) { - handleStartStop((OnOffType) command); + if (command instanceof OnOffType onOffCommand) { + handleStartStop(onOffCommand); } else { logger.debug("Got stopped update of type {} but OnOffType is expected.", command.getClass().getName()); diff --git a/bundles/org.openhab.binding.robonect/src/test/java/org/openhab/binding/robonect/internal/model/ModelParserTest.java b/bundles/org.openhab.binding.robonect/src/test/java/org/openhab/binding/robonect/internal/model/ModelParserTest.java index a05fad69e..6d27d66d5 100644 --- a/bundles/org.openhab.binding.robonect/src/test/java/org/openhab/binding/robonect/internal/model/ModelParserTest.java +++ b/bundles/org.openhab.binding.robonect/src/test/java/org/openhab/binding/robonect/internal/model/ModelParserTest.java @@ -183,14 +183,40 @@ public class ModelParserTest { @Test public void shouldParseVersionInfoV1betaToNA() { - String versionResponse = "{\n" + "mower: {\n" + "hardware: {\n" + "serial: 170602001,\n" - + "production: \"2017-02-07 15:12:00\"\n" + "},\n" + "msw: {\n" + "title: \"420\",\n" - + "version: \"7.10.00\",\n" + "compiled: \"2016-11-29 08:44:06\"\n" + "},\n" + "sub: {\n" - + "version: \"6.01.00\"\n" + "}\n" + "},\n" + "serial: \"05D80037-39355548-43163930\",\n" - + "bootloader: {\n" + "version: \"V0.4\",\n" + "compiled: \"2016-10-22 01:12:00\",\n" - + "comment: \"\"\n" + "},\n" + "wlan: {\n" + "at-version: \"V1.4.0\",\n" + "sdk-version: \"V2.1.0\"\n" - + "},\n" + "application: {\n" + "version: \"V1.0\",\n" + "compiled: \"2018-03-12 21:01:00\",\n" - + "comment: \"Release V1.0 Beta2\"\n" + "},\n" + "successful: true\n" + "}"; + String versionResponse = """ + { + mower: { + hardware: { + serial: 170602001, + production: "2017-02-07 15:12:00" + }, + msw: { + title: "420", + version: "7.10.00", + compiled: "2016-11-29 08:44:06" + }, + sub: { + version: "6.01.00" + } + }, + serial: "05D80037-39355548-43163930", + bootloader: { + version: "V0.4", + compiled: "2016-10-22 01:12:00", + comment: "" + }, + wlan: { + at-version: "V1.4.0", + sdk-version: "V2.1.0" + }, + application: { + version: "V1.0", + compiled: "2018-03-12 21:01:00", + comment: "Release V1.0 Beta2" + }, + successful: true + }\ + """; VersionInfo versionInfo = subject.parse(versionResponse, VersionInfo.class); assertTrue(versionInfo.isSuccessful()); assertEquals("n/a", versionInfo.getRobonect().getSerial()); diff --git a/bundles/org.openhab.binding.roku/src/main/java/org/openhab/binding/roku/internal/RokuHandlerFactory.java b/bundles/org.openhab.binding.roku/src/main/java/org/openhab/binding/roku/internal/RokuHandlerFactory.java index fad152a8d..dd18381cf 100644 --- a/bundles/org.openhab.binding.roku/src/main/java/org/openhab/binding/roku/internal/RokuHandlerFactory.java +++ b/bundles/org.openhab.binding.roku/src/main/java/org/openhab/binding/roku/internal/RokuHandlerFactory.java @@ -58,8 +58,7 @@ public class RokuHandlerFactory extends BaseThingHandlerFactory { ThingTypeUID thingTypeUID = thing.getThingTypeUID(); if (SUPPORTED_THING_TYPES_UIDS.contains(thingTypeUID)) { - RokuHandler handler = new RokuHandler(thing, httpClient, stateDescriptionProvider); - return handler; + return new RokuHandler(thing, httpClient, stateDescriptionProvider); } return null; diff --git a/bundles/org.openhab.binding.roku/src/main/java/org/openhab/binding/roku/internal/discovery/RokuDiscoveryService.java b/bundles/org.openhab.binding.roku/src/main/java/org/openhab/binding/roku/internal/discovery/RokuDiscoveryService.java index 23033036e..87dd34729 100644 --- a/bundles/org.openhab.binding.roku/src/main/java/org/openhab/binding/roku/internal/discovery/RokuDiscoveryService.java +++ b/bundles/org.openhab.binding.roku/src/main/java/org/openhab/binding/roku/internal/discovery/RokuDiscoveryService.java @@ -59,8 +59,13 @@ import org.slf4j.LoggerFactory; @Component(service = DiscoveryService.class, configurationPid = "discovery.roku") public class RokuDiscoveryService extends AbstractDiscoveryService { private final Logger logger = LoggerFactory.getLogger(RokuDiscoveryService.class); - private static final String ROKU_DISCOVERY_MESSAGE = "M-SEARCH * HTTP/1.1\r\n" + "Host: 239.255.255.250:1900\r\n" - + "Man: \"ssdp:discover\"\r\n" + "ST: roku:ecp\r\n" + "\r\n"; + private static final String ROKU_DISCOVERY_MESSAGE = """ + M-SEARCH * HTTP/1.1\r + Host: 239.255.255.250:1900\r + Man: "ssdp:discover"\r + ST: roku:ecp\r + \r + """; private static final Pattern USN_PATTERN = Pattern.compile("^(uuid:roku:)?ecp:([0-9a-zA-Z]{1,16})"); diff --git a/bundles/org.openhab.binding.rotel/src/main/java/org/openhab/binding/rotel/internal/handler/RotelHandler.java b/bundles/org.openhab.binding.rotel/src/main/java/org/openhab/binding/rotel/internal/handler/RotelHandler.java index 2d71478df..8fcaa13fe 100644 --- a/bundles/org.openhab.binding.rotel/src/main/java/org/openhab/binding/rotel/internal/handler/RotelHandler.java +++ b/bundles/org.openhab.binding.rotel/src/main/java/org/openhab/binding/rotel/internal/handler/RotelHandler.java @@ -868,8 +868,8 @@ public class RotelHandler extends BaseThingHandler implements RotelMessageEventL } else if (radioPreset > 0 && command instanceof IncreaseDecreaseType && command == IncreaseDecreaseType.DECREASE) { value = radioPreset - 1; - } else if (command instanceof DecimalType) { - value = ((DecimalType) command).intValue(); + } else if (command instanceof DecimalType decimalCommand) { + value = decimalCommand.intValue(); } if (value >= 1 && value <= 30) { RotelSource source = sources[0]; @@ -903,8 +903,8 @@ public class RotelHandler extends BaseThingHandler implements RotelMessageEventL } else if (!model.hasDimmerControl()) { success = false; logger.debug("Command {} from channel {} failed: unavailable feature", command, channel); - } else if (command instanceof PercentType) { - int dimmer = (int) Math.round(((PercentType) command).doubleValue() / 100.0 + } else if (command instanceof PercentType percentCommand) { + int dimmer = (int) Math.round(percentCommand.doubleValue() / 100.0 * (model.getDimmerLevelMax() - model.getDimmerLevelMin())) + model.getDimmerLevelMin(); sendCommand(RotelCommand.DIMMER_LEVEL_SET, dimmer); @@ -1043,8 +1043,8 @@ public class RotelHandler extends BaseThingHandler implements RotelMessageEventL sendCommand(upCmd); } else if (command instanceof IncreaseDecreaseType && command == IncreaseDecreaseType.DECREASE) { sendCommand(downCmd); - } else if (command instanceof DecimalType && setCmd == null) { - int value = ((DecimalType) command).intValue(); + } else if (command instanceof DecimalType decimalCommand && setCmd == null) { + int value = decimalCommand.intValue(); if (value >= minVolume && value <= maxVolume) { if (value > current) { sendCommand(upCmd); @@ -1052,9 +1052,8 @@ public class RotelHandler extends BaseThingHandler implements RotelMessageEventL sendCommand(downCmd); } } - } else if (command instanceof PercentType && setCmd != null) { - int value = (int) Math.round(((PercentType) command).doubleValue() / 100.0 * (maxVolume - minVolume)) - + minVolume; + } else if (command instanceof PercentType percentCommand && setCmd != null) { + int value = (int) Math.round(percentCommand.doubleValue() / 100.0 * (maxVolume - minVolume)) + minVolume; sendCommand(setCmd, value); } else { logger.debug("Command {} from channel {} failed: invalid command value", command, channel); @@ -1110,8 +1109,8 @@ public class RotelHandler extends BaseThingHandler implements RotelMessageEventL } else if (command instanceof IncreaseDecreaseType && command == IncreaseDecreaseType.DECREASE) { selectToneControl(nbSelect); sendCommand(downCmd); - } else if (command instanceof DecimalType) { - int value = ((DecimalType) command).intValue(); + } else if (command instanceof DecimalType decimalCommand) { + int value = decimalCommand.intValue(); if (value >= minToneLevel && value <= maxToneLevel) { if (protocol != RotelProtocol.HEX) { sendCommand(setCmd, value); @@ -1204,8 +1203,8 @@ public class RotelHandler extends BaseThingHandler implements RotelMessageEventL sendCommand(rightCmd); } else if (command instanceof IncreaseDecreaseType && command == IncreaseDecreaseType.DECREASE) { sendCommand(leftCmd); - } else if (command instanceof DecimalType) { - int value = ((DecimalType) command).intValue(); + } else if (command instanceof DecimalType decimalCommand) { + int value = decimalCommand.intValue(); if (value >= minBalanceLevel && value <= maxBalanceLevel) { sendCommand(setCmd, value); } @@ -1618,7 +1617,7 @@ public class RotelHandler extends BaseThingHandler implements RotelMessageEventL break; case KEY_TRACK: source = sources[0]; - if (source != null && source.getName().equals("CD") && !model.hasSourceControl()) { + if (source != null && "CD".equals(source.getName()) && !model.hasSourceControl()) { track = Integer.parseInt(value); updateChannelState(CHANNEL_TRACK); } @@ -2027,7 +2026,7 @@ public class RotelHandler extends BaseThingHandler implements RotelMessageEventL RotelSource source = sources[0]; if (model != RotelModel.RCD1570 && model != RotelModel.RCD1572 && (model != RotelModel.RCX1500 || source == null - || !source.getName().equals("CD"))) { + || !"CD".equals(source.getName()))) { sendCommand(RotelCommand.PLAY_STATUS); Thread.sleep(SLEEP_INTV); } else { @@ -2094,7 +2093,7 @@ public class RotelHandler extends BaseThingHandler implements RotelMessageEventL sendCommand(RotelCommand.PLAY_STATUS); Thread.sleep(SLEEP_INTV); RotelSource source = sources[0]; - if (source != null && source.getName().equals("CD") && !model.hasSourceControl()) { + if (source != null && "CD".equals(source.getName()) && !model.hasSourceControl()) { sendCommand(RotelCommand.TRACK); Thread.sleep(SLEEP_INTV); sendCommand(RotelCommand.RANDOM_MODE); @@ -2949,11 +2948,11 @@ public class RotelHandler extends BaseThingHandler implements RotelMessageEventL } connector.writeOutput(cmd, message); - if (connector instanceof RotelSimuConnector) { + if (connector instanceof RotelSimuConnector simuConnector) { if ((protocol == RotelProtocol.HEX && cmd.getHexType() != 0) || (protocol == RotelProtocol.ASCII_V1 && cmd.getAsciiCommandV1() != null) || (protocol == RotelProtocol.ASCII_V2 && cmd.getAsciiCommandV2() != null)) { - ((RotelSimuConnector) connector).buildFeedbackMessage(cmd, value); + simuConnector.buildFeedbackMessage(cmd, value); } } } diff --git a/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/discovery/RioSystemDeviceDiscoveryService.java b/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/discovery/RioSystemDeviceDiscoveryService.java index 322779e95..753704451 100644 --- a/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/discovery/RioSystemDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/discovery/RioSystemDeviceDiscoveryService.java @@ -181,7 +181,7 @@ public class RioSystemDeviceDiscoveryService extends AbstractDiscoveryService { final DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID) .withProperty(RioSourceConfig.SOURCE, s).withBridge(sysHandler.getThing().getUID()) - .withLabel((name == null || name.isEmpty() || name.equalsIgnoreCase("null") ? "Source" : name) + .withLabel((name == null || name.isEmpty() || "null".equalsIgnoreCase(name) ? "Source" : name) + " (" + s + ")") .build(); thingDiscovered(discoveryResult); @@ -214,7 +214,7 @@ public class RioSystemDeviceDiscoveryService extends AbstractDiscoveryService { final DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID) .withProperty(RioZoneConfig.ZONE, z).withBridge(controllerUID) - .withLabel((name.equalsIgnoreCase("null") ? "Zone" : name) + " (" + z + ")").build(); + .withLabel(("null".equalsIgnoreCase(name) ? "Zone" : name) + " (" + z + ")").build(); thingDiscovered(discoveryResult); } } diff --git a/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/discovery/RioSystemDiscovery.java b/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/discovery/RioSystemDiscovery.java index 6473cc980..573f582e9 100644 --- a/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/discovery/RioSystemDiscovery.java +++ b/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/discovery/RioSystemDiscovery.java @@ -22,6 +22,7 @@ import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; @@ -66,7 +67,7 @@ public class RioSystemDiscovery extends AbstractDiscoveryService { * 120 seconds (depending on how many network interfaces there are) */ public RioSystemDiscovery() { - super(Collections.singleton(RioConstants.BRIDGE_TYPE_RIO), 120); + super(Set.of(RioConstants.BRIDGE_TYPE_RIO), 120); } /** diff --git a/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/net/SocketChannelSession.java b/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/net/SocketChannelSession.java index 85fcc5847..95c389190 100644 --- a/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/net/SocketChannelSession.java +++ b/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/net/SocketChannelSession.java @@ -292,15 +292,15 @@ public class SocketChannelSession implements SocketSession { final Object response = responses.poll(1, TimeUnit.SECONDS); if (response != null) { - if (response instanceof String) { + if (response instanceof String stringCommand) { logger.debug("Dispatching response: {}", response); for (SocketSessionListener listener : listeners) { - listener.responseReceived((String) response); + listener.responseReceived(stringCommand); } - } else if (response instanceof IOException) { + } else if (response instanceof IOException ioException) { logger.debug("Dispatching exception: {}", response); for (SocketSessionListener listener : listeners) { - listener.responseException((IOException) response); + listener.responseException(ioException); } } else { logger.warn("Unknown response class: {}", response); diff --git a/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/net/WaitingSessionListener.java b/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/net/WaitingSessionListener.java index d59a42ace..86793e3d8 100644 --- a/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/net/WaitingSessionListener.java +++ b/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/net/WaitingSessionListener.java @@ -44,10 +44,10 @@ public class WaitingSessionListener implements SocketSessionListener { // will not come in until the other commands have been processed. So we need a large wait // time for it to be sent to us final Object lastResponse = responses.poll(60, TimeUnit.SECONDS); - if (lastResponse instanceof String) { - return (String) lastResponse; - } else if (lastResponse instanceof IOException) { - throw (IOException) lastResponse; + if (lastResponse instanceof String stringCommand) { + return stringCommand; + } else if (lastResponse instanceof IOException ioException) { + throw ioException; } else if (lastResponse == null) { throw new IOException("Didn't receive response in time"); } else { diff --git a/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/rio/AbstractBridgeHandler.java b/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/rio/AbstractBridgeHandler.java index 9665e0d3b..d1adf99a1 100644 --- a/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/rio/AbstractBridgeHandler.java +++ b/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/rio/AbstractBridgeHandler.java @@ -193,8 +193,8 @@ public abstract class AbstractBridgeHandler exten public void channelUnlinked(ChannelUID channelUID) { // Remove any state when unlinking (that way if it is relinked - we get it) final RioHandlerCallback callback = getProtocolHandler().getCallback(); - if (callback instanceof StatefulHandlerCallback) { - ((StatefulHandlerCallback) callback).removeState(channelUID.getId()); + if (callback instanceof StatefulHandlerCallback handlerCallback) { + handlerCallback.removeState(channelUID.getId()); } super.channelUnlinked(channelUID); } diff --git a/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/rio/AbstractThingHandler.java b/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/rio/AbstractThingHandler.java index 1b5970c05..632bdbeab 100644 --- a/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/rio/AbstractThingHandler.java +++ b/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/rio/AbstractThingHandler.java @@ -116,8 +116,8 @@ public abstract class AbstractThingHandler extend public void channelUnlinked(ChannelUID channelUID) { // Remove any state when unlinking (that way if it is relinked - we get it) final RioHandlerCallback callback = getProtocolHandler().getCallback(); - if (callback instanceof StatefulHandlerCallback) { - ((StatefulHandlerCallback) callback).removeState(channelUID.getId()); + if (callback instanceof StatefulHandlerCallback handlerCallback) { + handlerCallback.removeState(channelUID.getId()); } super.channelUnlinked(channelUID); } diff --git a/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/rio/controller/RioControllerHandler.java b/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/rio/controller/RioControllerHandler.java index 18da50cbf..09c262ea5 100644 --- a/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/rio/controller/RioControllerHandler.java +++ b/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/rio/controller/RioControllerHandler.java @@ -231,8 +231,8 @@ public class RioControllerHandler extends AbstractBridgeHandler JsonElement je = JsonParser.parseReader(in); - if (je instanceof JsonPrimitive) { + if (je instanceof JsonPrimitive jsonPrimitive) { value = new AtomicReference<>(); - value.set(((JsonPrimitive) je).getAsString()); - } else if (je instanceof JsonObject) { - JsonObject jsonObject = (JsonObject) je; + value.set(jsonPrimitive.getAsString()); + } else if (je instanceof JsonObject jsonObject) { value = new AtomicReference<>(); value.set(jsonObject.get("value").getAsString()); } diff --git a/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/rio/source/RioSourceProtocol.java b/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/rio/source/RioSourceProtocol.java index 7090456ac..58019283a 100644 --- a/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/rio/source/RioSourceProtocol.java +++ b/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/rio/source/RioSourceProtocol.java @@ -468,8 +468,8 @@ class RioSourceProtocol extends AbstractRioProtocol { infoLock.lock(); try { - infoText.append(infoTextValue.toString()); - if (attr != null && attr.toString().indexOf("E") >= 0) { + infoText.append(infoTextValue); + if (attr != null && attr.toString().contains("E")) { final String text = infoText.toString(); infoText.setLength(0); diff --git a/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/rio/system/RioSystemHandler.java b/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/rio/system/RioSystemHandler.java index 1c502b6d2..1b84e6892 100644 --- a/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/rio/system/RioSystemHandler.java +++ b/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/rio/system/RioSystemHandler.java @@ -180,8 +180,8 @@ public class RioSystemHandler extends AbstractBridgeHandler { } if (id.equals(RioConstants.CHANNEL_SYSLANG)) { - if (command instanceof StringType) { - getProtocolHandler().setSystemLanguage(((StringType) command).toString()); + if (command instanceof StringType stringCommand) { + getProtocolHandler().setSystemLanguage(stringCommand.toString()); } else { logger.debug("Received a SYSTEM LANGUAGE channel command with a non StringType: {}", command); } @@ -489,8 +489,8 @@ public class RioSystemHandler extends AbstractBridgeHandler { if (childHandler == null) { throw new IllegalArgumentException("childHandler cannot be null"); } - if (childHandler instanceof RioSourceHandler) { - final RioHandlerCallback callback = ((RioSourceHandler) childHandler).getRioHandlerCallback(); + if (childHandler instanceof RioSourceHandler sourceHandler) { + final RioHandlerCallback callback = sourceHandler.getRioHandlerCallback(); if (callback != null) { if (added) { callback.addListener(RioConstants.CHANNEL_SOURCENAME, handlerCallbackListener); diff --git a/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/rio/zone/RioZoneHandler.java b/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/rio/zone/RioZoneHandler.java index 4dfcf6500..b00ff37b9 100644 --- a/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/rio/zone/RioZoneHandler.java +++ b/bundles/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/rio/zone/RioZoneHandler.java @@ -139,31 +139,31 @@ public class RioZoneHandler extends AbstractThingHandler } if (id.equals(RioConstants.CHANNEL_ZONEBASS)) { - if (command instanceof DecimalType) { - getProtocolHandler().setZoneBass(((DecimalType) command).intValue()); + if (command instanceof DecimalType decimalCommand) { + getProtocolHandler().setZoneBass(decimalCommand.intValue()); } else { logger.debug("Received a ZONE BASS channel command with a non DecimalType: {}", command); } } else if (id.equals(RioConstants.CHANNEL_ZONETREBLE)) { - if (command instanceof DecimalType) { - getProtocolHandler().setZoneTreble(((DecimalType) command).intValue()); + if (command instanceof DecimalType decimalCommand) { + getProtocolHandler().setZoneTreble(decimalCommand.intValue()); } else { logger.debug("Received a ZONE TREBLE channel command with a non DecimalType: {}", command); } } else if (id.equals(RioConstants.CHANNEL_ZONEBALANCE)) { - if (command instanceof DecimalType) { - getProtocolHandler().setZoneBalance(((DecimalType) command).intValue()); + if (command instanceof DecimalType decimalCommand) { + getProtocolHandler().setZoneBalance(decimalCommand.intValue()); } else { logger.debug("Received a ZONE BALANCE channel command with a non DecimalType: {}", command); } } else if (id.equals(RioConstants.CHANNEL_ZONETURNONVOLUME)) { - if (command instanceof PercentType) { - getProtocolHandler().setZoneTurnOnVolume(((PercentType) command).intValue() / 100d); - } else if (command instanceof DecimalType) { - getProtocolHandler().setZoneTurnOnVolume(((DecimalType) command).doubleValue()); + if (command instanceof PercentType percentCommand) { + getProtocolHandler().setZoneTurnOnVolume(percentCommand.intValue() / 100d); + } else if (command instanceof DecimalType decimalCommand) { + getProtocolHandler().setZoneTurnOnVolume(decimalCommand.doubleValue()); } else { logger.debug("Received a ZONE TURN ON VOLUME channel command with a non PercentType/DecimalType: {}", command); @@ -177,15 +177,15 @@ public class RioZoneHandler extends AbstractThingHandler } } else if (id.equals(RioConstants.CHANNEL_ZONESLEEPTIMEREMAINING)) { - if (command instanceof DecimalType) { - getProtocolHandler().setZoneSleepTimeRemaining(((DecimalType) command).intValue()); + if (command instanceof DecimalType decimalCommand) { + getProtocolHandler().setZoneSleepTimeRemaining(decimalCommand.intValue()); } else { logger.debug("Received a ZONE SLEEP TIME REMAINING channel command with a non DecimalType: {}", command); } } else if (id.equals(RioConstants.CHANNEL_ZONESOURCE)) { - if (command instanceof DecimalType) { - getProtocolHandler().setZoneSource(((DecimalType) command).intValue()); + if (command instanceof DecimalType decimalCommand) { + getProtocolHandler().setZoneSource(decimalCommand.intValue()); } else { logger.debug("Received a ZONE SOURCE channel command with a non DecimalType: {}", command); } @@ -197,15 +197,15 @@ public class RioZoneHandler extends AbstractThingHandler logger.debug("Received a ZONE STATUS channel command with a non OnOffType: {}", command); } } else if (id.equals(RioConstants.CHANNEL_ZONEPARTYMODE)) { - if (command instanceof StringType) { - getProtocolHandler().setZonePartyMode(((StringType) command).toString()); + if (command instanceof StringType stringCommand) { + getProtocolHandler().setZonePartyMode(stringCommand.toString()); } else { logger.debug("Received a ZONE PARTY MODE channel command with a non StringType: {}", command); } } else if (id.equals(RioConstants.CHANNEL_ZONEDONOTDISTURB)) { - if (command instanceof StringType) { - getProtocolHandler().setZoneDoNotDisturb(((StringType) command).toString()); + if (command instanceof StringType stringCommand) { + getProtocolHandler().setZoneDoNotDisturb(stringCommand.toString()); } else { logger.debug("Received a ZONE DO NOT DISTURB channel command with a non StringType: {}", command); } @@ -236,10 +236,10 @@ public class RioZoneHandler extends AbstractThingHandler getProtocolHandler().setZoneStatus(command == OnOffType.ON); } else if (command instanceof IncreaseDecreaseType) { getProtocolHandler().setZoneVolume(command == IncreaseDecreaseType.INCREASE); - } else if (command instanceof PercentType) { - getProtocolHandler().setZoneVolume(((PercentType) command).intValue() / 100d); - } else if (command instanceof DecimalType) { - getProtocolHandler().setZoneVolume(((DecimalType) command).doubleValue()); + } else if (command instanceof PercentType percentCommand) { + getProtocolHandler().setZoneVolume(percentCommand.intValue() / 100d); + } else if (command instanceof DecimalType decimalCommand) { + getProtocolHandler().setZoneVolume(decimalCommand.doubleValue()); } else { logger.debug( "Received a ZONE VOLUME channel command with a non OnOffType/IncreaseDecreaseType/PercentType/DecimalTye: {}", @@ -254,36 +254,36 @@ public class RioZoneHandler extends AbstractThingHandler } } else if (id.equals(RioConstants.CHANNEL_ZONEKEYPRESS)) { - if (command instanceof StringType) { - getProtocolHandler().sendKeyPress(((StringType) command).toString()); + if (command instanceof StringType stringCommand) { + getProtocolHandler().sendKeyPress(stringCommand.toString()); } else { logger.debug("Received a ZONE KEYPRESS channel command with a non StringType: {}", command); } } else if (id.equals(RioConstants.CHANNEL_ZONEKEYRELEASE)) { - if (command instanceof StringType) { - getProtocolHandler().sendKeyRelease(((StringType) command).toString()); + if (command instanceof StringType stringCommand) { + getProtocolHandler().sendKeyRelease(stringCommand.toString()); } else { logger.debug("Received a ZONE KEYRELEASE channel command with a non StringType: {}", command); } } else if (id.equals(RioConstants.CHANNEL_ZONEKEYHOLD)) { - if (command instanceof StringType) { - getProtocolHandler().sendKeyHold(((StringType) command).toString()); + if (command instanceof StringType stringCommand) { + getProtocolHandler().sendKeyHold(stringCommand.toString()); } else { logger.debug("Received a ZONE KEYHOLD channel command with a non StringType: {}", command); } } else if (id.equals(RioConstants.CHANNEL_ZONEKEYCODE)) { - if (command instanceof StringType) { - getProtocolHandler().sendKeyCode(((StringType) command).toString()); + if (command instanceof StringType stringCommand) { + getProtocolHandler().sendKeyCode(stringCommand.toString()); } else { logger.debug("Received a ZONE KEYCODE channel command with a non StringType: {}", command); } } else if (id.equals(RioConstants.CHANNEL_ZONEEVENT)) { - if (command instanceof StringType) { - getProtocolHandler().sendEvent(((StringType) command).toString()); + if (command instanceof StringType stringCommand) { + getProtocolHandler().sendEvent(stringCommand.toString()); } else { logger.debug("Received a ZONE EVENT channel command with a non StringType: {}", command); } diff --git a/bundles/org.openhab.binding.sagercaster/src/main/java/org/openhab/binding/sagercaster/internal/SagerCasterHandlerFactory.java b/bundles/org.openhab.binding.sagercaster/src/main/java/org/openhab/binding/sagercaster/internal/SagerCasterHandlerFactory.java index ffe49bec7..489d09d3e 100644 --- a/bundles/org.openhab.binding.sagercaster/src/main/java/org/openhab/binding/sagercaster/internal/SagerCasterHandlerFactory.java +++ b/bundles/org.openhab.binding.sagercaster/src/main/java/org/openhab/binding/sagercaster/internal/SagerCasterHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.sagercaster.internal; import static org.openhab.binding.sagercaster.internal.SagerCasterBindingConstants.THING_TYPE_SAGERCASTER; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -39,7 +38,7 @@ import org.osgi.service.component.annotations.Reference; @Component(service = ThingHandlerFactory.class, configurationPid = "binding.sagercaster") @NonNullByDefault public class SagerCasterHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_SAGERCASTER); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_SAGERCASTER); private final WindDirectionStateDescriptionProvider stateDescriptionProvider; private final SagerWeatherCaster sagerWeatherCaster; diff --git a/bundles/org.openhab.binding.sagercaster/src/main/java/org/openhab/binding/sagercaster/internal/caster/SagerWeatherCaster.java b/bundles/org.openhab.binding.sagercaster/src/main/java/org/openhab/binding/sagercaster/internal/caster/SagerWeatherCaster.java index a1e5c2764..be82f1a8f 100644 --- a/bundles/org.openhab.binding.sagercaster/src/main/java/org/openhab/binding/sagercaster/internal/caster/SagerWeatherCaster.java +++ b/bundles/org.openhab.binding.sagercaster/src/main/java/org/openhab/binding/sagercaster/internal/caster/SagerWeatherCaster.java @@ -318,8 +318,7 @@ public class SagerWeatherCaster { d1 = "Z"; } } - String forecast = forecaster.getProperty( - d1 + String.valueOf(sagerPressure) + String.valueOf(pressureEvolution) + String.valueOf(nubes)); + String forecast = forecaster.getProperty(d1 + sagerPressure + pressureEvolution + nubes); prevision = Optional.ofNullable(forecast != null ? new SagerPrediction(forecast) : null); } diff --git a/bundles/org.openhab.binding.sagercaster/src/main/java/org/openhab/binding/sagercaster/internal/handler/SagerCasterHandler.java b/bundles/org.openhab.binding.sagercaster/src/main/java/org/openhab/binding/sagercaster/internal/handler/SagerCasterHandler.java index 05b934ed3..f4cbc0b7f 100644 --- a/bundles/org.openhab.binding.sagercaster/src/main/java/org/openhab/binding/sagercaster/internal/handler/SagerCasterHandler.java +++ b/bundles/org.openhab.binding.sagercaster/src/main/java/org/openhab/binding/sagercaster/internal/handler/SagerCasterHandler.java @@ -114,8 +114,7 @@ public class SagerCasterHandler extends BaseThingHandler { switch (id) { case CHANNEL_CLOUDINESS: logger.debug("Cloud level changed, updating forecast"); - if (command instanceof QuantityType) { - QuantityType cloudiness = (QuantityType) command; + if (command instanceof QuantityType cloudiness) { scheduler.submit(() -> { sagerWeatherCaster.setCloudLevel(cloudiness.intValue()); postNewForecast(); @@ -124,8 +123,7 @@ public class SagerCasterHandler extends BaseThingHandler { } case CHANNEL_IS_RAINING: logger.debug("Rain status updated, updating forecast"); - if (command instanceof OnOffType) { - OnOffType isRaining = (OnOffType) command; + if (command instanceof OnOffType isRaining) { scheduler.submit(() -> { sagerWeatherCaster.setRaining(isRaining == OnOffType.ON); postNewForecast(); @@ -136,18 +134,17 @@ public class SagerCasterHandler extends BaseThingHandler { break; case CHANNEL_RAIN_QTTY: logger.debug("Rain status updated, updating forecast"); - if (command instanceof QuantityType) { - updateRain((QuantityType) command); - } else if (command instanceof DecimalType) { - updateRain((DecimalType) command); + if (command instanceof QuantityType quantityCommand) { + updateRain(quantityCommand); + } else if (command instanceof DecimalType decimalCommand) { + updateRain(decimalCommand); } else { logger.debug("Channel '{}' accepts Number, Number:(Speed|Length) commands.", channelUID); } break; case CHANNEL_WIND_SPEED: logger.debug("Updated wind speed, updating forecast"); - if (command instanceof DecimalType) { - DecimalType newValue = (DecimalType) command; + if (command instanceof DecimalType newValue) { scheduler.submit(() -> { sagerWeatherCaster.setBeaufort(newValue.intValue()); postNewForecast(); diff --git a/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/SamsungTvHandlerFactory.java b/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/SamsungTvHandlerFactory.java index 595af45fe..b600ad335 100644 --- a/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/SamsungTvHandlerFactory.java +++ b/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/SamsungTvHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.samsungtv.internal; import static org.openhab.binding.samsungtv.internal.SamsungTvBindingConstants.SAMSUNG_TV_THING_TYPE; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -42,7 +41,7 @@ import org.osgi.service.component.annotations.Reference; @Component(service = ThingHandlerFactory.class, configurationPid = "binding.samsungtv") public class SamsungTvHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(SAMSUNG_TV_THING_TYPE); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(SAMSUNG_TV_THING_TYPE); private @NonNullByDefault({}) UpnpIOService upnpIOService; private @NonNullByDefault({}) UpnpService upnpService; diff --git a/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/WakeOnLanUtility.java b/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/WakeOnLanUtility.java index b8ca9a9cf..087b9bd99 100644 --- a/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/WakeOnLanUtility.java +++ b/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/WakeOnLanUtility.java @@ -48,9 +48,9 @@ public class WakeOnLanUtility { static { String os = System.getProperty("os.name").toLowerCase(); LOGGER.debug("os: {}", os); - if ((os.indexOf("win") >= 0)) { + if ((os.contains("win"))) { COMMAND = "arp -a %s"; - } else if ((os.indexOf("mac") >= 0)) { + } else if ((os.contains("mac"))) { COMMAND = "arp %s"; } else { // linux if (checkIfLinuxCommandExists("arp")) { diff --git a/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/discovery/SamsungTvDiscoveryParticipant.java b/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/discovery/SamsungTvDiscoveryParticipant.java index f65e7e46e..aaf837758 100644 --- a/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/discovery/SamsungTvDiscoveryParticipant.java +++ b/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/discovery/SamsungTvDiscoveryParticipant.java @@ -15,7 +15,6 @@ package org.openhab.binding.samsungtv.internal.discovery; import static org.openhab.binding.samsungtv.internal.SamsungTvBindingConstants.SAMSUNG_TV_THING_TYPE; import static org.openhab.binding.samsungtv.internal.config.SamsungTvConfiguration.HOST_NAME; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -46,7 +45,7 @@ public class SamsungTvDiscoveryParticipant implements UpnpDiscoveryParticipant { @Override public Set getSupportedThingTypeUIDs() { - return Collections.singleton(SAMSUNG_TV_THING_TYPE); + return Set.of(SAMSUNG_TV_THING_TYPE); } @Override diff --git a/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/service/DataConverters.java b/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/service/DataConverters.java index 91b421ea7..b07e5ebb0 100644 --- a/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/service/DataConverters.java +++ b/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/service/DataConverters.java @@ -45,8 +45,8 @@ public class DataConverters { value = Math.min(max, currentValue + 1); } else if (command instanceof IncreaseDecreaseType && command == IncreaseDecreaseType.DECREASE) { value = Math.max(min, currentValue - 1); - } else if (command instanceof DecimalType) { - value = ((DecimalType) command).intValue(); + } else if (command instanceof DecimalType decimalCommand) { + value = decimalCommand.intValue(); } else { throw new NumberFormatException("Command '" + command + "' not supported"); } diff --git a/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/service/MediaRendererService.java b/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/service/MediaRendererService.java index aed913493..12a1f3323 100644 --- a/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/service/MediaRendererService.java +++ b/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/service/MediaRendererService.java @@ -208,7 +208,7 @@ public class MediaRendererService implements UpnpIOParticipant, SamsungTvService case "CurrentMute": State newState = UnDefType.UNDEF; if (value != null) { - newState = value.equals("true") ? OnOffType.ON : OnOffType.OFF; + newState = "true".equals(value) ? OnOffType.ON : OnOffType.OFF; } listener.valueReceived(MUTE, newState); break; diff --git a/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/service/RemoteControllerService.java b/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/service/RemoteControllerService.java index e3e291efd..054324ec9 100644 --- a/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/service/RemoteControllerService.java +++ b/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/service/RemoteControllerService.java @@ -265,8 +265,7 @@ public class RemoteControllerService implements SamsungTvService, RemoteControll KeyCode key = null; - if (remoteController instanceof RemoteControllerWebSocket) { - RemoteControllerWebSocket remoteControllerWebSocket = (RemoteControllerWebSocket) remoteController; + if (remoteController instanceof RemoteControllerWebSocket remoteControllerWebSocket) { switch (channel) { case BROWSER_URL: if (command instanceof StringType) { @@ -372,8 +371,8 @@ public class RemoteControllerService implements SamsungTvService, RemoteControll return; case CHANNEL: - if (command instanceof DecimalType) { - int val = ((DecimalType) command).intValue(); + if (command instanceof DecimalType decimalCommand) { + int val = decimalCommand.intValue(); int num4 = val / 1000 % 10; int num3 = val / 100 % 10; int num2 = val / 10 % 10; @@ -419,8 +418,8 @@ public class RemoteControllerService implements SamsungTvService, RemoteControll private void sendKeyCodePress(KeyCode key) { try { - if (remoteController != null && remoteController instanceof RemoteControllerWebSocket) { - ((RemoteControllerWebSocket) remoteController).sendKeyPress(key); + if (remoteController instanceof RemoteControllerWebSocket remoteControllerWebSocket) { + remoteControllerWebSocket.sendKeyPress(key); } } catch (RemoteControllerException e) { reportError(String.format("Could not send command to device on %s:%d", host, port), e); diff --git a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/action/SatelEventLogActions.java b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/action/SatelEventLogActions.java index 1f919c930..dc3c4c602 100644 --- a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/action/SatelEventLogActions.java +++ b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/action/SatelEventLogActions.java @@ -43,8 +43,8 @@ public class SatelEventLogActions implements ThingActions { @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof SatelEventLogHandler) { - this.handler = (SatelEventLogHandler) handler; + if (handler instanceof SatelEventLogHandler logHandler) { + this.handler = logHandler; } } diff --git a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/command/ReadEventCommand.java b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/command/ReadEventCommand.java index 3f305c4d6..b892c4b8c 100644 --- a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/command/ReadEventCommand.java +++ b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/command/ReadEventCommand.java @@ -106,9 +106,7 @@ public class ReadEventCommand extends SatelCommandBase { if (year > currentYear) { year -= 4; } - LocalDateTime result = LocalDateTime.of(year, (payload[2] >> 4) & 0x0f, payload[1] & 0x1f, minutes / 60, - minutes % 60); - return result; + return LocalDateTime.of(year, (payload[2] >> 4) & 0x0f, payload[1] & 0x1f, minutes / 60, minutes % 60); } /** diff --git a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/command/SatelCommandBase.java b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/command/SatelCommandBase.java index 4413696c5..d39baf1db 100644 --- a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/command/SatelCommandBase.java +++ b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/command/SatelCommandBase.java @@ -224,9 +224,8 @@ public abstract class SatelCommandBase extends SatelMessage implements SatelComm public String getVersion(int offset) { // build version string final byte[] payload = getResponse().getPayload(); - String verStr = new String(payload, offset, 1) + "." + new String(payload, offset + 1, 2) + " " + return new String(payload, offset, 1) + "." + new String(payload, offset + 1, 2) + " " + new String(payload, offset + 3, 4) + "-" + new String(payload, offset + 7, 2) + "-" + new String(payload, offset + 9, 2); - return verStr; } } diff --git a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/Atd100Handler.java b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/Atd100Handler.java index a832b1f06..b50e8b1a7 100644 --- a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/Atd100Handler.java +++ b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/Atd100Handler.java @@ -14,7 +14,6 @@ package org.openhab.binding.satel.internal.handler; import static org.openhab.binding.satel.internal.SatelBindingConstants.*; -import java.util.Collections; import java.util.Optional; import java.util.Set; import java.util.concurrent.ScheduledFuture; @@ -46,7 +45,7 @@ import org.slf4j.LoggerFactory; @NonNullByDefault public class Atd100Handler extends WirelessChannelsHandler { - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_ATD100); + public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_ATD100); private final Logger logger = LoggerFactory.getLogger(getClass()); diff --git a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/Ethm1BridgeHandler.java b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/Ethm1BridgeHandler.java index cced3c913..86169372e 100644 --- a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/Ethm1BridgeHandler.java +++ b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/Ethm1BridgeHandler.java @@ -17,6 +17,7 @@ import static org.openhab.binding.satel.internal.config.Ethm1Config.HOST; import java.util.Collection; import java.util.Collections; +import java.util.List; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -40,7 +41,7 @@ import org.slf4j.LoggerFactory; @NonNullByDefault public class Ethm1BridgeHandler extends SatelBridgeHandler { - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_ETHM1); + public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_ETHM1); private final Logger logger = LoggerFactory.getLogger(Ethm1BridgeHandler.class); @@ -71,8 +72,8 @@ public class Ethm1BridgeHandler extends SatelBridgeHandler { // Check whether an IP address is provided if (host.isBlank()) { - configStatusMessages = Collections.singletonList(ConfigStatusMessage.Builder.error(HOST) - .withMessageKeySuffix("hostEmpty").withArguments(HOST).build()); + configStatusMessages = List.of(ConfigStatusMessage.Builder.error(HOST).withMessageKeySuffix("hostEmpty") + .withArguments(HOST).build()); } else { configStatusMessages = Collections.emptyList(); } diff --git a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/IntRSBridgeHandler.java b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/IntRSBridgeHandler.java index 50e0a63ad..7cf619185 100644 --- a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/IntRSBridgeHandler.java +++ b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/IntRSBridgeHandler.java @@ -17,6 +17,7 @@ import static org.openhab.binding.satel.internal.config.IntRSConfig.PORT; import java.util.Collection; import java.util.Collections; +import java.util.List; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -41,7 +42,7 @@ import org.slf4j.LoggerFactory; @NonNullByDefault public class IntRSBridgeHandler extends SatelBridgeHandler { - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_INTRS); + public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_INTRS); private final Logger logger = LoggerFactory.getLogger(IntRSBridgeHandler.class); @@ -76,8 +77,8 @@ public class IntRSBridgeHandler extends SatelBridgeHandler { // Check whether a serial port is provided if (port.isBlank()) { - configStatusMessages = Collections.singletonList(ConfigStatusMessage.Builder.error(PORT) - .withMessageKeySuffix("portEmpty").withArguments(PORT).build()); + configStatusMessages = List.of(ConfigStatusMessage.Builder.error(PORT).withMessageKeySuffix("portEmpty") + .withArguments(PORT).build()); } else { configStatusMessages = Collections.emptyList(); } diff --git a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelEventLogHandler.java b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelEventLogHandler.java index 67a928336..82dc52a87 100644 --- a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelEventLogHandler.java +++ b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelEventLogHandler.java @@ -17,7 +17,6 @@ import static org.openhab.binding.satel.internal.SatelBindingConstants.*; import java.nio.charset.Charset; import java.time.ZonedDateTime; import java.util.Collection; -import java.util.Collections; import java.util.Map; import java.util.Optional; import java.util.Set; @@ -55,7 +54,7 @@ import org.slf4j.LoggerFactory; @NonNullByDefault public class SatelEventLogHandler extends SatelThingHandler { - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_EVENTLOG); + public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_EVENTLOG); private static final String NOT_AVAILABLE_TEXT = "N/A"; private static final String DETAILS_SEPARATOR = ", "; @@ -166,8 +165,8 @@ public class SatelEventLogHandler extends SatelThingHandler { public void handleCommand(ChannelUID channelUID, Command command) { logger.debug("New command for {}: {}", channelUID, command); - if (CHANNEL_INDEX.equals(channelUID.getId()) && command instanceof DecimalType) { - int eventIndex = ((DecimalType) command).intValue(); + if (CHANNEL_INDEX.equals(channelUID.getId()) && command instanceof DecimalType decimalCommand) { + int eventIndex = decimalCommand.intValue(); withBridgeHandlerPresent(bridgeHandler -> readEvent(eventIndex).ifPresent(entry -> { // update items updateState(CHANNEL_INDEX, new DecimalType(entry.getIndex())); @@ -190,7 +189,7 @@ public class SatelEventLogHandler extends SatelThingHandler { @Override public Collection> getServices() { - return Collections.singleton(SatelEventLogActions.class); + return Set.of(SatelEventLogActions.class); } /** @@ -276,7 +275,7 @@ public class SatelEventLogHandler extends SatelThingHandler { eventDetails = "." + readEventCmd.getSource() + "." + (readEventCmd.getObject() * 32 + readEventCmd.getUserControlNumber()); Optional eventDescNext = getEventDescription(readEventCmd.getNextIndex()); - if (!eventDescNext.isPresent()) { + if (eventDescNext.isEmpty()) { return Optional.empty(); } final EventDescription eventDescNextItem = eventDescNext.get(); diff --git a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelOutputHandler.java b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelOutputHandler.java index 719fc78ae..e24e6ad59 100644 --- a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelOutputHandler.java +++ b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelOutputHandler.java @@ -14,7 +14,6 @@ package org.openhab.binding.satel.internal.handler; import static org.openhab.binding.satel.internal.SatelBindingConstants.THING_TYPE_OUTPUT; -import java.util.Collections; import java.util.Optional; import java.util.Set; @@ -39,7 +38,7 @@ import org.openhab.core.types.Command; @NonNullByDefault public class SatelOutputHandler extends WirelessChannelsHandler { - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_OUTPUT); + public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_OUTPUT); public SatelOutputHandler(Thing thing) { super(thing); diff --git a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelPartitionHandler.java b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelPartitionHandler.java index c48b54281..e8190cf08 100644 --- a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelPartitionHandler.java +++ b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelPartitionHandler.java @@ -14,7 +14,6 @@ package org.openhab.binding.satel.internal.handler; import static org.openhab.binding.satel.internal.SatelBindingConstants.THING_TYPE_PARTITION; -import java.util.Collections; import java.util.Optional; import java.util.Set; @@ -39,7 +38,7 @@ import org.openhab.core.types.Command; @NonNullByDefault public class SatelPartitionHandler extends SatelStateThingHandler { - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_PARTITION); + public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_PARTITION); public SatelPartitionHandler(Thing thing) { super(thing); diff --git a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelShutterHandler.java b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelShutterHandler.java index c54e1784f..b96c9ff5e 100644 --- a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelShutterHandler.java +++ b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelShutterHandler.java @@ -14,7 +14,6 @@ package org.openhab.binding.satel.internal.handler; import static org.openhab.binding.satel.internal.SatelBindingConstants.*; -import java.util.Collections; import java.util.Optional; import java.util.Set; @@ -44,7 +43,7 @@ import org.slf4j.LoggerFactory; @NonNullByDefault public class SatelShutterHandler extends SatelStateThingHandler { - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_SHUTTER); + public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_SHUTTER); private final Logger logger = LoggerFactory.getLogger(SatelShutterHandler.class); diff --git a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelSystemHandler.java b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelSystemHandler.java index d7fb8c814..54101b835 100644 --- a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelSystemHandler.java +++ b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelSystemHandler.java @@ -15,7 +15,6 @@ package org.openhab.binding.satel.internal.handler; import static org.openhab.binding.satel.internal.SatelBindingConstants.*; import java.util.Collection; -import java.util.Collections; import java.util.LinkedList; import java.util.Optional; import java.util.Set; @@ -51,7 +50,7 @@ import org.slf4j.LoggerFactory; @NonNullByDefault public class SatelSystemHandler extends SatelStateThingHandler { - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_SYSTEM); + public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_SYSTEM); private static final Set STATUS_CHANNELS = Stream .of(CHANNEL_DATE_TIME, CHANNEL_SERVICE_MODE, CHANNEL_TROUBLES, CHANNEL_TROUBLES_MEMORY, @@ -112,8 +111,8 @@ public class SatelSystemHandler extends SatelStateThingHandler { DateTimeType dateTime = null; if (command instanceof StringType) { dateTime = DateTimeType.valueOf(command.toString()); - } else if (command instanceof DateTimeType) { - dateTime = (DateTimeType) command; + } else if (command instanceof DateTimeType dateTimeCommand) { + dateTime = dateTimeCommand; } if (dateTime != null) { return Optional.of(new SetClockCommand(dateTime.getZonedDateTime() diff --git a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelThingHandler.java b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelThingHandler.java index e6a8705e6..85a9b81d9 100644 --- a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelThingHandler.java +++ b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelThingHandler.java @@ -57,9 +57,9 @@ public abstract class SatelThingHandler extends BaseThingHandler implements Sate final Bridge bridge = getBridge(); if (bridge != null) { final ThingHandler handler = bridge.getHandler(); - if (handler != null && handler instanceof SatelBridgeHandler) { - ((SatelBridgeHandler) handler).addEventListener(this); - this.bridgeHandler = (SatelBridgeHandler) handler; + if (handler instanceof SatelBridgeHandler satelBridgeHandler) { + satelBridgeHandler.addEventListener(this); + this.bridgeHandler = satelBridgeHandler; } if (bridge.getStatus() == ThingStatus.ONLINE) { updateStatus(ThingStatus.ONLINE); diff --git a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelZoneHandler.java b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelZoneHandler.java index d86d3ab50..6e2b4de59 100644 --- a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelZoneHandler.java +++ b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelZoneHandler.java @@ -14,7 +14,6 @@ package org.openhab.binding.satel.internal.handler; import static org.openhab.binding.satel.internal.SatelBindingConstants.THING_TYPE_ZONE; -import java.util.Collections; import java.util.Optional; import java.util.Set; @@ -39,7 +38,7 @@ import org.openhab.core.types.Command; @NonNullByDefault public class SatelZoneHandler extends WirelessChannelsHandler { - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_ZONE); + public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_ZONE); public SatelZoneHandler(Thing thing) { super(thing); diff --git a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/WirelessChannelsHandler.java b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/WirelessChannelsHandler.java index 7ffec9c4e..b4e0e3fe3 100644 --- a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/WirelessChannelsHandler.java +++ b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/WirelessChannelsHandler.java @@ -79,9 +79,9 @@ public abstract class WirelessChannelsHandler extends SatelStateThingHandler { @Override protected int getStateBitNbr(StateType stateType) { int bitNbr = getThingConfig().getId() - 1; - if (stateType instanceof TroubleState) { + if (stateType instanceof TroubleState troubleState) { // for wireless devices we need to correct bit number - switch ((TroubleState) stateType) { + switch (troubleState) { case DEVICE_LOBATT1: case DEVICE_NOCOMM1: case OUTPUT_NOCOMM1: diff --git a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/protocol/EncryptionHelper.java b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/protocol/EncryptionHelper.java index d9e07a266..0b87f20bf 100644 --- a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/protocol/EncryptionHelper.java +++ b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/protocol/EncryptionHelper.java @@ -44,7 +44,7 @@ public class EncryptionHelper { } // build encryption/decryption key based on given password - byte passwordBytes[] = keyString.getBytes(); + byte[] passwordBytes = keyString.getBytes(); byte[] keyBytes = new byte[24]; for (int i = 0; i < 12; ++i) { @@ -67,7 +67,7 @@ public class EncryptionHelper { * @throws GeneralSecurityException * on decryption errors */ - public void decrypt(byte buffer[]) throws GeneralSecurityException { + public void decrypt(byte[] buffer) throws GeneralSecurityException { byte[] cv = new byte[16]; byte[] c = new byte[16]; byte[] temp = new byte[16]; @@ -104,7 +104,7 @@ public class EncryptionHelper { * @param buffer bytes to encrypt * @throws GeneralSecurityException on encryption errors */ - public void encrypt(byte buffer[]) throws GeneralSecurityException { + public void encrypt(byte[] buffer) throws GeneralSecurityException { byte[] cv = new byte[16]; byte[] p = new byte[16]; int count = buffer.length; diff --git a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/protocol/SatelMessage.java b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/protocol/SatelMessage.java index ff3757387..c7f8dd641 100644 --- a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/protocol/SatelMessage.java +++ b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/protocol/SatelMessage.java @@ -113,7 +113,7 @@ public class SatelMessage { * @return the message as array of bytes */ public byte[] getBytes() { - byte buffer[] = new byte[this.payload.length + 3]; + byte[] buffer = new byte[this.payload.length + 3]; buffer[0] = this.command; if (this.payload.length > 0) { System.arraycopy(this.payload, 0, buffer, 1, this.payload.length); diff --git a/bundles/org.openhab.binding.semsportal/src/main/java/org/openhab/binding/semsportal/internal/StationHandler.java b/bundles/org.openhab.binding.semsportal/src/main/java/org/openhab/binding/semsportal/internal/StationHandler.java index 75521107f..88bf43c06 100644 --- a/bundles/org.openhab.binding.semsportal/src/main/java/org/openhab/binding/semsportal/internal/StationHandler.java +++ b/bundles/org.openhab.binding.semsportal/src/main/java/org/openhab/binding/semsportal/internal/StationHandler.java @@ -158,8 +158,8 @@ public class StationHandler extends BaseThingHandler { String uuid = getThing().getProperties().get(STATION_UUID); if (uuid == null) { Object uuidObj = getThing().getConfiguration().get(STATION_UUID); - if (uuidObj instanceof String) { - uuid = (String) uuidObj; + if (uuidObj instanceof String stringValue) { + uuid = stringValue; } } return uuid == null ? "" : uuid; diff --git a/bundles/org.openhab.binding.senechome/src/main/java/org/openhab/binding/senechome/internal/SenecHomeHandlerFactory.java b/bundles/org.openhab.binding.senechome/src/main/java/org/openhab/binding/senechome/internal/SenecHomeHandlerFactory.java index 169f88473..82757dbde 100644 --- a/bundles/org.openhab.binding.senechome/src/main/java/org/openhab/binding/senechome/internal/SenecHomeHandlerFactory.java +++ b/bundles/org.openhab.binding.senechome/src/main/java/org/openhab/binding/senechome/internal/SenecHomeHandlerFactory.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.senechome.internal; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -38,8 +37,8 @@ import org.osgi.service.component.annotations.Reference; @Component(configurationPid = "binding.senechome", service = ThingHandlerFactory.class) public class SenecHomeHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections - .singleton(SenecHomeBindingConstants.THING_TYPE_SENEC_HOME_BATTERY); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set + .of(SenecHomeBindingConstants.THING_TYPE_SENEC_HOME_BATTERY); private HttpClient httpClient; diff --git a/bundles/org.openhab.binding.seneye/src/main/java/org/openhab/binding/seneye/internal/SeneyeBindingConstants.java b/bundles/org.openhab.binding.seneye/src/main/java/org/openhab/binding/seneye/internal/SeneyeBindingConstants.java index 77eac52de..32def242e 100644 --- a/bundles/org.openhab.binding.seneye/src/main/java/org/openhab/binding/seneye/internal/SeneyeBindingConstants.java +++ b/bundles/org.openhab.binding.seneye/src/main/java/org/openhab/binding/seneye/internal/SeneyeBindingConstants.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.seneye.internal; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -53,5 +52,5 @@ public class SeneyeBindingConstants { public static final String PARAMETER_PASSWORD = "password"; public static final String PARAMETER_POLLTIME = "polltime"; - public static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_SENEYE); + public static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_SENEYE); } diff --git a/bundles/org.openhab.binding.seneye/src/main/java/org/openhab/binding/seneye/internal/SeneyeHandlerFactory.java b/bundles/org.openhab.binding.seneye/src/main/java/org/openhab/binding/seneye/internal/SeneyeHandlerFactory.java index 7e04566fd..1898f0139 100644 --- a/bundles/org.openhab.binding.seneye/src/main/java/org/openhab/binding/seneye/internal/SeneyeHandlerFactory.java +++ b/bundles/org.openhab.binding.seneye/src/main/java/org/openhab/binding/seneye/internal/SeneyeHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.seneye.internal; import static org.openhab.binding.seneye.internal.SeneyeBindingConstants.THING_TYPE_SENEYE; -import java.util.Collections; import java.util.Set; import org.openhab.binding.seneye.internal.handler.SeneyeHandler; @@ -34,7 +33,7 @@ import org.osgi.service.component.annotations.Component; @Component(service = ThingHandlerFactory.class, configurationPid = "binding.seneye") public class SeneyeHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_SENEYE); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_SENEYE); @Override public boolean supportsThingType(ThingTypeUID thingTypeUID) { diff --git a/bundles/org.openhab.binding.seneye/src/main/java/org/openhab/binding/seneye/internal/SeneyeStatus.java b/bundles/org.openhab.binding.seneye/src/main/java/org/openhab/binding/seneye/internal/SeneyeStatus.java index dc731bb50..51b4278dd 100644 --- a/bundles/org.openhab.binding.seneye/src/main/java/org/openhab/binding/seneye/internal/SeneyeStatus.java +++ b/bundles/org.openhab.binding.seneye/src/main/java/org/openhab/binding/seneye/internal/SeneyeStatus.java @@ -37,9 +37,8 @@ public class SeneyeStatus { } private String getTickAsDate(String tick) { - String date = new java.text.SimpleDateFormat(DateTimeType.DATE_PATTERN_WITH_TZ_AND_MS_ISO) + return new java.text.SimpleDateFormat(DateTimeType.DATE_PATTERN_WITH_TZ_AND_MS_ISO) .format(new java.util.Date(Long.parseLong(tick) * 1000)); - return date; } public String getWrong_slideString() { diff --git a/bundles/org.openhab.binding.seneye/src/main/java/org/openhab/binding/seneye/internal/handler/SeneyeHandler.java b/bundles/org.openhab.binding.seneye/src/main/java/org/openhab/binding/seneye/internal/handler/SeneyeHandler.java index 857e4fde0..6198f13e1 100644 --- a/bundles/org.openhab.binding.seneye/src/main/java/org/openhab/binding/seneye/internal/handler/SeneyeHandler.java +++ b/bundles/org.openhab.binding.seneye/src/main/java/org/openhab/binding/seneye/internal/handler/SeneyeHandler.java @@ -151,9 +151,8 @@ public final class SeneyeHandler extends BaseThingHandler implements ReadingsUpd } // ok, initialization succeeded - cachedSeneyeDeviceReading = new ExpiringCache<>(TimeUnit.SECONDS.toMillis(10), () -> { - return seneyeService.getDeviceReadings(); - }); + cachedSeneyeDeviceReading = new ExpiringCache<>(TimeUnit.SECONDS.toMillis(10), + () -> seneyeService.getDeviceReadings()); seneyeService.startAutomaticRefresh(scheduler, this); diff --git a/bundles/org.openhab.binding.sensebox/src/main/java/org/openhab/binding/sensebox/internal/SenseBoxHandlerFactory.java b/bundles/org.openhab.binding.sensebox/src/main/java/org/openhab/binding/sensebox/internal/SenseBoxHandlerFactory.java index ab429a4bc..06d740099 100644 --- a/bundles/org.openhab.binding.sensebox/src/main/java/org/openhab/binding/sensebox/internal/SenseBoxHandlerFactory.java +++ b/bundles/org.openhab.binding.sensebox/src/main/java/org/openhab/binding/sensebox/internal/SenseBoxHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.sensebox.internal; import static org.openhab.binding.sensebox.internal.SenseBoxBindingConstants.THING_TYPE_BOX; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -37,7 +36,7 @@ import org.osgi.service.component.annotations.Component; @NonNullByDefault public class SenseBoxHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_BOX); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_BOX); @Override public boolean supportsThingType(ThingTypeUID thingTypeUID) { diff --git a/bundles/org.openhab.binding.sensebox/src/main/java/org/openhab/binding/sensebox/internal/dto/SenseBoxSensor.java b/bundles/org.openhab.binding.sensebox/src/main/java/org/openhab/binding/sensebox/internal/dto/SenseBoxSensor.java index c317aee94..c62ece2c5 100644 --- a/bundles/org.openhab.binding.sensebox/src/main/java/org/openhab/binding/sensebox/internal/dto/SenseBoxSensor.java +++ b/bundles/org.openhab.binding.sensebox/src/main/java/org/openhab/binding/sensebox/internal/dto/SenseBoxSensor.java @@ -59,7 +59,7 @@ public class SenseBoxSensor { public String getUnit() { // the uom library uses the 'MICRO SIGN', so if we encounter the GREEK SMALL LETTER MU, // replace it with the proper representation. - return unit != null ? unit.replaceAll("\u03bc", "\u00b5") : ""; + return unit != null ? unit.replace("\u03bc", "\u00b5") : ""; } public void setUnit(String unit) { diff --git a/bundles/org.openhab.binding.sensebox/src/main/java/org/openhab/binding/sensebox/internal/handler/SenseBoxHandler.java b/bundles/org.openhab.binding.sensebox/src/main/java/org/openhab/binding/sensebox/internal/handler/SenseBoxHandler.java index f599cd59b..e1bfb58bd 100644 --- a/bundles/org.openhab.binding.sensebox/src/main/java/org/openhab/binding/sensebox/internal/handler/SenseBoxHandler.java +++ b/bundles/org.openhab.binding.sensebox/src/main/java/org/openhab/binding/sensebox/internal/handler/SenseBoxHandler.java @@ -102,9 +102,7 @@ public class SenseBoxHandler extends BaseThingHandler { } if (senseBoxId != null && validConfig) { - cache.put(CACHE_KEY_DATA, () -> { - return connection.reallyFetchDataFromServer(senseBoxId); - }); + cache.put(CACHE_KEY_DATA, () -> connection.reallyFetchDataFromServer(senseBoxId)); updateStatus(ThingStatus.UNKNOWN); startAutomaticRefresh(); } else { diff --git a/bundles/org.openhab.binding.sensibo/src/main/java/org/openhab/binding/sensibo/internal/discovery/SensiboDiscoveryService.java b/bundles/org.openhab.binding.sensibo/src/main/java/org/openhab/binding/sensibo/internal/discovery/SensiboDiscoveryService.java index a93ff92b2..050b5cdeb 100644 --- a/bundles/org.openhab.binding.sensibo/src/main/java/org/openhab/binding/sensibo/internal/discovery/SensiboDiscoveryService.java +++ b/bundles/org.openhab.binding.sensibo/src/main/java/org/openhab/binding/sensibo/internal/discovery/SensiboDiscoveryService.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.sensibo.internal.discovery; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; @@ -39,8 +38,8 @@ import org.slf4j.LoggerFactory; */ @NonNullByDefault public class SensiboDiscoveryService extends AbstractDiscoveryService { - public static final Set DISCOVERABLE_THING_TYPES_UIDS = Collections - .singleton(SensiboBindingConstants.THING_TYPE_SENSIBOSKY); + public static final Set DISCOVERABLE_THING_TYPES_UIDS = Set + .of(SensiboBindingConstants.THING_TYPE_SENSIBOSKY); private static final long REFRESH_INTERVAL_MINUTES = 60; private final Logger logger = LoggerFactory.getLogger(SensiboDiscoveryService.class); private final SensiboAccountHandler accountHandler; @@ -67,7 +66,7 @@ public class SensiboDiscoveryService extends AbstractDiscoveryService { final SensiboModel model = accountHandler.getModel(); for (final SensiboSky pod : model.getPods()) { final ThingUID podUID = new ThingUID(SensiboBindingConstants.THING_TYPE_SENSIBOSKY, accountUID, - String.valueOf(pod.getMacAddress())); + pod.getMacAddress()); Map properties = pod.getThingProperties(); // DiscoveryResult result uses Map as properties while ThingBuilder uses diff --git a/bundles/org.openhab.binding.sensibo/src/main/java/org/openhab/binding/sensibo/internal/handler/SensiboSkyHandler.java b/bundles/org.openhab.binding.sensibo/src/main/java/org/openhab/binding/sensibo/internal/handler/SensiboSkyHandler.java index b8aa3166e..124d3078a 100644 --- a/bundles/org.openhab.binding.sensibo/src/main/java/org/openhab/binding/sensibo/internal/handler/SensiboSkyHandler.java +++ b/bundles/org.openhab.binding.sensibo/src/main/java/org/openhab/binding/sensibo/internal/handler/SensiboSkyHandler.java @@ -16,7 +16,6 @@ import static org.openhab.binding.sensibo.internal.SensiboBindingConstants.*; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; @@ -190,8 +189,7 @@ public class SensiboSkyHandler extends SensiboBaseThingHandler implements Channe } else { updateState(channelUID, UnDefType.UNDEF); } - } else if (command instanceof DecimalType) { - final DecimalType newValue = (DecimalType) command; + } else if (command instanceof DecimalType newValue) { updateTimer(newValue.intValue()); } else { updateTimer(null); @@ -205,8 +203,7 @@ public class SensiboSkyHandler extends SensiboBaseThingHandler implements Channe } else { updateState(channelUID, UnDefType.UNDEF); } - } else if (command instanceof StringType) { - final StringType newValue = (StringType) command; + } else if (command instanceof StringType newValue) { updateAcState(sensiboSky, FAN_LEVEL_PROPERTY, newValue.toString()); } } @@ -218,8 +215,7 @@ public class SensiboSkyHandler extends SensiboBaseThingHandler implements Channe } else { updateState(channelUID, UnDefType.UNDEF); } - } else if (command instanceof StringType) { - final StringType newValue = (StringType) command; + } else if (command instanceof StringType newValue) { updateAcState(sensiboSky, SWING_PROPERTY, newValue.toString()); } } @@ -231,8 +227,7 @@ public class SensiboSkyHandler extends SensiboBaseThingHandler implements Channe } else { updateState(channelUID, UnDefType.UNDEF); } - } else if (command instanceof StringType) { - final StringType newValue = (StringType) command; + } else if (command instanceof StringType newValue) { updateAcState(sensiboSky, MODE_PROPERTY, newValue.toString()); addDynamicChannelsAndProperties(sensiboSky); } @@ -249,11 +244,10 @@ public class SensiboSkyHandler extends SensiboBaseThingHandler implements Channe updateState(channelUID, UnDefType.UNDEF); } }); - if (!sensiboSky.getAcState().isPresent()) { + if (sensiboSky.getAcState().isEmpty()) { updateState(channelUID, UnDefType.UNDEF); } - } else if (command instanceof QuantityType) { - QuantityType newValue = (QuantityType) command; + } else if (command instanceof QuantityType newValue) { if (!Objects.equals(sensiboSky.getTemperatureUnit(), newValue.getUnit())) { // If quantity is given in celsius when fahrenheit is used or opposite try { @@ -296,7 +290,7 @@ public class SensiboSkyHandler extends SensiboBaseThingHandler implements Channe @Override public Collection> getServices() { - return Collections.singleton(CallbackChannelsTypeProvider.class); + return Set.of(CallbackChannelsTypeProvider.class); } @Override @@ -379,7 +373,7 @@ public class SensiboSkyHandler extends SensiboBaseThingHandler implements Channe final ChannelTypeUID channelTypeUID = new ChannelTypeUID(SensiboBindingConstants.BINDING_ID, channelTypePrefix + getThing().getUID().getId()); final List stateOptions = options.stream() - .map(e -> new StateOption(e.toString(), e instanceof String ? beautify((String) e) : e.toString())) + .map(e -> new StateOption(e.toString(), e instanceof String s ? beautify(s) : e.toString())) .collect(Collectors.toList()); StateDescriptionFragmentBuilder stateDescription = StateDescriptionFragmentBuilder.create().withReadOnly(false) diff --git a/bundles/org.openhab.binding.sensorcommunity/src/main/java/org/openhab/binding/sensorcommunity/internal/utils/NumberUtils.java b/bundles/org.openhab.binding.sensorcommunity/src/main/java/org/openhab/binding/sensorcommunity/internal/utils/NumberUtils.java index cf8ef3bb5..b7d13f68c 100644 --- a/bundles/org.openhab.binding.sensorcommunity/src/main/java/org/openhab/binding/sensorcommunity/internal/utils/NumberUtils.java +++ b/bundles/org.openhab.binding.sensorcommunity/src/main/java/org/openhab/binding/sensorcommunity/internal/utils/NumberUtils.java @@ -40,8 +40,8 @@ public class NumberUtils { public static double convert(Object o) { // ensure value not null double value = UNDEF; - if (o instanceof Number) { - value = ((Number) o).doubleValue(); + if (o instanceof Number number) { + value = number.doubleValue(); } else if (o instanceof String) { value = Double.parseDouble(o.toString()); } diff --git a/bundles/org.openhab.binding.sensorcommunity/src/test/java/org/openhab/binding/sensorcommunity/internal/DTOTest.java b/bundles/org.openhab.binding.sensorcommunity/src/test/java/org/openhab/binding/sensorcommunity/internal/DTOTest.java index 9d9fcfbb7..60d5d1c5d 100644 --- a/bundles/org.openhab.binding.sensorcommunity/src/test/java/org/openhab/binding/sensorcommunity/internal/DTOTest.java +++ b/bundles/org.openhab.binding.sensorcommunity/src/test/java/org/openhab/binding/sensorcommunity/internal/DTOTest.java @@ -70,7 +70,7 @@ public class DTOTest { SensorData d = valueArray[0]; // Assure latest data is taken String dateStr = d.getTimeStamp(); - if (dateStr.equals("2020-06-09 06:38:08")) { + if ("2020-06-09 06:38:08".equals(dateStr)) { // take newer one d = valueArray[1]; } diff --git a/bundles/org.openhab.binding.sensorcommunity/src/test/java/org/openhab/binding/sensorcommunity/internal/util/FileReader.java b/bundles/org.openhab.binding.sensorcommunity/src/test/java/org/openhab/binding/sensorcommunity/internal/util/FileReader.java index 35d2592d5..6be88d3c3 100644 --- a/bundles/org.openhab.binding.sensorcommunity/src/test/java/org/openhab/binding/sensorcommunity/internal/util/FileReader.java +++ b/bundles/org.openhab.binding.sensorcommunity/src/test/java/org/openhab/binding/sensorcommunity/internal/util/FileReader.java @@ -31,7 +31,7 @@ import org.eclipse.jdt.annotation.Nullable; public class FileReader { public static @Nullable String readFileInString(String filename) { - try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "CP1252"));) { + try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "CP1252"))) { StringBuffer buf = new StringBuffer(); String sCurrentLine; diff --git a/bundles/org.openhab.binding.serialbutton/src/main/java/org/openhab/binding/serialbutton/internal/SerialButtonHandlerFactory.java b/bundles/org.openhab.binding.serialbutton/src/main/java/org/openhab/binding/serialbutton/internal/SerialButtonHandlerFactory.java index 8d6201a8a..ba99c8336 100644 --- a/bundles/org.openhab.binding.serialbutton/src/main/java/org/openhab/binding/serialbutton/internal/SerialButtonHandlerFactory.java +++ b/bundles/org.openhab.binding.serialbutton/src/main/java/org/openhab/binding/serialbutton/internal/SerialButtonHandlerFactory.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.serialbutton.internal; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -37,8 +36,8 @@ import org.osgi.service.component.annotations.Reference; @NonNullByDefault public class SerialButtonHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections - .singleton(SerialButtonBindingConstants.THING_TYPE_BUTTON); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set + .of(SerialButtonBindingConstants.THING_TYPE_BUTTON); private @NonNullByDefault({}) SerialPortManager serialPortManager; diff --git a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/ShellyHandlerFactory.java b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/ShellyHandlerFactory.java index a9857c501..f0cf33be8 100755 --- a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/ShellyHandlerFactory.java +++ b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/ShellyHandlerFactory.java @@ -156,8 +156,8 @@ public class ShellyHandlerFactory extends BaseThingHandlerFactory { */ @Override protected synchronized void removeHandler(@NonNull ThingHandler thingHandler) { - if (thingHandler instanceof ShellyBaseHandler) { - ((ShellyBaseHandler) thingHandler).stop(); + if (thingHandler instanceof ShellyBaseHandler shellyBaseHandler) { + shellyBaseHandler.stop(); String uid = thingHandler.getThing().getUID().getAsString(); thingTable.removeThing(uid); } diff --git a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api1/Shelly1CoIoTProtocol.java b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api1/Shelly1CoIoTProtocol.java index 960321217..3b5603b9f 100644 --- a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api1/Shelly1CoIoTProtocol.java +++ b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api1/Shelly1CoIoTProtocol.java @@ -263,9 +263,9 @@ public class Shelly1CoIoTProtocol { // continue until we find the correct one continue; } - if (d.desc.equalsIgnoreCase("brightness")) { + if ("brightness".equalsIgnoreCase(d.desc)) { brightness = update.value; - } else if (d.desc.equalsIgnoreCase("output") || d.desc.equalsIgnoreCase("state")) { + } else if ("output".equalsIgnoreCase(d.desc) || "state".equalsIgnoreCase(d.desc)) { power = update.value; } } @@ -356,8 +356,8 @@ public class Shelly1CoIoTProtocol { int idx = 0; for (Map.Entry se : sensorMap.entrySet()) { CoIotDescrSen sen = se.getValue(); - if (sen.desc.equalsIgnoreCase("external_temperature") || sen.desc.equalsIgnoreCase("external temperature c") - || (sen.desc.equalsIgnoreCase("extTemp") && !sen.unit.equalsIgnoreCase(SHELLY_TEMP_FAHRENHEIT))) { + if ("external_temperature".equalsIgnoreCase(sen.desc) || "external temperature c".equalsIgnoreCase(sen.desc) + || ("extTemp".equalsIgnoreCase(sen.desc) && !sen.unit.equalsIgnoreCase(SHELLY_TEMP_FAHRENHEIT))) { idx++; // iterate from temperature1..2..n } if (sen.id.equalsIgnoreCase(sensorId)) { diff --git a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api1/Shelly1CoIoTVersion2.java b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api1/Shelly1CoIoTVersion2.java index 0e5384791..24f2b7147 100644 --- a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api1/Shelly1CoIoTVersion2.java +++ b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api1/Shelly1CoIoTVersion2.java @@ -210,7 +210,6 @@ public class Shelly1CoIoTVersion2 extends Shelly1CoIoTProtocol implements Shelly break; case "3104": // T, deviceTemp, Celsius -40/300; 999=unknown if ("targetTemp".equalsIgnoreCase(sen.desc)) { - break; // target temp in F-> ignore } // sensor_0: T, internalTemp, F, 39/88, unknown 999 @@ -383,7 +382,7 @@ public class Shelly1CoIoTVersion2 extends Shelly1CoIoTProtocol implements Shelly } break; case "9102": // EV, wakeupEvent, battery/button/periodic/poweron/sensor/ext_power, "unknown"=unknown - if (s.valueArray.size() > 0) { + if (!s.valueArray.isEmpty()) { thingHandler.updateWakeupReason(s.valueArray); lastWakeup = (String) s.valueArray.get(0); } diff --git a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api1/Shelly1CoapHandler.java b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api1/Shelly1CoapHandler.java index af71ad844..9d9992fd8 100644 --- a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api1/Shelly1CoapHandler.java +++ b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api1/Shelly1CoapHandler.java @@ -271,7 +271,7 @@ public class Shelly1CoapHandler implements Shelly1CoapListener { // The device changes the serial on every update, receiving a message with the same serial is a // duplicate, excep for battery devices! Those reset the serial every time when they wake-up if ((serial == lastSerial) && payload.equals(lastPayload) && (!profile.hasBattery - || coiot.getLastWakeup().equalsIgnoreCase("ext_power") || ((serial & 0xFF) != 0))) { + || "ext_power".equalsIgnoreCase(coiot.getLastWakeup()) || ((serial & 0xFF) != 0))) { logger.debug("{}: Serial {} was already processed, ignore update", thingName, serial); return; } diff --git a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api2/Shelly2ApiClient.java b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api2/Shelly2ApiClient.java index afb0482ad..a8c771fe6 100644 --- a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api2/Shelly2ApiClient.java +++ b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api2/Shelly2ApiClient.java @@ -157,7 +157,7 @@ public class Shelly2ApiClient extends ShellyHttpClient { addRelaySettings(relays, dc.switch2); addRelaySettings(relays, dc.switch3); addRelaySettings(relays, dc.switch100); - return relays.size() > 0 ? relays : null; + return !relays.isEmpty() ? relays : null; } private void addRelaySettings(ArrayList<@Nullable ShellySettingsRelay> relays, @@ -496,7 +496,7 @@ public class Shelly2ApiClient extends ShellyHttpClient { fav.name = fav.pos + "%"; profile.settings.favorites.add(fav); } - profile.settings.favoritesEnabled = profile.settings.favorites.size() > 0; + profile.settings.favoritesEnabled = !profile.settings.favorites.isEmpty(); logger.debug("{}: Roller Favorites loaded: {}", thingName, profile.settings.favoritesEnabled ? profile.settings.favorites.size() : "none"); } diff --git a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api2/Shelly2ApiRpc.java b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api2/Shelly2ApiRpc.java index de378feda..f25188faf 100644 --- a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api2/Shelly2ApiRpc.java +++ b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api2/Shelly2ApiRpc.java @@ -312,7 +312,7 @@ public class Shelly2ApiRpc extends Shelly2ApiClient implements ShellyApiInterfac if (dc.led != null) { profile.settings.ledStatusDisable = !getBool(dc.led.sysLedEnable); - profile.settings.ledPowerDisable = getString(dc.led.powerLed).equals("off"); + profile.settings.ledPowerDisable = "off".equals(getString(dc.led.powerLed)); } profile.initialized = true; @@ -1159,7 +1159,7 @@ public class Shelly2ApiRpc extends Shelly2ApiClient implements ShellyApiInterfac authInfo = new Shelly2AuthChallenge(); for (String o : options) { String key = substringBefore(o, "=").stripLeading().trim(); - String value = substringAfter(o, "=").replaceAll("\"", "").trim(); + String value = substringAfter(o, "=").replace("\"", "").trim(); switch (key) { case "Digest qop": authInfo.authType = SHELLY2_AUTHTTYPE_DIGEST; @@ -1189,7 +1189,7 @@ public class Shelly2ApiRpc extends Shelly2ApiClient implements ShellyApiInterfac // return sub element result as requested class type json = gson.toJson(gson.fromJson(json, Shelly2RpcBaseMessage.class).result); boolean isString = response.result instanceof String; - return fromJson(gson, isString && ((String) response.result).equalsIgnoreCase("null") ? "{}" : json, + return fromJson(gson, isString && "null".equalsIgnoreCase(((String) response.result)) ? "{}" : json, classOfT); } else { // return direct format diff --git a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api2/Shelly2RpcSocket.java b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api2/Shelly2RpcSocket.java index a043772cd..06159751e 100644 --- a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api2/Shelly2RpcSocket.java +++ b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api2/Shelly2RpcSocket.java @@ -259,7 +259,7 @@ public class Shelly2RpcSocket { } else { for (Shelly2NotifyEvent e : events.params.events) { if (getString(e.event).startsWith(SHELLY2_EVENT_BLUPREFIX)) { - String address = getString(e.data.addr).replaceAll(":", ""); + String address = getString(e.data.addr).replace(":", ""); if (thingTable != null && thingTable.findThing(address) != null) { if (thingTable != null) { // known device ShellyThingInterface thing = thingTable.getThing(address); diff --git a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api2/ShellyBluApi.java b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api2/ShellyBluApi.java index 7d35d051e..533d4448e 100644 --- a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api2/ShellyBluApi.java +++ b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api2/ShellyBluApi.java @@ -303,9 +303,7 @@ public class ShellyBluApi extends Shelly2ApiRpc { logger.debug("{}: Unable to process event", thingName, e); t.incProtErrors(); } - if (updated) { - } } diff --git a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/config/ShellyBindingConfiguration.java b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/config/ShellyBindingConfiguration.java index 3950378d0..493d03fd8 100644 --- a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/config/ShellyBindingConfiguration.java +++ b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/config/ShellyBindingConfiguration.java @@ -55,9 +55,9 @@ public class ShellyBindingConfiguration { break; case CONFIG_AUTOCOIOT: Object value = e.getValue(); - if (value instanceof String) { + if (value instanceof String stringValue) { // support config through shelly.cfg - autoCoIoT = ((String) value).equalsIgnoreCase("true"); + autoCoIoT = "true".equalsIgnoreCase(stringValue); } else { autoCoIoT = (boolean) value; } diff --git a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/handler/ShellyBaseHandler.java b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/handler/ShellyBaseHandler.java index 959c845e0..9cb3078df 100755 --- a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/handler/ShellyBaseHandler.java +++ b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/handler/ShellyBaseHandler.java @@ -317,7 +317,7 @@ public abstract class ShellyBaseHandler extends BaseThingHandler } if (tmpPrf.settings.sleepMode != null && !tmpPrf.isTRV) { // Sensor, usually 12h, H&T in USB mode 10min - tmpPrf.updatePeriod = getString(tmpPrf.settings.sleepMode.unit).equalsIgnoreCase("m") + tmpPrf.updatePeriod = "m".equalsIgnoreCase(getString(tmpPrf.settings.sleepMode.unit)) ? tmpPrf.settings.sleepMode.period * 60 // minutes : tmpPrf.settings.sleepMode.period * 3600; // hours tmpPrf.updatePeriod += 60; // give 1min extra @@ -495,14 +495,14 @@ public abstract class ShellyBaseHandler extends BaseThingHandler } private double getNumber(Command command) { - if (command instanceof QuantityType) { - return ((QuantityType) command).doubleValue(); + if (command instanceof QuantityType quantityCommand) { + return quantityCommand.doubleValue(); } - if (command instanceof DecimalType) { - return ((DecimalType) command).doubleValue(); + if (command instanceof DecimalType decimalCommand) { + return decimalCommand.doubleValue(); } - if (command instanceof Number) { - return ((Number) command).doubleValue(); + if (command instanceof Number numberCommand) { + return numberCommand.doubleValue(); } throw new IllegalArgumentException("Invalid Number type for conversion: " + command); } @@ -609,15 +609,19 @@ public abstract class ShellyBaseHandler extends BaseThingHandler profile.hostname, profile.deviceType, profile.hwRev, profile.hwBatchId, profile.fwVersion, profile.fwDate); logger.debug("{}: Shelly settings info for {}: {}", thingName, profile.hostname, profile.settingsJson); - logger.debug("{}: Device " - + "hasRelays:{} (numRelays={}),isRoller:{} (numRoller={}),isDimmer:{},numMeter={},isEMeter:{}), ext. Switch Add-On: {}" - + ",isSensor:{},isDS:{},hasBattery:{}{},isSense:{},isMotion:{},isLight:{},isBulb:{},isDuo:{},isRGBW2:{},inColor:{}, BLU Gateway support: {}" - + ",alwaysOn:{}, updatePeriod:{}sec", thingName, profile.hasRelays, profile.numRelays, profile.isRoller, - profile.numRollers, profile.isDimmer, profile.numMeters, profile.isEMeter, - profile.settings.extSwitch != null ? "installed" : "n/a", profile.isSensor, profile.isDW, - profile.hasBattery, profile.hasBattery ? " (low battery threshold=" + config.lowBattery + "%)" : "", - profile.isSense, profile.isMotion, profile.isLight, profile.isBulb, profile.isDuo, profile.isRGBW2, - profile.inColor, profile.alwaysOn, profile.updatePeriod, config.enableBluGateway); + logger.debug( + """ + {}: Device \ + hasRelays:{} (numRelays={}),isRoller:{} (numRoller={}),isDimmer:{},numMeter={},isEMeter:{}), ext. Switch Add-On: {}\ + ,isSensor:{},isDS:{},hasBattery:{}{},isSense:{},isMotion:{},isLight:{},isBulb:{},isDuo:{},isRGBW2:{},inColor:{}, BLU Gateway support: {}\ + ,alwaysOn:{}, updatePeriod:{}sec\ + """, + thingName, profile.hasRelays, profile.numRelays, profile.isRoller, profile.numRollers, profile.isDimmer, + profile.numMeters, profile.isEMeter, profile.settings.extSwitch != null ? "installed" : "n/a", + profile.isSensor, profile.isDW, profile.hasBattery, + profile.hasBattery ? " (low battery threshold=" + config.lowBattery + "%)" : "", profile.isSense, + profile.isMotion, profile.isLight, profile.isBulb, profile.isDuo, profile.isRGBW2, profile.inColor, + profile.alwaysOn, profile.updatePeriod, config.enableBluGateway); if (profile.status.extTemperature != null || profile.status.extHumidity != null || profile.status.extVoltage != null || profile.status.extAnalogInput != null) { logger.debug("{}: Shelly Add-On detected with at least 1 external sensor", thingName); @@ -876,7 +880,7 @@ public abstract class ShellyBaseHandler extends BaseThingHandler String payload = ""; String parmType = getString(parameters.get("type")); String event = !parmType.isEmpty() ? parmType : type; - boolean isButton = profile.inButtonMode(idx - 1) || type.equals("button"); + boolean isButton = profile.inButtonMode(idx - 1) || "button".equals(type); switch (event) { case SHELLY_EVENT_SHORTPUSH: case SHELLY_EVENT_DOUBLE_SHORTPUSH: @@ -996,8 +1000,8 @@ public abstract class ShellyBaseHandler extends BaseThingHandler return; } - config.deviceAddress = config.deviceAddress.toLowerCase().replaceAll(":", ""); // remove : from MAC address and - // convert to lower case + config.deviceAddress = config.deviceAddress.toLowerCase().replace(":", ""); // remove : from MAC address and + // convert to lower case if (!config.deviceIp.isEmpty()) { try { InetAddress addr = InetAddress.getByName(config.deviceIp); @@ -1055,7 +1059,7 @@ public abstract class ShellyBaseHandler extends BaseThingHandler } } if (!gen2 && bindingConfig.autoCoIoT && ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWCOIOT)) >= 0) - || (prf.fwVersion.equalsIgnoreCase("production_test"))) { + || ("production_test".equalsIgnoreCase(prf.fwVersion))) { if (!config.eventsCoIoT) { logger.info("{}: {}", thingName, messages.get("versioncheck.autocoiot")); } @@ -1296,11 +1300,11 @@ public abstract class ShellyBaseHandler extends BaseThingHandler public double getChannelDouble(String group, String channel) { State value = getChannelValue(group, channel); if (value != UnDefType.NULL) { - if (value instanceof QuantityType) { - return ((QuantityType) value).toBigDecimal().doubleValue(); + if (value instanceof QuantityType quantityCommand) { + return quantityCommand.toBigDecimal().doubleValue(); } - if (value instanceof DecimalType) { - return ((DecimalType) value).doubleValue(); + if (value instanceof DecimalType decimalCommand) { + return decimalCommand.doubleValue(); } } return -1; diff --git a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/handler/ShellyBluSensorHandler.java b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/handler/ShellyBluSensorHandler.java index 3cd8975b8..d79967a0d 100644 --- a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/handler/ShellyBluSensorHandler.java +++ b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/handler/ShellyBluSensorHandler.java @@ -38,7 +38,7 @@ import org.slf4j.LoggerFactory; * @author Markus Michels - Initial contribution */ public class ShellyBluSensorHandler extends ShellyBaseHandler { - private final static Logger logger = LoggerFactory.getLogger(ShellyBluSensorHandler.class); + private static final Logger logger = LoggerFactory.getLogger(ShellyBluSensorHandler.class); public ShellyBluSensorHandler(final Thing thing, final ShellyTranslationProvider translationProvider, final ShellyBindingConfiguration bindingConfig, final ShellyThingTable thingTable, @@ -54,7 +54,7 @@ public class ShellyBluSensorHandler extends ShellyBaseHandler { public static void addBluThing(String gateway, Shelly2NotifyEvent e, ShellyThingTable thingTable) { String model = substringBefore(getString(e.data.name), "-").toUpperCase(); - String mac = e.data.addr.replaceAll(":", ""); + String mac = e.data.addr.replace(":", ""); String ttype = ""; logger.debug("{}: Create thing for new BLU device {}: {} / {}", gateway, e.data.name, model, mac); ThingTypeUID tuid; diff --git a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/handler/ShellyColorUtils.java b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/handler/ShellyColorUtils.java index e221e114c..7e035d8e7 100644 --- a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/handler/ShellyColorUtils.java +++ b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/handler/ShellyColorUtils.java @@ -142,10 +142,10 @@ public class ShellyColorUtils { } public Integer[] fromRGBW(String rgbwString) { - Integer values[] = new Integer[4]; + Integer[] values = new Integer[4]; values[0] = values[1] = values[2] = values[3] = -1; try { - String rgbw[] = rgbwString.split(","); + String[] rgbw = rgbwString.split(","); for (int i = 0; i < rgbw.length; i++) { values[i] = Integer.parseInt(rgbw[i]); } diff --git a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/handler/ShellyComponents.java b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/handler/ShellyComponents.java index ddec6f962..8e05ff4f5 100644 --- a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/handler/ShellyComponents.java +++ b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/handler/ShellyComponents.java @@ -369,8 +369,7 @@ public class ShellyComponents { // EM: compute from provided values if (emeter.reactive != null && Math.abs(emeter.power) + Math.abs(emeter.reactive) > 1.5) { - double pf = emeter.power / Math.sqrt(emeter.power * emeter.power + emeter.reactive * emeter.reactive); - return pf; + return emeter.power / Math.sqrt(emeter.power * emeter.power + emeter.reactive * emeter.reactive); } return 0.0; } @@ -491,7 +490,7 @@ public class ShellyComponents { updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_PPM, toQuantityType( getInteger(sdata.concentration.ppm).doubleValue(), DIGITS_NONE, Units.PARTS_PER_MILLION)); } - if ((sdata.adcs != null) && (sdata.adcs.size() > 0)) { + if ((sdata.adcs != null) && (!sdata.adcs.isEmpty())) { ShellyADC adc = sdata.adcs.get(0); updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_VOLTAGE, toQuantityType(getDouble(adc.voltage), 2, Units.VOLT)); diff --git a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/handler/ShellyLightHandler.java b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/handler/ShellyLightHandler.java index 94ba3d829..8fc49526f 100644 --- a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/handler/ShellyLightHandler.java +++ b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/handler/ShellyLightHandler.java @@ -145,12 +145,12 @@ public class ShellyLightHandler extends ShellyBaseHandler { break; } - if (command instanceof PercentType) { - Float percent = ((PercentType) command).floatValue(); + if (command instanceof PercentType percentCommand) { + Float percent = percentCommand.floatValue(); value = percent.intValue(); // 0..100% = 0..100 logger.debug("{}: Set brightness to {}%/{}", thingName, percent, value); - } else if (command instanceof DecimalType) { - value = ((DecimalType) command).intValue(); + } else if (command instanceof DecimalType decimalCommand) { + value = decimalCommand.intValue(); logger.debug("{}: Set brightness to {} (Integer)", thingName, value); } if (value == 0) { @@ -158,9 +158,9 @@ public class ShellyLightHandler extends ShellyBaseHandler { api.setLightTurn(lightId, SHELLY_API_OFF); update = false; } else { - if (command instanceof IncreaseDecreaseType) { + if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) { ShellyShortLightStatus light = api.getLightStatus(lightId); - if (((IncreaseDecreaseType) command).equals(IncreaseDecreaseType.INCREASE)) { + if (increaseDecreaseCommand.equals(IncreaseDecreaseType.INCREASE)) { value = Math.min(light.brightness + DIM_STEPSIZE, 100); } else { value = Math.max(light.brightness - DIM_STEPSIZE, 0); @@ -178,14 +178,14 @@ public class ShellyLightHandler extends ShellyBaseHandler { case CHANNEL_COLOR_TEMP: Integer temp = -1; - if (command instanceof PercentType) { - logger.debug("{}: Set color temp to {}%", thingName, ((PercentType) command).floatValue()); - Float percent = ((PercentType) command).floatValue() / 100; + if (command instanceof PercentType percentCommand) { + logger.debug("{}: Set color temp to {}%", thingName, percentCommand.floatValue()); + Float percent = percentCommand.floatValue() / 100; temp = new DecimalType(col.minTemp + ((col.maxTemp - col.minTemp)) * percent).intValue(); logger.debug("{}: Converted color-temp {}% to {}K (from Percent to Integer)", thingName, percent, temp); - } else if (command instanceof DecimalType) { - temp = ((DecimalType) command).intValue(); + } else if (command instanceof DecimalType decimalCommand) { + temp = decimalCommand.intValue(); logger.debug("{}: Set color temp to {}K (Integer)", thingName, temp); } validateRange(CHANNEL_COLOR_TEMP, temp, col.minTemp, col.maxTemp); @@ -225,9 +225,7 @@ public class ShellyLightHandler extends ShellyBaseHandler { private boolean handleColorPicker(ShellyDeviceProfile profile, Integer lightId, ShellyColorUtils col, Command command) throws ShellyApiException { boolean updated = false; - if (command instanceof HSBType) { - HSBType hsb = (HSBType) command; - + if (command instanceof HSBType hsb) { logger.debug("HSB-Info={}, Hue={}, getRGB={}, toRGB={}/{}/{}", hsb, hsb.getHue(), String.format("0x%08X", hsb.getRGB()), hsb.toRGB()[0], hsb.toRGB()[1], hsb.toRGB()[2]); if (hsb.toString().contains("360,")) { @@ -242,16 +240,15 @@ public class ShellyLightHandler extends ShellyBaseHandler { col.setBrightness(getColorFromHSB(hsb.getBrightness(), BRIGHTNESS_FACTOR)); // white, gain and temp are not part of the HSB color scheme updated = true; - } else if (command instanceof PercentType) { + } else if (command instanceof PercentType percentCommand) { if (!profile.inColor || profile.isBulb) { - col.brightness = SHELLY_MAX_BRIGHTNESS * ((PercentType) command).intValue(); + col.brightness = SHELLY_MAX_BRIGHTNESS * percentCommand.intValue(); updated = true; } - } else if (command instanceof OnOffType) { - logger.debug("{}: Switch light {}", thingName, command); - api.setLightParm(lightId, SHELLY_LIGHT_TURN, - (OnOffType) command == OnOffType.ON ? SHELLY_API_ON : SHELLY_API_OFF); - col.power = (OnOffType) command; + } else if (command instanceof OnOffType onOffCommand) { + logger.debug("{}: Switch light {}", thingName, onOffCommand); + api.setLightParm(lightId, SHELLY_LIGHT_TURN, onOffCommand == OnOffType.ON ? SHELLY_API_ON : SHELLY_API_OFF); + col.power = onOffCommand; } else if (command instanceof IncreaseDecreaseType) { if (!profile.inColor || profile.isBulb) { logger.debug("{}: {} brightness by {}", thingName, command, SHELLY_DIM_STEPSIZE); @@ -410,16 +407,15 @@ public class ShellyLightHandler extends ShellyBaseHandler { throws ShellyApiException, IllegalArgumentException { Integer value = -1; logger.debug("{}: Set {} to {} ({})", thingName, colorName, command, command.getClass()); - if (command instanceof PercentType) { - PercentType percent = (PercentType) command; - double v = (double) maxValue * percent.doubleValue() / 100.0; + if (command instanceof PercentType percentCommand) { + double v = (double) maxValue * percentCommand.doubleValue() / 100.0; value = (int) v; - logger.debug("{}: Value for {} is in percent: {}%={}", thingName, colorName, percent, value); - } else if (command instanceof DecimalType) { - value = ((DecimalType) command).intValue(); + logger.debug("{}: Value for {} is in percent: {}%={}", thingName, colorName, percentCommand, value); + } else if (command instanceof DecimalType decimalCommand) { + value = decimalCommand.intValue(); logger.debug("Value for {} is a number: {}", colorName, value); - } else if (command instanceof OnOffType) { - value = ((OnOffType) command).equals(OnOffType.ON) ? SHELLY_MAX_COLOR : SHELLY_MIN_COLOR; + } else if (command instanceof OnOffType onOffCommand) { + value = onOffCommand.equals(OnOffType.ON) ? SHELLY_MAX_COLOR : SHELLY_MIN_COLOR; logger.debug("{}: Value for {} of type OnOff was converted to {}", thingName, colorName, value); } else { throw new IllegalArgumentException( diff --git a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/handler/ShellyRelayHandler.java b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/handler/ShellyRelayHandler.java index c62bf58a7..93182b86e 100644 --- a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/handler/ShellyRelayHandler.java +++ b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/handler/ShellyRelayHandler.java @@ -113,8 +113,8 @@ public class ShellyRelayHandler extends ShellyBaseHandler { break; case CHANNEL_ROL_CONTROL_FAV: - if (command instanceof Number) { - int id = ((Number) command).intValue() - 1; + if (command instanceof Number numberCommand) { + int id = numberCommand.intValue() - 1; int pos = profile.getRollerFav(id); if (pos > 0) { logger.debug("{}: Selecting favorite {}, position = {}", thingName, id, pos); @@ -156,13 +156,13 @@ public class ShellyRelayHandler extends ShellyBaseHandler { */ private void handleBrightness(Command command, Integer index) throws ShellyApiException { Integer value = -1; - if (command instanceof PercentType) { // Dimmer - value = ((PercentType) command).intValue(); - } else if (command instanceof DecimalType) { // Number - value = ((DecimalType) command).intValue(); - } else if (command instanceof OnOffType) { // Switch + if (command instanceof PercentType percentCommand) { // Dimmer + value = percentCommand.intValue(); + } else if (command instanceof DecimalType decimalCommand) { // Number + value = decimalCommand.intValue(); + } else if (command instanceof OnOffType onOffCommand) { // Switch logger.debug("{}: Switch output {}", thingName, command); - updateBrightnessChannel(index, (OnOffType) command, value); + updateBrightnessChannel(index, onOffCommand, value); return; } else if (command instanceof IncreaseDecreaseType) { ShellyShortLightStatus light = api.getLightStatus(index); @@ -236,7 +236,7 @@ public class ShellyRelayHandler extends ShellyBaseHandler { } if (command == UpDownType.UP || command == OnOffType.ON - || ((command instanceof DecimalType) && (((DecimalType) command).intValue() == 100))) { + || ((command instanceof DecimalType decimalCommand) && (decimalCommand.intValue() == 100))) { logger.debug("{}: Open roller", thingName); int shpos = profile.getRollerFav(config.favoriteUP - 1); if (shpos > 0) { @@ -248,7 +248,7 @@ public class ShellyRelayHandler extends ShellyBaseHandler { api.setRollerTurn(index, SHELLY_ALWD_ROLLER_TURN_OPEN); } } else if (command == UpDownType.DOWN || command == OnOffType.OFF - || ((command instanceof DecimalType) && (((DecimalType) command).intValue() == 0))) { + || ((command instanceof DecimalType decimalCommand) && (decimalCommand.intValue() == 0))) { logger.debug("{}: Closing roller", thingName); int shpos = profile.getRollerFav(config.favoriteDOWN - 1); if (shpos > 0) { @@ -266,12 +266,10 @@ public class ShellyRelayHandler extends ShellyBaseHandler { api.setRollerTurn(index, SHELLY_ALWD_ROLLER_TURN_STOP); } else { logger.debug("{}: Set roller to position {}", thingName, command); - if (command instanceof PercentType) { - PercentType p = (PercentType) command; - position = p.intValue(); - } else if (command instanceof DecimalType) { - DecimalType d = (DecimalType) command; - position = d.intValue(); + if (command instanceof PercentType percentCommand) { + position = percentCommand.intValue(); + } else if (command instanceof DecimalType decimalCommand) { + position = decimalCommand.intValue(); } else { throw new IllegalArgumentException( "Invalid value type for roller control/position" + command.getClass().toString()); diff --git a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/manager/ShellyManagerCache.java b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/manager/ShellyManagerCache.java index 8fffe8ced..7131fc425 100644 --- a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/manager/ShellyManagerCache.java +++ b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/manager/ShellyManagerCache.java @@ -49,8 +49,7 @@ public class ShellyManagerCache extends ConcurrentHashMap { public @Nullable V put(K key, V value) { Date date = new Date(); timeMap.put(key, date.getTime()); - V returnVal = super.put(key, value); - return returnVal; + return super.put(key, value); } @Override diff --git a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/manager/ShellyManagerOverviewPage.java b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/manager/ShellyManagerOverviewPage.java index a27db0d01..ddc696e80 100644 --- a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/manager/ShellyManagerOverviewPage.java +++ b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/manager/ShellyManagerOverviewPage.java @@ -126,7 +126,7 @@ public class ShellyManagerOverviewPage extends ShellyManagerPage { properties.clear(); properties.put("numberDevices", "" + "Number of devices: " + filteredDevices - + " of " + String.valueOf(getThingHandlers().size()) + " "); + + " of " + getThingHandlers().size() + " "); properties.put(ATTRIBUTE_CSS_FOOTER, loadHTML(OVERVIEW_FOOTER, properties)); html += deviceHtml + loadHTML(FOOTER_HTML, properties); return new ShellyMgrResponse(fillAttributes(html, properties), HttpStatus.OK_200); diff --git a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/manager/ShellyManagerPage.java b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/manager/ShellyManagerPage.java index 7de4246c4..a70b4472d 100644 --- a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/manager/ShellyManagerPage.java +++ b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/manager/ShellyManagerPage.java @@ -338,15 +338,14 @@ public class ShellyManagerPage { State state = thingHandler.getChannelValue(group, attribute); String value = ""; if (state != UnDefType.NULL) { - if (state instanceof DateTimeType) { - DateTimeType dt = (DateTimeType) state; + if (state instanceof DateTimeType dateTimeState) { switch (attribute) { case ATTRIBUTE_LAST_ALARM: - value = dt.format(null).replace('T', ' ').replace('-', '/'); + value = dateTimeState.format(null).replace('T', ' ').replace('-', '/'); break; default: - value = getTimestamp(dt); - value = dt.format(null).replace('T', ' ').replace('-', '/'); + value = getTimestamp(dateTimeState); + value = dateTimeState.format(null).replace('T', ' ').replace('-', '/'); } } else { value = state.toString(); diff --git a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/provider/ShellyChannelDefinitions.java b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/provider/ShellyChannelDefinitions.java index e71b6e54d..5dbaf024f 100644 --- a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/provider/ShellyChannelDefinitions.java +++ b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/provider/ShellyChannelDefinitions.java @@ -585,7 +585,7 @@ public class ShellyChannelDefinitions { ? new ChannelTypeUID(channelDef.typeId) : new ChannelTypeUID(BINDING_ID, channelDef.typeId); ChannelBuilder builder; - if (channelDef.typeId.equalsIgnoreCase("system:button")) { + if ("system:button".equalsIgnoreCase(channelDef.typeId)) { builder = ChannelBuilder.create(channelUID, null).withKind(ChannelKind.TRIGGER); } else { builder = ChannelBuilder.create(channelUID, channelDef.itemType); diff --git a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/util/ShellyUtils.java b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/util/ShellyUtils.java index 4cc05cd21..6d51d4b29 100644 --- a/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/util/ShellyUtils.java +++ b/bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/util/ShellyUtils.java @@ -236,11 +236,11 @@ public class ShellyUtils { } public static Double getNumber(Command command) throws IllegalArgumentException { - if (command instanceof DecimalType) { - return ((DecimalType) command).doubleValue(); + if (command instanceof DecimalType decimalCommand) { + return decimalCommand.doubleValue(); } - if (command instanceof QuantityType) { - return ((QuantityType) command).doubleValue(); + if (command instanceof QuantityType quantityCommand) { + return quantityCommand.doubleValue(); } throw new IllegalArgumentException("Unable to convert number"); } diff --git a/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/internal/RdsBindingConstants.java b/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/internal/RdsBindingConstants.java index ce07389b6..36b0e5721 100644 --- a/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/internal/RdsBindingConstants.java +++ b/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/internal/RdsBindingConstants.java @@ -45,8 +45,14 @@ public class RdsBindingConstants { private static final String API = "https://api.climatixic.com/"; - private static final String ARG_RDS = "?filterId=[" + "{\"asn\":\"RDS110\"}," + "{\"asn\":\"RDS120\"}," - + "{\"asn\":\"RDS110.R\"}," + "{\"asn\":\"RDS120.B\"}" + "]"; + private static final String ARG_RDS = """ + ?filterId=[\ + {"asn":"RDS110"},\ + {"asn":"RDS120"},\ + {"asn":"RDS110.R"},\ + {"asn":"RDS120.B"}\ + ]\ + """; private static final String ARG_PARENT = "?parentId=[\"%s\"]&take=100"; private static final String ARG_POINT = "?filterId=[%s]"; diff --git a/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/internal/RdsDiscoveryService.java b/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/internal/RdsDiscoveryService.java index d988725d7..89ed78b30 100644 --- a/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/internal/RdsDiscoveryService.java +++ b/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/internal/RdsDiscoveryService.java @@ -201,7 +201,6 @@ public class RdsDiscoveryService extends AbstractDiscoveryService { bridgeUID, label, plantId); thingDiscovered(disco); - ; } catch (RdsCloudException e) { logger.warn(LOG_SYSTEM_EXCEPTION, "publishPlant()", e.getClass().getName(), e.getMessage()); } catch (JsonParseException | IOException e) { diff --git a/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/internal/RdsHandler.java b/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/internal/RdsHandler.java index 987db143a..a32662331 100644 --- a/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/internal/RdsHandler.java +++ b/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/internal/RdsHandler.java @@ -34,7 +34,6 @@ import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingStatusDetail; import org.openhab.core.thing.ThingStatusInfo; import org.openhab.core.thing.binding.BaseThingHandler; -import org.openhab.core.thing.binding.BridgeHandler; import org.openhab.core.types.Command; import org.openhab.core.types.RefreshType; import org.openhab.core.types.State; @@ -314,9 +313,9 @@ public class RdsHandler extends BaseThingHandler { switch (channel.id) { case CHA_TARGET_TEMP: { Command doCommand = command; - if (command instanceof QuantityType) { + if (command instanceof QuantityType quantityCommand) { Unit unit = points.getPointByClass(channel.clazz).getUnit(); - QuantityType temp = ((QuantityType) command).toUnit(unit); + QuantityType temp = quantityCommand.toUnit(unit); if (temp != null) { doCommand = temp; } @@ -381,11 +380,9 @@ public class RdsHandler extends BaseThingHandler { private RdsCloudHandler getCloudHandler() throws RdsCloudException { @Nullable Bridge b; - @Nullable - BridgeHandler h; - if ((b = getBridge()) != null && (h = b.getHandler()) != null && h instanceof RdsCloudHandler) { - return (RdsCloudHandler) h; + if ((b = getBridge()) != null && (b.getHandler() instanceof RdsCloudHandler cloudHandler)) { + return cloudHandler; } throw new RdsCloudException("no cloud handler found"); } diff --git a/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/internal/RdsHandlerFactory.java b/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/internal/RdsHandlerFactory.java index 5e5bab082..4c2f9981a 100644 --- a/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/internal/RdsHandlerFactory.java +++ b/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/internal/RdsHandlerFactory.java @@ -14,10 +14,7 @@ package org.openhab.binding.siemensrds.internal; import static org.openhab.binding.siemensrds.internal.RdsBindingConstants.*; -import java.util.Arrays; -import java.util.Collections; import java.util.HashMap; -import java.util.HashSet; import java.util.Hashtable; import java.util.Map; import java.util.Set; @@ -44,8 +41,7 @@ import org.osgi.service.component.annotations.Component; @Component(configurationPid = "binding.siemensrds", service = ThingHandlerFactory.class) public class RdsHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections - .unmodifiableSet(new HashSet<>(Arrays.asList(THING_TYPE_CLOUD, THING_TYPE_RDS))); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_CLOUD, THING_TYPE_RDS); private final Map> discos = new HashMap<>(); @@ -58,8 +54,8 @@ public class RdsHandlerFactory extends BaseThingHandlerFactory { protected @Nullable ThingHandler createHandler(Thing thing) { ThingTypeUID thingTypeUID = thing.getThingTypeUID(); - if ((thingTypeUID.equals(THING_TYPE_CLOUD)) && (thing instanceof Bridge)) { - RdsCloudHandler handler = new RdsCloudHandler((Bridge) thing); + if ((thingTypeUID.equals(THING_TYPE_CLOUD)) && (thing instanceof Bridge bridge)) { + RdsCloudHandler handler = new RdsCloudHandler(bridge); createDiscoveryService(handler); return handler; } @@ -73,8 +69,8 @@ public class RdsHandlerFactory extends BaseThingHandlerFactory { @Override protected synchronized void removeHandler(ThingHandler handler) { - if (handler instanceof RdsCloudHandler) { - destroyDiscoveryService((RdsCloudHandler) handler); + if (handler instanceof RdsCloudHandler cloudHandler) { + destroyDiscoveryService(cloudHandler); } } diff --git a/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/points/NestedNumberPoint.java b/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/points/NestedNumberPoint.java index 186a2f29b..970cc651e 100644 --- a/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/points/NestedNumberPoint.java +++ b/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/points/NestedNumberPoint.java @@ -72,8 +72,8 @@ public class NestedNumberPoint extends BasePoint { @Override public void refreshValueFrom(BasePoint from) { super.refreshValueFrom(from); - if (from instanceof NestedNumberPoint) { - NestedNumberValue fromInner = ((NestedNumberPoint) from).inner; + if (from instanceof NestedNumberPoint point) { + NestedNumberValue fromInner = point.inner; NestedNumberValue thisInner = this.inner; if (thisInner != null && fromInner != null) { thisInner.value = fromInner.value; diff --git a/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/points/NumberPoint.java b/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/points/NumberPoint.java index ee40b24d8..17a2f6ef7 100644 --- a/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/points/NumberPoint.java +++ b/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/points/NumberPoint.java @@ -46,8 +46,8 @@ public class NumberPoint extends BasePoint { @Override public void refreshValueFrom(BasePoint from) { super.refreshValueFrom(from); - if (from instanceof NumberPoint) { - this.value = ((NumberPoint) from).value; + if (from instanceof NumberPoint point) { + this.value = point.value; } } } diff --git a/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/points/PointDeserializer.java b/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/points/PointDeserializer.java index e2aa34299..7ebb793d1 100644 --- a/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/points/PointDeserializer.java +++ b/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/points/PointDeserializer.java @@ -33,7 +33,7 @@ import com.google.gson.JsonSyntaxException; @NonNullByDefault public class PointDeserializer implements JsonDeserializer { - private static enum PointType { + private enum PointType { UNDEFINED, STRING, NESTED_NUMBER, diff --git a/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/points/StringPoint.java b/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/points/StringPoint.java index b628d3d37..d0d96f4f8 100644 --- a/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/points/StringPoint.java +++ b/bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/points/StringPoint.java @@ -52,8 +52,8 @@ public class StringPoint extends BasePoint { @Override public void refreshValueFrom(BasePoint from) { super.refreshValueFrom(from); - if (from instanceof StringPoint) { - this.value = ((StringPoint) from).value; + if (from instanceof StringPoint stringPoint) { + this.value = stringPoint.value; } } } diff --git a/bundles/org.openhab.binding.silvercrestwifisocket/src/main/java/org/openhab/binding/silvercrestwifisocket/internal/SilvercrestWifiSocketBindingConstants.java b/bundles/org.openhab.binding.silvercrestwifisocket/src/main/java/org/openhab/binding/silvercrestwifisocket/internal/SilvercrestWifiSocketBindingConstants.java index a7066254b..ad918d8fe 100644 --- a/bundles/org.openhab.binding.silvercrestwifisocket/src/main/java/org/openhab/binding/silvercrestwifisocket/internal/SilvercrestWifiSocketBindingConstants.java +++ b/bundles/org.openhab.binding.silvercrestwifisocket/src/main/java/org/openhab/binding/silvercrestwifisocket/internal/SilvercrestWifiSocketBindingConstants.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.silvercrestwifisocket.internal; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -47,7 +46,7 @@ public class SilvercrestWifiSocketBindingConstants { /** * The supported thing types. */ - public static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_WIFI_SOCKET); + public static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_WIFI_SOCKET); // -------------- Configuration arguments ---------------- /** diff --git a/bundles/org.openhab.binding.silvercrestwifisocket/src/main/java/org/openhab/binding/silvercrestwifisocket/internal/SilvercrestWifiSocketHandlerFactory.java b/bundles/org.openhab.binding.silvercrestwifisocket/src/main/java/org/openhab/binding/silvercrestwifisocket/internal/SilvercrestWifiSocketHandlerFactory.java index 33d1de23c..187496280 100644 --- a/bundles/org.openhab.binding.silvercrestwifisocket/src/main/java/org/openhab/binding/silvercrestwifisocket/internal/SilvercrestWifiSocketHandlerFactory.java +++ b/bundles/org.openhab.binding.silvercrestwifisocket/src/main/java/org/openhab/binding/silvercrestwifisocket/internal/SilvercrestWifiSocketHandlerFactory.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.silvercrestwifisocket.internal; -import java.util.Collections; import java.util.Set; import org.openhab.binding.silvercrestwifisocket.internal.exceptions.MacAddressNotValidException; @@ -37,8 +36,8 @@ import org.slf4j.LoggerFactory; @Component(service = ThingHandlerFactory.class, configurationPid = "binding.silvercrestwifisocket") public class SilvercrestWifiSocketHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections - .singleton(SilvercrestWifiSocketBindingConstants.THING_TYPE_WIFI_SOCKET); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set + .of(SilvercrestWifiSocketBindingConstants.THING_TYPE_WIFI_SOCKET); private final Logger logger = LoggerFactory.getLogger(SilvercrestWifiSocketHandlerFactory.class); diff --git a/bundles/org.openhab.binding.silvercrestwifisocket/src/main/java/org/openhab/binding/silvercrestwifisocket/internal/handler/SilvercrestWifiSocketHandler.java b/bundles/org.openhab.binding.silvercrestwifisocket/src/main/java/org/openhab/binding/silvercrestwifisocket/internal/handler/SilvercrestWifiSocketHandler.java index a4e212631..947164cd4 100644 --- a/bundles/org.openhab.binding.silvercrestwifisocket/src/main/java/org/openhab/binding/silvercrestwifisocket/internal/handler/SilvercrestWifiSocketHandler.java +++ b/bundles/org.openhab.binding.silvercrestwifisocket/src/main/java/org/openhab/binding/silvercrestwifisocket/internal/handler/SilvercrestWifiSocketHandler.java @@ -180,11 +180,11 @@ public class SilvercrestWifiSocketHandler extends BaseThingHandler { // if the host of the packet is different from the host address set in handler, update the host // address. if (!receivedMessage.getHostAddress().equals(this.hostAddress)) { - logger.debug( - "The host of the packet is different from the host address set in handler. " - + "Will update the host address. handler of mac: {}. " - + "Old host address: '{}' -> new host address: '{}'", - this.macAddress, this.hostAddress, receivedMessage.getHostAddress()); + logger.debug(""" + The host of the packet is different from the host address set in handler. \ + Will update the host address. handler of mac: {}. \ + Old host address: '{}' -> new host address: '{}'\ + """, this.macAddress, this.hostAddress, receivedMessage.getHostAddress()); this.hostAddress = receivedMessage.getHostAddress(); this.saveConfigurationsUsingCurrentStates(); @@ -252,7 +252,7 @@ public class SilvercrestWifiSocketHandler extends BaseThingHandler { if (ValidationUtils.isMacNotValid(macAddress)) { throw new MacAddressNotValidException("Mac address is not valid", macAddress); } - this.macAddress = macAddress.replaceAll(":", "").toUpperCase(); + this.macAddress = macAddress.replace(":", "").toUpperCase(); } if (this.macAddress == null) { throw new MacAddressNotValidException("Mac address is not valid", this.macAddress); diff --git a/bundles/org.openhab.binding.sinope/src/main/java/org/openhab/binding/sinope/handler/SinopeGatewayHandler.java b/bundles/org.openhab.binding.sinope/src/main/java/org/openhab/binding/sinope/handler/SinopeGatewayHandler.java index 2a7f638e7..190c93a3f 100644 --- a/bundles/org.openhab.binding.sinope/src/main/java/org/openhab/binding/sinope/handler/SinopeGatewayHandler.java +++ b/bundles/org.openhab.binding.sinope/src/main/java/org/openhab/binding/sinope/handler/SinopeGatewayHandler.java @@ -173,9 +173,7 @@ public class SinopeGatewayHandler extends ConfigStatusBridgeHandler { InputStream inputStream = clientSocket.getInputStream(); outToServer.write(command.getPayload()); outToServer.flush(); - SinopeAnswer answ = command.getReplyAnswer(inputStream); - - return answ; + return command.getReplyAnswer(inputStream); } synchronized SinopeAnswer execute(SinopeDataRequest command) throws UnknownHostException, IOException { diff --git a/bundles/org.openhab.binding.sinope/src/main/java/org/openhab/binding/sinope/handler/SinopeThermostatHandler.java b/bundles/org.openhab.binding.sinope/src/main/java/org/openhab/binding/sinope/handler/SinopeThermostatHandler.java index 752887481..e87d12103 100644 --- a/bundles/org.openhab.binding.sinope/src/main/java/org/openhab/binding/sinope/handler/SinopeThermostatHandler.java +++ b/bundles/org.openhab.binding.sinope/src/main/java/org/openhab/binding/sinope/handler/SinopeThermostatHandler.java @@ -67,12 +67,12 @@ public class SinopeThermostatHandler extends BaseThingHandler { if (getSinopeGatewayHandler() != null) { try { if (SinopeBindingConstants.CHANNEL_SETTEMP.equals(channelUID.getId()) - && command instanceof QuantityType) { - setSetpointTemp(((QuantityType) command).floatValue()); + && command instanceof QuantityType quantityCommand) { + setSetpointTemp(quantityCommand.floatValue()); } if (SinopeBindingConstants.CHANNEL_SETMODE.equals(channelUID.getId()) - && command instanceof DecimalType) { - setSetpointMode(((DecimalType) command).intValue()); + && command instanceof DecimalType decimalCommand) { + setSetpointMode(decimalCommand.intValue()); } } catch (IOException e) { logger.debug("Cannot handle command for channel {} because of {}", channelUID.getId(), diff --git a/bundles/org.openhab.binding.sinope/src/main/java/org/openhab/binding/sinope/internal/core/base/SinopeDataRequest.java b/bundles/org.openhab.binding.sinope/src/main/java/org/openhab/binding/sinope/internal/core/base/SinopeDataRequest.java index 032e99f35..c16feef8c 100644 --- a/bundles/org.openhab.binding.sinope/src/main/java/org/openhab/binding/sinope/internal/core/base/SinopeDataRequest.java +++ b/bundles/org.openhab.binding.sinope/src/main/java/org/openhab/binding/sinope/internal/core/base/SinopeDataRequest.java @@ -162,7 +162,7 @@ public abstract class SinopeDataRequest extends SinopeRequest { @Override protected byte[] getFrameData() { int appDataLen = getAppDataSize(); - byte b[] = new byte[seq.length + 1 + 1 + 1 + res3.length + res4.length + dstDeviceId.length + 1 + appDataLen]; + byte[] b = new byte[seq.length + 1 + 1 + 1 + res3.length + res4.length + dstDeviceId.length + 1 + appDataLen]; ByteBuffer bb = ByteBuffer.wrap(b); diff --git a/bundles/org.openhab.binding.sinope/src/main/java/org/openhab/binding/sinope/internal/util/CRC8.java b/bundles/org.openhab.binding.sinope/src/main/java/org/openhab/binding/sinope/internal/util/CRC8.java index 312868edf..07023a368 100644 --- a/bundles/org.openhab.binding.sinope/src/main/java/org/openhab/binding/sinope/internal/util/CRC8.java +++ b/bundles/org.openhab.binding.sinope/src/main/java/org/openhab/binding/sinope/internal/util/CRC8.java @@ -25,7 +25,7 @@ public class CRC8 implements Checksum { private final int init; /** The Constant crcTable. */ - private static final int crcTable[] = { 0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15, 0x38, 0x3f, 0x36, 0x31, + private static final int[] crcTable = { 0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15, 0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d, 0x70, 0x77, 0x7e, 0x79, 0x6c, 0x6b, 0x62, 0x65, 0x48, 0x4f, 0x46, 0x41, 0x54, 0x53, 0x5a, 0x5d, 0xe0, 0xe7, 0xee, 0xe9, 0xfc, 0xfb, 0xf2, 0xf5, 0xd8, 0xdf, 0xd6, 0xd1, 0xc4, 0xc3, 0xca, 0xcd, 0x90, 0x97, 0x9e, 0x99, 0x8c, 0x8b, 0x82, 0x85, 0xa8, 0xaf, 0xa6, 0xa1, 0xb4, 0xb3, 0xba, 0xbd, 0xc7, 0xc0, @@ -67,6 +67,7 @@ public class CRC8 implements Checksum { * * @param buffer the buffer */ + @Override public void update(byte[] buffer) { update(buffer, 0, buffer.length); } diff --git a/bundles/org.openhab.binding.sleepiq/src/main/java/org/openhab/binding/sleepiq/internal/SleepIQHandlerFactory.java b/bundles/org.openhab.binding.sleepiq/src/main/java/org/openhab/binding/sleepiq/internal/SleepIQHandlerFactory.java index 7bda6c000..d9d58fa5e 100644 --- a/bundles/org.openhab.binding.sleepiq/src/main/java/org/openhab/binding/sleepiq/internal/SleepIQHandlerFactory.java +++ b/bundles/org.openhab.binding.sleepiq/src/main/java/org/openhab/binding/sleepiq/internal/SleepIQHandlerFactory.java @@ -88,8 +88,8 @@ public class SleepIQHandlerFactory extends BaseThingHandlerFactory { @Override protected void removeHandler(final ThingHandler thingHandler) { logger.debug("Removing SleepIQ thing handler"); - if (thingHandler instanceof SleepIQCloudHandler) { - unregisterBedDiscoveryService((SleepIQCloudHandler) thingHandler); + if (thingHandler instanceof SleepIQCloudHandler sleepIQCloudHandler) { + unregisterBedDiscoveryService(sleepIQCloudHandler); } } diff --git a/bundles/org.openhab.binding.sleepiq/src/main/java/org/openhab/binding/sleepiq/internal/handler/SleepIQCloudHandler.java b/bundles/org.openhab.binding.sleepiq/src/main/java/org/openhab/binding/sleepiq/internal/handler/SleepIQCloudHandler.java index 880a70811..73b4e9fef 100644 --- a/bundles/org.openhab.binding.sleepiq/src/main/java/org/openhab/binding/sleepiq/internal/handler/SleepIQCloudHandler.java +++ b/bundles/org.openhab.binding.sleepiq/src/main/java/org/openhab/binding/sleepiq/internal/handler/SleepIQCloudHandler.java @@ -17,7 +17,6 @@ import static org.openhab.binding.sleepiq.internal.config.SleepIQCloudConfigurat import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; @@ -71,7 +70,7 @@ import org.slf4j.LoggerFactory; */ @NonNullByDefault public class SleepIQCloudHandler extends ConfigStatusBridgeHandler { - public static final Set SUPPORTED_THING_TYPE_UIDS = Collections.singleton(THING_TYPE_CLOUD); + public static final Set SUPPORTED_THING_TYPE_UIDS = Set.of(THING_TYPE_CLOUD); private static final int SLEEPER_POLLING_INTERVAL_HOURS = 12; diff --git a/bundles/org.openhab.binding.sleepiq/src/main/java/org/openhab/binding/sleepiq/internal/handler/SleepIQDualBedHandler.java b/bundles/org.openhab.binding.sleepiq/src/main/java/org/openhab/binding/sleepiq/internal/handler/SleepIQDualBedHandler.java index 189372fe1..b3e23e423 100644 --- a/bundles/org.openhab.binding.sleepiq/src/main/java/org/openhab/binding/sleepiq/internal/handler/SleepIQDualBedHandler.java +++ b/bundles/org.openhab.binding.sleepiq/src/main/java/org/openhab/binding/sleepiq/internal/handler/SleepIQDualBedHandler.java @@ -14,7 +14,6 @@ package org.openhab.binding.sleepiq.internal.handler; import static org.openhab.binding.sleepiq.internal.SleepIQBindingConstants.*; -import java.util.Collections; import java.util.Set; import java.util.concurrent.TimeUnit; @@ -61,7 +60,7 @@ import org.slf4j.LoggerFactory; */ @NonNullByDefault public class SleepIQDualBedHandler extends BaseThingHandler implements BedStatusListener { - public static final Set SUPPORTED_THING_TYPE_UIDS = Collections.singleton(THING_TYPE_DUAL_BED); + public static final Set SUPPORTED_THING_TYPE_UIDS = Set.of(THING_TYPE_DUAL_BED); private static final long GET_SLEEP_DATA_DELAY_MINUTES = 5; @@ -146,12 +145,12 @@ public class SleepIQDualBedHandler extends BaseThingHandler implements BedStatus switch (channelId) { case CHANNEL_LEFT_SLEEP_NUMBER: case CHANNEL_RIGHT_SLEEP_NUMBER: - if (command instanceof DecimalType) { + if (command instanceof DecimalType decimalCommand) { Side side = Side.convertFromGroup(groupId); logger.debug("BedHandler: Set sleepnumber to {} for bedId={}, side={}", command, bedId, side); SleepIQCloudHandler cloudHandler = getCloudHandler(); if (cloudHandler != null) { - cloudHandler.setSleepNumber(bedId, side, ((DecimalType) command).intValue()); + cloudHandler.setSleepNumber(bedId, side, decimalCommand.intValue()); } } break; @@ -169,10 +168,10 @@ public class SleepIQDualBedHandler extends BaseThingHandler implements BedStatus case CHANNEL_LEFT_FOUNDATION_PRESET: case CHANNEL_RIGHT_FOUNDATION_PRESET: logger.debug("Received command {} on channel {} to set preset", command, channelUID); - if (isFoundationInstalled() && command instanceof DecimalType) { + if (isFoundationInstalled() && command instanceof DecimalType decimalCommand) { try { Side side = Side.convertFromGroup(groupId); - FoundationPreset preset = FoundationPreset.forValue(((DecimalType) command).intValue()); + FoundationPreset preset = FoundationPreset.forValue(decimalCommand.intValue()); logger.debug("BedHandler: Set foundation preset to {} for bedId={}, side={}", command, bedId, side); SleepIQCloudHandler cloudHandler = getCloudHandler(); diff --git a/bundles/org.openhab.binding.smaenergymeter/src/main/java/org/openhab/binding/smaenergymeter/internal/SMAEnergyMeterBindingConstants.java b/bundles/org.openhab.binding.smaenergymeter/src/main/java/org/openhab/binding/smaenergymeter/internal/SMAEnergyMeterBindingConstants.java index 178f8583b..bccc1078d 100644 --- a/bundles/org.openhab.binding.smaenergymeter/src/main/java/org/openhab/binding/smaenergymeter/internal/SMAEnergyMeterBindingConstants.java +++ b/bundles/org.openhab.binding.smaenergymeter/src/main/java/org/openhab/binding/smaenergymeter/internal/SMAEnergyMeterBindingConstants.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.smaenergymeter.internal; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -32,7 +31,7 @@ public class SMAEnergyMeterBindingConstants { // List of all Thing Type UIDs public static final ThingTypeUID THING_TYPE_ENERGY_METER = new ThingTypeUID(BINDING_ID, "energymeter"); - public static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_ENERGY_METER); + public static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_ENERGY_METER); // List of all Channel IDs public static final String CHANNEL_POWER_IN = "powerIn"; diff --git a/bundles/org.openhab.binding.smaenergymeter/src/main/java/org/openhab/binding/smaenergymeter/internal/handler/EnergyMeter.java b/bundles/org.openhab.binding.smaenergymeter/src/main/java/org/openhab/binding/smaenergymeter/internal/handler/EnergyMeter.java index ab2da3a75..92af827bf 100644 --- a/bundles/org.openhab.binding.smaenergymeter/src/main/java/org/openhab/binding/smaenergymeter/internal/handler/EnergyMeter.java +++ b/bundles/org.openhab.binding.smaenergymeter/src/main/java/org/openhab/binding/smaenergymeter/internal/handler/EnergyMeter.java @@ -92,7 +92,7 @@ public class EnergyMeter { socket.receive(msgPacket); String sma = new String(Arrays.copyOfRange(bytes, 0x00, 0x03)); - if (!sma.equals("SMA")) { + if (!"SMA".equals(sma)) { throw new IOException("Not a SMA telegram." + sma); } diff --git a/bundles/org.openhab.binding.smartmeter/src/3rdparty/java/org/openmuc/jrxtx/SerialPort.java b/bundles/org.openhab.binding.smartmeter/src/3rdparty/java/org/openmuc/jrxtx/SerialPort.java index 7732ab777..f21df546d 100644 --- a/bundles/org.openhab.binding.smartmeter/src/3rdparty/java/org/openmuc/jrxtx/SerialPort.java +++ b/bundles/org.openhab.binding.smartmeter/src/3rdparty/java/org/openmuc/jrxtx/SerialPort.java @@ -41,6 +41,7 @@ public interface SerialPort extends Closeable { * @throws IOException * if an I/O error occurred. */ + @Override void close() throws IOException; /** diff --git a/bundles/org.openhab.binding.smartmeter/src/main/java/org/openhab/binding/smartmeter/SmartMeterBindingConstants.java b/bundles/org.openhab.binding.smartmeter/src/main/java/org/openhab/binding/smartmeter/SmartMeterBindingConstants.java index e181e555c..bfaeac087 100644 --- a/bundles/org.openhab.binding.smartmeter/src/main/java/org/openhab/binding/smartmeter/SmartMeterBindingConstants.java +++ b/bundles/org.openhab.binding.smartmeter/src/main/java/org/openhab/binding/smartmeter/SmartMeterBindingConstants.java @@ -44,7 +44,7 @@ public class SmartMeterBindingConstants { public static final String CHANNEL_TYPE_METERREADER_OBIS = "channel-type:" + BINDING_ID + ":obis"; public static String getObisChannelIdPattern(String obis) { - return obis.replaceAll("\\.", "-").replaceAll(":|\\*", "_"); + return obis.replace(".", "-").replaceAll(":|\\*", "_"); } public static String getObisChannelId(String obis) { diff --git a/bundles/org.openhab.binding.smartmeter/src/main/java/org/openhab/binding/smartmeter/internal/SmartMeterHandler.java b/bundles/org.openhab.binding.smartmeter/src/main/java/org/openhab/binding/smartmeter/internal/SmartMeterHandler.java index 2f9a5dec1..559b460ec 100644 --- a/bundles/org.openhab.binding.smartmeter/src/main/java/org/openhab/binding/smartmeter/internal/SmartMeterHandler.java +++ b/bundles/org.openhab.binding.smartmeter/src/main/java/org/openhab/binding/smartmeter/internal/SmartMeterHandler.java @@ -269,12 +269,12 @@ public class SmartMeterHandler extends BaseThingHandler { valueString += " " + value.getUnit(); } State state = TypeParser.parseState(List.of(QuantityType.class, StringType.class), valueString); - if (channel != null && state instanceof QuantityType) { + if (channel != null && state instanceof QuantityType quantityCommand) { state = applyConformity(channel, (QuantityType) state); Number conversionRatio = (Number) channel.getConfiguration() .get(SmartMeterBindingConstants.CONFIGURATION_CONVERSION); if (conversionRatio != null) { - state = ((QuantityType) state).divide(BigDecimal.valueOf(conversionRatio.doubleValue())); + state = quantityCommand.divide(BigDecimal.valueOf(conversionRatio.doubleValue())); } } return state; diff --git a/bundles/org.openhab.binding.smartmeter/src/main/java/org/openhab/binding/smartmeter/internal/SmartMeterHandlerFactory.java b/bundles/org.openhab.binding.smartmeter/src/main/java/org/openhab/binding/smartmeter/internal/SmartMeterHandlerFactory.java index d5873b833..fe7173d51 100644 --- a/bundles/org.openhab.binding.smartmeter/src/main/java/org/openhab/binding/smartmeter/internal/SmartMeterHandlerFactory.java +++ b/bundles/org.openhab.binding.smartmeter/src/main/java/org/openhab/binding/smartmeter/internal/SmartMeterHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.smartmeter.internal; import static org.openhab.binding.smartmeter.SmartMeterBindingConstants.THING_TYPE_SMLREADER; -import java.util.Collections; import java.util.Set; import java.util.function.Supplier; @@ -40,7 +39,7 @@ import org.osgi.service.component.annotations.Reference; @NonNullByDefault public class SmartMeterHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_SMLREADER); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_SMLREADER); private @NonNullByDefault({}) SmartMeterChannelTypeProvider channelProvider; private @NonNullByDefault({}) Supplier serialPortManagerSupplier = () -> null; diff --git a/bundles/org.openhab.binding.smartmeter/src/main/java/org/openhab/binding/smartmeter/internal/conformity/negate/NegateBitParser.java b/bundles/org.openhab.binding.smartmeter/src/main/java/org/openhab/binding/smartmeter/internal/conformity/negate/NegateBitParser.java index a3f62b092..f6d6a700f 100644 --- a/bundles/org.openhab.binding.smartmeter/src/main/java/org/openhab/binding/smartmeter/internal/conformity/negate/NegateBitParser.java +++ b/bundles/org.openhab.binding.smartmeter/src/main/java/org/openhab/binding/smartmeter/internal/conformity/negate/NegateBitParser.java @@ -44,7 +44,7 @@ public class NegateBitParser { String[] split = substring.split(":"); int negatePosition = Integer.parseInt(split[0]); boolean negateBit = Integer.parseInt(split[1]) == 0 ? false : true; - boolean status = split.length > 2 ? split[2].equalsIgnoreCase("status") : false; + boolean status = split.length > 2 ? "status".equalsIgnoreCase(split[2]) : false; return new NegateBitModel((byte) negatePosition, negateBit, obis, status); } } catch (Exception e) { diff --git a/bundles/org.openhab.binding.smartmeter/src/main/java/org/openhab/binding/smartmeter/internal/sml/SmlValueExtractor.java b/bundles/org.openhab.binding.smartmeter/src/main/java/org/openhab/binding/smartmeter/internal/sml/SmlValueExtractor.java index 8b555637e..eea8b450d 100644 --- a/bundles/org.openhab.binding.smartmeter/src/main/java/org/openhab/binding/smartmeter/internal/sml/SmlValueExtractor.java +++ b/bundles/org.openhab.binding.smartmeter/src/main/java/org/openhab/binding/smartmeter/internal/sml/SmlValueExtractor.java @@ -151,10 +151,8 @@ public final class SmlValueExtractor { * @return the hex encoded OBIS code as readable string. */ protected static String getObisAsString(byte[] octetBytes) { - String formattedObis = String.format(SmartMeterBindingConstants.OBIS_FORMAT_MINIMAL, byteToInt(octetBytes[0]), + return String.format(SmartMeterBindingConstants.OBIS_FORMAT_MINIMAL, byteToInt(octetBytes[0]), byteToInt(octetBytes[1]), byteToInt(octetBytes[2]), byteToInt(octetBytes[3]), byteToInt(octetBytes[4])); - - return formattedObis; } public String getObisCode() { diff --git a/bundles/org.openhab.binding.smartmeter/src/test/java/org/openhab/binding/smartmeter/TestNegateBit.java b/bundles/org.openhab.binding.smartmeter/src/test/java/org/openhab/binding/smartmeter/TestNegateBit.java index 4700d650a..b72daed5c 100644 --- a/bundles/org.openhab.binding.smartmeter/src/test/java/org/openhab/binding/smartmeter/TestNegateBit.java +++ b/bundles/org.openhab.binding.smartmeter/src/test/java/org/openhab/binding/smartmeter/TestNegateBit.java @@ -40,9 +40,8 @@ public class TestNegateBit { public void testNegateHandlingTrue() { String negateProperty = "1-0_1-8-0:5:1"; - boolean negateState = NegateHandler.shouldNegateState(negateProperty, obis -> { - return new MeterValue<>(obis, "65954", null); - }); + boolean negateState = NegateHandler.shouldNegateState(negateProperty, + obis -> new MeterValue<>(obis, "65954", null)); assertTrue(negateState); } @@ -51,9 +50,8 @@ public class TestNegateBit { public void testNegateHandlingFalse() { String negateProperty = "1-0_1-8-0:5:1"; - boolean negateState = NegateHandler.shouldNegateState(negateProperty, obis -> { - return new MeterValue<>(obis, "0", null, "65922"); - }); + boolean negateState = NegateHandler.shouldNegateState(negateProperty, + obis -> new MeterValue<>(obis, "0", null, "65922")); assertFalse(negateState); } diff --git a/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/SmartthingsHandlerFactory.java b/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/SmartthingsHandlerFactory.java index 6091b11d3..02c0fbefd 100644 --- a/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/SmartthingsHandlerFactory.java +++ b/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/SmartthingsHandlerFactory.java @@ -123,6 +123,7 @@ public class SmartthingsHandlerFactory extends BaseThingHandlerFactory * @throws TimeoutException * @throws ExecutionException */ + @Override public void sendDeviceCommand(String path, int timeout, String data) throws InterruptedException, TimeoutException, ExecutionException { ContentResponse response = httpClient diff --git a/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/converter/SmartthingsColor100Converter.java b/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/converter/SmartthingsColor100Converter.java index 78368ae2c..115ab6b53 100644 --- a/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/converter/SmartthingsColor100Converter.java +++ b/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/converter/SmartthingsColor100Converter.java @@ -53,11 +53,11 @@ public class SmartthingsColor100Converter extends SmartthingsConverter { // The command should be of HSBType. The hue component needs to be divided by 3.6 to convert 0-360 degrees to // 0-100 percent // The easiest way to do this is to create a new HSBType with the hue component changed. - if (command instanceof HSBType) { - HSBType hsb = (HSBType) command; - double hue = Math.round((hsb.getHue().doubleValue() / 3.60)); // add .5 to round + if (command instanceof HSBType hsbCommand) { + double hue = Math.round((hsbCommand.getHue().doubleValue() / 3.60)); // add .5 to round long hueInt = (long) hue; - HSBType hsb100 = new HSBType(new DecimalType(hueInt), hsb.getSaturation(), hsb.getBrightness()); + HSBType hsb100 = new HSBType(new DecimalType(hueInt), hsbCommand.getSaturation(), + hsbCommand.getBrightness()); // now use the default converter to convert to a JSON string jsonMsg = defaultConvertToSmartthings(channelUid, hsb100); } else { @@ -95,7 +95,7 @@ public class SmartthingsColor100Converter extends SmartthingsConverter { } // Get the RGB colors - int rgb[] = new int[3]; + int[] rgb = new int[3]; for (int i = 0, pos = 1; i < 3; i++, pos += 2) { String c = value.substring(pos, pos + 2); rgb[i] = Integer.parseInt(c, 16); diff --git a/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/converter/SmartthingsColorConverter.java b/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/converter/SmartthingsColorConverter.java index 080c12d37..d7273293a 100644 --- a/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/converter/SmartthingsColorConverter.java +++ b/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/converter/SmartthingsColorConverter.java @@ -47,8 +47,7 @@ public class SmartthingsColorConverter extends SmartthingsConverter { @Override public String convertToSmartthings(ChannelUID channelUid, Command command) { - String jsonMsg = defaultConvertToSmartthings(channelUid, command); - return jsonMsg; + return defaultConvertToSmartthings(channelUid, command); } /* @@ -78,14 +77,13 @@ public class SmartthingsColorConverter extends SmartthingsConverter { } // Get the RGB colors - int rgb[] = new int[3]; + int[] rgb = new int[3]; for (int i = 0, pos = 1; i < 3; i++, pos += 2) { String c = value.substring(pos, pos + 2); rgb[i] = Integer.parseInt(c, 16); } // Convert to state - State state = HSBType.fromRGB(rgb[0], rgb[1], rgb[2]); - return state; + return HSBType.fromRGB(rgb[0], rgb[1], rgb[2]); } } diff --git a/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/converter/SmartthingsConverter.java b/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/converter/SmartthingsConverter.java index e3d307c55..d6d363d01 100644 --- a/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/converter/SmartthingsConverter.java +++ b/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/converter/SmartthingsConverter.java @@ -76,13 +76,11 @@ public abstract class SmartthingsConverter { protected String defaultConvertToSmartthings(ChannelUID channelUid, Command command) { String value; - if (command instanceof DateTimeType) { - DateTimeType dt = (DateTimeType) command; - value = dt.format("%m/%d/%Y %H.%M.%S"); - } else if (command instanceof HSBType) { - HSBType hsb = (HSBType) command; - value = String.format("[%d, %d, %d ]", hsb.getHue().intValue(), hsb.getSaturation().intValue(), - hsb.getBrightness().intValue()); + if (command instanceof DateTimeType dateTimeCommand) { + value = dateTimeCommand.format("%m/%d/%Y %H.%M.%S"); + } else if (command instanceof HSBType hsbCommand) { + value = String.format("[%d, %d, %d ]", hsbCommand.getHue().intValue(), + hsbCommand.getSaturation().intValue(), hsbCommand.getBrightness().intValue()); } else if (command instanceof DecimalType) { value = command.toString(); } else if (command instanceof IncreaseDecreaseType) { // Need to surround with double quotes @@ -121,11 +119,9 @@ public abstract class SmartthingsConverter { value = command.toString().toLowerCase(); } - String jsonMsg = String.format( + return String.format( "{\"capabilityKey\": \"%s\", \"deviceDisplayName\": \"%s\", \"capabilityAttribute\": \"%s\", \"value\": %s}", thingTypeId, smartthingsName, channelUid.getId(), value); - - return jsonMsg; } protected String surroundWithQuotes(String param) { @@ -159,16 +155,16 @@ public abstract class SmartthingsConverter { return UnDefType.UNDEF; case "Dimmer": // The value coming in should be a number - if (deviceValue instanceof String) { - return new PercentType((String) deviceValue); + if (deviceValue instanceof String stringCommand) { + return new PercentType(stringCommand); } else { logger.warn("Failed to convert {} with a value of {} from class {} to an appropriate type.", deviceType, deviceValue, deviceValue.getClass().getName()); return UnDefType.UNDEF; } case "Number": - if (deviceValue instanceof String) { - return new DecimalType(Double.parseDouble((String) deviceValue)); + if (deviceValue instanceof String stringCommand2) { + return new DecimalType(Double.parseDouble(stringCommand2)); } else if (deviceValue instanceof Double) { return new DecimalType((Double) deviceValue); } else if (deviceValue instanceof Long) { @@ -196,8 +192,8 @@ public abstract class SmartthingsConverter { // But if the result is from sensor change via a subscription to a threeAxis device the results will // be a String of the format "value":"-873,-70,484" // which GSON returns as a LinkedTreeMap - if (deviceValue instanceof String) { - return new StringType((String) deviceValue); + if (deviceValue instanceof String stringCommand3) { + return new StringType(stringCommand3); } else if (deviceValue instanceof Map) { Map map = (Map) deviceValue; String s = String.format("%.0f,%.0f,%.0f", map.get("x"), map.get("y"), map.get("z")); diff --git a/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/converter/SmartthingsDefaultConverter.java b/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/converter/SmartthingsDefaultConverter.java index 3195725ba..533e71c8c 100644 --- a/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/converter/SmartthingsDefaultConverter.java +++ b/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/converter/SmartthingsDefaultConverter.java @@ -41,13 +41,11 @@ public class SmartthingsDefaultConverter extends SmartthingsConverter { @Override public String convertToSmartthings(ChannelUID channelUid, Command command) { - String jsonMsg = defaultConvertToSmartthings(channelUid, command); - return jsonMsg; + return defaultConvertToSmartthings(channelUid, command); } @Override public State convertToOpenHab(@Nullable String acceptedChannelType, SmartthingsStateData dataFromSmartthings) { - State state = defaultConvertToOpenHab(acceptedChannelType, dataFromSmartthings); - return state; + return defaultConvertToOpenHab(acceptedChannelType, dataFromSmartthings); } } diff --git a/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/converter/SmartthingsHue100Converter.java b/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/converter/SmartthingsHue100Converter.java index 81bd43695..15174da3c 100644 --- a/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/converter/SmartthingsHue100Converter.java +++ b/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/converter/SmartthingsHue100Converter.java @@ -47,11 +47,10 @@ public class SmartthingsHue100Converter extends SmartthingsConverter { public String convertToSmartthings(ChannelUID channelUid, Command command) { String jsonMsg; - if (command instanceof HSBType) { - HSBType hsb = (HSBType) command; - double hue = hsb.getHue().doubleValue() / 3.60; - String value = String.format("[%.0f, %d, %d ]", hue, hsb.getSaturation().intValue(), - hsb.getBrightness().intValue()); + if (command instanceof HSBType hsbCommand) { + double hue = hsbCommand.getHue().doubleValue() / 3.60; + String value = String.format("[%.0f, %d, %d ]", hue, hsbCommand.getSaturation().intValue(), + hsbCommand.getBrightness().intValue()); jsonMsg = String.format( "{\"capabilityKey\": \"%s\", \"deviceDisplayName\": \"%s\", \"capabilityAttribute\": \"%s\", \"value\": %s}", thingTypeId, smartthingsName, channelUid.getId(), value); @@ -74,20 +73,20 @@ public class SmartthingsHue100Converter extends SmartthingsConverter { } if (acceptedChannelType != null && "Number".contentEquals(acceptedChannelType)) { - if (deviceValue instanceof String) { - double d = Double.parseDouble((String) deviceValue); + if (deviceValue instanceof String stringCommand) { + double d = Double.parseDouble(stringCommand); d *= 3.6; return new DecimalType(d); } else if (deviceValue instanceof Long) { double d = ((Long) deviceValue).longValue(); d *= 3.6; return new DecimalType(d); - } else if (deviceValue instanceof BigDecimal) { - double d = ((BigDecimal) deviceValue).doubleValue(); + } else if (deviceValue instanceof BigDecimal decimalValue) { + double d = decimalValue.doubleValue(); d *= 3.6; return new DecimalType(d); - } else if (deviceValue instanceof Number) { - double d = ((Number) deviceValue).doubleValue(); + } else if (deviceValue instanceof Number numberValue) { + double d = numberValue.doubleValue(); d *= 3.6; return new DecimalType(d); } else { diff --git a/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/converter/SmartthingsOpenCloseControlConverter.java b/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/converter/SmartthingsOpenCloseControlConverter.java index 519fe1def..03359bb7f 100644 --- a/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/converter/SmartthingsOpenCloseControlConverter.java +++ b/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/converter/SmartthingsOpenCloseControlConverter.java @@ -37,19 +37,15 @@ public class SmartthingsOpenCloseControlConverter extends SmartthingsConverter { @Override public String convertToSmartthings(ChannelUID channelUid, Command command) { - String smartthingsValue = (command.toString().toLowerCase().equals("open")) ? "open" : "close"; + String smartthingsValue = ("open".equals(command.toString().toLowerCase())) ? "open" : "close"; smartthingsValue = surroundWithQuotes(smartthingsValue); - String jsonMsg = String.format("{\"capabilityKey\": \"%s\", \"deviceDisplayName\": \"%s\", \"value\": %s}", - thingTypeId, smartthingsName, smartthingsValue); - - return jsonMsg; + return String.format("{\"capabilityKey\": \"%s\", \"deviceDisplayName\": \"%s\", \"value\": %s}", thingTypeId, + smartthingsName, smartthingsValue); } @Override public State convertToOpenHab(@Nullable String acceptedChannelType, SmartthingsStateData dataFromSmartthings) { - State state = defaultConvertToOpenHab(acceptedChannelType, dataFromSmartthings); - - return state; + return defaultConvertToOpenHab(acceptedChannelType, dataFromSmartthings); } } diff --git a/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/handler/SmartthingsThingHandler.java b/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/handler/SmartthingsThingHandler.java index 00b3be269..22a998a51 100644 --- a/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/handler/SmartthingsThingHandler.java +++ b/bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/handler/SmartthingsThingHandler.java @@ -128,8 +128,7 @@ public class SmartthingsThingHandler extends ConfigStatusThingHandler { * @return channel id */ private String getSmartthingsAttributeFromChannel(ChannelUID channelUID) { - String id = channelUID.getId(); - return id; + return channelUID.getId(); } /** @@ -211,8 +210,7 @@ public class SmartthingsThingHandler extends ConfigStatusThingHandler { try { Constructor constr = Class.forName(converterClassName.toString()).getDeclaredConstructor(Thing.class); constr.setAccessible(true); - SmartthingsConverter cvtr = (SmartthingsConverter) constr.newInstance(thing); - return cvtr; + return (SmartthingsConverter) constr.newInstance(thing); } catch (ClassNotFoundException e) { // Most of the time there is no channel specific converter, the default converter is all that is needed. logger.trace("No Custom converter exists for {} ({})", converterName, converterClassName); diff --git a/bundles/org.openhab.binding.smhi/src/main/java/org/openhab/binding/smhi/internal/SmhiHandler.java b/bundles/org.openhab.binding.smhi/src/main/java/org/openhab/binding/smhi/internal/SmhiHandler.java index 6923bf567..ca3a5f767 100644 --- a/bundles/org.openhab.binding.smhi/src/main/java/org/openhab/binding/smhi/internal/SmhiHandler.java +++ b/bundles/org.openhab.binding.smhi/src/main/java/org/openhab/binding/smhi/internal/SmhiHandler.java @@ -425,9 +425,7 @@ public class SmhiHandler extends BaseThingHandler { break; } - Channel channel = ChannelBuilder.create(channelUID, itemType) - .withType(new ChannelTypeUID(BINDING_ID, channelID)).build(); - return channel; + return ChannelBuilder.create(channelUID, itemType).withType(new ChannelTypeUID(BINDING_ID, channelID)).build(); } /** diff --git a/bundles/org.openhab.binding.smhi/src/main/java/org/openhab/binding/smhi/internal/SmhiHandlerFactory.java b/bundles/org.openhab.binding.smhi/src/main/java/org/openhab/binding/smhi/internal/SmhiHandlerFactory.java index 9ed93d0cc..9b8ac6132 100644 --- a/bundles/org.openhab.binding.smhi/src/main/java/org/openhab/binding/smhi/internal/SmhiHandlerFactory.java +++ b/bundles/org.openhab.binding.smhi/src/main/java/org/openhab/binding/smhi/internal/SmhiHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.smhi.internal; import static org.openhab.binding.smhi.internal.SmhiBindingConstants.THING_TYPE_FORECAST; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -40,7 +39,7 @@ import org.osgi.service.component.annotations.Reference; @Component(configurationPid = "binding.smhi", service = ThingHandlerFactory.class) public class SmhiHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_FORECAST); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_FORECAST); private final HttpClient httpClient; diff --git a/bundles/org.openhab.binding.smsmodem/src/3rdparty/java/org/smslib/MessageReader.java b/bundles/org.openhab.binding.smsmodem/src/3rdparty/java/org/smslib/MessageReader.java index ce83446c1..ec64cc1c2 100644 --- a/bundles/org.openhab.binding.smsmodem/src/3rdparty/java/org/smslib/MessageReader.java +++ b/bundles/org.openhab.binding.smsmodem/src/3rdparty/java/org/smslib/MessageReader.java @@ -102,13 +102,13 @@ public class MessageReader extends Thread { pduString = "00" + pduString; } Pdu pdu = parser.parsePdu(pduString); - if (pdu instanceof SmsDeliveryPdu) { + if (pdu instanceof SmsDeliveryPdu deliveryPdu) { logger.debug("PDU = {}", pdu.toString()); InboundMessage msg = null; if (pdu.isBinary()) { - msg = new InboundBinaryMessage((SmsDeliveryPdu) pdu, memLocation, memIndex); + msg = new InboundBinaryMessage(deliveryPdu, memLocation, memIndex); } else { - msg = new InboundMessage((SmsDeliveryPdu) pdu, memLocation, memIndex); + msg = new InboundMessage(deliveryPdu, memLocation, memIndex); } msg.setGatewayId(this.modem.getGatewayId()); msg.setGatewayId(this.modem.getGatewayId()); @@ -153,9 +153,9 @@ public class MessageReader extends Thread { mpMsgList.add(tmpList); } } - } else if (pdu instanceof SmsStatusReportPdu) { + } else if (pdu instanceof SmsStatusReportPdu statusReportPdu) { DeliveryReportMessage msg; - msg = new DeliveryReportMessage((SmsStatusReportPdu) pdu, memLocation, memIndex); + msg = new DeliveryReportMessage(statusReportPdu, memLocation, memIndex); msg.setGatewayId(this.modem.getGatewayId()); messageList.add(msg); } @@ -376,8 +376,8 @@ public class MessageReader extends Thread { String messageSignature = message.getSignature(); if (!this.modem.getReadMessagesSet().contains(messageSignature)) { this.modem.getDeviceInformation().increaseTotalReceived(); - if (message instanceof DeliveryReportMessage) { - modem.processDeliveryReport((DeliveryReportMessage) message); + if (message instanceof DeliveryReportMessage deliveryReportMessage) { + modem.processDeliveryReport(deliveryReportMessage); } else { modem.processMessage(message); } diff --git a/bundles/org.openhab.binding.smsmodem/src/3rdparty/java/org/smslib/message/AbstractMessage.java b/bundles/org.openhab.binding.smsmodem/src/3rdparty/java/org/smslib/message/AbstractMessage.java index d358faaaf..eaad8128b 100644 --- a/bundles/org.openhab.binding.smsmodem/src/3rdparty/java/org/smslib/message/AbstractMessage.java +++ b/bundles/org.openhab.binding.smsmodem/src/3rdparty/java/org/smslib/message/AbstractMessage.java @@ -194,30 +194,30 @@ public abstract class AbstractMessage implements Serializable { b.append(String.format("Recipient Address: %s%n", getRecipientAddress())); b.append(String.format("Payload Type: %s%n", payload.getType())); b.append(String.format("Text payload: %s%n", payload.getText() == null ? "null" : payload.getText())); - if (this instanceof InboundMessage) { + if (this instanceof InboundMessage message) { b.append(String.format("Sent Date: %s%n", getSentDate())); - b.append(String.format("Memory Storage Location: %s%n", ((InboundMessage) this).getMemLocation())); - b.append(String.format("Memory Index: %d%n", ((InboundMessage) this).getMemIndex())); - b.append(String.format("Memory MP Index: %s%n", ((InboundMessage) this).getMpMemIndex())); + b.append(String.format("Memory Storage Location: %s%n", message.getMemLocation())); + b.append(String.format("Memory Index: %d%n", message.getMemIndex())); + b.append(String.format("Memory MP Index: %s%n", message.getMpMemIndex())); } - if (this instanceof OutboundMessage) { + if (this instanceof OutboundMessage message) { b.append(String.format("Sent Date: %s%n", - (((OutboundMessage) this).getSentStatus() == SentStatus.Sent ? getSentDate() : "N/A"))); + (message.getSentStatus() == SentStatus.Sent ? getSentDate() : "N/A"))); String ids = ""; - for (String opId : ((OutboundMessage) this).getOperatorMessageIds()) { + for (String opId : message.getOperatorMessageIds()) { ids += (ids.length() == 0 ? opId : "," + opId); } b.append(String.format("Operator Message IDs: %s%n", ids)); - b.append(String.format("Status: %s%n", ((OutboundMessage) this).getSentStatus().toString())); - b.append(String.format("Failure: %s%n", ((OutboundMessage) this).getFailureCause().toString())); + b.append(String.format("Status: %s%n", message.getSentStatus().toString())); + b.append(String.format("Failure: %s%n", message.getFailureCause().toString())); b.append(String.format("Request Delivery Reports: %b%n", - ((OutboundMessage) this).getRequestDeliveryReport())); + message.getRequestDeliveryReport())); } - if (this instanceof DeliveryReportMessage) { + if (this instanceof DeliveryReportMessage message) { b.append(String.format("Original Operator Message Id: %s%n", - ((DeliveryReportMessage) this).getOriginalOperatorMessageId())); - b.append(String.format("Delivery Date: %s%n", ((DeliveryReportMessage) this).getOriginalReceivedDate())); - b.append(String.format("Delivery Status: %s%n", ((DeliveryReportMessage) this).getDeliveryStatus())); + message.getOriginalOperatorMessageId())); + b.append(String.format("Delivery Date: %s%n", message.getOriginalReceivedDate())); + b.append(String.format("Delivery Status: %s%n", message.getDeliveryStatus())); } b.append(String .format("== MESSAGE END ========================================================================%n")); diff --git a/bundles/org.openhab.binding.smsmodem/src/main/java/org/openhab/binding/smsmodem/internal/actions/SMSModemActions.java b/bundles/org.openhab.binding.smsmodem/src/main/java/org/openhab/binding/smsmodem/internal/actions/SMSModemActions.java index f79adde82..6423bca16 100644 --- a/bundles/org.openhab.binding.smsmodem/src/main/java/org/openhab/binding/smsmodem/internal/actions/SMSModemActions.java +++ b/bundles/org.openhab.binding.smsmodem/src/main/java/org/openhab/binding/smsmodem/internal/actions/SMSModemActions.java @@ -68,8 +68,8 @@ public class SMSModemActions implements ThingActions { public static void sendSMS(@Nullable ThingActions actions, @Nullable String recipient, @Nullable String message, @Nullable String encoding) { - if (actions instanceof SMSModemActions) { - ((SMSModemActions) actions).sendSMS(recipient, message, encoding); + if (actions instanceof SMSModemActions smsModemActions) { + smsModemActions.sendSMS(recipient, message, encoding); } else { throw new IllegalArgumentException("Instance is not an SMSModemActions class."); } diff --git a/bundles/org.openhab.binding.smsmodem/src/main/java/org/openhab/binding/smsmodem/internal/handler/SMSConversationHandler.java b/bundles/org.openhab.binding.smsmodem/src/main/java/org/openhab/binding/smsmodem/internal/handler/SMSConversationHandler.java index 6014e40b1..c214d9f4f 100644 --- a/bundles/org.openhab.binding.smsmodem/src/main/java/org/openhab/binding/smsmodem/internal/handler/SMSConversationHandler.java +++ b/bundles/org.openhab.binding.smsmodem/src/main/java/org/openhab/binding/smsmodem/internal/handler/SMSConversationHandler.java @@ -65,8 +65,8 @@ public class SMSConversationHandler extends BaseThingHandler { thing.getUID(), getRecipient()); } ThingHandler handler = bridge.getHandler(); - if (handler instanceof SMSModemBridgeHandler) { - this.bridgeHandler = (SMSModemBridgeHandler) handler; + if (handler instanceof SMSModemBridgeHandler smsModemBridgeHandler) { + this.bridgeHandler = smsModemBridgeHandler; } else { throw new ConfigurationException("No available bridge handler found for SMSConversation {} bridge {} .", thing.getUID(), bridge.getUID()); diff --git a/bundles/org.openhab.binding.sncf/src/main/java/org/openhab/binding/sncf/internal/discovery/SncfDiscoveryService.java b/bundles/org.openhab.binding.sncf/src/main/java/org/openhab/binding/sncf/internal/discovery/SncfDiscoveryService.java index 809143246..eead07953 100644 --- a/bundles/org.openhab.binding.sncf/src/main/java/org/openhab/binding/sncf/internal/discovery/SncfDiscoveryService.java +++ b/bundles/org.openhab.binding.sncf/src/main/java/org/openhab/binding/sncf/internal/discovery/SncfDiscoveryService.java @@ -102,9 +102,9 @@ public class SncfDiscoveryService extends AbstractDiscoveryService implements Th @Override public void setThingHandler(ThingHandler handler) { - if (handler instanceof SncfBridgeHandler) { - this.bridgeHandler = (SncfBridgeHandler) handler; - this.locationProvider = ((SncfBridgeHandler) handler).getLocationProvider(); + if (handler instanceof SncfBridgeHandler sncfBridgeHandler) { + this.bridgeHandler = sncfBridgeHandler; + this.locationProvider = sncfBridgeHandler.getLocationProvider(); } } diff --git a/bundles/org.openhab.binding.snmp/src/main/java/org/openhab/binding/snmp/internal/SnmpTargetHandler.java b/bundles/org.openhab.binding.snmp/src/main/java/org/openhab/binding/snmp/internal/SnmpTargetHandler.java index 6709a817a..f43ea5463 100644 --- a/bundles/org.openhab.binding.snmp/src/main/java/org/openhab/binding/snmp/internal/SnmpTargetHandler.java +++ b/bundles/org.openhab.binding.snmp/src/main/java/org/openhab/binding/snmp/internal/SnmpTargetHandler.java @@ -139,12 +139,12 @@ public class SnmpTargetHandler extends BaseThingHandler implements ResponseListe } } else { Command rawValue = command; - if (command instanceof QuantityType) { + if (command instanceof QuantityType quantityCommand) { Unit channelUnit = channel.unit; if (channelUnit == null) { - rawValue = new DecimalType(((QuantityType) command).toBigDecimal()); + rawValue = new DecimalType(quantityCommand.toBigDecimal()); } else { - QuantityType convertedValue = ((QuantityType) command).toUnit(channelUnit); + QuantityType convertedValue = quantityCommand.toUnit(channelUnit); if (convertedValue == null) { logger.warn("Cannot convert '{}' to configured unit '{}'", command, channelUnit); return; @@ -443,7 +443,6 @@ public class SnmpTargetHandler extends BaseThingHandler implements ResponseListe octets[3] << 24 | octets[4] << 16 | octets[5] << 8 | octets[6]); state = channelUnit == null ? new DecimalType(floatValue) : new QuantityType<>(floatValue, channelUnit); - } else { throw new UnsupportedOperationException("Unknown opaque datatype" + value); } @@ -491,36 +490,36 @@ public class SnmpTargetHandler extends BaseThingHandler implements ResponseListe private Variable convertDatatype(Command command, SnmpDatatype datatype) { switch (datatype) { case INT32 -> { - if (command instanceof DecimalType) { - return new Integer32(((DecimalType) command).intValue()); - } else if (command instanceof StringType) { - return new Integer32((new DecimalType(((StringType) command).toString())).intValue()); + if (command instanceof DecimalType decimalCommand) { + return new Integer32(decimalCommand.intValue()); + } else if (command instanceof StringType stringCommand) { + return new Integer32((new DecimalType(stringCommand.toString())).intValue()); } } case UINT32 -> { - if (command instanceof DecimalType) { - return new UnsignedInteger32(((DecimalType) command).intValue()); - } else if (command instanceof StringType) { - return new UnsignedInteger32((new DecimalType(((StringType) command).toString())).intValue()); + if (command instanceof DecimalType decimalCommand) { + return new UnsignedInteger32(decimalCommand.intValue()); + } else if (command instanceof StringType stringCommand) { + return new UnsignedInteger32((new DecimalType(stringCommand.toString())).intValue()); } } case COUNTER64 -> { - if (command instanceof DecimalType) { - return new Counter64(((DecimalType) command).longValue()); - } else if (command instanceof StringType) { - return new Counter64((new DecimalType(((StringType) command).toString())).longValue()); + if (command instanceof DecimalType decimalCommand) { + return new Counter64(decimalCommand.longValue()); + } else if (command instanceof StringType stringCommand) { + return new Counter64((new DecimalType(stringCommand.toString())).longValue()); } } case FLOAT, STRING -> { - if (command instanceof DecimalType) { - return new OctetString(((DecimalType) command).toString()); - } else if (command instanceof StringType) { - return new OctetString(((StringType) command).toString()); + if (command instanceof DecimalType decimalCommand) { + return new OctetString(decimalCommand.toString()); + } else if (command instanceof StringType stringCommand) { + return new OctetString(stringCommand.toString()); } } case HEXSTRING -> { - if (command instanceof StringType) { - String commandString = ((StringType) command).toString().toLowerCase(); + if (command instanceof StringType stringCommand) { + String commandString = stringCommand.toString().toLowerCase(); Matcher commandMatcher = HEXSTRING_VALIDITY.matcher(commandString); if (commandMatcher.matches()) { commandString = HEXSTRING_EXTRACTOR.matcher(commandString).replaceAll(""); @@ -529,8 +528,8 @@ public class SnmpTargetHandler extends BaseThingHandler implements ResponseListe } } case IPADDRESS -> { - if (command instanceof StringType) { - return new IpAddress(((StringType) command).toString()); + if (command instanceof StringType stringCommand) { + return new IpAddress(stringCommand.toString()); } } default -> { diff --git a/bundles/org.openhab.binding.snmp/src/test/java/org/openhab/binding/snmp/internal/AbstractSnmpTargetHandlerTest.java b/bundles/org.openhab.binding.snmp/src/test/java/org/openhab/binding/snmp/internal/AbstractSnmpTargetHandlerTest.java index ac46fd432..4b0e29ccc 100644 --- a/bundles/org.openhab.binding.snmp/src/test/java/org/openhab/binding/snmp/internal/AbstractSnmpTargetHandlerTest.java +++ b/bundles/org.openhab.binding.snmp/src/test/java/org/openhab/binding/snmp/internal/AbstractSnmpTargetHandlerTest.java @@ -18,8 +18,8 @@ import static org.mockito.Mockito.*; import static org.openhab.binding.snmp.internal.SnmpBindingConstants.THING_TYPE_TARGET; import java.io.IOException; -import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Vector; @@ -116,7 +116,7 @@ public abstract class AbstractSnmpTargetHandlerTest extends JavaTest { setup(SnmpBindingConstants.CHANNEL_TYPE_UID_STRING, channelMode); PDU responsePDU = new PDU(PDU.RESPONSE, - Collections.singletonList(new VariableBinding(new OID(TEST_OID), new OctetString(TEST_STRING)))); + List.of(new VariableBinding(new OID(TEST_OID), new OctetString(TEST_STRING)))); ResponseEvent event = new ResponseEvent("test", null, null, responsePDU, null); thingHandler.onResponse(event); @@ -132,8 +132,7 @@ public abstract class AbstractSnmpTargetHandlerTest extends JavaTest { String onValue, String offValue, Variable value, boolean refresh) { setup(SnmpBindingConstants.CHANNEL_TYPE_UID_SWITCH, channelMode, datatype, onValue, offValue); - PDU responsePDU = new PDU(PDU.RESPONSE, - Collections.singletonList(new VariableBinding(new OID(TEST_OID), value))); + PDU responsePDU = new PDU(PDU.RESPONSE, List.of(new VariableBinding(new OID(TEST_OID), value))); ResponseEvent event = new ResponseEvent("test", null, null, responsePDU, null); thingHandler.onResponse(event); diff --git a/bundles/org.openhab.binding.snmp/src/test/java/org/openhab/binding/snmp/internal/StringChannelTest.java b/bundles/org.openhab.binding.snmp/src/test/java/org/openhab/binding/snmp/internal/StringChannelTest.java index 4d09dd3c4..0c7a8d5dd 100644 --- a/bundles/org.openhab.binding.snmp/src/test/java/org/openhab/binding/snmp/internal/StringChannelTest.java +++ b/bundles/org.openhab.binding.snmp/src/test/java/org/openhab/binding/snmp/internal/StringChannelTest.java @@ -17,7 +17,7 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; import java.io.IOException; -import java.util.Collections; +import java.util.List; import org.eclipse.jdt.annotation.NonNullByDefault; import org.junit.jupiter.api.Test; @@ -93,8 +93,8 @@ public class StringChannelTest extends AbstractSnmpTargetHandlerTest { @Test public void testStringChannelsProperlyUpdatingOnHexString() throws IOException { setup(SnmpBindingConstants.CHANNEL_TYPE_UID_STRING, SnmpChannelMode.READ, SnmpDatatype.HEXSTRING); - PDU responsePDU = new PDU(PDU.RESPONSE, Collections - .singletonList(new VariableBinding(new OID(TEST_OID), OctetString.fromHexStringPairs("aa11bb")))); + PDU responsePDU = new PDU(PDU.RESPONSE, + List.of(new VariableBinding(new OID(TEST_OID), OctetString.fromHexStringPairs("aa11bb")))); ResponseEvent event = new ResponseEvent("test", null, null, responsePDU, null); thingHandler.onResponse(event); verify(thingHandlerCallback, atLeast(1)).stateUpdated(eq(CHANNEL_UID), eq(new StringType("aa 11 bb"))); diff --git a/bundles/org.openhab.binding.snmp/src/test/java/org/openhab/binding/snmp/internal/SwitchChannelTest.java b/bundles/org.openhab.binding.snmp/src/test/java/org/openhab/binding/snmp/internal/SwitchChannelTest.java index 0ae04d144..c2c2063e2 100644 --- a/bundles/org.openhab.binding.snmp/src/test/java/org/openhab/binding/snmp/internal/SwitchChannelTest.java +++ b/bundles/org.openhab.binding.snmp/src/test/java/org/openhab/binding/snmp/internal/SwitchChannelTest.java @@ -17,7 +17,7 @@ import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.io.IOException; -import java.util.Collections; +import java.util.List; import org.eclipse.jdt.annotation.NonNullByDefault; import org.junit.jupiter.api.Test; @@ -77,8 +77,7 @@ public class SwitchChannelTest extends AbstractSnmpTargetHandlerTest { @Test public void testSwitchChannelsProperlyUpdatingOnValue() throws IOException { setup(SnmpBindingConstants.CHANNEL_TYPE_UID_SWITCH, SnmpChannelMode.READ, SnmpDatatype.STRING, "on", "off"); - PDU responsePDU = new PDU(PDU.RESPONSE, - Collections.singletonList(new VariableBinding(new OID(TEST_OID), new OctetString("on")))); + PDU responsePDU = new PDU(PDU.RESPONSE, List.of(new VariableBinding(new OID(TEST_OID), new OctetString("on")))); ResponseEvent event = new ResponseEvent("test", null, null, responsePDU, null); thingHandler.onResponse(event); verifyResponse(OnOffType.ON); @@ -87,8 +86,7 @@ public class SwitchChannelTest extends AbstractSnmpTargetHandlerTest { @Test public void testSwitchChannelsProperlyUpdatingOffValue() throws IOException { setup(SnmpBindingConstants.CHANNEL_TYPE_UID_SWITCH, SnmpChannelMode.READ, SnmpDatatype.INT32, "0", "3"); - PDU responsePDU = new PDU(PDU.RESPONSE, - Collections.singletonList(new VariableBinding(new OID(TEST_OID), new Integer32(3)))); + PDU responsePDU = new PDU(PDU.RESPONSE, List.of(new VariableBinding(new OID(TEST_OID), new Integer32(3)))); ResponseEvent event = new ResponseEvent("test", null, null, responsePDU, null); thingHandler.onResponse(event); verifyResponse(OnOffType.OFF); @@ -98,8 +96,8 @@ public class SwitchChannelTest extends AbstractSnmpTargetHandlerTest { public void testSwitchChannelsProperlyUpdatingHexValue() throws IOException { setup(SnmpBindingConstants.CHANNEL_TYPE_UID_SWITCH, SnmpChannelMode.READ, SnmpDatatype.HEXSTRING, "AA bb 11", "cc ba 1d"); - PDU responsePDU = new PDU(PDU.RESPONSE, Collections - .singletonList(new VariableBinding(new OID(TEST_OID), OctetString.fromHexStringPairs("aabb11")))); + PDU responsePDU = new PDU(PDU.RESPONSE, + List.of(new VariableBinding(new OID(TEST_OID), OctetString.fromHexStringPairs("aabb11")))); ResponseEvent event = new ResponseEvent("test", null, null, responsePDU, null); thingHandler.onResponse(event); verifyResponse(OnOffType.ON); @@ -108,8 +106,7 @@ public class SwitchChannelTest extends AbstractSnmpTargetHandlerTest { @Test public void testSwitchChannelsIgnoresArbitraryValue() throws IOException { setup(SnmpBindingConstants.CHANNEL_TYPE_UID_SWITCH, SnmpChannelMode.READ, SnmpDatatype.COUNTER64, "0", "12223"); - PDU responsePDU = new PDU(PDU.RESPONSE, - Collections.singletonList(new VariableBinding(new OID(TEST_OID), new Counter64(17)))); + PDU responsePDU = new PDU(PDU.RESPONSE, List.of(new VariableBinding(new OID(TEST_OID), new Counter64(17)))); ResponseEvent event = new ResponseEvent("test", null, null, responsePDU, null); thingHandler.onResponse(event); verify(thingHandlerCallback, never()).stateUpdated(eq(CHANNEL_UID), any()); @@ -119,8 +116,7 @@ public class SwitchChannelTest extends AbstractSnmpTargetHandlerTest { @Test public void testSwitchChannelSendsUndefExceptionValue() throws IOException { setup(SnmpBindingConstants.CHANNEL_TYPE_UID_SWITCH, SnmpChannelMode.READ, SnmpDatatype.COUNTER64, "0", "12223"); - PDU responsePDU = new PDU(PDU.RESPONSE, - Collections.singletonList(new VariableBinding(new OID(TEST_OID), Null.noSuchInstance))); + PDU responsePDU = new PDU(PDU.RESPONSE, List.of(new VariableBinding(new OID(TEST_OID), Null.noSuchInstance))); ResponseEvent event = new ResponseEvent("test", null, null, responsePDU, null); thingHandler.onResponse(event); verifyResponse(UnDefType.UNDEF); @@ -130,8 +126,7 @@ public class SwitchChannelTest extends AbstractSnmpTargetHandlerTest { public void testSwitchChannelSendsConfiguredExceptionValue() throws IOException { setup(SnmpBindingConstants.CHANNEL_TYPE_UID_SWITCH, SnmpChannelMode.READ, SnmpDatatype.COUNTER64, "0", "12223", "OFF"); - PDU responsePDU = new PDU(PDU.RESPONSE, - Collections.singletonList(new VariableBinding(new OID(TEST_OID), Null.noSuchInstance))); + PDU responsePDU = new PDU(PDU.RESPONSE, List.of(new VariableBinding(new OID(TEST_OID), Null.noSuchInstance))); ResponseEvent event = new ResponseEvent("test", null, null, responsePDU, null); thingHandler.onResponse(event); verifyResponse(OnOffType.OFF); diff --git a/bundles/org.openhab.binding.solaredge/src/main/java/org/openhab/binding/solaredge/internal/SolarEdgeBindingConstants.java b/bundles/org.openhab.binding.solaredge/src/main/java/org/openhab/binding/solaredge/internal/SolarEdgeBindingConstants.java index dae67f3b5..4c8e6ee64 100644 --- a/bundles/org.openhab.binding.solaredge/src/main/java/org/openhab/binding/solaredge/internal/SolarEdgeBindingConstants.java +++ b/bundles/org.openhab.binding.solaredge/src/main/java/org/openhab/binding/solaredge/internal/SolarEdgeBindingConstants.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.solaredge.internal; -import java.util.Collections; import java.util.Set; import java.util.concurrent.TimeUnit; @@ -111,5 +110,5 @@ public class SolarEdgeBindingConstants { public static final String STATUS_NO_METER_CONFIGURED = "@text/status.no.meter.configured"; public static final String STATUS_WAITING_FOR_LOGIN = "@text/status.waiting.for.login"; - public static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_GENERIC); + public static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_GENERIC); } diff --git a/bundles/org.openhab.binding.solaredge/src/main/java/org/openhab/binding/solaredge/internal/handler/SolarEdgeGenericHandler.java b/bundles/org.openhab.binding.solaredge/src/main/java/org/openhab/binding/solaredge/internal/handler/SolarEdgeGenericHandler.java index 0af1180dc..8ca79b159 100644 --- a/bundles/org.openhab.binding.solaredge/src/main/java/org/openhab/binding/solaredge/internal/handler/SolarEdgeGenericHandler.java +++ b/bundles/org.openhab.binding.solaredge/src/main/java/org/openhab/binding/solaredge/internal/handler/SolarEdgeGenericHandler.java @@ -234,7 +234,6 @@ public class SolarEdgeGenericHandler extends BaseThingHandler implements SolarEd public @Nullable Channel getChannel(String groupId, String channelId) { ThingUID thingUID = this.getThing().getUID(); ChannelGroupUID channelGroupUID = new ChannelGroupUID(thingUID, groupId); - Channel channel = getThing().getChannel(new ChannelUID(channelGroupUID, channelId)); - return channel; + return getThing().getChannel(new ChannelUID(channelGroupUID, channelId)); } } diff --git a/bundles/org.openhab.binding.solaredge/src/main/java/org/openhab/binding/solaredge/internal/model/AggregateDataResponseTransformerPublicApi.java b/bundles/org.openhab.binding.solaredge/src/main/java/org/openhab/binding/solaredge/internal/model/AggregateDataResponseTransformerPublicApi.java index a9533ad9e..d11209f52 100644 --- a/bundles/org.openhab.binding.solaredge/src/main/java/org/openhab/binding/solaredge/internal/model/AggregateDataResponseTransformerPublicApi.java +++ b/bundles/org.openhab.binding.solaredge/src/main/java/org/openhab/binding/solaredge/internal/model/AggregateDataResponseTransformerPublicApi.java @@ -89,7 +89,6 @@ public class AggregateDataResponseTransformerPublicApi extends AbstractDataRespo */ private final void fillAggregateData(AggregatePeriod period, String unit, MeterTelemetries meter, String channelId, Map valueMap) { - String group = convertPeriodToGroup(period); List values = meter.values; diff --git a/bundles/org.openhab.binding.solarlog/src/main/java/org/openhab/binding/solarlog/internal/SolarLogHandlerFactory.java b/bundles/org.openhab.binding.solarlog/src/main/java/org/openhab/binding/solarlog/internal/SolarLogHandlerFactory.java index 4bee160fd..37a0c862b 100644 --- a/bundles/org.openhab.binding.solarlog/src/main/java/org/openhab/binding/solarlog/internal/SolarLogHandlerFactory.java +++ b/bundles/org.openhab.binding.solarlog/src/main/java/org/openhab/binding/solarlog/internal/SolarLogHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.solarlog.internal; import static org.openhab.binding.solarlog.internal.SolarLogBindingConstants.THING_SOLARLOG; -import java.util.Collections; import java.util.Set; import org.openhab.binding.solarlog.internal.handler.SolarLogHandler; @@ -36,7 +35,7 @@ import org.slf4j.LoggerFactory; @Component(configurationPid = "binding.solarlog", service = ThingHandlerFactory.class) public class SolarLogHandlerFactory extends BaseThingHandlerFactory { private final Logger logger = LoggerFactory.getLogger(SolarLogHandlerFactory.class); - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_SOLARLOG); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_SOLARLOG); @Override public boolean supportsThingType(ThingTypeUID thingTypeUID) { diff --git a/bundles/org.openhab.binding.solarwatt/src/main/java/org/openhab/binding/solarwatt/internal/discovery/SolarwattDevicesDiscoveryService.java b/bundles/org.openhab.binding.solarwatt/src/main/java/org/openhab/binding/solarwatt/internal/discovery/SolarwattDevicesDiscoveryService.java index 67ce49264..806591bdb 100644 --- a/bundles/org.openhab.binding.solarwatt/src/main/java/org/openhab/binding/solarwatt/internal/discovery/SolarwattDevicesDiscoveryService.java +++ b/bundles/org.openhab.binding.solarwatt/src/main/java/org/openhab/binding/solarwatt/internal/discovery/SolarwattDevicesDiscoveryService.java @@ -84,8 +84,8 @@ public class SolarwattDevicesDiscoveryService extends AbstractDiscoveryService @Override public void setThingHandler(final @Nullable ThingHandler handler) { - if (handler instanceof EnergyManagerHandler) { - this.energyManagerHandler = (EnergyManagerHandler) handler; + if (handler instanceof EnergyManagerHandler energyManagerHandler) { + this.energyManagerHandler = energyManagerHandler; } } @@ -196,7 +196,7 @@ public class SolarwattDevicesDiscoveryService extends AbstractDiscoveryService * @return guid for openhab */ private String rewriteGuid(String emGuid) { - return emGuid.replaceAll(":", "-"); + return emGuid.replace(":", "-"); } public class EnergymanagerScan implements Runnable { diff --git a/bundles/org.openhab.binding.solarwatt/src/main/java/org/openhab/binding/solarwatt/internal/domain/SolarwattTag.java b/bundles/org.openhab.binding.solarwatt/src/main/java/org/openhab/binding/solarwatt/internal/domain/SolarwattTag.java index 3f43561b2..526938f94 100644 --- a/bundles/org.openhab.binding.solarwatt/src/main/java/org/openhab/binding/solarwatt/internal/domain/SolarwattTag.java +++ b/bundles/org.openhab.binding.solarwatt/src/main/java/org/openhab/binding/solarwatt/internal/domain/SolarwattTag.java @@ -27,7 +27,7 @@ public class SolarwattTag { public SolarwattTag(String tagName) { this.tagName = tagName; - char chars[] = tagName.toCharArray(); + char[] chars = tagName.toCharArray(); chars[0] = Character.toLowerCase(chars[0]); this.channelName = new String(chars); } diff --git a/bundles/org.openhab.binding.solarwatt/src/main/java/org/openhab/binding/solarwatt/internal/handler/EnergyManagerHandler.java b/bundles/org.openhab.binding.solarwatt/src/main/java/org/openhab/binding/solarwatt/internal/handler/EnergyManagerHandler.java index 28468df54..756e27711 100644 --- a/bundles/org.openhab.binding.solarwatt/src/main/java/org/openhab/binding/solarwatt/internal/handler/EnergyManagerHandler.java +++ b/bundles/org.openhab.binding.solarwatt/src/main/java/org/openhab/binding/solarwatt/internal/handler/EnergyManagerHandler.java @@ -22,9 +22,9 @@ import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -113,7 +113,7 @@ public class EnergyManagerHandler extends BaseBridgeHandler { */ @Override public Collection> getServices() { - return Collections.singleton(SolarwattDevicesDiscoveryService.class); + return Set.of(SolarwattDevicesDiscoveryService.class); } /** diff --git a/bundles/org.openhab.binding.solarwatt/src/main/java/org/openhab/binding/solarwatt/internal/handler/SimpleDeviceHandler.java b/bundles/org.openhab.binding.solarwatt/src/main/java/org/openhab/binding/solarwatt/internal/handler/SimpleDeviceHandler.java index 91d85248d..8a100bc93 100644 --- a/bundles/org.openhab.binding.solarwatt/src/main/java/org/openhab/binding/solarwatt/internal/handler/SimpleDeviceHandler.java +++ b/bundles/org.openhab.binding.solarwatt/src/main/java/org/openhab/binding/solarwatt/internal/handler/SimpleDeviceHandler.java @@ -212,8 +212,8 @@ public class SimpleDeviceHandler extends BaseThingHandler { Bridge bridge = this.getBridge(); if (bridge != null) { BridgeHandler bridgeHandler = bridge.getHandler(); - if (bridgeHandler instanceof EnergyManagerHandler) { - return (EnergyManagerHandler) bridgeHandler; + if (bridgeHandler instanceof EnergyManagerHandler energyManagerHandler) { + return energyManagerHandler; } else { // happens while dynamically reloading the binding this.logger.warn("BridgeHandler is not implementing EnergyManagerHandler {}", bridgeHandler); diff --git a/bundles/org.openhab.binding.somfymylink/src/main/java/org/openhab/binding/somfymylink/internal/discovery/SomfyMyLinkDeviceDiscoveryService.java b/bundles/org.openhab.binding.somfymylink/src/main/java/org/openhab/binding/somfymylink/internal/discovery/SomfyMyLinkDeviceDiscoveryService.java index e285cc9aa..f346c8311 100644 --- a/bundles/org.openhab.binding.somfymylink/src/main/java/org/openhab/binding/somfymylink/internal/discovery/SomfyMyLinkDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.somfymylink/src/main/java/org/openhab/binding/somfymylink/internal/discovery/SomfyMyLinkDeviceDiscoveryService.java @@ -64,8 +64,8 @@ public class SomfyMyLinkDeviceDiscoveryService extends AbstractDiscoveryService @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof SomfyMyLinkBridgeHandler) { - this.mylinkHandler = (SomfyMyLinkBridgeHandler) handler; + if (handler instanceof SomfyMyLinkBridgeHandler bridgeHandler) { + this.mylinkHandler = bridgeHandler; } } diff --git a/bundles/org.openhab.binding.somfymylink/src/main/java/org/openhab/binding/somfymylink/internal/handler/SomfyMyLinkBridgeHandler.java b/bundles/org.openhab.binding.somfymylink/src/main/java/org/openhab/binding/somfymylink/internal/handler/SomfyMyLinkBridgeHandler.java index 62651cdd9..4207f1c87 100644 --- a/bundles/org.openhab.binding.somfymylink/src/main/java/org/openhab/binding/somfymylink/internal/handler/SomfyMyLinkBridgeHandler.java +++ b/bundles/org.openhab.binding.somfymylink/src/main/java/org/openhab/binding/somfymylink/internal/handler/SomfyMyLinkBridgeHandler.java @@ -25,9 +25,9 @@ import java.net.SocketTimeoutException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.List; import java.util.Objects; +import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -145,7 +145,7 @@ public class SomfyMyLinkBridgeHandler extends BaseBridgeHandler { @Override public Collection> getServices() { - return Collections.singleton(SomfyMyLinkDeviceDiscoveryService.class); + return Set.of(SomfyMyLinkDeviceDiscoveryService.class); } private boolean validConfiguration(@Nullable SomfyMyLinkConfiguration config) { diff --git a/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/console/SomfyTahomaCommandExtension.java b/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/console/SomfyTahomaCommandExtension.java index 33f26a65d..d1de68ee1 100644 --- a/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/console/SomfyTahomaCommandExtension.java +++ b/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/console/SomfyTahomaCommandExtension.java @@ -62,8 +62,8 @@ public class SomfyTahomaCommandExtension extends AbstractConsoleCommandExtension SomfyTahomaBridgeHandler bridgeHandler = null; if (thing != null) { thingHandler = thing.getHandler(); - if (thingHandler instanceof SomfyTahomaBridgeHandler) { - bridgeHandler = (SomfyTahomaBridgeHandler) thingHandler; + if (thingHandler instanceof SomfyTahomaBridgeHandler tahomaBridgeHandler) { + bridgeHandler = tahomaBridgeHandler; } } if (thing == null) { diff --git a/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/discovery/SomfyTahomaItemDiscoveryService.java b/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/discovery/SomfyTahomaItemDiscoveryService.java index bd8fb354b..54f55a4b7 100644 --- a/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/discovery/SomfyTahomaItemDiscoveryService.java +++ b/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/discovery/SomfyTahomaItemDiscoveryService.java @@ -79,8 +79,8 @@ public class SomfyTahomaItemDiscoveryService extends AbstractDiscoveryService @Override public void setThingHandler(@NonNullByDefault({}) ThingHandler handler) { - if (handler instanceof SomfyTahomaBridgeHandler) { - bridgeHandler = (SomfyTahomaBridgeHandler) handler; + if (handler instanceof SomfyTahomaBridgeHandler tahomaBridgeHandler) { + bridgeHandler = tahomaBridgeHandler; } } diff --git a/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/handler/SomfyTahomaBaseThingHandler.java b/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/handler/SomfyTahomaBaseThingHandler.java index dffde476f..8f0f177ad 100644 --- a/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/handler/SomfyTahomaBaseThingHandler.java +++ b/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/handler/SomfyTahomaBaseThingHandler.java @@ -475,20 +475,19 @@ public abstract class SomfyTahomaBaseThingHandler extends BaseThingHandler { } public int toInteger(Command command) { - return (command instanceof DecimalType) ? ((DecimalType) command).intValue() : 0; + return (command instanceof DecimalType dateTimeCommand) ? dateTimeCommand.intValue() : 0; } public @Nullable BigDecimal toTemperature(Command command) { BigDecimal temperature = null; - if (command instanceof QuantityType) { - QuantityType quantity = (QuantityType) command; - QuantityType convertedQuantity = quantity.toUnit(getTemperatureUnit()); + if (command instanceof QuantityType quantityCommand) { + QuantityType convertedQuantity = quantityCommand.toUnit(getTemperatureUnit()); if (convertedQuantity != null) { - quantity = convertedQuantity; + quantityCommand = convertedQuantity; } - temperature = quantity.toBigDecimal(); - } else if (command instanceof DecimalType) { - temperature = ((DecimalType) command).toBigDecimal(); + temperature = quantityCommand.toBigDecimal(); + } else if (command instanceof DecimalType decimalCommand) { + temperature = decimalCommand.toBigDecimal(); } return temperature; } diff --git a/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/handler/SomfyTahomaBridgeHandler.java b/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/handler/SomfyTahomaBridgeHandler.java index 664530bf9..d40841b59 100644 --- a/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/handler/SomfyTahomaBridgeHandler.java +++ b/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/handler/SomfyTahomaBridgeHandler.java @@ -21,10 +21,10 @@ import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.Instant; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledFuture; @@ -466,7 +466,7 @@ public class SomfyTahomaBridgeHandler extends BaseBridgeHandler { @Override public Collection> getServices() { - return Collections.singleton(SomfyTahomaItemDiscoveryService.class); + return Set.of(SomfyTahomaItemDiscoveryService.class); } @Override @@ -677,7 +677,7 @@ public class SomfyTahomaBridgeHandler extends BaseBridgeHandler { private void unregisterExecution(String execId) { if (executions.containsValue(execId)) { - executions.values().removeAll(Collections.singleton(execId)); + executions.values().removeAll(Set.of(execId)); } else { logger.debug("Cannot remove execution id: {}, because it is not registered", execId); } diff --git a/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/handler/SomfyTahomaExteriorHeatingSystemHandler.java b/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/handler/SomfyTahomaExteriorHeatingSystemHandler.java index 88a86bbef..b5a8f459e 100644 --- a/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/handler/SomfyTahomaExteriorHeatingSystemHandler.java +++ b/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/handler/SomfyTahomaExteriorHeatingSystemHandler.java @@ -44,8 +44,8 @@ public class SomfyTahomaExteriorHeatingSystemHandler extends SomfyTahomaBaseThin Channel chLevel = thing.getChannel(HEATING_LEVEL); if (chLevel != null) { State newState = parseTahomaState(state); - if (newState != null && newState instanceof PercentType) { - int value = ((PercentType) newState).intValue(); + if (newState instanceof PercentType percentState) { + int value = percentState.intValue(); PercentType inverted = new PercentType(100 - value); updateState(chLevel.getUID(), inverted); } diff --git a/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/handler/SomfyTahomaWaterHeatingSystemHandler.java b/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/handler/SomfyTahomaWaterHeatingSystemHandler.java index 449f9127e..437af5088 100644 --- a/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/handler/SomfyTahomaWaterHeatingSystemHandler.java +++ b/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/handler/SomfyTahomaWaterHeatingSystemHandler.java @@ -83,14 +83,14 @@ public class SomfyTahomaWaterHeatingSystemHandler extends SomfyTahomaBaseThingHa Object relaunchValue = data.get("relaunch"); if (relaunchValue != null) { - this.boostMode = relaunchValue.toString().equalsIgnoreCase("on"); + this.boostMode = "on".equalsIgnoreCase(relaunchValue.toString()); logger.debug("Boost Value: {}", this.boostMode); updateState(BOOST_MODE, OnOffType.from(this.boostMode)); } Object awayValue = data.get("absence"); if (awayValue != null) { - this.awayMode = awayValue.toString().equalsIgnoreCase("on"); + this.awayMode = "on".equalsIgnoreCase(awayValue.toString()); logger.debug("Away Value: {}", this.awayMode); updateState(AWAY_MODE, OnOffType.from(this.awayMode)); } diff --git a/bundles/org.openhab.binding.somneo/src/main/java/org/openhab/binding/somneo/internal/SomneoHandler.java b/bundles/org.openhab.binding.somneo/src/main/java/org/openhab/binding/somneo/internal/SomneoHandler.java index c56893043..18856b60b 100644 --- a/bundles/org.openhab.binding.somneo/src/main/java/org/openhab/binding/somneo/internal/SomneoHandler.java +++ b/bundles/org.openhab.binding.somneo/src/main/java/org/openhab/binding/somneo/internal/SomneoHandler.java @@ -396,8 +396,8 @@ public class SomneoHandler extends BaseThingHandler { } break; case CHANNEL_ALARM_SOUND: - if (command instanceof StringType) { - connector.setAlarmSound(alarmPosition, (StringType) command); + if (command instanceof StringType stringCommand) { + connector.setAlarmSound(alarmPosition, stringCommand); } break; case CHANNEL_ALARM_VOLUME: diff --git a/bundles/org.openhab.binding.somneo/src/main/java/org/openhab/binding/somneo/internal/SomneoHttpConnector.java b/bundles/org.openhab.binding.somneo/src/main/java/org/openhab/binding/somneo/internal/SomneoHttpConnector.java index c01378f4b..58e43a2fd 100644 --- a/bundles/org.openhab.binding.somneo/src/main/java/org/openhab/binding/somneo/internal/SomneoHttpConnector.java +++ b/bundles/org.openhab.binding.somneo/src/main/java/org/openhab/binding/somneo/internal/SomneoHttpConnector.java @@ -510,7 +510,7 @@ public class SomneoHttpConnector { logger.debug("Method failed: {}", statusLine); } - final String encoding = response.getEncoding() != null ? response.getEncoding().replaceAll("\"", "").trim() + final String encoding = response.getEncoding() != null ? response.getEncoding().replace("\"", "").trim() : StandardCharsets.UTF_8.name(); try { diff --git a/bundles/org.openhab.binding.sonos/src/main/java/org/openhab/binding/sonos/internal/handler/ZonePlayerHandler.java b/bundles/org.openhab.binding.sonos/src/main/java/org/openhab/binding/sonos/internal/handler/ZonePlayerHandler.java index 4d305d6b8..c4d253276 100644 --- a/bundles/org.openhab.binding.sonos/src/main/java/org/openhab/binding/sonos/internal/handler/ZonePlayerHandler.java +++ b/bundles/org.openhab.binding.sonos/src/main/java/org/openhab/binding/sonos/internal/handler/ZonePlayerHandler.java @@ -1823,8 +1823,8 @@ public class ZonePlayerHandler extends BaseThingHandler implements UpnpIOPartici newValue = "100"; } else if (command == OnOffType.OFF) { newValue = "0"; - } else if (command instanceof DecimalType) { - newValue = String.valueOf(((DecimalType) command).intValue()); + } else if (command instanceof DecimalType decimalCommand) { + newValue = String.valueOf(decimalCommand.intValue()); } else { return; } @@ -1880,8 +1880,8 @@ public class ZonePlayerHandler extends BaseThingHandler implements UpnpIOPartici } else if (command == IncreaseDecreaseType.DECREASE && currentValue != null) { int i = Integer.valueOf(currentValue); newValue = String.valueOf(Math.max(minValue, i - 1)); - } else if (command instanceof DecimalType) { - newValue = String.valueOf(((DecimalType) command).intValue()); + } else if (command instanceof DecimalType decimalCommand) { + newValue = String.valueOf(decimalCommand.intValue()); } } return newValue; @@ -2317,8 +2317,8 @@ public class ZonePlayerHandler extends BaseThingHandler implements UpnpIOPartici Thing thing = localThingRegistry.get(new ThingUID(supportedThingType, remotePlayerName)); if (thing != null) { ThingHandler handler = thing.getHandler(); - if (handler instanceof ZonePlayerHandler) { - return (ZonePlayerHandler) handler; + if (handler instanceof ZonePlayerHandler zonePlayerHandler) { + return zonePlayerHandler; } } } @@ -2326,8 +2326,8 @@ public class ZonePlayerHandler extends BaseThingHandler implements UpnpIOPartici if (SonosBindingConstants.SUPPORTED_THING_TYPES_UIDS.contains(aThing.getThingTypeUID()) && aThing.getConfiguration().get(ZonePlayerConfiguration.UDN).equals(remotePlayerName)) { ThingHandler handler = aThing.getHandler(); - if (handler instanceof ZonePlayerHandler) { - return (ZonePlayerHandler) handler; + if (handler instanceof ZonePlayerHandler zonePlayerHandler) { + return zonePlayerHandler; } } } @@ -2462,8 +2462,8 @@ public class ZonePlayerHandler extends BaseThingHandler implements UpnpIOPartici } public void snoozeAlarm(Command command) { - if (isAlarmRunning() && command instanceof DecimalType) { - int minutes = ((DecimalType) command).intValue(); + if (isAlarmRunning() && command instanceof DecimalType decimalCommand) { + int minutes = decimalCommand.intValue(); Map inputs = new HashMap<>(); @@ -3164,11 +3164,11 @@ public class ZonePlayerHandler extends BaseThingHandler implements UpnpIOPartici } public void playTrack(Command command) { - if (command instanceof DecimalType) { + if (command instanceof DecimalType decimalCommand) { try { ZonePlayerHandler coordinator = getCoordinatorHandler(); - String trackNumber = String.valueOf(((DecimalType) command).intValue()); + String trackNumber = String.valueOf(decimalCommand.intValue()); coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + "#0", ""); @@ -3315,9 +3315,9 @@ public class ZonePlayerHandler extends BaseThingHandler implements UpnpIOPartici * Use empty String "" to switch the sleep timer off */ public void setSleepTimer(Command command) { - if (command instanceof DecimalType) { + if (command instanceof DecimalType decimalCommand) { this.service.invokeAction(this, SERVICE_AV_TRANSPORT, ACTION_CONFIGURE_SLEEP_TIMER, Map.of("InstanceID", - "0", "NewSleepTimerDuration", sleepSecondsToTimeStr(((DecimalType) command).longValue()))); + "0", "NewSleepTimerDuration", sleepSecondsToTimeStr(decimalCommand.longValue()))); } } diff --git a/bundles/org.openhab.binding.sonos/src/main/java/org/openhab/binding/sonos/internal/util/StringUtils.java b/bundles/org.openhab.binding.sonos/src/main/java/org/openhab/binding/sonos/internal/util/StringUtils.java index 4600b1824..7833a4a4f 100644 --- a/bundles/org.openhab.binding.sonos/src/main/java/org/openhab/binding/sonos/internal/util/StringUtils.java +++ b/bundles/org.openhab.binding.sonos/src/main/java/org/openhab/binding/sonos/internal/util/StringUtils.java @@ -32,11 +32,11 @@ public class StringUtils { * ' - ' */ public static String escapeXml(String xml) { - xml = xml.replaceAll("&", "&"); - xml = xml.replaceAll("<", "<"); - xml = xml.replaceAll(">", ">"); - xml = xml.replaceAll("\"", """); - xml = xml.replaceAll("'", "'"); + xml = xml.replace("&", "&"); + xml = xml.replace("<", "<"); + xml = xml.replace(">", ">"); + xml = xml.replace("\"", """); + xml = xml.replace("'", "'"); return xml; } @@ -50,11 +50,11 @@ public class StringUtils { * ' - ' */ public static String unEscapeXml(String xml) { - xml = xml.replaceAll("&", "&"); - xml = xml.replaceAll("<", "<"); - xml = xml.replaceAll(">", ">"); - xml = xml.replaceAll(""", "\""); - xml = xml.replaceAll("'", "'"); + xml = xml.replace("&", "&"); + xml = xml.replace("<", "<"); + xml = xml.replace(">", ">"); + xml = xml.replace(""", "\""); + xml = xml.replace("'", "'"); return xml; } } diff --git a/bundles/org.openhab.binding.sonyaudio/src/main/java/org/openhab/binding/sonyaudio/internal/handler/SonyAudioHandler.java b/bundles/org.openhab.binding.sonyaudio/src/main/java/org/openhab/binding/sonyaudio/internal/handler/SonyAudioHandler.java index f0b3bc77c..a10448559 100644 --- a/bundles/org.openhab.binding.sonyaudio/src/main/java/org/openhab/binding/sonyaudio/internal/handler/SonyAudioHandler.java +++ b/bundles/org.openhab.binding.sonyaudio/src/main/java/org/openhab/binding/sonyaudio/internal/handler/SonyAudioHandler.java @@ -252,9 +252,9 @@ abstract class SonyAudioHandler extends BaseThingHandler implements SonyAudioEve updateState(channelUID, new StringType(result.get("soundField"))); } } - if (command instanceof StringType) { + if (command instanceof StringType stringCommand) { logger.debug("handleSoundSettings set {}", command); - connection.setSoundSettings("soundField", ((StringType) command).toString()); + connection.setSoundSettings("soundField", stringCommand.toString()); } } @@ -266,9 +266,9 @@ abstract class SonyAudioHandler extends BaseThingHandler implements SonyAudioEve updateState(channelUID, new StringType(result.get("nightMode"))); } } - if (command instanceof OnOffType) { + if (command instanceof OnOffType onOffCommand) { logger.debug("handleNightMode set {}", command); - connection.setSoundSettings("nightMode", ((OnOffType) command) == OnOffType.ON ? "on" : "off"); + connection.setSoundSettings("nightMode", onOffCommand == OnOffType.ON ? "on" : "off"); } } @@ -286,9 +286,9 @@ abstract class SonyAudioHandler extends BaseThingHandler implements SonyAudioEve throw new IOException(ex.getCause()); } } - if (command instanceof OnOffType) { + if (command instanceof OnOffType onOffCommand) { logger.debug("handlePowerCommand set {} {}", zone, command); - connection.setPower(((OnOffType) command) == OnOffType.ON, zone); + connection.setPower(onOffCommand == OnOffType.ON, zone); } } @@ -338,18 +338,18 @@ abstract class SonyAudioHandler extends BaseThingHandler implements SonyAudioEve throw new IOException(ex.getCause()); } } - if (command instanceof PercentType) { + if (command instanceof PercentType percentCommand) { logger.debug("handleVolumeCommand PercentType set {} {}", zone, command); - connection.setVolume(((PercentType) command).intValue(), zone); + connection.setVolume(percentCommand.intValue(), zone); } if (command instanceof IncreaseDecreaseType) { logger.debug("handleVolumeCommand IncreaseDecreaseType set {} {}", zone, command); String change = command == IncreaseDecreaseType.INCREASE ? "+1" : "-1"; connection.setVolume(change, zone); } - if (command instanceof OnOffType) { + if (command instanceof OnOffType onOffCommand) { logger.debug("handleVolumeCommand OnOffType set {} {}", zone, command); - connection.setMute(((OnOffType) command) == OnOffType.ON, zone); + connection.setMute(onOffCommand == OnOffType.ON, zone); } } @@ -369,9 +369,9 @@ abstract class SonyAudioHandler extends BaseThingHandler implements SonyAudioEve throw new IOException(ex.getCause()); } } - if (command instanceof OnOffType) { + if (command instanceof OnOffType onOffCommand) { logger.debug("handleMuteCommand set {} {}", zone, command); - connection.setMute(((OnOffType) command) == OnOffType.ON, zone); + connection.setMute(onOffCommand == OnOffType.ON, zone); } } @@ -382,8 +382,8 @@ abstract class SonyAudioHandler extends BaseThingHandler implements SonyAudioEve if (command instanceof RefreshType) { updateState(channelUID, new DecimalType(currentRadioStation)); } - if (command instanceof DecimalType) { - currentRadioStation = ((DecimalType) command).intValue(); + if (command instanceof DecimalType decimalCommand) { + currentRadioStation = decimalCommand.intValue(); String radioCommand = "radio:fm?contentId=" + currentRadioStation; for (int i = 1; i <= 4; i++) { @@ -399,8 +399,8 @@ abstract class SonyAudioHandler extends BaseThingHandler implements SonyAudioEve if (command instanceof RefreshType) { updateState(channelUID, new StringType("")); } - if (command instanceof StringType) { - switch (((StringType) command).toString()) { + if (command instanceof StringType stringCommand) { + switch (stringCommand.toString()) { case "fwdSeeking": connection.radioSeekFwd(); break; @@ -420,16 +420,16 @@ abstract class SonyAudioHandler extends BaseThingHandler implements SonyAudioEve String path = (String) config.get(SonyAudioBindingConstants.SCALAR_PATH_PARAMETER); Object port_o = config.get(SonyAudioBindingConstants.SCALAR_PORT_PARAMETER); int port = 10000; - if (port_o instanceof BigDecimal) { - port = ((BigDecimal) port_o).intValue(); + if (port_o instanceof BigDecimal decimalValue) { + port = decimalValue.intValue(); } else if (port_o instanceof Integer) { port = (int) port_o; } Object refresh_o = config.get(SonyAudioBindingConstants.REFRESHINTERVAL); int refresh = 0; - if (refresh_o instanceof BigDecimal) { - refresh = ((BigDecimal) refresh_o).intValue(); + if (refresh_o instanceof BigDecimal decimalValue) { + refresh = decimalValue.intValue(); } else if (refresh_o instanceof Integer) { refresh = (int) refresh_o; } diff --git a/bundles/org.openhab.binding.sonyaudio/src/main/java/org/openhab/binding/sonyaudio/internal/handler/SrsZr5Handler.java b/bundles/org.openhab.binding.sonyaudio/src/main/java/org/openhab/binding/sonyaudio/internal/handler/SrsZr5Handler.java index 2c625e099..7fdaf5d49 100644 --- a/bundles/org.openhab.binding.sonyaudio/src/main/java/org/openhab/binding/sonyaudio/internal/handler/SrsZr5Handler.java +++ b/bundles/org.openhab.binding.sonyaudio/src/main/java/org/openhab/binding/sonyaudio/internal/handler/SrsZr5Handler.java @@ -91,7 +91,7 @@ public class SrsZr5Handler extends SonyAudioHandler { if (result != null) { logger.debug("SrsZr5Handler Updating sound field to {} {}", result.get("clearAudio"), result.get("soundField")); - if (result.get("clearAudio").equalsIgnoreCase("on")) { + if ("on".equalsIgnoreCase(result.get("clearAudio"))) { updateState(channelUID, new StringType("clearAudio")); } else { updateState(channelUID, new StringType(result.get("soundField"))); @@ -101,11 +101,11 @@ public class SrsZr5Handler extends SonyAudioHandler { throw new IOException(ex.getCause()); } } - if (command instanceof StringType) { - if (((StringType) command).toString().equalsIgnoreCase("clearAudio")) { + if (command instanceof StringType stringCommand) { + if ("clearAudio".equalsIgnoreCase(stringCommand.toString())) { connection.setSoundSettings("clearAudio", "on"); } else { - connection.setSoundSettings("soundField", ((StringType) command).toString()); + connection.setSoundSettings("soundField", stringCommand.toString()); } } } diff --git a/bundles/org.openhab.binding.sonyaudio/src/main/java/org/openhab/binding/sonyaudio/internal/handler/StrDn1080Handler.java b/bundles/org.openhab.binding.sonyaudio/src/main/java/org/openhab/binding/sonyaudio/internal/handler/StrDn1080Handler.java index 64156adb9..bd62eadf4 100644 --- a/bundles/org.openhab.binding.sonyaudio/src/main/java/org/openhab/binding/sonyaudio/internal/handler/StrDn1080Handler.java +++ b/bundles/org.openhab.binding.sonyaudio/src/main/java/org/openhab/binding/sonyaudio/internal/handler/StrDn1080Handler.java @@ -127,7 +127,7 @@ public class StrDn1080Handler extends SonyAudioHandler { if (result != null) { logger.debug("StrDn1080Handler Updateing sound field to {} {}", result.get("pureDirect"), result.get("soundField")); - if (result.get("pureDirect").equalsIgnoreCase("on")) { + if ("on".equalsIgnoreCase(result.get("pureDirect"))) { updateState(channelUID, new StringType("pureDirect")); } else { updateState(channelUID, new StringType(result.get("soundField"))); @@ -137,11 +137,11 @@ public class StrDn1080Handler extends SonyAudioHandler { throw new IOException(ex.getCause()); } } - if (command instanceof StringType) { - if (((StringType) command).toString().equalsIgnoreCase("pureDirect")) { + if (command instanceof StringType stringCommand) { + if ("pureDirect".equalsIgnoreCase(stringCommand.toString())) { connection.setSoundSettings("pureDirect", "on"); } else { - connection.setSoundSettings("soundField", ((StringType) command).toString()); + connection.setSoundSettings("soundField", stringCommand.toString()); } } } diff --git a/bundles/org.openhab.binding.sonyaudio/src/main/java/org/openhab/binding/sonyaudio/internal/protocol/SonyAudioConnection.java b/bundles/org.openhab.binding.sonyaudio/src/main/java/org/openhab/binding/sonyaudio/internal/protocol/SonyAudioConnection.java index fee53a1bb..52a355210 100644 --- a/bundles/org.openhab.binding.sonyaudio/src/main/java/org/openhab/binding/sonyaudio/internal/protocol/SonyAudioConnection.java +++ b/bundles/org.openhab.binding.sonyaudio/src/main/java/org/openhab/binding/sonyaudio/internal/protocol/SonyAudioConnection.java @@ -118,7 +118,7 @@ public class SonyAudioConnection implements SonyAudioClientSocketEventListener { } } - if (json.get("method").getAsString().equalsIgnoreCase("notifyPlayingContentInfo")) { + if ("notifyPlayingContentInfo".equalsIgnoreCase(json.get("method").getAsString())) { SonyAudioInput input = new SonyAudioInput(); input.input = param.get("uri").getAsString(); if (param.has("broadcastFreq")) { @@ -130,19 +130,19 @@ public class SonyAudioConnection implements SonyAudioClientSocketEventListener { listener.updateSeekStation(""); } - if (json.get("method").getAsString().equalsIgnoreCase("notifyVolumeInformation")) { + if ("notifyVolumeInformation".equalsIgnoreCase(json.get("method").getAsString())) { SonyAudioVolume volume = new SonyAudioVolume(); int rawVolume = param.get("volume").getAsInt(); volume.volume = Math.round(100 * (rawVolume - min_volume) / (max_volume - min_volume)); - volume.mute = param.get("mute").getAsString().equalsIgnoreCase("on"); + volume.mute = "on".equalsIgnoreCase(param.get("mute").getAsString()); listener.updateVolume(zone, volume); } - if (json.get("method").getAsString().equalsIgnoreCase("notifyPowerStatus")) { + if ("notifyPowerStatus".equalsIgnoreCase(json.get("method").getAsString())) { String power = param.get("status").getAsString(); - listener.updatePowerStatus(zone, power.equalsIgnoreCase("active")); + listener.updatePowerStatus(zone, "active".equalsIgnoreCase(power)); } listener.updateConnectionState(true); @@ -193,7 +193,7 @@ public class SonyAudioConnection implements SonyAudioClientSocketEventListener { for (Iterator iter = notifications.disabled.listIterator(); iter.hasNext();) { Notification a = iter.next(); - if (a.name.equalsIgnoreCase("notifyPlayingContentInfo")) { + if ("notifyPlayingContentInfo".equalsIgnoreCase(a.name)) { notifications.enabled.add(a); iter.remove(); } @@ -209,7 +209,7 @@ public class SonyAudioConnection implements SonyAudioClientSocketEventListener { for (Iterator iter = notifications.disabled.listIterator(); iter.hasNext();) { Notification a = iter.next(); - if (a.name.equalsIgnoreCase("notifyVolumeInformation")) { + if ("notifyVolumeInformation".equalsIgnoreCase(a.name)) { notifications.enabled.add(a); iter.remove(); } @@ -225,7 +225,7 @@ public class SonyAudioConnection implements SonyAudioClientSocketEventListener { for (Iterator iter = notifications.disabled.listIterator(); iter.hasNext();) { Notification a = iter.next(); - if (a.name.equalsIgnoreCase("notifyPowerStatus")) { + if ("notifyPowerStatus".equalsIgnoreCase(a.name)) { notifications.enabled.add(a); iter.remove(); } @@ -294,7 +294,7 @@ public class SonyAudioConnection implements SonyAudioClientSocketEventListener { JsonObject terminal = terminals.next().getAsJsonObject(); String uri = terminal.get("uri").getAsString(); if (uri.equalsIgnoreCase("extOutput:zone?zone=" + Integer.toString(zone))) { - return terminal.get("active").getAsString().equalsIgnoreCase("active") ? true : false; + return "active".equalsIgnoreCase(terminal.get("active").getAsString()) ? true : false; } } } @@ -310,7 +310,7 @@ public class SonyAudioConnection implements SonyAudioClientSocketEventListener { if (element != null && element.isJsonArray()) { String powerStatus = element.getAsJsonArray().get(0).getAsJsonObject().get("status").getAsString(); - return powerStatus.equalsIgnoreCase("active") ? true : false; + return "active".equalsIgnoreCase(powerStatus) ? true : false; } throw new IOException("Unexpected responses: Unable to parse GetPowerStatus response message"); } @@ -434,7 +434,7 @@ public class SonyAudioConnection implements SonyAudioClientSocketEventListener { ret.volume = vol; String mute = result.get("mute").getAsString(); - ret.mute = mute.equalsIgnoreCase("on") ? true : false; + ret.mute = "on".equalsIgnoreCase(mute) ? true : false; return ret; } diff --git a/bundles/org.openhab.binding.sonyprojector/src/main/java/org/openhab/binding/sonyprojector/internal/handler/SonyProjectorHandler.java b/bundles/org.openhab.binding.sonyprojector/src/main/java/org/openhab/binding/sonyprojector/internal/handler/SonyProjectorHandler.java index 07ffde54a..006c2925d 100644 --- a/bundles/org.openhab.binding.sonyprojector/src/main/java/org/openhab/binding/sonyprojector/internal/handler/SonyProjectorHandler.java +++ b/bundles/org.openhab.binding.sonyprojector/src/main/java/org/openhab/binding/sonyprojector/internal/handler/SonyProjectorHandler.java @@ -156,46 +156,46 @@ public class SonyProjectorHandler extends BaseThingHandler { refreshChannel(CHANNEL_XVCOLOR, true); break; case CHANNEL_CONTRAST: - if (command instanceof DecimalType) { - connector.setContrast(((DecimalType) command).intValue()); - } else if (command instanceof PercentType) { - connector.setContrast(((PercentType) command).intValue()); + if (command instanceof DecimalType decimalCommand) { + connector.setContrast(decimalCommand.intValue()); + } else if (command instanceof PercentType percentCommand) { + connector.setContrast(percentCommand.intValue()); } else { throw new SonyProjectorException("Invalid command value"); } break; case CHANNEL_BRIGHTNESS: - if (command instanceof DecimalType) { - connector.setBrightness(((DecimalType) command).intValue()); - } else if (command instanceof PercentType) { - connector.setBrightness(((PercentType) command).intValue()); + if (command instanceof DecimalType decimalCommand) { + connector.setBrightness(decimalCommand.intValue()); + } else if (command instanceof PercentType percentCommand2) { + connector.setBrightness(percentCommand2.intValue()); } else { throw new SonyProjectorException("Invalid command value"); } break; case CHANNEL_COLOR: - if (command instanceof DecimalType) { - connector.setColor(((DecimalType) command).intValue()); - } else if (command instanceof PercentType) { - connector.setColor(((PercentType) command).intValue()); + if (command instanceof DecimalType decimalCommand) { + connector.setColor(decimalCommand.intValue()); + } else if (command instanceof PercentType percentCommand3) { + connector.setColor(percentCommand3.intValue()); } else { throw new SonyProjectorException("Invalid command value"); } break; case CHANNEL_HUE: - if (command instanceof DecimalType) { - connector.setHue(((DecimalType) command).intValue()); - } else if (command instanceof PercentType) { - connector.setHue(((PercentType) command).intValue()); + if (command instanceof DecimalType decimalCommand) { + connector.setHue(decimalCommand.intValue()); + } else if (command instanceof PercentType percentCommand4) { + connector.setHue(percentCommand4.intValue()); } else { throw new SonyProjectorException("Invalid command value"); } break; case CHANNEL_SHARPNESS: - if (command instanceof DecimalType) { - connector.setSharpness(((DecimalType) command).intValue()); - } else if (command instanceof PercentType) { - connector.setSharpness(((PercentType) command).intValue()); + if (command instanceof DecimalType decimalCommand) { + connector.setSharpness(decimalCommand.intValue()); + } else if (command instanceof PercentType percentCommand5) { + connector.setSharpness(percentCommand5.intValue()); } else { throw new SonyProjectorException("Invalid command value"); } @@ -208,10 +208,10 @@ public class SonyProjectorHandler extends BaseThingHandler { refreshChannel(CHANNEL_IRIS_MANUAL, true); break; case CHANNEL_IRIS_MANUAL: - if (command instanceof DecimalType) { - connector.setIrisManual(((DecimalType) command).intValue()); - } else if (command instanceof PercentType) { - connector.setIrisManual(((PercentType) command).intValue()); + if (command instanceof DecimalType decimalCommand) { + connector.setIrisManual(decimalCommand.intValue()); + } else if (command instanceof PercentType percentCommand6) { + connector.setIrisManual(percentCommand6.intValue()); } else { throw new SonyProjectorException("Invalid command value"); } diff --git a/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/discovery/SoulissGatewayDiscovery.java b/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/discovery/SoulissGatewayDiscovery.java index 5ade569be..0c40fbe39 100644 --- a/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/discovery/SoulissGatewayDiscovery.java +++ b/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/discovery/SoulissGatewayDiscovery.java @@ -263,8 +263,7 @@ public class SoulissGatewayDiscovery extends AbstractDiscoveryService @Override public void setThingHandler(ThingHandler handler) { - if (handler instanceof SoulissGatewayHandler) { - SoulissGatewayHandler localGwHandler = (SoulissGatewayHandler) handler; + if (handler instanceof SoulissGatewayHandler localGwHandler) { this.soulissGwHandler = localGwHandler; localGwHandler.discoverResult = this; } diff --git a/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissGatewayHandler.java b/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissGatewayHandler.java index 476d5e3a0..19986eebe 100644 --- a/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissGatewayHandler.java +++ b/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissGatewayHandler.java @@ -13,7 +13,7 @@ package org.openhab.binding.souliss.internal.handler; import java.util.Collection; -import java.util.Collections; +import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; @@ -94,7 +94,7 @@ public class SoulissGatewayHandler extends BaseBridgeHandler { @Override public Collection> getServices() { - return Collections.singleton(SoulissGatewayDiscovery.class); + return Set.of(SoulissGatewayDiscovery.class); } @Override diff --git a/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT13Handler.java b/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT13Handler.java index 3a8f52177..e30c80c0e 100644 --- a/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT13Handler.java +++ b/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT13Handler.java @@ -51,12 +51,12 @@ public class SoulissT13Handler extends SoulissGenericHandler { public void setState(@Nullable PrimitiveType state) { super.setLastStatusStored(); if (state != null) { - if (state instanceof OnOffType) { - this.updateState(SoulissBindingConstants.STATEONOFF_CHANNEL, (OnOffType) state); + if (state instanceof OnOffType onOffCommand) { + this.updateState(SoulissBindingConstants.STATEONOFF_CHANNEL, onOffCommand); } - if (state instanceof OpenClosedType) { - this.updateState(SoulissBindingConstants.STATEOPENCLOSE_CHANNEL, (OpenClosedType) state); + if (state instanceof OpenClosedType openClosedCommand) { + this.updateState(SoulissBindingConstants.STATEOPENCLOSE_CHANNEL, openClosedCommand); } } } diff --git a/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT16Handler.java b/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT16Handler.java index c6822f9a6..d3f4202ea 100644 --- a/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT16Handler.java +++ b/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT16Handler.java @@ -126,9 +126,7 @@ public class SoulissT16Handler extends SoulissGenericHandler { break; case SoulissBindingConstants.LED_COLOR_CHANNEL: - if (command instanceof HSBType) { - HSBType localHsbState = (HSBType) command; - + if (command instanceof HSBType localHsbState) { updateState(SoulissBindingConstants.DIMMER_BRIGHTNESS_CHANNEL, PercentType.valueOf(hsbState.getBrightness().toString())); commandSendRgb(SoulissProtocolConstants.SOULISS_T1N_SET, diff --git a/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT19Handler.java b/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT19Handler.java index cb1fc1d47..3b56b1586 100644 --- a/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT19Handler.java +++ b/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT19Handler.java @@ -79,10 +79,10 @@ public class SoulissT19Handler extends SoulissGenericHandler { break; case SoulissBindingConstants.DIMMER_BRIGHTNESS_CHANNEL: - if (command instanceof PercentType) { - updateState(SoulissBindingConstants.DIMMER_BRIGHTNESS_CHANNEL, (PercentType) command); + if (command instanceof PercentType percentCommand) { + updateState(SoulissBindingConstants.DIMMER_BRIGHTNESS_CHANNEL, percentCommand); commandSEND(SoulissProtocolConstants.SOULISS_T1N_SET, - (byte) (((PercentType) command).shortValue() * 255.00 / 100.00)); + (byte) (percentCommand.shortValue() * 255.00 / 100.00)); } else if (command.equals(OnOffType.ON)) { commandSEND(SoulissProtocolConstants.SOULISS_T1N_ON_CMD); diff --git a/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT22Handler.java b/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT22Handler.java index ebfd78bbc..d0112b2a5 100644 --- a/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT22Handler.java +++ b/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT22Handler.java @@ -88,8 +88,8 @@ public class SoulissT22Handler extends SoulissGenericHandler { } public void setState(PrimitiveType state) { - if (state instanceof PercentType) { - this.updateState(SoulissBindingConstants.ROLLERSHUTTER_CHANNEL, (PercentType) state); + if (state instanceof PercentType percentCommand) { + this.updateState(SoulissBindingConstants.ROLLERSHUTTER_CHANNEL, percentCommand); } } diff --git a/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT31Handler.java b/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT31Handler.java index 63eaad822..967b09be6 100644 --- a/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT31Handler.java +++ b/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT31Handler.java @@ -119,8 +119,8 @@ public class SoulissT31Handler extends SoulissGenericHandler { } break; case SoulissBindingConstants.T31_SETPOINT_CHANNEL: - if (command instanceof QuantityType) { - int uu = HalfFloatUtils.fromFloat(((QuantityType) command).floatValue()); + if (command instanceof QuantityType quantityCommand) { + int uu = HalfFloatUtils.fromFloat(quantityCommand.floatValue()); byte b2 = (byte) (uu >> 8); byte b1 = (byte) uu; // setpoint command @@ -151,7 +151,7 @@ public class SoulissT31Handler extends SoulissGenericHandler { this.updateState(SoulissBindingConstants.T31_BUTTON_CHANNEL, OnOffType.OFF); super.setLastStatusStored(); - if (state instanceof StringType) { + if (state instanceof StringType stringState) { switch (state.toString()) { case SoulissBindingConstants.T31_FANLOW_MESSAGE_FAN_CHANNEL: case SoulissBindingConstants.T31_FANMEDIUM_MESSAGE_FAN_CHANNEL: @@ -159,48 +159,48 @@ public class SoulissT31Handler extends SoulissGenericHandler { case SoulissBindingConstants.T31_FANAUTO_MESSAGE_FAN_CHANNEL: case SoulissBindingConstants.T31_FANOFF_MESSAGE_FAN_CHANNEL: if (!fanStateValue.equals(state)) { - this.updateState(SoulissBindingConstants.T31_FAN_CHANNEL, (StringType) state); - fanStateValue = (StringType) state; + this.updateState(SoulissBindingConstants.T31_FAN_CHANNEL, stringState); + fanStateValue = stringState; } break; case SoulissBindingConstants.T31_HEATINGMODE_MESSAGE_MODE_CHANNEL: if (!modeStateValue.equals(state)) { - this.updateState(SoulissBindingConstants.T31_MODE_CHANNEL, (StringType) state); - modeStateValue = (StringType) state; + this.updateState(SoulissBindingConstants.T31_MODE_CHANNEL, stringState); + modeStateValue = stringState; } break; case SoulissBindingConstants.T31_COOLINGMODE_MESSAGE_MODE_CHANNEL: if (!modeStateValue.equals(state)) { - this.updateState(SoulissBindingConstants.T31_MODE_CHANNEL, (StringType) state); - modeStateValue = (StringType) state; + this.updateState(SoulissBindingConstants.T31_MODE_CHANNEL, stringState); + modeStateValue = stringState; } break; case SoulissBindingConstants.T31_OFF_MESSAGE_SYSTEM_CHANNEL: if (!powerState.equals(state)) { this.updateState(SoulissBindingConstants.T31_SYSTEM_CHANNEL, OnOffType.OFF); - powerState = (StringType) state; + powerState = stringState; } break; case SoulissBindingConstants.T31_ON_MESSAGE_SYSTEM_CHANNEL: if (!powerState.equals(state)) { this.updateState(SoulissBindingConstants.T31_SYSTEM_CHANNEL, OnOffType.ON); - powerState = (StringType) state; + powerState = stringState; } break; case SoulissBindingConstants.T31_ON_MESSAGE_FIRE_CHANNEL: if (!fireState.equals(state)) { this.updateState(SoulissBindingConstants.T31_FIRE_CHANNEL, OnOffType.ON); - fireState = (StringType) state; + fireState = stringState; } break; case SoulissBindingConstants.T31_OFF_MESSAGE_FIRE_CHANNEL: if (!fireState.equals(state)) { this.updateState(SoulissBindingConstants.T31_FIRE_CHANNEL, OnOffType.OFF); - fireState = (StringType) state; + fireState = stringState; } break; diff --git a/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT41Handler.java b/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT41Handler.java index 6b30284d6..2e893fd01 100644 --- a/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT41Handler.java +++ b/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT41Handler.java @@ -75,8 +75,8 @@ public class SoulissT41Handler extends SoulissGenericHandler { } public void setState(PrimitiveType state) { - if (state instanceof OnOffType) { - this.updateState(SoulissBindingConstants.T4N_ONOFFALARM_CHANNEL, (OnOffType) state); + if (state instanceof OnOffType onOffState) { + this.updateState(SoulissBindingConstants.T4N_ONOFFALARM_CHANNEL, onOffState); } else if (state instanceof StringType) { switch (String.valueOf(state)) { case SoulissBindingConstants.T4N_ALARMON_MESSAGE_CHANNEL: diff --git a/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT6nHandler.java b/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT6nHandler.java index 5cfe04208..d338f17af 100644 --- a/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT6nHandler.java +++ b/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/handler/SoulissT6nHandler.java @@ -40,8 +40,8 @@ public class SoulissT6nHandler extends SoulissGenericHandler { @Override public void handleCommand(ChannelUID channelUID, Command command) { - if (command instanceof DecimalType) { - int uu = HalfFloatUtils.fromFloat(((DecimalType) command).floatValue()); + if (command instanceof DecimalType decimalCommand) { + int uu = HalfFloatUtils.fromFloat(decimalCommand.floatValue()); byte b2 = (byte) (uu >> 8); byte b1 = (byte) uu; // setpoint command diff --git a/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/protocol/SendDispatcherRunnable.java b/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/protocol/SendDispatcherRunnable.java index 38da8a39f..8338b6e69 100644 --- a/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/protocol/SendDispatcherRunnable.java +++ b/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/protocol/SendDispatcherRunnable.java @@ -136,7 +136,7 @@ public class SendDispatcherRunnable implements Runnable { public void run() { DatagramSocket sender = null; - try (var channel = DatagramChannel.open();) { + try (var channel = DatagramChannel.open()) { if (checkTime()) { PacketStruct sp = pop(); if (sp != null) { diff --git a/bundles/org.openhab.binding.speedtest/src/main/java/org/openhab/binding/speedtest/internal/SpeedtestHandler.java b/bundles/org.openhab.binding.speedtest/src/main/java/org/openhab/binding/speedtest/internal/SpeedtestHandler.java index 3b09827bc..6c43ef3cf 100644 --- a/bundles/org.openhab.binding.speedtest/src/main/java/org/openhab/binding/speedtest/internal/SpeedtestHandler.java +++ b/bundles/org.openhab.binding.speedtest/src/main/java/org/openhab/binding/speedtest/internal/SpeedtestHandler.java @@ -210,7 +210,7 @@ public class SpeedtestHandler extends BaseThingHandler { if ((versionString != null) && !versionString.isEmpty()) { int newLI = versionString.indexOf(System.lineSeparator()); String versionLine = versionString.substring(0, newLI); - if (versionString.indexOf("Speedtest by Ookla") > -1) { + if (versionString.contains("Speedtest by Ookla")) { logger.debug("Speedtest Version: {}", versionLine); return true; } else { @@ -285,7 +285,7 @@ public class SpeedtestHandler extends BaseThingHandler { ResultContainer tmpCont = doExecuteRequest(" -f json --accept-license --accept-gdpr" + postCommand, ResultContainer.class); if (tmpCont != null) { - if (tmpCont.getType().equals("result")) { + if ("result".equals(tmpCont.getType())) { pingJitter = tmpCont.getPing().getJitter(); pingLatency = tmpCont.getPing().getLatency(); downloadBandwidth = tmpCont.getDownload().getBandwidth(); @@ -365,15 +365,13 @@ public class SpeedtestHandler extends BaseThingHandler { updateState(new ChannelUID(getThing().getUID(), SpeedtestBindingConstants.UPLOAD_ELAPSED), newState); updateState(new ChannelUID(getThing().getUID(), SpeedtestBindingConstants.INTERFACE_EXTERNALIP), - new StringType(String.valueOf(interfaceExternalIp))); + new StringType(interfaceExternalIp)); updateState(new ChannelUID(getThing().getUID(), SpeedtestBindingConstants.INTERFACE_INTERNALIP), - new StringType(String.valueOf(interfaceInternalIp))); - updateState(new ChannelUID(getThing().getUID(), SpeedtestBindingConstants.ISP), - new StringType(String.valueOf(isp))); + new StringType(interfaceInternalIp)); + updateState(new ChannelUID(getThing().getUID(), SpeedtestBindingConstants.ISP), new StringType(isp)); updateState(new ChannelUID(getThing().getUID(), SpeedtestBindingConstants.RESULT_URL), - new StringType(String.valueOf(resultUrl))); - updateState(new ChannelUID(getThing().getUID(), SpeedtestBindingConstants.SERVER), - new StringType(String.valueOf(server))); + new StringType(resultUrl)); + updateState(new ChannelUID(getThing().getUID(), SpeedtestBindingConstants.SERVER), new StringType(server)); } /** @@ -489,8 +487,7 @@ public class SpeedtestHandler extends BaseThingHandler { } else { logger.debug("Splitting by spaces"); try { - String[] splitCmd = commandLine.split(" "); - return splitCmd; + return commandLine.split(" "); } catch (PatternSyntaxException e) { logger.warn("An exception occurred while splitting '{}': '{}'", commandLine, e.getMessage()); return new String[] {}; diff --git a/bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/SpotifyHandlerFactory.java b/bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/SpotifyHandlerFactory.java index ce8e46e73..a3d450ecf 100644 --- a/bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/SpotifyHandlerFactory.java +++ b/bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/SpotifyHandlerFactory.java @@ -81,8 +81,8 @@ public class SpotifyHandlerFactory extends BaseThingHandlerFactory { @Override protected synchronized void removeHandler(ThingHandler thingHandler) { - if (thingHandler instanceof SpotifyBridgeHandler) { - authService.removeSpotifyAccountHandler((SpotifyBridgeHandler) thingHandler); + if (thingHandler instanceof SpotifyBridgeHandler bridgeHandler) { + authService.removeSpotifyAccountHandler(bridgeHandler); } } } diff --git a/bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/api/SpotifyConnector.java b/bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/api/SpotifyConnector.java index 1328cd1e7..7538bee8f 100644 --- a/bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/api/SpotifyConnector.java +++ b/bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/api/SpotifyConnector.java @@ -87,8 +87,8 @@ class SpotifyConnector { } catch (ExecutionException e) { final Throwable cause = e.getCause(); - if (cause instanceof RuntimeException) { - throw (RuntimeException) cause; + if (cause instanceof RuntimeException runtimeException) { + throw runtimeException; } else { throw new SpotifyException(e.getMessage(), e); } diff --git a/bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/discovery/SpotifyDeviceDiscoveryService.java b/bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/discovery/SpotifyDeviceDiscoveryService.java index 9109d2f51..eb5576ded 100644 --- a/bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/discovery/SpotifyDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/discovery/SpotifyDeviceDiscoveryService.java @@ -16,7 +16,6 @@ import static org.openhab.binding.spotify.internal.SpotifyBindingConstants.PROPE import static org.openhab.binding.spotify.internal.SpotifyBindingConstants.THING_TYPE_DEVICE; import java.time.Duration; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -52,7 +51,7 @@ public class SpotifyDeviceDiscoveryService extends AbstractDiscoveryService // id for device is derived by stripping id of device with this length private static final int PLAYER_ID_LENGTH = 4; // Only devices can be discovered. A bridge must be manually added. - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_DEVICE); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_DEVICE); // The call to listDevices is fast private static final int DISCOVERY_TIME_SECONDS = 10; // Check every minute for new devices @@ -90,8 +89,8 @@ public class SpotifyDeviceDiscoveryService extends AbstractDiscoveryService @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof SpotifyAccountHandler) { - bridgeHandler = (SpotifyAccountHandler) handler; + if (handler instanceof SpotifyAccountHandler accountHandler) { + bridgeHandler = accountHandler; bridgeUID = bridgeHandler.getUID(); } } diff --git a/bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/handler/SpotifyHandleCommands.java b/bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/handler/SpotifyHandleCommands.java index b36ad152c..b118a2392 100644 --- a/bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/handler/SpotifyHandleCommands.java +++ b/bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/handler/SpotifyHandleCommands.java @@ -101,8 +101,8 @@ class SpotifyHandleCommands { commandRun = handleDevicePlay(command, active, deviceId); break; case CHANNEL_DEVICESHUFFLE: - if (command instanceof OnOffType) { - spotifyApi.setShuffleState(deviceId, (OnOffType) command); + if (command instanceof OnOffType onOffCommand) { + spotifyApi.setShuffleState(deviceId, onOffCommand); commandRun = true; } break; @@ -112,9 +112,9 @@ class SpotifyHandleCommands { commandRun = true; } case CHANNEL_DEVICEVOLUME: - if (command instanceof DecimalType) { - final PercentType volume = command instanceof PercentType ? (PercentType) command - : new PercentType(((DecimalType) command).intValue()); + if (command instanceof DecimalType decimalCommand) { + final PercentType volume = command instanceof PercentType percentType ? percentType + : new PercentType(decimalCommand.intValue()); spotifyApi.setVolume(deviceId, volume.intValue()); commandRun = true; diff --git a/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/SqueezeBoxAudioSink.java b/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/SqueezeBoxAudioSink.java index 6fdf586b1..a52232938 100644 --- a/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/SqueezeBoxAudioSink.java +++ b/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/SqueezeBoxAudioSink.java @@ -88,8 +88,8 @@ public class SqueezeBoxAudioSink extends AudioSinkSync { } String url; - if (audioStream instanceof URLAudioStream) { - url = ((URLAudioStream) audioStream).getURL(); + if (audioStream instanceof URLAudioStream urlAudioStream) { + url = urlAudioStream.getURL(); tryClose(audioStream); } else { try { diff --git a/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/SqueezeBoxHandlerFactory.java b/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/SqueezeBoxHandlerFactory.java index d43ada5c5..31d1ec9df 100644 --- a/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/SqueezeBoxHandlerFactory.java +++ b/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/SqueezeBoxHandlerFactory.java @@ -149,7 +149,7 @@ public class SqueezeBoxHandlerFactory extends BaseThingHandlerFactory { @Override protected synchronized void removeHandler(ThingHandler thingHandler) { - if (thingHandler instanceof SqueezeBoxServerHandler) { + if (thingHandler instanceof SqueezeBoxServerHandler serverHandler) { logger.trace("removing handler for bridge thing {}", thingHandler.getThing()); ServiceRegistration serviceReg = this.discoveryServiceRegs.get(thingHandler.getThing().getUID()); @@ -162,7 +162,7 @@ public class SqueezeBoxHandlerFactory extends BaseThingHandlerFactory { discoveryService.cancelRequestPlayerJob(); // Unregister the PlayerListener from the SqueezeBoxServerHandler - ((SqueezeBoxServerHandler) thingHandler).unregisterSqueezeBoxPlayerListener( + serverHandler.unregisterSqueezeBoxPlayerListener( (SqueezeBoxPlayerEventListener) bundleContext.getService(serviceReg.getReference())); // Unregister the PlayerListener service @@ -173,8 +173,8 @@ public class SqueezeBoxHandlerFactory extends BaseThingHandlerFactory { } } - if (thingHandler instanceof SqueezeBoxPlayerHandler) { - SqueezeBoxServerHandler bridge = ((SqueezeBoxPlayerHandler) thingHandler).getSqueezeBoxServerHandler(); + if (thingHandler instanceof SqueezeBoxPlayerHandler playerHandler) { + SqueezeBoxServerHandler bridge = playerHandler.getSqueezeBoxServerHandler(); if (bridge != null) { // Unregister the player's audio sink logger.trace("Unregistering the audio sync service for player thing {}", @@ -186,7 +186,7 @@ public class SqueezeBoxHandlerFactory extends BaseThingHandlerFactory { } logger.trace("removing handler for player thing {}", thingHandler.getThing()); - bridge.removePlayerCache(((SqueezeBoxPlayerHandler) thingHandler).getMac()); + bridge.removePlayerCache(playerHandler.getMac()); } } } diff --git a/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/discovery/SqueezeBoxServerDiscoveryParticipant.java b/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/discovery/SqueezeBoxServerDiscoveryParticipant.java index 302ad69ff..fce31a41d 100644 --- a/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/discovery/SqueezeBoxServerDiscoveryParticipant.java +++ b/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/discovery/SqueezeBoxServerDiscoveryParticipant.java @@ -15,7 +15,6 @@ package org.openhab.binding.squeezebox.internal.discovery; import static org.openhab.binding.squeezebox.internal.SqueezeBoxBindingConstants.SQUEEZEBOXSERVER_THING_TYPE; import java.net.URI; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -51,7 +50,7 @@ public class SqueezeBoxServerDiscoveryParticipant implements UpnpDiscoveryPartic @Override public Set getSupportedThingTypeUIDs() { - return Collections.singleton(SQUEEZEBOXSERVER_THING_TYPE); + return Set.of(SQUEEZEBOXSERVER_THING_TYPE); } @Override diff --git a/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/handler/SqueezeBoxNotificationListener.java b/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/handler/SqueezeBoxNotificationListener.java index d75bca01e..a25390ab2 100644 --- a/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/handler/SqueezeBoxNotificationListener.java +++ b/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/handler/SqueezeBoxNotificationListener.java @@ -105,12 +105,12 @@ public final class SqueezeBoxNotificationListener implements SqueezeBoxPlayerEve } logger.trace("Mode is {} for player {}", mode, mac); - if (mode.equals("play")) { + if ("play".equals(mode)) { this.started.set(true); - } else if (this.started.get() && mode.equals("stop")) { + } else if (this.started.get() && "stop".equals(mode)) { this.stopped.set(true); } - if (mode.equals("pause")) { + if ("pause".equals(mode)) { this.paused.set(true); } } diff --git a/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/handler/SqueezeBoxPlayerHandler.java b/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/handler/SqueezeBoxPlayerHandler.java index 217544e3a..e87043514 100644 --- a/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/handler/SqueezeBoxPlayerHandler.java +++ b/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/handler/SqueezeBoxPlayerHandler.java @@ -73,8 +73,7 @@ import org.slf4j.LoggerFactory; public class SqueezeBoxPlayerHandler extends BaseThingHandler implements SqueezeBoxPlayerEventListener { private final Logger logger = LoggerFactory.getLogger(SqueezeBoxPlayerHandler.class); - public static final Set SUPPORTED_THING_TYPES_UIDS = Collections - .singleton(SQUEEZEBOXPLAYER_THING_TYPE); + public static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(SQUEEZEBOXPLAYER_THING_TYPE); /** * We need to remember some states to change offsets in volume, time index, @@ -244,8 +243,8 @@ public class SqueezeBoxPlayerHandler extends BaseThingHandler implements Squeeze } break; case CHANNEL_VOLUME: - if (command instanceof PercentType) { - squeezeBoxServerHandler.setVolume(mac, ((PercentType) command).intValue()); + if (command instanceof PercentType percentCommand) { + squeezeBoxServerHandler.setVolume(mac, percentCommand.intValue()); } else if (command.equals(IncreaseDecreaseType.INCREASE)) { squeezeBoxServerHandler.volumeUp(mac, currentVolume()); } else if (command.equals(IncreaseDecreaseType.DECREASE)) { @@ -317,8 +316,8 @@ public class SqueezeBoxPlayerHandler extends BaseThingHandler implements Squeeze } break; case CHANNEL_SLEEP: - if (command instanceof DecimalType) { - Duration sleepDuration = Duration.ofMinutes(((DecimalType) command).longValue()); + if (command instanceof DecimalType decimalCommand) { + Duration sleepDuration = Duration.ofMinutes(decimalCommand.longValue()); if (sleepDuration.isNegative() || sleepDuration.compareTo(Duration.ofDays(1)) > 0) { logger.debug("Sleep timer of {} minutes must be >= 0 and <= 1 day", sleepDuration.toMinutes()); return; @@ -647,7 +646,7 @@ public class SqueezeBoxPlayerHandler extends BaseThingHandler implements Squeeze private int cachedStateAsInt(String key) { State state = stateMap.get(key); - return state instanceof DecimalType ? ((DecimalType) state).intValue() : 0; + return state instanceof DecimalType decimalValue ? decimalValue.intValue() : 0; } /** diff --git a/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/handler/SqueezeBoxServerHandler.java b/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/handler/SqueezeBoxServerHandler.java index 53fb46cd6..72cf92376 100644 --- a/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/handler/SqueezeBoxServerHandler.java +++ b/bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/handler/SqueezeBoxServerHandler.java @@ -84,8 +84,7 @@ import com.google.gson.JsonSyntaxException; public class SqueezeBoxServerHandler extends BaseBridgeHandler { private final Logger logger = LoggerFactory.getLogger(SqueezeBoxServerHandler.class); - public static final Set SUPPORTED_THING_TYPES_UIDS = Collections - .singleton(SQUEEZEBOXSERVER_THING_TYPE); + public static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(SQUEEZEBOXSERVER_THING_TYPE); // time in seconds to try to reconnect private static final int RECONNECT_TIME = 60; @@ -262,7 +261,7 @@ public class SqueezeBoxServerHandler extends BaseBridgeHandler { int newVolume = volume; newVolume = Math.min(100, newVolume); newVolume = Math.max(0, newVolume); - sendCommand(mac + " mixer volume " + String.valueOf(newVolume)); + sendCommand(mac + " mixer volume " + newVolume); } public void showString(String mac, String line) { @@ -270,7 +269,7 @@ public class SqueezeBoxServerHandler extends BaseBridgeHandler { } public void showString(String mac, String line, int duration) { - sendCommand(mac + " show line1:" + line + " duration:" + String.valueOf(duration)); + sendCommand(mac + " show line1:" + line + " duration:" + duration); } public void showStringHuge(String mac, String line) { @@ -278,7 +277,7 @@ public class SqueezeBoxServerHandler extends BaseBridgeHandler { } public void showStringHuge(String mac, String line, int duration) { - sendCommand(mac + " show line1:" + line + " font:huge duration:" + String.valueOf(duration)); + sendCommand(mac + " show line1:" + line + " font:huge duration:" + duration); } public void showStrings(String mac, String line1, String line2) { @@ -286,7 +285,7 @@ public class SqueezeBoxServerHandler extends BaseBridgeHandler { } public void showStrings(String mac, String line1, String line2, int duration) { - sendCommand(mac + " show line1:" + line1 + " line2:" + line2 + " duration:" + String.valueOf(duration)); + sendCommand(mac + " show line1:" + line1 + " line2:" + line2 + " duration:" + duration); } public void playFavorite(String mac, String favorite) { @@ -300,7 +299,7 @@ public class SqueezeBoxServerHandler extends BaseBridgeHandler { } public void sleep(String mac, Duration sleepDuration) { - sendCommand(mac + " sleep " + String.valueOf(sleepDuration.toSeconds())); + sendCommand(mac + " sleep " + sleepDuration.toSeconds()); } /** @@ -856,18 +855,18 @@ public class SqueezeBoxServerHandler extends BaseBridgeHandler { } String action = messageParts[2]; String mode; - if (action.equals("newsong")) { + if ("newsong".equals(action)) { mode = "play"; // Execute in separate thread to avoid delaying listener scheduler.execute(() -> updateCustomButtons(mac)); // Set the track duration to 0 updatePlayer(listener -> listener.durationEvent(mac, 0)); - } else if (action.equals("pause")) { + } else if ("pause".equals(action)) { if (messageParts.length < 4) { return; } - mode = messageParts[3].equals("0") ? "play" : "pause"; - } else if (action.equals("stop")) { + mode = "0".equals(messageParts[3]) ? "play" : "pause"; + } else if ("stop".equals(action)) { mode = "stop"; } else if ("play".equals(action) && "playlist".equals(messageParts[1])) { if (messageParts.length >= 4) { @@ -884,7 +883,7 @@ public class SqueezeBoxServerHandler extends BaseBridgeHandler { } private void handleSourceChangeMessage(String mac, String rawSource) { - String source = URLDecoder.decode(rawSource); + String source = URLDecoder.decode(rawSource, StandardCharsets.UTF_8); updatePlayer(listener -> listener.sourceChangeEvent(mac, source)); } @@ -893,13 +892,13 @@ public class SqueezeBoxServerHandler extends BaseBridgeHandler { return; } // server prefsets - if (messageParts[2].equals("server")) { + if ("server".equals(messageParts[2])) { String function = messageParts[3]; String value = messageParts[4]; - if (function.equals("power")) { - final boolean power = value.equals("1"); + if ("power".equals(function)) { + final boolean power = "1".equals(value); updatePlayer(listener -> listener.powerChangeEvent(mac, power)); - } else if (function.equals("volume")) { + } else if ("volume".equals(function)) { final int volume = (int) Double.parseDouble(value); updatePlayer(listener -> listener.absoluteVolumeChangeEvent(mac, volume)); } @@ -967,7 +966,7 @@ public class SqueezeBoxServerHandler extends BaseBridgeHandler { String quote = includeQuotes.booleanValue() ? "\"" : ""; StringBuilder sb = new StringBuilder(); for (Favorite favorite : favorites) { - sb.append(favorite.shortId).append("=").append(quote).append(favorite.name.replaceAll(",", "")) + sb.append(favorite.shortId).append("=").append(quote).append(favorite.name.replace(",", "")) .append(quote).append(","); } @@ -1063,8 +1062,9 @@ public class SqueezeBoxServerHandler extends BaseBridgeHandler { List things = bridge.getThings(); for (Thing thing : things) { ThingHandler handler = thing.getHandler(); - if (handler instanceof SqueezeBoxPlayerEventListener && !squeezeBoxPlayerListeners.contains(handler)) { - event.updateListener((SqueezeBoxPlayerEventListener) handler); + if (handler instanceof SqueezeBoxPlayerEventListener playerEventListener + && !squeezeBoxPlayerListeners.contains(handler)) { + event.updateListener(playerEventListener); } } } diff --git a/bundles/org.openhab.binding.surepetcare/src/main/java/org/openhab/binding/surepetcare/internal/SurePetcareConstants.java b/bundles/org.openhab.binding.surepetcare/src/main/java/org/openhab/binding/surepetcare/internal/SurePetcareConstants.java index 13a474203..643352e0f 100644 --- a/bundles/org.openhab.binding.surepetcare/src/main/java/org/openhab/binding/surepetcare/internal/SurePetcareConstants.java +++ b/bundles/org.openhab.binding.surepetcare/src/main/java/org/openhab/binding/surepetcare/internal/SurePetcareConstants.java @@ -16,7 +16,6 @@ import java.time.LocalDate; import java.time.LocalTime; import java.time.ZonedDateTime; import java.util.Arrays; -import java.util.Collections; import java.util.HashSet; import java.util.Set; @@ -48,7 +47,7 @@ public class SurePetcareConstants { public static final ThingTypeUID THING_TYPE_FLAP_DEVICE = new ThingTypeUID(BINDING_ID, "flapDevice"); public static final ThingTypeUID THING_TYPE_FEEDER_DEVICE = new ThingTypeUID(BINDING_ID, "feederDevice"); - public static final Set BRIDGE_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_BRIDGE); + public static final Set BRIDGE_THING_TYPES_UIDS = Set.of(THING_TYPE_BRIDGE); public static final Set SUPPORTED_THING_TYPES_UIDS = new HashSet<>(Arrays.asList(THING_TYPE_HOUSEHOLD, THING_TYPE_PET, THING_TYPE_HUB_DEVICE, THING_TYPE_FLAP_DEVICE, THING_TYPE_FEEDER_DEVICE)); diff --git a/bundles/org.openhab.binding.surepetcare/src/main/java/org/openhab/binding/surepetcare/internal/discovery/SurePetcareDiscoveryService.java b/bundles/org.openhab.binding.surepetcare/src/main/java/org/openhab/binding/surepetcare/internal/discovery/SurePetcareDiscoveryService.java index e350eb06c..89e6ec1a2 100644 --- a/bundles/org.openhab.binding.surepetcare/src/main/java/org/openhab/binding/surepetcare/internal/discovery/SurePetcareDiscoveryService.java +++ b/bundles/org.openhab.binding.surepetcare/src/main/java/org/openhab/binding/surepetcare/internal/discovery/SurePetcareDiscoveryService.java @@ -14,7 +14,6 @@ package org.openhab.binding.surepetcare.internal.discovery; import static org.openhab.binding.surepetcare.internal.SurePetcareConstants.*; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -51,7 +50,7 @@ public class SurePetcareDiscoveryService extends AbstractDiscoveryService private final Logger logger = LoggerFactory.getLogger(SurePetcareDiscoveryService.class); - private static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_BRIDGE); + private static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_BRIDGE); private static final int DISCOVER_TIMEOUT_SECONDS = 5; private static final int DISCOVERY_SCAN_DELAY_MINUTES = 1; diff --git a/bundles/org.openhab.binding.surepetcare/src/main/java/org/openhab/binding/surepetcare/internal/handler/SurePetcareBridgeHandler.java b/bundles/org.openhab.binding.surepetcare/src/main/java/org/openhab/binding/surepetcare/internal/handler/SurePetcareBridgeHandler.java index abd28ca55..853c1acc7 100644 --- a/bundles/org.openhab.binding.surepetcare/src/main/java/org/openhab/binding/surepetcare/internal/handler/SurePetcareBridgeHandler.java +++ b/bundles/org.openhab.binding.surepetcare/src/main/java/org/openhab/binding/surepetcare/internal/handler/SurePetcareBridgeHandler.java @@ -15,8 +15,8 @@ package org.openhab.binding.surepetcare.internal.handler; import static org.openhab.binding.surepetcare.internal.SurePetcareConstants.*; import java.util.Collection; -import java.util.Collections; import java.util.Map; +import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -113,7 +113,7 @@ public class SurePetcareBridgeHandler extends BaseBridgeHandler { @Override public Collection> getServices() { - return Collections.singleton(SurePetcareDiscoveryService.class); + return Set.of(SurePetcareDiscoveryService.class); } @Override diff --git a/bundles/org.openhab.binding.synopanalyzer/src/main/java/org/openhab/binding/synopanalyzer/internal/stationdb/StationDbService.java b/bundles/org.openhab.binding.synopanalyzer/src/main/java/org/openhab/binding/synopanalyzer/internal/stationdb/StationDbService.java index 516312d72..c7f98e1ee 100644 --- a/bundles/org.openhab.binding.synopanalyzer/src/main/java/org/openhab/binding/synopanalyzer/internal/stationdb/StationDbService.java +++ b/bundles/org.openhab.binding.synopanalyzer/src/main/java/org/openhab/binding/synopanalyzer/internal/stationdb/StationDbService.java @@ -48,7 +48,7 @@ public class StationDbService { @Activate public StationDbService() { try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("/db/stations.json"); - Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8);) { + Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) { Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); stations = Arrays.asList(gson.fromJson(reader, Station[].class)); } catch (IOException | JsonSyntaxException | JsonIOException e) { diff --git a/bundles/org.openhab.binding.synopanalyzer/src/main/java/org/openhab/binding/synopanalyzer/internal/synop/Synop.java b/bundles/org.openhab.binding.synopanalyzer/src/main/java/org/openhab/binding/synopanalyzer/internal/synop/Synop.java index 5657757b1..f761f3b93 100644 --- a/bundles/org.openhab.binding.synopanalyzer/src/main/java/org/openhab/binding/synopanalyzer/internal/synop/Synop.java +++ b/bundles/org.openhab.binding.synopanalyzer/src/main/java/org/openhab/binding/synopanalyzer/internal/synop/Synop.java @@ -66,7 +66,7 @@ public abstract class Synop { private static final int HV_LESS_THAN_10_HP_LIMIT = 96; private static final int HV_LESS_THAN_50_HP_LIMIT = 98; - public static enum HorizontalVisibility { + public enum HorizontalVisibility { UNDEFINED, LESS_THAN_1, LESS_THAN_10, diff --git a/bundles/org.openhab.binding.systeminfo/src/main/java/org/openhab/binding/systeminfo/internal/discovery/SysteminfoDiscoveryService.java b/bundles/org.openhab.binding.systeminfo/src/main/java/org/openhab/binding/systeminfo/internal/discovery/SysteminfoDiscoveryService.java index d33e43b33..b76fc6773 100644 --- a/bundles/org.openhab.binding.systeminfo/src/main/java/org/openhab/binding/systeminfo/internal/discovery/SysteminfoDiscoveryService.java +++ b/bundles/org.openhab.binding.systeminfo/src/main/java/org/openhab/binding/systeminfo/internal/discovery/SysteminfoDiscoveryService.java @@ -16,7 +16,6 @@ import static org.openhab.binding.systeminfo.internal.SysteminfoBindingConstants import java.net.InetAddress; import java.net.UnknownHostException; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -46,7 +45,7 @@ public class SysteminfoDiscoveryService extends AbstractDiscoveryService { private final Logger logger = LoggerFactory.getLogger(SysteminfoDiscoveryService.class); - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_COMPUTER); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_COMPUTER); private static final int DISCOVERY_TIME_SECONDS = 30; private static final String THING_UID_VALID_CHARS = "A-Za-z0-9_-"; @@ -82,7 +81,6 @@ public class SysteminfoDiscoveryService extends AbstractDiscoveryService { protected String getHostName() throws UnknownHostException { InetAddress addr = InetAddress.getLocalHost(); - String hostname = addr.getHostName(); - return hostname; + return addr.getHostName(); } } diff --git a/bundles/org.openhab.binding.systeminfo/src/main/java/org/openhab/binding/systeminfo/internal/handler/SysteminfoHandler.java b/bundles/org.openhab.binding.systeminfo/src/main/java/org/openhab/binding/systeminfo/internal/handler/SysteminfoHandler.java index 36ba69e20..29f66a9ea 100644 --- a/bundles/org.openhab.binding.systeminfo/src/main/java/org/openhab/binding/systeminfo/internal/handler/SysteminfoHandler.java +++ b/bundles/org.openhab.binding.systeminfo/src/main/java/org/openhab/binding/systeminfo/internal/handler/SysteminfoHandler.java @@ -675,8 +675,7 @@ public class SysteminfoHandler extends BaseThingHandler { } if (channelGroupID.contains(CHANNEL_GROUP_CURRENT_PROCESS)) { - int pid = systeminfo.getCurrentProcessID(); - return pid; + return systeminfo.getCurrentProcessID(); } // First try to get device index in group id, delete all non-digits from id diff --git a/bundles/org.openhab.binding.touchwand/src/main/java/org/openhab/binding/touchwand/internal/TouchWandRestClient.java b/bundles/org.openhab.binding.touchwand/src/main/java/org/openhab/binding/touchwand/internal/TouchWandRestClient.java index 8d5822ba3..adc776a5b 100644 --- a/bundles/org.openhab.binding.touchwand/src/main/java/org/openhab/binding/touchwand/internal/TouchWandRestClient.java +++ b/bundles/org.openhab.binding.touchwand/src/main/java/org/openhab/binding/touchwand/internal/TouchWandRestClient.java @@ -109,7 +109,7 @@ public class TouchWandRestClient { String command = buildUrl(CMD_LOGIN) + "user=" + encodedUser + "&" + "psw=" + encodedPass; response = sendCommand(command, METHOD_GET, ""); - return !response.equals("Unauthorized"); + return !"Unauthorized".equals(response); } public String cmdListUnits() { diff --git a/bundles/org.openhab.binding.touchwand/src/main/java/org/openhab/binding/touchwand/internal/dto/AlarmSensorUnitDataDeserializer.java b/bundles/org.openhab.binding.touchwand/src/main/java/org/openhab/binding/touchwand/internal/dto/AlarmSensorUnitDataDeserializer.java index 3ab13bf84..995030b18 100644 --- a/bundles/org.openhab.binding.touchwand/src/main/java/org/openhab/binding/touchwand/internal/dto/AlarmSensorUnitDataDeserializer.java +++ b/bundles/org.openhab.binding.touchwand/src/main/java/org/openhab/binding/touchwand/internal/dto/AlarmSensorUnitDataDeserializer.java @@ -40,7 +40,6 @@ public class AlarmSensorUnitDataDeserializer implements JsonDeserializer