From edaf17b345e489172d616a79327cf428278adba7 Mon Sep 17 00:00:00 2001 From: Holger Friedrich Date: Fri, 8 Sep 2023 14:36:59 +0200 Subject: [PATCH] Java 17 features (H-M) (#15520) - add missing @override - Java style array syntax - remove redundant modifiers - always move String constants to left side in comparisons - simplify lambda expressions and return statements - use replace instead of replaceAll w/o regex - instanceof matching and multiline strings - remove null check before instanceof Signed-off-by: Holger Friedrich --- .../internal/HaasSohnpelletstoveHandler.java | 6 +- .../internal/MD5Utils.java | 3 +- .../handler/HarmonyDeviceHandler.java | 3 +- .../internal/handler/HarmonyHubHandler.java | 4 +- .../internal/HaywardBindingConstants.java | 16 +- .../internal/HaywardThingHandler.java | 10 +- .../discovery/HaywardDiscoveryService.java | 4 +- .../handler/HaywardBackyardHandler.java | 10 +- .../handler/HaywardBridgeHandler.java | 47 +-- .../handler/HaywardChlorinatorHandler.java | 2 +- .../handler/HaywardColorLogicHandler.java | 2 +- .../handler/HaywardFilterHandler.java | 2 +- .../handler/HaywardHeaterHandler.java | 2 +- .../internal/handler/HaywardPumpHandler.java | 2 +- .../handler/HaywardVirtualHeaterHandler.java | 4 +- .../HCCRubbishCollectionHandlerFactory.java | 3 +- .../internal/handler/Mhub4K431Handler.java | 2 +- .../handler/MultiroomPlusHandler.java | 4 +- .../internal/GatewayWebTargets.java | 2 +- .../builders/AutomationChannelBuilder.java | 6 +- .../console/HDPowerViewCommandExtension.java | 8 +- .../database/ShadeCapabilitiesDatabase.java | 8 +- .../HDPowerViewDeviceDiscoveryService.java | 4 +- .../HDPowerViewHubDiscoveryParticipant.java | 3 +- .../HDPowerViewHubDiscoveryService.java | 4 +- .../discovery/ShadeDiscoveryService.java | 4 +- .../internal/dto/ShadePosition.java | 8 +- .../internal/dto/gen3/PowerType.java | 2 +- .../handler/GatewayBridgeHandler.java | 4 +- .../handler/HDPowerViewHubHandler.java | 8 +- .../handler/HDPowerViewShadeHandler.java | 18 +- .../internal/handler/ShadeThingHandler.java | 15 +- .../providers/MockedLocaleProvider.java | 1 + .../internal/handler/HeliosHandler221.java | 88 ++--- .../HeliosVentilationHandlerFactory.java | 4 +- .../heos/internal/action/HeosActions.java | 4 +- .../discovery/HeosDiscoveryParticipant.java | 3 +- .../internal/handler/HeosBridgeHandler.java | 18 +- .../handler/HeosThingBaseHandler.java | 8 +- .../heos/internal/resources/Telnet.java | 4 +- .../json/HeosJsonParserResponseTest.java | 50 +-- .../herzborg/internal/CurtainHandler.java | 4 +- .../internal/client/HomeConnectApiClient.java | 3 +- .../HomeConnectDiscoveryService.java | 4 +- .../AbstractHomeConnectThingHandler.java | 44 +-- .../handler/HomeConnectBridgeHandler.java | 4 +- .../handler/HomeConnectHoodHandler.java | 36 ++- .../internal/common/HomematicConfig.java | 14 +- .../communicator/client/XmlRpcClient.java | 3 +- .../communicator/message/BinRpcMessage.java | 20 +- .../communicator/message/RpcUtils.java | 16 +- .../communicator/message/XmlRpcRequest.java | 12 +- .../communicator/message/XmlRpcResponse.java | 4 +- .../communicator/parser/CommonRpcParser.java | 7 +- .../parser/GetParamsetParser.java | 2 +- .../server/BinRpcNetworkService.java | 6 +- ...leteDeviceModeVirtualDatapointHandler.java | 2 +- .../DeleteDeviceVirtualDatapointHandler.java | 2 +- ...DisplayOptionsVirtualDatapointHandler.java | 3 +- ...nTimeAutomaticVirtualDatapointHandler.java | 4 +- .../discovery/CcuDiscoveryService.java | 4 +- .../HomegearDiscoveryParticipant.java | 3 +- .../HomematicDeviceDiscoveryService.java | 8 +- .../handler/HomematicBridgeHandler.java | 4 +- .../handler/HomematicThingHandler.java | 7 +- .../homematic/internal/model/HmDatapoint.java | 7 +- .../internal/model/HmDatapointInfo.java | 2 +- .../homematic/internal/model/HmDevice.java | 2 +- .../type/HomematicTypeGeneratorImpl.java | 12 +- .../homewizard/internal/P1Payload.java | 7 +- .../hpprinter/internal/api/HPFeatures.java | 4 +- .../hpprinter/internal/api/HPUsage.java | 3 +- .../openhab/binding/http/internal/Util.java | 4 +- .../converter/ColorItemConverter.java | 31 +- .../converter/DimmerItemConverter.java | 12 +- .../converter/GenericItemConverter.java | 2 + .../converter/RollershutterItemConverter.java | 4 +- .../internal/http/HttpResponseListener.java | 3 +- .../api/graphql/HydrawiseGraphQLClient.java | 6 +- .../api/graphql/dto/MutationResponse.java | 2 +- .../api/local/HydrawiseLocalApiClient.java | 5 +- ...rawiseCloudControllerDiscoveryService.java | 7 +- .../handler/HydrawiseAccountHandler.java | 5 +- .../handler/HydrawiseLocalHandler.java | 2 +- .../HyperionDiscoveryParticipant.java | 3 +- .../connection/JsonTcpConnection.java | 2 - .../internal/handler/HyperionHandler.java | 10 +- .../internal/handler/HyperionNgHandler.java | 11 +- .../internal/Iammeter3080THandler.java | 2 +- .../internal/handler/IAqualinkHandler.java | 6 +- .../internal/ICalendarHandlerFactory.java | 9 +- .../internal/handler/EventFilterHandler.java | 25 +- .../internal/handler/ICalendarHandler.java | 4 +- .../internal/logic/EventTextFilter.java | 4 +- .../icloud/internal/ICloudHandlerFactory.java | 4 +- .../handler/ICloudAccountBridgeHandler.java | 9 +- .../internal/handler/ICloudDeviceHandler.java | 4 +- .../openhab/binding/icloud/TestICloud.java | 5 +- .../ihc/internal/handler/IhcHandler.java | 8 +- .../profiles/PushButtonToCommandProfile.java | 4 +- .../internal/ws/http/IhcConnectionPool.java | 1 - .../ws/projectfile/ProjectFileUtils.java | 3 +- .../ws/services/IhcAuthenticationService.java | 22 +- .../internal/ws/services/IhcBaseService.java | 12 +- .../ws/services/IhcControllerService.java | 38 ++- .../IhcResourceInteractionService.java | 306 ++++++++++-------- .../internal/device/CommandHandler.java | 4 +- .../internal/device/DeviceFeature.java | 5 +- .../internal/device/DeviceTypeLoader.java | 2 +- .../device/FeatureTemplateLoader.java | 10 +- .../device/GroupMessageStateMachine.java | 2 +- .../internal/device/InsteonDevice.java | 2 +- .../internal/device/MessageHandler.java | 4 +- .../internal/device/ModemDBBuilder.java | 6 +- .../handler/InsteonDeviceHandler.java | 16 +- .../insteon/internal/message/Field.java | 6 +- .../internal/message/XMLMessageReader.java | 9 +- .../binding/insteon/internal/utils/Utils.java | 11 +- .../internal/handler/IntesisBoxHandler.java | 5 +- .../internal/handler/IntesisHomeHandler.java | 12 +- .../ipcamera/internal/AmcrestHandler.java | 3 +- .../ipcamera/internal/DoorBirdHandler.java | 3 +- .../binding/ipcamera/internal/Helper.java | 4 +- .../ipcamera/internal/InstarHandler.java | 8 +- .../internal/IpCameraBindingConstants.java | 2 +- .../ipcamera/internal/MyNettyAuthHandler.java | 5 +- .../ipcamera/internal/ReolinkHandler.java | 4 +- .../internal/handler/IpCameraHandler.java | 17 +- .../ipcamera/internal/onvif/OnvifCodec.java | 3 +- .../internal/onvif/OnvifConnection.java | 2 +- .../internal/onvif/OnvifDiscovery.java | 2 +- .../internal/IpObserverDiscoveryService.java | 2 +- .../internal/handler/IppPrinterHandler.java | 8 +- .../irobot/internal/IRobotHandlerFactory.java | 3 +- .../irobot/internal/dto/MQTTProtocol.java | 2 +- .../binding/irtrans/internal/IrCommand.java | 2 +- .../discovery/JablotronDiscoveryService.java | 4 +- .../handler/JablotronBridgeHandler.java | 4 +- .../internal/ec3k/Ec3kReadingConverter.java | 9 +- .../internal/lacrosse/LgwSensorHandler.java | 4 +- .../internal/lacrosse/Tx22SensorHandler.java | 4 +- .../internal/pca301/Pca301SensorHandler.java | 4 +- .../revolt/RevoltReadingConverter.java | 7 +- .../internal/revolt/RevoltSensorHandler.java | 4 +- .../internal/JellyfinHandlerFactory.java | 3 +- .../JellyfinClientDiscoveryService.java | 5 +- .../JellyfinServerDiscoveryService.java | 2 +- .../handler/JellyfinClientHandler.java | 9 +- .../handler/JellyfinServerHandler.java | 12 +- .../jellyfin/internal/util/SyncResponse.java | 4 +- .../discovery/JuiceNetDiscoveryService.java | 3 +- .../handler/JuiceNetBridgeHandler.java | 4 +- .../KaleidescapeDiscoveryService.java | 1 - .../internal/handler/KaleidescapeHandler.java | 8 +- .../keba/internal/KebaHandlerFactory.java | 3 +- .../internal/handler/KeContactHandler.java | 23 +- .../handler/KeContactTransceiver.java | 2 +- .../binding/km200/internal/KM200Device.java | 4 +- .../internal/handler/KM200DataHandler.java | 2 +- .../internal/handler/KM200GatewayHandler.java | 2 +- .../knx/internal/dpt/ValueDecoder.java | 6 +- .../internal/handler/DeviceThingHandler.java | 7 +- .../binding/kodi/internal/KodiAudioSink.java | 4 +- .../kodi/internal/KodiBindingConstants.java | 3 +- .../KodiUpnpDiscoveryParticipant.java | 6 +- .../kodi/internal/handler/KodiHandler.java | 28 +- .../internal/protocol/KodiConnection.java | 4 +- .../internal/KonnectedHandlerFactory.java | 1 - .../discovery/KonnectedUPnPServer.java | 3 +- .../internal/handler/KonnectedHandler.java | 12 +- .../SecondGenerationConfigurationHandler.java | 7 +- .../SecondGenerationHandler.java | 8 +- .../kvv/internal/KVVBridgeHandler.java | 1 - .../HttpAuthenticationFeature.java | 2 +- .../HttpAuthenticationFilter.java | 10 +- .../LaMetricTimeDiscoveryParticipant.java | 3 +- .../internal/handler/LaMetricTimeHandler.java | 10 +- .../internal/handler/RadioAppHandler.java | 8 +- .../lcn/internal/DimmerOutputProfile.java | 12 +- .../internal/LcnModuleDiscoveryService.java | 4 +- .../lcn/internal/LcnModuleHandler.java | 52 ++- .../lcn/internal/LcnProfileFactory.java | 6 +- .../lcn/internal/PckGatewayHandler.java | 4 +- .../binding/lcn/internal/common/LcnDefs.java | 6 +- .../lcn/internal/connection/Connection.java | 2 +- .../lcn/internal/converter/S0Converter.java | 4 +- .../internal/converter/ValueConverter.java | 4 +- ...LcnModuleRollershutterRelaySubHandler.java | 4 +- .../LcnModuleBinarySensorSubHandler.java | 4 +- .../LcnModuleHostCommandSubHandler.java | 4 +- .../LcnModuleKeyLockTableSubHandler.java | 4 +- .../LcnModuleMetaFirmwareSubHandler.java | 4 +- .../subhandler/LcnModuleRelaySubHandler.java | 4 +- .../LcnModuleS0CounterSubHandler.java | 4 +- .../internal/LeapMotionColorProfile.java | 7 +- .../internal/LeapMotionHandlerFactory.java | 3 +- .../discovery/LeapMotionDiscoveryService.java | 4 +- .../internal/LGHomBotBindingConstants.java | 3 +- .../internal/LGHomBotHandlerFactory.java | 3 +- .../internal/discovery/LGHomBotDiscovery.java | 12 +- .../serial/responses/OnOffResponse.java | 2 +- .../internal/LGWebOSBindingConstants.java | 3 +- .../lgwebos/internal/PowerControlPower.java | 8 +- .../lgwebos/internal/VolumeControlVolume.java | 12 +- .../lgwebos/internal/WakeOnLanUtility.java | 4 +- .../internal/action/LGWebOSActions.java | 2 +- .../console/LGWebOSCommandExtension.java | 4 +- .../internal/handler/LGWebOSHandler.java | 3 +- .../LifxLightCommunicationHandler.java | 3 +- .../LifxLightCurrentStateUpdater.java | 32 +- .../lifx/internal/LifxLightDiscovery.java | 15 +- .../internal/LifxLightPropertiesUpdater.java | 14 +- .../internal/LifxSequenceNumberSupplier.java | 4 +- .../internal/dto/LightLastHevCycleResult.java | 2 +- .../lifx/internal/fields/LittleField.java | 4 +- .../internal/handler/LifxLightHandler.java | 77 +++-- .../lifx/internal/util/LifxMessageUtil.java | 12 +- .../lifx/internal/util/LifxNetworkUtil.java | 4 +- .../lifx/internal/util/LifxSelectorUtil.java | 21 +- .../console/LinkyCommandExtension.java | 4 +- .../binding/linky/internal/dto/AuthData.java | 2 +- .../linky/internal/handler/LinkyHandler.java | 12 +- .../internal/LinuxInputDiscoveryService.java | 4 +- .../internal/LinuxInputHandler.java | 2 +- .../internal/LinuxInputHandlerFactory.java | 3 +- .../internal/LiquidCheckHandler.java | 4 +- .../lirc/internal/LIRCBindingConstants.java | 5 +- .../LivisiDeviceDiscoveryService.java | 4 +- .../internal/handler/LivisiBridgeHandler.java | 8 +- .../internal/handler/LivisiDeviceHandler.java | 17 +- .../internal/client/LivisiClientTest.java | 17 +- .../client/entity/device/DeviceDTOTest.java | 8 +- .../handler/LivisiBridgeHandlerTest.java | 4 +- .../handler/LivisiDeviceHandlerTest.java | 2 +- .../org/apache/commons/io/input/Tailer.java | 2 +- .../internal/handler/LogHandler.java | 2 +- .../internal/searchengine/SearchEngine.java | 2 +- .../loxone/internal/LxHandlerFactory.java | 7 +- .../loxone/internal/LxServerHandler.java | 6 +- .../binding/loxone/internal/LxWebSocket.java | 2 +- .../loxone/internal/controls/LxControl.java | 4 +- .../internal/controls/LxControlAlarm.java | 4 +- .../controls/LxControlColorPickerV2.java | 16 +- .../internal/controls/LxControlEIBDimmer.java | 13 +- .../controls/LxControlIRoomControllerV2.java | 10 +- .../internal/controls/LxControlJalousie.java | 20 +- .../controls/LxControlLightController.java | 18 +- .../controls/LxControlLightControllerV2.java | 16 +- .../internal/controls/LxControlMeter.java | 2 +- .../controls/LxControlPushbutton.java | 4 +- .../internal/controls/LxControlRadio.java | 7 +- .../internal/controls/LxControlSauna.java | 18 +- .../internal/controls/LxControlSwitch.java | 4 +- .../controls/LxControlUpDownAnalog.java | 4 +- .../controls/LxControlUpDownDigital.java | 8 +- .../controls/LxControlValueSelector.java | 20 +- .../binding/loxone/internal/types/LxTags.java | 9 +- .../binding/loxone/internal/types/LxUuid.java | 2 +- .../LxControlAlarmNoPresenceTest.java | 2 +- .../LxControlInfoOnlyAnalogTempTagTest.java | 4 +- .../controls/LxControlJalousieTest.java | 5 +- .../LxControlLightControllerV2Test.java | 8 +- .../controls/LxControlPushbuttonTest.java | 4 +- .../controls/LxControlSwitchTest.java | 4 +- .../controls/LxControlTimedSwitchTest.java | 4 +- .../lutron/internal/LutronHandlerFactory.java | 5 +- .../lutron/internal/action/DimmerActions.java | 4 +- .../discovery/LeapDeviceDiscoveryService.java | 4 +- .../LutronDeviceDiscoveryService.java | 8 +- .../LutronMcastBridgeDiscoveryService.java | 3 +- .../LutronMdnsBridgeDiscoveryService.java | 3 +- .../internal/grxprg/GrafikEyeHandler.java | 12 +- .../internal/grxprg/PrgBridgeHandler.java | 8 +- .../internal/grxprg/PrgProtocolHandler.java | 16 +- .../lutron/internal/grxprg/SocketSession.java | 8 +- .../lutron/internal/handler/BlindHandler.java | 8 +- .../internal/handler/DimmerHandler.java | 8 +- .../lutron/internal/handler/FanHandler.java | 4 +- .../internal/handler/GreenModeHandler.java | 4 +- .../internal/handler/IPBridgeHandler.java | 2 +- .../lutron/internal/handler/QSIOHandler.java | 2 +- .../lutron/internal/handler/ShadeHandler.java | 4 +- .../internal/handler/SysvarHandler.java | 4 +- .../internal/handler/TimeclockHandler.java | 16 +- .../lutron/internal/handler/VcrxHandler.java | 2 +- .../lutron/internal/handler/WciHandler.java | 2 +- .../lutron/internal/hw/HwDimmerHandler.java | 4 +- .../internal/hw/HwDiscoveryService.java | 6 +- .../internal/hw/HwSerialBridgeHandler.java | 4 +- .../internal/keypadconfig/KeypadConfig.java | 2 +- .../keypadconfig/KeypadConfigGrafikEye.java | 2 +- .../KeypadConfigIntlSeetouch.java | 2 +- .../keypadconfig/KeypadConfigPalladiom.java | 2 +- .../keypadconfig/KeypadConfigPico.java | 2 +- .../keypadconfig/KeypadConfigSeetouch.java | 2 +- .../KeypadConfigTabletopSeetouch.java | 2 +- .../lutron/internal/protocol/LIPCommand.java | 3 +- .../protocol/leap/LeapMessageParser.java | 2 +- .../internal/protocol/leap/Request.java | 68 ++-- .../internal/protocol/lip/TargetType.java | 2 +- .../internal/radiora/RS232Connection.java | 2 +- .../radiora/handler/DimmerHandler.java | 16 +- .../radiora/handler/LutronHandler.java | 4 +- .../radiora/handler/PhantomButtonHandler.java | 4 +- .../radiora/handler/RS232Handler.java | 4 +- .../radiora/handler/SwitchHandler.java | 12 +- .../radiora/protocol/ButtonPressCommand.java | 2 +- .../protocol/SetDimmerLevelCommand.java | 2 +- .../protocol/SetSwitchLevelCommand.java | 2 +- .../internal/handler/LuxomDimmerHandler.java | 9 +- .../internal/handler/LuxomThingHandler.java | 1 - .../internal/protocol/LuxomCommunication.java | 1 - .../LuxtronikHeatpumpBindingConstants.java | 3 +- .../internal/LuxtronikHeatpumpHandler.java | 8 +- .../internal/enums/HeatpumpType.java | 2 +- .../internal/MagentaTVBindingConstants.java | 3 +- .../config/MagentaTVDynamicConfig.java | 4 +- .../MagentaTVDiscoveryParticipant.java | 5 +- .../internal/handler/MagentaTVControl.java | 6 +- .../internal/handler/MagentaTVHandler.java | 4 +- .../internal/network/MagentaTVHttp.java | 1 - .../internal/network/MagentaTVNetwork.java | 2 +- .../network/MagentaTVNotifyServlet.java | 3 +- .../internal/network/MagentaTVOAuth.java | 6 +- .../activation/PatchedMailcapCommandMap.java | 4 +- .../mail/internal/POP3IMAPHandler.java | 4 +- .../binding/mail/internal/SMTPHandler.java | 3 +- .../mail/internal/action/SendMailActions.java | 4 +- .../openhab/binding/max/internal/Utils.java | 8 +- .../max/internal/actions/MaxCubeActions.java | 4 +- .../internal/actions/MaxDevicesActions.java | 4 +- .../max/internal/command/CCommand.java | 3 +- .../max/internal/command/UdpCubeCommand.java | 4 +- .../discovery/MaxCubeBridgeDiscovery.java | 2 +- .../discovery/MaxDeviceDiscoveryService.java | 4 +- .../internal/handler/MaxDevicesHandler.java | 8 +- .../max/internal/handler/SendCommand.java | 3 +- .../internal/message/MessageProcessor.java | 2 +- .../max/internal/command/MCommandTest.java | 2 +- .../max/internal/message/UtilsTest.java | 4 +- .../internal/handler/SensorThingHandler.java | 16 +- .../handler/SensorThingHandlerTest.java | 48 ++- .../internal/Mcp23017HandlerFactory.java | 3 +- .../meater/internal/api/MeaterRestAPI.java | 4 +- .../console/MeaterCommandExtension.java | 4 +- .../discovery/MeaterDiscoveryService.java | 8 +- .../internal/handler/MeaterBridgeHandler.java | 5 +- .../internal/MelCloudHandlerFactory.java | 9 +- .../internal/api/MelCloudConnection.java | 6 +- .../discovery/MelCloudDiscoveryService.java | 12 +- .../handler/MelCloudAccountHandler.java | 3 +- .../internal/handler/AccountHandler.java | 2 +- .../internal/handler/VehicleHandler.java | 2 +- .../internal/server/CallbackServer.java | 4 +- .../internal/MeteoAlertIconProvider.java | 1 - .../internal/handler/MeteoAlerteHandler.java | 8 +- .../binding/meteoblue/internal/Forecast.java | 2 +- .../internal/MeteoBlueBindingConstants.java | 3 +- .../handler/MeteoBlueBridgeHandler.java | 3 +- .../internal/handler/MeteoBlueHandler.java | 21 +- .../handler/MeteostickBridgeHandler.java | 5 +- .../handler/MeteostickEventListener.java | 2 +- .../handler/MeteostickSensorHandler.java | 2 +- .../MieleApplianceDiscoveryService.java | 3 +- .../handler/CoffeeMachineChannelSelector.java | 1 + .../handler/DishwasherChannelSelector.java | 1 + .../internal/handler/DishwasherHandler.java | 1 + .../handler/FridgeChannelSelector.java | 1 + .../handler/FridgeFreezerChannelSelector.java | 1 + .../internal/handler/HobChannelSelector.java | 1 + .../internal/handler/HoodChannelSelector.java | 1 + .../handler/MieleApplianceHandler.java | 8 +- .../internal/handler/OvenChannelSelector.java | 1 + .../handler/TumbleDryerChannelSelector.java | 1 + .../WashingMachineChannelSelector.java | 1 + .../handler/WashingMachineHandler.java | 1 + .../config/ThingsTemplateGenerator.java | 4 +- .../servlet/AccountOverviewServlet.java | 11 +- .../discovery/ThingDiscoveryService.java | 3 +- .../discovery/ThingInformationExtractor.java | 4 +- .../handler/AbstractMieleThingHandler.java | 2 +- .../internal/handler/MieleBridgeHandler.java | 9 +- .../handler/channel/ChannelTypeUtil.java | 2 +- .../webservice/DefaultMieleWebservice.java | 8 +- .../internal/webservice/HttpUtil.java | 4 +- .../internal/webservice/api/DeviceState.java | 4 +- .../webservice/api/TransitionState.java | 2 +- .../AuthorizationFailedRetryStrategy.java | 2 +- .../config/ThingsTemplateGeneratorTest.java | 36 ++- .../DefaultMieleWebserviceTest.java | 1 - .../webservice/api/ActionsStateTest.java | 18 +- .../webservice/api/DeviceStateTest.java | 9 +- .../api/json/ActionsCollectionTest.java | 10 +- .../webservice/api/json/ActionsTest.java | 3 +- .../XiaomiBridgeDiscoveryService.java | 5 +- .../discovery/XiaomiItemDiscoveryService.java | 2 +- .../handler/XiaomiActorGatewayHandler.java | 25 +- .../internal/handler/XiaomiBridgeHandler.java | 12 +- .../handler/XiaomiDeviceBaseHandler.java | 8 +- .../handler/XiaomiSensorMagnetHandler.java | 4 +- .../handler/XiaomiSensorMotionHandler.java | 4 +- .../mihome/internal/socket/XiaomiSocket.java | 4 +- .../miio/internal/basic/ActionConditions.java | 4 +- .../internal/config/InterfaceThingConfig.java | 1 + .../internal/config/RouterosThingConfig.java | 1 + .../config/WirelessClientThingConfig.java | 1 + .../MikrotikRouterosBridgeHandler.java | 4 +- .../internal/model/RouterosCapInterface.java | 8 +- .../internal/model/RouterosInterfaceBase.java | 4 +- .../internal/model/RouterosInterfaceType.java | 1 + .../model/RouterosPPPCliInterface.java | 1 + .../model/RouterosPPPoECliInterface.java | 1 + .../model/RouterosRouterboardInfo.java | 2 +- .../discovery/MilightBridgeDiscovery.java | 3 +- .../internal/handler/AbstractLedHandler.java | 77 ++--- .../internal/handler/MilightV2RGBHandler.java | 4 +- .../handler/MilightV3RGBWHandler.java | 34 +- .../handler/MilightV3WhiteHandler.java | 32 +- .../protocol/MilightV6SessionManager.java | 4 +- .../internal/test/EmulatedV6Bridge.java | 28 +- .../GetIndependentDevicesByHomeResponse.java | 2 +- .../handler/MillheatAccountHandler.java | 8 +- .../internal/handler/MillheatHomeHandler.java | 4 +- .../internal/model/MillheatModel.java | 2 +- .../internal/MinecraftHandlerFactory.java | 6 +- .../discovery/MinecraftDiscoveryService.java | 10 +- .../MinecraftMDNSDiscoveryParticipant.java | 5 +- .../handler/MinecraftPlayerHandler.java | 4 +- .../handler/MinecraftSignHandler.java | 4 +- .../internal/handler/E3DCThingHandler.java | 5 +- .../internal/HeliosEasyControlsActions.java | 1 - .../internal/HeliosEasyControlsHandler.java | 21 +- .../HeliosEasyControlsHandlerFactory.java | 5 +- .../internal/StiebelEltronHandlerFactory.java | 3 +- .../handler/StiebelEltronHandler.java | 17 +- .../modbus/studer/internal/StuderHandler.java | 7 +- .../modbus/studer/internal/StuderParser.java | 2 +- .../discovery/SunspecDiscoveryProcess.java | 4 +- .../handler/AbstractSunSpecHandler.java | 7 +- .../ModbusEndpointDiscoveryService.java | 4 +- .../handler/BaseModbusThingHandler.java | 4 +- .../handler/ModbusPollerThingHandler.java | 9 +- .../CascadedValueTransformationImpl.java | 3 +- .../internal/SingleValueTransformation.java | 3 +- .../handler/ModbusDataThingHandler.java | 22 +- .../handler/ModbusSerialThingHandler.java | 4 +- .../handler/ModbusTcpThingHandler.java | 4 +- .../profiles/ModbusGainOffsetProfile.java | 29 +- .../profiles/ModbusGainOffsetProfileTest.java | 17 +- .../handler/MonopriceAudioHandler.java | 32 +- .../mpd/internal/MPDHandlerFactory.java | 3 +- .../mpd/internal/action/MPDActions.java | 4 +- .../discovery/MPDDiscoveryParticipant.java | 6 +- .../mpd/internal/handler/MPDHandler.java | 11 +- .../mpd/internal/protocol/MPDCommand.java | 4 +- .../handler/EspMilightHubHandler.java | 11 +- .../mapping/SubscribeFieldToMQTTtopic.java | 6 +- .../mqtt/generic/values/ColorValue.java | 13 +- .../mqtt/generic/values/DateTimeValue.java | 4 +- .../mqtt/generic/values/LocationValue.java | 4 +- .../mqtt/generic/values/NumberValue.java | 16 +- .../mqtt/generic/values/OnOffValue.java | 4 +- .../mqtt/generic/values/OpenCloseValue.java | 4 +- .../mqtt/generic/values/PercentageValue.java | 24 +- .../generic/values/RollershutterValue.java | 8 +- .../binding/mqtt/generic/values/Value.java | 2 +- .../ChannelStateTransformationTests.java | 2 +- .../handler/GenericThingHandlerTests.java | 2 +- .../component/AbstractRawSchemaLight.java | 8 +- .../internal/component/Climate.java | 2 +- .../component/DefaultSchemaLight.java | 8 +- .../internal/component/DeviceTrigger.java | 2 +- .../internal/component/JSONSchemaLight.java | 1 + ...hannelConfigurationTypeAdapterFactory.java | 3 +- .../config/ConnectionDeserializer.java | 8 +- .../config/ListOrStringDeserializer.java | 3 +- .../homeassistant/internal/HaIDTests.java | 8 +- .../component/AlarmControlPanelTests.java | 52 +-- .../internal/component/BinarySensorTests.java | 148 +++++---- .../internal/component/CameraTests.java | 38 +-- .../internal/component/ClimateTests.java | 231 ++++++------- .../internal/component/CoverTests.java | 46 +-- .../component/DefaultSchemaLightTests.java | 152 +++++---- .../internal/component/FanTests.java | 44 +-- .../component/JSONSchemaLightTests.java | 78 ++--- .../internal/component/LockTests.java | 90 +++--- .../internal/component/SensorTests.java | 110 ++++--- .../internal/component/SwitchTests.java | 116 ++++--- .../internal/component/VacuumTests.java | 230 +++++++------ .../internal/discovery/Homie300Discovery.java | 4 +- .../internal/handler/HomieThingHandler.java | 15 +- .../homie/internal/homie300/Property.java | 13 +- .../internal/parser/GatewayPayloadParser.java | 3 +- .../discovery/RuuviGatewayDiscoveryTests.java | 22 +- .../parser/GatewayPayloadParserTests.java | 53 +-- .../mqtt/handler/AbstractBrokerHandler.java | 4 +- .../binding/mqtt/internal/MqttThingID.java | 2 +- .../mybmw/internal/MyBMWHandlerFactory.java | 4 +- .../internal/discovery/VehicleDiscovery.java | 4 +- .../internal/handler/MyBMWBridgeHandler.java | 4 +- .../mybmw/internal/handler/MyBMWProxy.java | 12 +- .../internal/handler/VehicleHandler.java | 6 +- .../mybmw/internal/utils/Converter.java | 4 +- .../internal/utils/VehicleStatusUtils.java | 3 +- .../mybmw/internal/dto/StatusWrapper.java | 16 +- .../mybmw/internal/handler/AuthTest.java | 4 +- .../mybmw/internal/util/FileReader.java | 2 +- .../internal/api/MycroftConnection.java | 2 - .../internal/channels/AudioPlayerChannel.java | 12 +- .../internal/channels/MuteChannel.java | 3 +- .../internal/channels/VolumeChannel.java | 17 +- .../internal/api/MycroftConnectionTest.java | 2 - .../internal/xml/dto/Authentication.java | 2 +- .../mynice/internal/xml/dto/Device.java | 2 +- .../mynice/internal/xml/dto/Properties.java | 2 +- .../myq/internal/MyQDiscoveryService.java | 4 +- .../internal/handler/MyQAccountHandler.java | 12 +- .../handler/MyQGarageDoorHandler.java | 4 +- .../mystrom/internal/MyStromBulbHandler.java | 23 +- 519 files changed, 2703 insertions(+), 2660 deletions(-) diff --git a/bundles/org.openhab.binding.haassohnpelletstove/src/main/java/org/openhab/binding/haassohnpelletstove/internal/HaasSohnpelletstoveHandler.java b/bundles/org.openhab.binding.haassohnpelletstove/src/main/java/org/openhab/binding/haassohnpelletstove/internal/HaasSohnpelletstoveHandler.java index 6673fa4c2..c9ff21423 100644 --- a/bundles/org.openhab.binding.haassohnpelletstove/src/main/java/org/openhab/binding/haassohnpelletstove/internal/HaasSohnpelletstoveHandler.java +++ b/bundles/org.openhab.binding.haassohnpelletstove/src/main/java/org/openhab/binding/haassohnpelletstove/internal/HaasSohnpelletstoveHandler.java @@ -82,11 +82,9 @@ public class HaasSohnpelletstoveHandler extends BaseThingHandler { updateOvenData(postData); } } else if (channelUID.getId().equals(CHANNELSPTEMP)) { - if (command instanceof QuantityType) { - QuantityType value = (QuantityType) command; - + if (command instanceof QuantityType quantityCommand) { Unit unit = SIUnits.CELSIUS; - value = value.toUnit(unit); + QuantityType value = quantityCommand.toUnit(unit); if (value != null) { double a = value.doubleValue(); String postdata = "{\"sp_temp\":" + a + "}"; diff --git a/bundles/org.openhab.binding.haassohnpelletstove/src/main/java/org/openhab/binding/haassohnpelletstove/internal/MD5Utils.java b/bundles/org.openhab.binding.haassohnpelletstove/src/main/java/org/openhab/binding/haassohnpelletstove/internal/MD5Utils.java index 7907b8685..7cfa0b3b9 100644 --- a/bundles/org.openhab.binding.haassohnpelletstove/src/main/java/org/openhab/binding/haassohnpelletstove/internal/MD5Utils.java +++ b/bundles/org.openhab.binding.haassohnpelletstove/src/main/java/org/openhab/binding/haassohnpelletstove/internal/MD5Utils.java @@ -38,8 +38,7 @@ public class MD5Utils { } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException(e); } - byte[] result = md.digest(input); - return result; + return md.digest(input); } private static String bytesToHex(byte[] bytes) { diff --git a/bundles/org.openhab.binding.harmonyhub/src/main/java/org/openhab/binding/harmonyhub/internal/handler/HarmonyDeviceHandler.java b/bundles/org.openhab.binding.harmonyhub/src/main/java/org/openhab/binding/harmonyhub/internal/handler/HarmonyDeviceHandler.java index a13ce2afb..e8f688e5a 100644 --- a/bundles/org.openhab.binding.harmonyhub/src/main/java/org/openhab/binding/harmonyhub/internal/handler/HarmonyDeviceHandler.java +++ b/bundles/org.openhab.binding.harmonyhub/src/main/java/org/openhab/binding/harmonyhub/internal/handler/HarmonyDeviceHandler.java @@ -15,7 +15,6 @@ package org.openhab.binding.harmonyhub.internal.handler; import static org.openhab.binding.harmonyhub.internal.HarmonyHubBindingConstants.*; import java.util.ArrayList; -import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Set; @@ -65,7 +64,7 @@ public class HarmonyDeviceHandler extends BaseThingHandler { private final Logger logger = LoggerFactory.getLogger(HarmonyDeviceHandler.class); - public static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(HARMONY_DEVICE_THING_TYPE); + public static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(HARMONY_DEVICE_THING_TYPE); private final HarmonyHubDynamicTypeProvider typeProvider; diff --git a/bundles/org.openhab.binding.harmonyhub/src/main/java/org/openhab/binding/harmonyhub/internal/handler/HarmonyHubHandler.java b/bundles/org.openhab.binding.harmonyhub/src/main/java/org/openhab/binding/harmonyhub/internal/handler/HarmonyHubHandler.java index e015f3854..4138b8231 100644 --- a/bundles/org.openhab.binding.harmonyhub/src/main/java/org/openhab/binding/harmonyhub/internal/handler/HarmonyHubHandler.java +++ b/bundles/org.openhab.binding.harmonyhub/src/main/java/org/openhab/binding/harmonyhub/internal/handler/HarmonyHubHandler.java @@ -126,9 +126,9 @@ public class HarmonyHubHandler extends BaseBridgeHandler implements HarmonyClien switch (channel.getUID().getId()) { case CHANNEL_CURRENT_ACTIVITY: - if (command instanceof DecimalType) { + if (command instanceof DecimalType decimalCommand) { try { - client.startActivity(((DecimalType) command).intValue()); + client.startActivity(decimalCommand.intValue()); } catch (Exception e) { logger.warn("Could not start activity", e); } diff --git a/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/HaywardBindingConstants.java b/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/HaywardBindingConstants.java index 7646e87fc..6a434b097 100644 --- a/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/HaywardBindingConstants.java +++ b/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/HaywardBindingConstants.java @@ -174,11 +174,13 @@ public class HaywardBindingConstants { // Hayward Command html public static final String COMMAND_PARAMETERS = ""; - public static final String COMMAND_SCHEDULE = "false" - + "0" - + "0" - + "0" - + "0" - + "0" - + "false"; + public static final String COMMAND_SCHEDULE = """ + false\ + 0\ + 0\ + 0\ + 0\ + 0\ + false\ + """; } diff --git a/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/HaywardThingHandler.java b/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/HaywardThingHandler.java index 0266686bc..48db232ca 100644 --- a/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/HaywardThingHandler.java +++ b/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/HaywardThingHandler.java @@ -93,7 +93,7 @@ public abstract class HaywardThingHandler extends BaseThingHandler { if (bridge != null) { HaywardBridgeHandler bridgehandler = (HaywardBridgeHandler) bridge.getHandler(); if (bridgehandler != null) { - if (bridgehandler.account.units.equals("Standard")) { + if ("Standard".equals(bridgehandler.account.units)) { return new QuantityType<>(Integer.parseInt(value), ImperialUnits.FAHRENHEIT); } else { return new QuantityType<>(Integer.parseInt(value), SIUnits.CELSIUS); @@ -112,10 +112,10 @@ public abstract class HaywardThingHandler extends BaseThingHandler { return "0"; } else if (command == OnOffType.ON) { return "1"; - } else if (command instanceof DecimalType) { - return ((DecimalType) command).toString(); - } else if (command instanceof QuantityType) { - return ((QuantityType) command).format("%1.0f"); + } else if (command instanceof DecimalType decimalCommand) { + return decimalCommand.toString(); + } else if (command instanceof QuantityType quantityCommand) { + return quantityCommand.format("%1.0f"); } else { return command.toString(); } diff --git a/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/discovery/HaywardDiscoveryService.java b/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/discovery/HaywardDiscoveryService.java index 568d36c05..84c34f15a 100644 --- a/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/discovery/HaywardDiscoveryService.java +++ b/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/discovery/HaywardDiscoveryService.java @@ -349,8 +349,8 @@ public class HaywardDiscoveryService extends AbstractDiscoveryService implements @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof HaywardBridgeHandler) { - this.discoveryBridgehandler = (HaywardBridgeHandler) handler; + if (handler instanceof HaywardBridgeHandler bridgeHandler) { + this.discoveryBridgehandler = bridgeHandler; } } diff --git a/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardBackyardHandler.java b/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardBackyardHandler.java index c28577c37..ab1790210 100644 --- a/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardBackyardHandler.java +++ b/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardBackyardHandler.java @@ -83,10 +83,12 @@ public class HaywardBackyardHandler extends HaywardThingHandler { HaywardBridgeHandler bridgehandler = (HaywardBridgeHandler) bridge.getHandler(); if (bridgehandler != null) { // *****Request Alarm List from Hayward server - String urlParameters = "GetAlarmList" - + "" + bridgehandler.account.token - + "" + "" - + bridgehandler.account.mspSystemID + "" + String urlParameters = """ + GetAlarmList\ + \ + """ + bridgehandler.account.token + "" + + "" + bridgehandler.account.mspSystemID + + "" + "en-us"; try { diff --git a/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardBridgeHandler.java b/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardBridgeHandler.java index 51b7097a0..fd09bddf0 100644 --- a/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardBridgeHandler.java +++ b/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardBridgeHandler.java @@ -15,9 +15,9 @@ package org.openhab.binding.haywardomnilogic.internal.handler; import java.io.StringReader; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -82,7 +82,7 @@ public class HaywardBridgeHandler extends BaseBridgeHandler { @Override public Collection> getServices() { - return Collections.singleton(HaywardDiscoveryService.class); + return Set.of(HaywardDiscoveryService.class); } public HaywardBridgeHandler(HaywardDynamicStateDescriptionProvider stateDescriptionProvider, Bridge bridge, @@ -191,10 +191,12 @@ public class HaywardBridgeHandler extends BaseBridgeHandler { String status; // *****Login to Hayward server - String urlParameters = "" + "Login" - + "" + config.username + "" - + "" + config.password + "" - + ""; + String urlParameters = """ + \ + Login\ + \ + """ + config.username + "" + "" + + config.password + "" + ""; xmlResponse = httpXmlResponse(urlParameters); @@ -219,9 +221,11 @@ public class HaywardBridgeHandler extends BaseBridgeHandler { String xmlResponse; // *****getApiDef from Hayward server - String urlParameters = "GetAPIDef" - + "" + account.token + "" - + "" + account.mspSystemID + ";" + String urlParameters = """ + GetAPIDef\ + \ + """ + account.token + "" + "" + + account.mspSystemID + ";" + "0.4\r\n" + "en\r\n" + ""; @@ -239,9 +243,10 @@ public class HaywardBridgeHandler extends BaseBridgeHandler { String status; // *****Get MSP - String urlParameters = "GetSiteList" - + "" + account.token - + "" + account.userID + String urlParameters = """ + GetSiteList\ + \ + """ + account.token + "" + account.userID + ""; xmlResponse = httpXmlResponse(urlParameters); @@ -269,10 +274,11 @@ public class HaywardBridgeHandler extends BaseBridgeHandler { public synchronized String getMspConfig() throws HaywardException, InterruptedException { // *****getMspConfig from Hayward server - String urlParameters = "GetMspConfigFile" - + "" + account.token + "" - + "" + account.mspSystemID - + "0\r\n" + String urlParameters = """ + GetMspConfigFile\ + \ + """ + account.token + "" + "" + + account.mspSystemID + "0\r\n" + ""; String xmlResponse = httpXmlResponse(urlParameters); @@ -312,10 +318,11 @@ public class HaywardBridgeHandler extends BaseBridgeHandler { public synchronized boolean getTelemetryData() throws HaywardException, InterruptedException { // *****getTelemetry from Hayward server - String urlParameters = "GetTelemetryData" - + "" + account.token + "" - + "" + account.mspSystemID - + ""; + String urlParameters = """ + GetTelemetryData\ + \ + """ + account.token + "" + "" + + account.mspSystemID + ""; String xmlResponse = httpXmlResponse(urlParameters); diff --git a/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardChlorinatorHandler.java b/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardChlorinatorHandler.java index ef15ceb90..35271515e 100644 --- a/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardChlorinatorHandler.java +++ b/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardChlorinatorHandler.java @@ -90,7 +90,7 @@ public class HaywardChlorinatorHandler extends HaywardThingHandler { data = bridgehandler.evaluateXPath("//Chlorinator/@status", xmlResponse); updateData(HaywardBindingConstants.CHANNEL_CHLORINATOR_STATUS, data.get(i)); - if (data.get(i).equals("0")) { + if ("0".equals(data.get(i))) { updateData(HaywardBindingConstants.CHANNEL_CHLORINATOR_ENABLE, "0"); // chlorState is used to set the chlorinator cfgState in the timedPercent command this.chlorState = "2"; diff --git a/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardColorLogicHandler.java b/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardColorLogicHandler.java index 861431665..a1681db19 100644 --- a/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardColorLogicHandler.java +++ b/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardColorLogicHandler.java @@ -60,7 +60,7 @@ public class HaywardColorLogicHandler extends HaywardThingHandler { data = bridgehandler.evaluateXPath("//ColorLogic-Light/@lightState", xmlResponse); updateData(HaywardBindingConstants.CHANNEL_COLORLOGIC_LIGHTSTATE, data.get(i)); - if (data.get(i).equals("0")) { + if ("0".equals(data.get(i))) { updateData(HaywardBindingConstants.CHANNEL_COLORLOGIC_ENABLE, "0"); } else { updateData(HaywardBindingConstants.CHANNEL_COLORLOGIC_ENABLE, "1"); diff --git a/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardFilterHandler.java b/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardFilterHandler.java index c4eb8ccba..45dcc0ab1 100644 --- a/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardFilterHandler.java +++ b/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardFilterHandler.java @@ -154,7 +154,7 @@ public class HaywardFilterHandler extends HaywardThingHandler { updateData(HaywardBindingConstants.CHANNEL_FILTER_SPEEDRPM, rpmSpeed.toString()); } - if (data.get(i).equals("0")) { + if ("0".equals(data.get(i))) { updateData(HaywardBindingConstants.CHANNEL_FILTER_ENABLE, "0"); } else { updateData(HaywardBindingConstants.CHANNEL_FILTER_ENABLE, "1"); diff --git a/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardHeaterHandler.java b/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardHeaterHandler.java index 1b2b58213..3ceca8361 100644 --- a/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardHeaterHandler.java +++ b/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardHeaterHandler.java @@ -58,7 +58,7 @@ public class HaywardHeaterHandler extends HaywardThingHandler { // Enable data = bridgehandler.evaluateXPath("//Heater/@enable", xmlResponse); - if (data.get(i).equals("0")) { + if ("0".equals(data.get(i))) { updateData(HaywardBindingConstants.CHANNEL_HEATER_ENABLE, "0"); } else { updateData(HaywardBindingConstants.CHANNEL_HEATER_ENABLE, "1"); diff --git a/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardPumpHandler.java b/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardPumpHandler.java index d89e5298d..fb9e6b61c 100644 --- a/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardPumpHandler.java +++ b/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardPumpHandler.java @@ -150,7 +150,7 @@ public class HaywardPumpHandler extends HaywardThingHandler { updateData(HaywardBindingConstants.CHANNEL_PUMP_SPEEDRPM, rpmSpeed.toString()); } - if (data.get(i).equals("0")) { + if ("0".equals(data.get(i))) { updateData(HaywardBindingConstants.CHANNEL_PUMP_ENABLE, "0"); } else { updateData(HaywardBindingConstants.CHANNEL_PUMP_ENABLE, "1"); diff --git a/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardVirtualHeaterHandler.java b/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardVirtualHeaterHandler.java index 3698b59e1..8601fbfa5 100644 --- a/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardVirtualHeaterHandler.java +++ b/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/handler/HaywardVirtualHeaterHandler.java @@ -95,9 +95,9 @@ public class HaywardVirtualHeaterHandler extends HaywardThingHandler { updateData(HaywardBindingConstants.CHANNEL_VIRTUALHEATER_CURRENTSETPOINT, data.get(i)); data = bridgehandler.evaluateXPath("//VirtualHeater/@enable", xmlResponse); - if (data.get(i).equals("yes")) { + if ("yes".equals(data.get(i))) { updateData(HaywardBindingConstants.CHANNEL_VIRTUALHEATER_ENABLE, "1"); - } else if (data.get(i).equals("no")) { + } else if ("no".equals(data.get(i))) { updateData(HaywardBindingConstants.CHANNEL_VIRTUALHEATER_ENABLE, "0"); } } diff --git a/bundles/org.openhab.binding.hccrubbishcollection/src/main/java/org/openhab/binding/hccrubbishcollection/internal/HCCRubbishCollectionHandlerFactory.java b/bundles/org.openhab.binding.hccrubbishcollection/src/main/java/org/openhab/binding/hccrubbishcollection/internal/HCCRubbishCollectionHandlerFactory.java index 6a9ea917a..093bb1a7a 100644 --- a/bundles/org.openhab.binding.hccrubbishcollection/src/main/java/org/openhab/binding/hccrubbishcollection/internal/HCCRubbishCollectionHandlerFactory.java +++ b/bundles/org.openhab.binding.hccrubbishcollection/src/main/java/org/openhab/binding/hccrubbishcollection/internal/HCCRubbishCollectionHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.hccrubbishcollection.internal; import static org.openhab.binding.hccrubbishcollection.internal.HCCRubbishCollectionBindingConstants.*; -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 HCCRubbishCollectionHandlerFactory extends BaseThingHandlerFactory { private final HttpClient httpClient; - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_COLLECTION); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_COLLECTION); @Activate public HCCRubbishCollectionHandlerFactory(final @Reference HttpClientFactory httpClientFactory) { diff --git a/bundles/org.openhab.binding.hdanywhere/src/main/java/org/openhab/binding/hdanywhere/internal/handler/Mhub4K431Handler.java b/bundles/org.openhab.binding.hdanywhere/src/main/java/org/openhab/binding/hdanywhere/internal/handler/Mhub4K431Handler.java index a29c53d43..536c673f8 100644 --- a/bundles/org.openhab.binding.hdanywhere/src/main/java/org/openhab/binding/hdanywhere/internal/handler/Mhub4K431Handler.java +++ b/bundles/org.openhab.binding.hdanywhere/src/main/java/org/openhab/binding/hdanywhere/internal/handler/Mhub4K431Handler.java @@ -143,7 +143,7 @@ public class Mhub4K431Handler extends BaseThingHandler { String content = "{CMD="; content = content + command.toString() + "B"; - content = content + String.valueOf(outputPort) + "."; + content = content + outputPort + "."; InputStream stream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)); diff --git a/bundles/org.openhab.binding.hdanywhere/src/main/java/org/openhab/binding/hdanywhere/internal/handler/MultiroomPlusHandler.java b/bundles/org.openhab.binding.hdanywhere/src/main/java/org/openhab/binding/hdanywhere/internal/handler/MultiroomPlusHandler.java index 561500604..6ab58a748 100644 --- a/bundles/org.openhab.binding.hdanywhere/src/main/java/org/openhab/binding/hdanywhere/internal/handler/MultiroomPlusHandler.java +++ b/bundles/org.openhab.binding.hdanywhere/src/main/java/org/openhab/binding/hdanywhere/internal/handler/MultiroomPlusHandler.java @@ -114,11 +114,11 @@ public class MultiroomPlusHandler extends BaseThingHandler { String httpMethod = "GET"; String url = "http://" + host + "/switch.cgi?command=3&data0="; - url = url + String.valueOf(outputPort) + "&data1="; + url = url + outputPort + "&data1="; url = url + command.toString() + "&checksum="; int checksum = 3 + outputPort + sourcePort; - url = url + String.valueOf(checksum); + url = url + checksum; try { HttpUtil.executeUrl(httpMethod, url, null, null, null, timeout); diff --git a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/GatewayWebTargets.java b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/GatewayWebTargets.java index 1ee0b0bcf..afc5cae81 100644 --- a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/GatewayWebTargets.java +++ b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/GatewayWebTargets.java @@ -422,7 +422,7 @@ public class GatewayWebTargets implements Closeable, HostnameVerifier { * @throws HubProcessingException if any error occurs. */ public void stopShade(int shadeId) throws HubProcessingException { - invoke(HttpMethod.PUT, shadeStop, Query.of(IDS, Integer.valueOf(shadeId).toString()), null); + invoke(HttpMethod.PUT, shadeStop, Query.of(IDS, Integer.toString(shadeId)), null); } /** diff --git a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/builders/AutomationChannelBuilder.java b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/builders/AutomationChannelBuilder.java index a29e7766e..5d5b9fd29 100644 --- a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/builders/AutomationChannelBuilder.java +++ b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/builders/AutomationChannelBuilder.java @@ -147,10 +147,8 @@ public class AutomationChannelBuilder extends BaseChannelBuilder { String label = getScheduledEventName(referencedName, scheduledEvent); String description = translationProvider.getText("dynamic-channel.automation-enabled.description", referencedName); - Channel channel = ChannelBuilder.create(channelUid, CoreItemFactory.SWITCH).withType(channelTypeUid) - .withLabel(label).withDescription(description).build(); - - return channel; + return ChannelBuilder.create(channelUid, CoreItemFactory.SWITCH).withType(channelTypeUid).withLabel(label) + .withDescription(description).build(); } private @Nullable String getReferencedSceneOrSceneCollectionName(ScheduledEvent scheduledEvent) { diff --git a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/console/HDPowerViewCommandExtension.java b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/console/HDPowerViewCommandExtension.java index 3a257db25..b58a18418 100644 --- a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/console/HDPowerViewCommandExtension.java +++ b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/console/HDPowerViewCommandExtension.java @@ -67,9 +67,9 @@ public class HDPowerViewCommandExtension extends AbstractConsoleCommandExtension for (Thing thing : thingRegistry.getAll()) { ThingHandler thingHandler = thing.getHandler(); - if (thingHandler instanceof HDPowerViewHubHandler) { + if (thingHandler instanceof HDPowerViewHubHandler hubHandler) { console.println("Generation 1/2 API hub: " + thing.getLabel()); - HDPowerViewWebTargets webTargets = ((HDPowerViewHubHandler) thingHandler).getWebTargets(); + HDPowerViewWebTargets webTargets = hubHandler.getWebTargets(); try { List shades = webTargets.getShades().shadeData; @@ -90,9 +90,9 @@ public class HDPowerViewCommandExtension extends AbstractConsoleCommandExtension } catch (HubException e) { console.println("Error retrieving ID's: " + e.getMessage()); } - } else if (thingHandler instanceof GatewayBridgeHandler) { + } else if (thingHandler instanceof GatewayBridgeHandler gatewayHandler) { console.println("Generation 3 API gateway: " + thing.getLabel()); - GatewayWebTargets webTargets = ((GatewayBridgeHandler) thingHandler).getWebTargets(); + GatewayWebTargets webTargets = gatewayHandler.getWebTargets(); try { List shades = webTargets.getShades(); diff --git a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/database/ShadeCapabilitiesDatabase.java b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/database/ShadeCapabilitiesDatabase.java index 70dd23308..bae6a2359 100644 --- a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/database/ShadeCapabilitiesDatabase.java +++ b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/database/ShadeCapabilitiesDatabase.java @@ -418,9 +418,9 @@ public class ShadeCapabilitiesDatabase { * @param propertyValue */ public void logPropertyMismatch(String propertyKey, int type, int capabilities, boolean propertyValue) { - logger.warn( - "The '{}:{}' property actually reported by shade 'type:{}' is different " - + "than expected from its 'capabilities:{}' in the database!{}", - propertyKey, propertyValue, type, capabilities, REQUEST_DEVELOPERS_TO_UPDATE); + logger.warn(""" + The '{}:{}' property actually reported by shade 'type:{}' is different \ + than expected from its 'capabilities:{}' in the database!{}\ + """, propertyKey, propertyValue, type, capabilities, REQUEST_DEVELOPERS_TO_UPDATE); } } diff --git a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/discovery/HDPowerViewDeviceDiscoveryService.java b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/discovery/HDPowerViewDeviceDiscoveryService.java index c8c1b8312..25f852ff8 100644 --- a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/discovery/HDPowerViewDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/discovery/HDPowerViewDeviceDiscoveryService.java @@ -12,8 +12,8 @@ */ package org.openhab.binding.hdpowerview.internal.discovery; -import java.util.Collections; import java.util.List; +import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -55,7 +55,7 @@ public class HDPowerViewDeviceDiscoveryService extends AbstractDiscoveryService private final ShadeCapabilitiesDatabase db = new ShadeCapabilitiesDatabase(); public HDPowerViewDeviceDiscoveryService(HDPowerViewHubHandler hub) { - super(Collections.singleton(HDPowerViewBindingConstants.THING_TYPE_SHADE), 60, true); + super(Set.of(HDPowerViewBindingConstants.THING_TYPE_SHADE), 60, true); this.hub = hub; this.scanner = createScanner(); } diff --git a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/discovery/HDPowerViewHubDiscoveryParticipant.java b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/discovery/HDPowerViewHubDiscoveryParticipant.java index a4c98977e..fdb94b7d8 100644 --- a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/discovery/HDPowerViewHubDiscoveryParticipant.java +++ b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/discovery/HDPowerViewHubDiscoveryParticipant.java @@ -14,7 +14,6 @@ package org.openhab.binding.hdpowerview.internal.discovery; import static org.openhab.binding.hdpowerview.internal.HDPowerViewBindingConstants.*; -import java.util.Collections; import java.util.Set; import javax.jmdns.ServiceInfo; @@ -46,7 +45,7 @@ public class HDPowerViewHubDiscoveryParticipant implements MDNSDiscoveryParticip @Override public Set getSupportedThingTypeUIDs() { - return Collections.singleton(THING_TYPE_HUB); + return Set.of(THING_TYPE_HUB); } @Override diff --git a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/discovery/HDPowerViewHubDiscoveryService.java b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/discovery/HDPowerViewHubDiscoveryService.java index 6defbf71a..d5a77b4f7 100644 --- a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/discovery/HDPowerViewHubDiscoveryService.java +++ b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/discovery/HDPowerViewHubDiscoveryService.java @@ -15,7 +15,7 @@ package org.openhab.binding.hdpowerview.internal.discovery; import static org.openhab.binding.hdpowerview.internal.HDPowerViewBindingConstants.*; import java.net.UnknownHostException; -import java.util.Collections; +import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -48,7 +48,7 @@ public class HDPowerViewHubDiscoveryService extends AbstractDiscoveryService { private @Nullable ScheduledFuture backgroundFuture; public HDPowerViewHubDiscoveryService() { - super(Collections.singleton(THING_TYPE_HUB), 60, true); + super(Set.of(THING_TYPE_HUB), 60, true); scanner = createScanner(); } diff --git a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/discovery/ShadeDiscoveryService.java b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/discovery/ShadeDiscoveryService.java index 80ae30968..f6b4ba186 100644 --- a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/discovery/ShadeDiscoveryService.java +++ b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/discovery/ShadeDiscoveryService.java @@ -12,7 +12,7 @@ */ package org.openhab.binding.hdpowerview.internal.discovery; -import java.util.Collections; +import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -44,7 +44,7 @@ public class ShadeDiscoveryService extends AbstractDiscoveryService { private @Nullable ScheduledFuture backgroundFuture; public ShadeDiscoveryService(GatewayBridgeHandler hub) { - super(Collections.singleton(HDPowerViewBindingConstants.THING_TYPE_SHADE3), 60, true); + super(Set.of(HDPowerViewBindingConstants.THING_TYPE_SHADE3), 60, true); this.hub = hub; this.scanner = createScanner(); } diff --git a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/dto/ShadePosition.java b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/dto/ShadePosition.java index 1c536dea8..8f8b250b8 100644 --- a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/dto/ShadePosition.java +++ b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/dto/ShadePosition.java @@ -85,8 +85,8 @@ public class ShadePosition { if (shadeCapabilities.supportsPrimary() && shadeCapabilities.supportsSecondary()) { // on dual rail shades constrain percent to not move the lower rail above the upper State secondary = getState(shadeCapabilities, SECONDARY_POSITION); - if (secondary instanceof PercentType) { - int secPercent = ((PercentType) secondary).intValue(); + if (secondary instanceof PercentType percentCommand) { + int secPercent = percentCommand.intValue(); if (percent < secPercent) { percent = secPercent; } @@ -221,8 +221,8 @@ public class ShadePosition { if (shadeCapabilities.supportsPrimary() && shadeCapabilities.supportsSecondary()) { // on dual rail shades constrain percent to not move the upper rail below the lower State primary = getState(shadeCapabilities, PRIMARY_POSITION); - if (primary instanceof PercentType) { - int primaryPercent = ((PercentType) primary).intValue(); + if (primary instanceof PercentType percentCommand) { + int primaryPercent = percentCommand.intValue(); if (percent > primaryPercent) { percent = primaryPercent; } diff --git a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/dto/gen3/PowerType.java b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/dto/gen3/PowerType.java index 62a85c4a6..369b49e3c 100644 --- a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/dto/gen3/PowerType.java +++ b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/dto/gen3/PowerType.java @@ -20,5 +20,5 @@ package org.openhab.binding.hdpowerview.internal.dto.gen3; public enum PowerType { BATTERY, HARDWIRED, - RECHARGEABLE; + RECHARGEABLE } diff --git a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/handler/GatewayBridgeHandler.java b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/handler/GatewayBridgeHandler.java index b8c01af68..e1bc5aeca 100644 --- a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/handler/GatewayBridgeHandler.java +++ b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/handler/GatewayBridgeHandler.java @@ -88,8 +88,8 @@ public class GatewayBridgeHandler extends BaseBridgeHandler { @Override public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) { - if (childHandler instanceof ShadeThingHandler) { - refreshShade(((ShadeThingHandler) childHandler).getShadeId()); + if (childHandler instanceof ShadeThingHandler shadeThingHandler) { + refreshShade(shadeThingHandler.getShadeId()); } } diff --git a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/handler/HDPowerViewHubHandler.java b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/handler/HDPowerViewHubHandler.java index 68065587d..f688e371d 100644 --- a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/handler/HDPowerViewHubHandler.java +++ b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/handler/HDPowerViewHubHandler.java @@ -601,8 +601,8 @@ public class HDPowerViewHubHandler extends BaseBridgeHandler { continue; } ThingHandler handler = thing.getHandler(); - if (handler instanceof HDPowerViewShadeHandler) { - ((HDPowerViewShadeHandler) handler).requestRefreshShadePosition(); + if (handler instanceof HDPowerViewShadeHandler shadeHandler) { + shadeHandler.requestRefreshShadePosition(); } else { int shadeId = item.getValue(); logger.debug("Shade '{}' handler not initialized", shadeId); @@ -620,8 +620,8 @@ public class HDPowerViewHubHandler extends BaseBridgeHandler { continue; } ThingHandler handler = thing.getHandler(); - if (handler instanceof HDPowerViewShadeHandler) { - ((HDPowerViewShadeHandler) handler).requestRefreshShadeBatteryLevel(); + if (handler instanceof HDPowerViewShadeHandler shadeHandler) { + shadeHandler.requestRefreshShadeBatteryLevel(); } else { int shadeId = item.getValue(); logger.debug("Shade '{}' handler not initialized", shadeId); diff --git a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/handler/HDPowerViewShadeHandler.java b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/handler/HDPowerViewShadeHandler.java index ec0a6fdab..5da73ab1e 100644 --- a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/handler/HDPowerViewShadeHandler.java +++ b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/handler/HDPowerViewShadeHandler.java @@ -193,8 +193,8 @@ public class HDPowerViewShadeHandler extends AbstractHubbedThingHandler { HubShadeTimeoutException { switch (channelId) { case CHANNEL_SHADE_POSITION: - if (command instanceof PercentType) { - moveShade(PRIMARY_POSITION, ((PercentType) command).intValue(), webTargets, shadeId); + if (command instanceof PercentType percentCommand) { + moveShade(PRIMARY_POSITION, percentCommand.intValue(), webTargets, shadeId); } else if (command instanceof UpDownType) { moveShade(PRIMARY_POSITION, UpDownType.UP == command ? 0 : 100, webTargets, shadeId); } else if (command instanceof StopMoveType) { @@ -207,16 +207,16 @@ public class HDPowerViewShadeHandler extends AbstractHubbedThingHandler { break; case CHANNEL_SHADE_VANE: - if (command instanceof PercentType) { - moveShade(VANE_TILT_POSITION, ((PercentType) command).intValue(), webTargets, shadeId); + if (command instanceof PercentType percentCommand) { + moveShade(VANE_TILT_POSITION, percentCommand.intValue(), webTargets, shadeId); } else if (command instanceof OnOffType) { moveShade(VANE_TILT_POSITION, OnOffType.ON == command ? 100 : 0, webTargets, shadeId); } break; case CHANNEL_SHADE_SECONDARY_POSITION: - if (command instanceof PercentType) { - moveShade(SECONDARY_POSITION, ((PercentType) command).intValue(), webTargets, shadeId); + if (command instanceof PercentType percentCommand) { + moveShade(SECONDARY_POSITION, percentCommand.intValue(), webTargets, shadeId); } else if (command instanceof UpDownType) { moveShade(SECONDARY_POSITION, UpDownType.UP == command ? 0 : 100, webTargets, shadeId); } else if (command instanceof StopMoveType) { @@ -229,11 +229,11 @@ public class HDPowerViewShadeHandler extends AbstractHubbedThingHandler { break; case CHANNEL_SHADE_COMMAND: - if (command instanceof StringType) { - if (COMMAND_IDENTIFY.equals(((StringType) command).toString())) { + if (command instanceof StringType stringCommand) { + if (COMMAND_IDENTIFY.equals(stringCommand.toString())) { logger.debug("Identify shade {}", shadeId); identifyShade(webTargets, shadeId); - } else if (COMMAND_CALIBRATE.equals(((StringType) command).toString())) { + } else if (COMMAND_CALIBRATE.equals(stringCommand.toString())) { logger.debug("Calibrate shade {}", shadeId); calibrateShade(webTargets, shadeId); } diff --git a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/handler/ShadeThingHandler.java b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/handler/ShadeThingHandler.java index a106c52d9..cca96c223 100644 --- a/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/handler/ShadeThingHandler.java +++ b/bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/handler/ShadeThingHandler.java @@ -116,8 +116,8 @@ public class ShadeThingHandler extends BaseThingHandler { try { switch (channelUID.getId()) { case CHANNEL_SHADE_POSITION: - if (command instanceof PercentType) { - position.setPosition(PRIMARY_POSITION, ((PercentType) command)); + if (command instanceof PercentType percentCommand) { + position.setPosition(PRIMARY_POSITION, percentCommand); webTargets.moveShade(shadeId, new Shade().setShadePosition(position)); break; } else if (command instanceof UpDownType) { @@ -134,8 +134,8 @@ public class ShadeThingHandler extends BaseThingHandler { throw new IllegalArgumentException(INVALID_COMMAND); case CHANNEL_SHADE_SECONDARY_POSITION: - if (command instanceof PercentType) { - position.setPosition(SECONDARY_POSITION, ((PercentType) command)); + if (command instanceof PercentType percentCommand) { + position.setPosition(SECONDARY_POSITION, percentCommand); webTargets.moveShade(shadeId, new Shade().setShadePosition(position)); break; } else if (command instanceof UpDownType) { @@ -153,8 +153,8 @@ public class ShadeThingHandler extends BaseThingHandler { throw new IllegalArgumentException(INVALID_COMMAND); case CHANNEL_SHADE_VANE: - if (command instanceof PercentType) { - position.setPosition(VANE_TILT_POSITION, ((PercentType) command)); + if (command instanceof PercentType percentCommand) { + position.setPosition(VANE_TILT_POSITION, percentCommand); webTargets.moveShade(shadeId, new Shade().setShadePosition(position)); break; } else if (command instanceof UpDownType) { @@ -166,7 +166,8 @@ public class ShadeThingHandler extends BaseThingHandler { throw new IllegalArgumentException(INVALID_COMMAND); case CHANNEL_SHADE_COMMAND: - if ((command instanceof StringType) && COMMAND_IDENTIFY.equals(((StringType) command).toString())) { + if ((command instanceof StringType stringCommand) + && COMMAND_IDENTIFY.equals(stringCommand.toString())) { webTargets.jogShade(shadeId); break; } diff --git a/bundles/org.openhab.binding.hdpowerview/src/test/java/org/openhab/binding/hdpowerview/internal/providers/MockedLocaleProvider.java b/bundles/org.openhab.binding.hdpowerview/src/test/java/org/openhab/binding/hdpowerview/internal/providers/MockedLocaleProvider.java index 2293e2db1..af0fcfc1f 100644 --- a/bundles/org.openhab.binding.hdpowerview/src/test/java/org/openhab/binding/hdpowerview/internal/providers/MockedLocaleProvider.java +++ b/bundles/org.openhab.binding.hdpowerview/src/test/java/org/openhab/binding/hdpowerview/internal/providers/MockedLocaleProvider.java @@ -24,6 +24,7 @@ import org.openhab.core.i18n.LocaleProvider; */ @NonNullByDefault public class MockedLocaleProvider implements LocaleProvider { + @Override public Locale getLocale() { return Locale.ENGLISH; } diff --git a/bundles/org.openhab.binding.helios/src/main/java/org/openhab/binding/helios/internal/handler/HeliosHandler221.java b/bundles/org.openhab.binding.helios/src/main/java/org/openhab/binding/helios/internal/handler/HeliosHandler221.java index 7a88f0c15..b8cd69052 100644 --- a/bundles/org.openhab.binding.helios/src/main/java/org/openhab/binding/helios/internal/handler/HeliosHandler221.java +++ b/bundles/org.openhab.binding.helios/src/main/java/org/openhab/binding/helios/internal/handler/HeliosHandler221.java @@ -209,15 +209,15 @@ public class HeliosHandler221 extends BaseThingHandler { if (logger.isTraceEnabled()) { logger.trace("initialize() Request : {}", systemTarget.resolveTemplate("ip", ipAddress) .resolveTemplate("cmd", INFO).getUri().toASCIIString()); - if (jsonObject.get("success").toString().equals("true")) { + if ("true".equals(jsonObject.get("success").toString())) { logger.trace("initialize() Response: {}", jsonObject.get("result")); } - if (jsonObject.get("success").toString().equals("false")) { + if ("false".equals(jsonObject.get("success").toString())) { logger.trace("initialize() Response: {}", jsonObject.get("error")); } } - if (jsonObject.get("success").toString().equals("false")) { + if ("false".equals(jsonObject.get("success").toString())) { RESTError error = gson.fromJson(jsonObject.get("error").toString(), RESTError.class); logger.debug( "An error occurred while communicating with the Helios IP Vario '{}': code '{}', param '{}' : '{}'", @@ -228,7 +228,7 @@ public class HeliosHandler221 extends BaseThingHandler { return; } - if (jsonObject.get("success").toString().equals("true")) { + if ("true".equals(jsonObject.get("success").toString())) { if (logJob == null || logJob.isCancelled()) { logJob = scheduler.scheduleWithFixedDelay(logRunnable, 0, 1, TimeUnit.SECONDS); } @@ -316,15 +316,15 @@ public class HeliosHandler221 extends BaseThingHandler { logTarget.resolveTemplate("ip", ipAddress).resolveTemplate("cmd", SUBSCRIBE) .queryParam("include", "new").queryParam("duration", HELIOS_DURATION).getUri() .toASCIIString()); - if (jsonObject.get("success").toString().equals("true")) { + if ("true".equals(jsonObject.get("success").toString())) { logger.trace("subscribe() Response: {}", jsonObject.get("result")); } - if (jsonObject.get("success").toString().equals("false")) { + if ("false".equals(jsonObject.get("success").toString())) { logger.trace("subscribe() Response: {}", jsonObject.get("error")); } } - if (jsonObject.get("success").toString().equals("true")) { + if ("true".equals(jsonObject.get("success").toString())) { RESTSubscribeResponse subscribeResponse = gson.fromJson(jsonObject.get("result").toString(), RESTSubscribeResponse.class); logger.debug("The subscription id to pull logs from the Helios IP Vario '{}' is '{}'", @@ -377,15 +377,15 @@ public class HeliosHandler221 extends BaseThingHandler { logger.trace("unsubscribe() Request : {}", logTarget.resolveTemplate("ip", ipAddress).resolveTemplate("cmd", UNSUBSCRIBE) .queryParam("id", logSubscriptionID).getUri().toASCIIString()); - if (jsonObject.get("success").toString().equals("true")) { + if ("true".equals(jsonObject.get("success").toString())) { logger.trace("unsubscribe() Response: {}", jsonObject.get("result")); } - if (jsonObject.get("success").toString().equals("false")) { + if ("false".equals(jsonObject.get("success").toString())) { logger.trace("unsubscribe() Response: {}", jsonObject.get("error")); } } - if (jsonObject.get("success").toString().equals("true")) { + if ("true".equals(jsonObject.get("success").toString())) { logger.debug("Successfully unsubscribed from the log entries of the Helios IP Vario '{}'", getThing().getUID().toString()); } else { @@ -439,15 +439,15 @@ public class HeliosHandler221 extends BaseThingHandler { logTarget.resolveTemplate("ip", ipAddress).resolveTemplate("cmd", PULL) .queryParam("id", logSubscriptionID).queryParam("timeout", HELIOS_PULL_DURATION) .getUri().toASCIIString()); - if (jsonObject.get("success").toString().equals("true")) { + if ("true".equals(jsonObject.get("success").toString())) { logger.trace("pullLog() Response: {}", jsonObject.get("result")); } - if (jsonObject.get("success").toString().equals("false")) { + if ("false".equals(jsonObject.get("success").toString())) { logger.trace("pullLog() Response: {}", jsonObject.get("error")); } } - if (jsonObject.get("success").toString().equals("true")) { + if ("true".equals(jsonObject.get("success").toString())) { logger.trace("Successfully pulled log entries from the Helios IP Vario '{}'", getThing().getUID().toString()); JsonObject js = (JsonObject) jsonObject.get("result"); @@ -499,15 +499,15 @@ public class HeliosHandler221 extends BaseThingHandler { if (logger.isTraceEnabled()) { logger.trace("getSwitches() Request : {}", switchTarget.resolveTemplate("ip", ipAddress) .resolveTemplate("cmd", CAPABILITIES).getUri().toASCIIString()); - if (jsonObject.get("success").toString().equals("true")) { + if ("true".equals(jsonObject.get("success").toString())) { logger.trace("getSwitches() Response: {}", jsonObject.get("result")); } - if (jsonObject.get("success").toString().equals("false")) { + if ("false".equals(jsonObject.get("success").toString())) { logger.trace("getSwitches() Response: {}", jsonObject.get("error")); } } - if (jsonObject.get("success").toString().equals("true")) { + if ("true".equals(jsonObject.get("success").toString())) { logger.debug("Successfully requested switch capabilities from the Helios IP Vario '{}'", getThing().getUID().toString()); String result = jsonObject.get("result").toString(); @@ -566,15 +566,15 @@ public class HeliosHandler221 extends BaseThingHandler { logger.trace("triggerSwitch() Request : {}", switchTarget.resolveTemplate("ip", ipAddress).resolveTemplate("cmd", CONTROL) .queryParam("switch", id).queryParam("action", "trigger").getUri().toASCIIString()); - if (jsonObject.get("success").toString().equals("true")) { + if ("true".equals(jsonObject.get("success").toString())) { logger.trace("triggerSwitch() Response: {}", jsonObject.get("result")); } - if (jsonObject.get("success").toString().equals("false")) { + if ("false".equals(jsonObject.get("success").toString())) { logger.trace("triggerSwitch() Response: {}", jsonObject.get("error")); } } - if (jsonObject.get("success").toString().equals("true")) { + if ("true".equals(jsonObject.get("success").toString())) { logger.debug("Successfully triggered a switch on the Helios IP Vario '{}'", getThing().getUID().toString()); } else { @@ -622,15 +622,15 @@ public class HeliosHandler221 extends BaseThingHandler { switchTarget.resolveTemplate("ip", ipAddress).resolveTemplate("cmd", CONTROL) .queryParam("switch", id).queryParam("action", flag ? "on" : "off").getUri() .toASCIIString()); - if (jsonObject.get("success").toString().equals("true")) { + if ("true".equals(jsonObject.get("success").toString())) { logger.trace("enableSwitch() Response: {}", jsonObject.get("result")); } - if (jsonObject.get("success").toString().equals("false")) { + if ("false".equals(jsonObject.get("success").toString())) { logger.trace("enableSwitch() Response: {}", jsonObject.get("error")); } } - if (jsonObject.get("success").toString().equals("true")) { + if ("true".equals(jsonObject.get("success").toString())) { logger.debug("Successfully dis/enabled a switch on the Helios IP Vario '{}'", getThing().getUID().toString()); } else { @@ -675,15 +675,15 @@ public class HeliosHandler221 extends BaseThingHandler { if (logger.isTraceEnabled()) { logger.trace("getPorts() Request : {}", portTarget.resolveTemplate("ip", ipAddress) .resolveTemplate("cmd", CAPABILITIES).getUri().toASCIIString()); - if (jsonObject.get("success").toString().equals("true")) { + if ("true".equals(jsonObject.get("success").toString())) { logger.trace("getPorts() Response: {}", jsonObject.get("result")); } - if (jsonObject.get("success").toString().equals("false")) { + if ("false".equals(jsonObject.get("success").toString())) { logger.trace("getPorts() Response: {}", jsonObject.get("error")); } } - if (jsonObject.get("success").toString().equals("true")) { + if ("true".equals(jsonObject.get("success").toString())) { logger.debug("Successfully requested port capabilities from the Helios IP Vario '{}'", getThing().getUID().toString()); JsonObject js = (JsonObject) jsonObject.get("result"); @@ -743,10 +743,10 @@ public class HeliosHandler221 extends BaseThingHandler { if (logger.isTraceEnabled()) { logger.trace("configureRunnable Request : {}", systemTarget.resolveTemplate("ip", ipAddress) .resolveTemplate("cmd", INFO).getUri().toASCIIString()); - if (jsonObject.get("success").toString().equals("true")) { + if ("true".equals(jsonObject.get("success").toString())) { logger.trace("configureRunnable Response: {}", jsonObject.get("result")); } - if (jsonObject.get("success").toString().equals("false")) { + if ("false".equals(jsonObject.get("success").toString())) { logger.trace("configureRunnable Response: {}", jsonObject.get("error")); } } @@ -767,7 +767,7 @@ public class HeliosHandler221 extends BaseThingHandler { if (switches != null) { for (RESTSwitch aSwitch : switches) { - if (aSwitch.enabled.equals("true")) { + if ("true".equals(aSwitch.enabled)) { logger.debug("Adding a channel to the Helios IP Vario '{}' for the switch with id '{}'", getThing().getUID().toString(), aSwitch.id); ThingBuilder thingBuilder = editThing(); @@ -852,9 +852,9 @@ public class HeliosHandler221 extends BaseThingHandler { break; } case AUDIOLOOPTEST: { - if (event.params.get("result").getAsString().equals("passed")) { + if ("passed".equals(event.params.get("result").getAsString())) { updateState(AUDIO_LOOP_TEST, OnOffType.ON); - } else if (event.params.get("result").getAsString().equals("failed")) { + } else if ("failed".equals(event.params.get("result").getAsString())) { updateState(AUDIO_LOOP_TEST, OnOffType.OFF); } else { updateState(AUDIO_LOOP_TEST, UnDefType.UNDEF); @@ -864,9 +864,9 @@ public class HeliosHandler221 extends BaseThingHandler { break; } case MOTIONDETECTED: { - if (event.params.get("state").getAsString().equals("in")) { + if ("in".equals(event.params.get("state").getAsString())) { updateState(MOTION, OnOffType.ON); - } else if (event.params.get("state").getAsString().equals("out")) { + } else if ("out".equals(event.params.get("state").getAsString())) { updateState(MOTION, OnOffType.OFF); } else { updateState(MOTION, UnDefType.UNDEF); @@ -876,9 +876,9 @@ public class HeliosHandler221 extends BaseThingHandler { break; } case NOISEDETECTED: { - if (event.params.get("state").getAsString().equals("in")) { + if ("in".equals(event.params.get("state").getAsString())) { updateState(NOISE, OnOffType.ON); - } else if (event.params.get("state").getAsString().equals("out")) { + } else if ("out".equals(event.params.get("state").getAsString())) { updateState(NOISE, OnOffType.OFF); } else { updateState(NOISE, UnDefType.UNDEF); @@ -902,9 +902,9 @@ public class HeliosHandler221 extends BaseThingHandler { case CODEENTERED: { triggerChannel(CODE, event.params.get("code").getAsString()); - if (event.params.get("valid").getAsString().equals("true")) { + if ("true".equals(event.params.get("valid").getAsString())) { updateState(CODE_VALID, OnOffType.ON); - } else if (event.params.get("valid").getAsString().equals("false")) { + } else if ("false".equals(event.params.get("valid").getAsString())) { updateState(CODE_VALID, OnOffType.OFF); } else { updateState(CODE_VALID, UnDefType.UNDEF); @@ -916,9 +916,9 @@ public class HeliosHandler221 extends BaseThingHandler { case CARDENTERED: { triggerChannel(CARD, event.params.get("uid").getAsString()); - if (event.params.get("valid").getAsString().equals("true")) { + if ("true".equals(event.params.get("valid").getAsString())) { updateState(CARD_VALID, OnOffType.ON); - } else if (event.params.get("valid").getAsString().equals("false")) { + } else if ("false".equals(event.params.get("valid").getAsString())) { updateState(CARD_VALID, OnOffType.OFF); } else { updateState(CARD_VALID, UnDefType.UNDEF); @@ -931,9 +931,9 @@ public class HeliosHandler221 extends BaseThingHandler { ChannelUID inputChannel = new ChannelUID(getThing().getUID(), "io" + event.params.get("port").getAsString()); - if (event.params.get("state").getAsString().equals("true")) { + if ("true".equals(event.params.get("state").getAsString())) { updateState(inputChannel, OnOffType.ON); - } else if (event.params.get("state").getAsString().equals("false")) { + } else if ("false".equals(event.params.get("state").getAsString())) { updateState(inputChannel, OnOffType.OFF); } else { updateState(inputChannel, UnDefType.UNDEF); @@ -944,9 +944,9 @@ public class HeliosHandler221 extends BaseThingHandler { ChannelUID inputChannel = new ChannelUID(getThing().getUID(), "io" + event.params.get("port").getAsString()); - if (event.params.get("state").getAsString().equals("true")) { + if ("true".equals(event.params.get("state").getAsString())) { updateState(inputChannel, OnOffType.ON); - } else if (event.params.get("state").getAsString().equals("false")) { + } else if ("false".equals(event.params.get("state").getAsString())) { updateState(inputChannel, OnOffType.OFF); } else { updateState(inputChannel, UnDefType.UNDEF); @@ -967,9 +967,9 @@ public class HeliosHandler221 extends BaseThingHandler { break; } case SWITCHSTATECHANGED: { - if (event.params.get("state").getAsString().equals("true")) { + if ("true".equals(event.params.get("state").getAsString())) { updateState(SWITCH_STATE, OnOffType.ON); - } else if (event.params.get("state").getAsString().equals("false")) { + } else if ("false".equals(event.params.get("state").getAsString())) { updateState(SWITCH_STATE, OnOffType.OFF); } else { updateState(SWITCH_STATE, UnDefType.UNDEF); diff --git a/bundles/org.openhab.binding.heliosventilation/src/main/java/org/openhab/binding/heliosventilation/internal/HeliosVentilationHandlerFactory.java b/bundles/org.openhab.binding.heliosventilation/src/main/java/org/openhab/binding/heliosventilation/internal/HeliosVentilationHandlerFactory.java index 4207beda6..f91ac3a17 100644 --- a/bundles/org.openhab.binding.heliosventilation/src/main/java/org/openhab/binding/heliosventilation/internal/HeliosVentilationHandlerFactory.java +++ b/bundles/org.openhab.binding.heliosventilation/src/main/java/org/openhab/binding/heliosventilation/internal/HeliosVentilationHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.heliosventilation.internal; import static org.openhab.binding.heliosventilation.internal.HeliosVentilationBindingConstants.THING_TYPE_HELIOS_VENTILATION; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -39,8 +38,7 @@ import org.osgi.service.component.annotations.Reference; @Component(configurationPid = "binding.heliosventilation", service = ThingHandlerFactory.class) public class HeliosVentilationHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections - .singleton(THING_TYPE_HELIOS_VENTILATION); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_HELIOS_VENTILATION); private final SerialPortManager serialPortManager; diff --git a/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/action/HeosActions.java b/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/action/HeosActions.java index 8cd281586..5ed5fae19 100644 --- a/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/action/HeosActions.java +++ b/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/action/HeosActions.java @@ -43,8 +43,8 @@ public class HeosActions implements ThingActions { @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof HeosBridgeHandler) { - this.handler = (HeosBridgeHandler) handler; + if (handler instanceof HeosBridgeHandler bridgeHandler) { + this.handler = bridgeHandler; } } diff --git a/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/discovery/HeosDiscoveryParticipant.java b/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/discovery/HeosDiscoveryParticipant.java index e55cbdad3..88067dbfc 100644 --- a/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/discovery/HeosDiscoveryParticipant.java +++ b/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/discovery/HeosDiscoveryParticipant.java @@ -14,7 +14,6 @@ package org.openhab.binding.heos.internal.discovery; import static org.openhab.binding.heos.internal.HeosBindingConstants.*; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -48,7 +47,7 @@ public class HeosDiscoveryParticipant implements UpnpDiscoveryParticipant { @Override public Set getSupportedThingTypeUIDs() { - return Collections.singleton(THING_TYPE_BRIDGE); + return Set.of(THING_TYPE_BRIDGE); } @Override diff --git a/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/handler/HeosBridgeHandler.java b/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/handler/HeosBridgeHandler.java index 1efd1223a..bc97f0dcb 100644 --- a/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/handler/HeosBridgeHandler.java +++ b/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/handler/HeosBridgeHandler.java @@ -19,7 +19,6 @@ import static org.openhab.core.thing.ThingStatus.ONLINE; import java.io.IOException; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -220,9 +219,8 @@ public class HeosBridgeHandler extends BaseBridgeHandler implements HeosEventLis try { @Nullable ThingHandler handler = thing.getHandler(); - if (handler instanceof HeosThingBaseHandler) { + if (handler instanceof HeosThingBaseHandler heosHandler) { Set target = handler instanceof HeosPlayerHandler ? players : groups; - HeosThingBaseHandler heosHandler = (HeosThingBaseHandler) handler; String id = heosHandler.getId(); if (target.contains(id)) { @@ -303,12 +301,12 @@ public class HeosBridgeHandler extends BaseBridgeHandler implements HeosEventLis } else if (childHandler instanceof HeosPlayerHandler) { String channelIdentifier = "P" + childThing.getUID().getId(); updateThingChannels(channelManager.removeSingleChannel(channelIdentifier)); - } else if (childHandler instanceof HeosGroupHandler) { + } else if (childHandler instanceof HeosGroupHandler groupHandler) { String channelIdentifier = "G" + childThing.getUID().getId(); updateThingChannels(channelManager.removeSingleChannel(channelIdentifier)); // removes the handler from the groupMemberMap that handler is no longer called // if group is getting online - removeGroupHandlerInformation((HeosGroupHandler) childHandler); + removeGroupHandlerInformation(groupHandler); } } @@ -361,13 +359,13 @@ public class HeosBridgeHandler extends BaseBridgeHandler implements HeosEventLis String pid = ""; @Nullable ThingHandler handler = childThing.getHandler(); - if (handler instanceof HeosPlayerHandler) { + if (handler instanceof HeosPlayerHandler playerHandler) { channelIdentifier = "P" + childThing.getUID().getId(); - pid = ((HeosPlayerHandler) handler).getId(); - } else if (handler instanceof HeosGroupHandler) { + pid = playerHandler.getId(); + } else if (handler instanceof HeosGroupHandler groupHandler) { channelIdentifier = "G" + childThing.getUID().getId(); if (groupId == null) { - pid = ((HeosGroupHandler) handler).getId(); + pid = groupHandler.getId(); } else { pid = groupId; } @@ -520,7 +518,7 @@ public class HeosBridgeHandler extends BaseBridgeHandler implements HeosEventLis @Override public Collection> getServices() { - return Collections.singletonList(HeosActions.class); + return List.of(HeosActions.class); } public void registerMediaEventListener(HeosMediaEventListener heosMediaEventListener) { diff --git a/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/handler/HeosThingBaseHandler.java b/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/handler/HeosThingBaseHandler.java index 8dea3c4a9..e839fb54a 100644 --- a/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/handler/HeosThingBaseHandler.java +++ b/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/handler/HeosThingBaseHandler.java @@ -387,16 +387,16 @@ public abstract class HeosThingBaseHandler extends BaseThingHandler implements H case GET_NOW_PLAYING_MEDIA: @Nullable T mediaPayload = responseObject.payload; - if (mediaPayload instanceof Media) { - handleThingMediaUpdate((Media) mediaPayload); + if (mediaPayload instanceof Media media) { + handleThingMediaUpdate(media); } break; case GET_PLAYER_INFO: @Nullable T playerPayload = responseObject.payload; - if (playerPayload instanceof Player) { - handlePlayerInfo((Player) playerPayload); + if (playerPayload instanceof Player player) { + handlePlayerInfo(player); } break; } diff --git a/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/resources/Telnet.java b/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/resources/Telnet.java index 046823daf..83b378f4b 100644 --- a/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/resources/Telnet.java +++ b/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/resources/Telnet.java @@ -166,8 +166,8 @@ public class Telnet { throw new ReadException(e); } catch (ExecutionException e) { Throwable cause = e.getCause(); - if (cause instanceof IOException) { - throw (IOException) cause; + if (cause instanceof IOException exception) { + throw exception; } else { throw new ReadException(cause); } diff --git a/bundles/org.openhab.binding.heos/src/test/java/org/openhab/binding/heos/internal/json/HeosJsonParserResponseTest.java b/bundles/org.openhab.binding.heos/src/test/java/org/openhab/binding/heos/internal/json/HeosJsonParserResponseTest.java index 1b838dc85..e2f496173 100644 --- a/bundles/org.openhab.binding.heos/src/test/java/org/openhab/binding/heos/internal/json/HeosJsonParserResponseTest.java +++ b/bundles/org.openhab.binding.heos/src/test/java/org/openhab/binding/heos/internal/json/HeosJsonParserResponseTest.java @@ -138,9 +138,11 @@ public class HeosJsonParserResponseTest { @Test public void get_players() { HeosResponseObject response = subject.parseResponse( - "{\"heos\": {\"command\": \"player/get_players\", \"result\": \"success\", \"message\": \"\"}, \"payload\": [" - + "{\"name\": \"Kantoor HEOS 3\", \"pid\": -831584083, \"model\": \"HEOS 3\", \"version\": \"1.520.200\", \"ip\": \"192.168.1.230\", \"network\": \"wired\", \"lineout\": 0, \"serial\": \"ACNG9180110887\"}, " - + "{\"name\": \"HEOS Bar\", \"pid\": 1958912779, \"model\": \"HEOS Bar\", \"version\": \"1.520.200\", \"ip\": \"192.168.1.195\", \"network\": \"wired\", \"lineout\": 0, \"serial\": \"ADAG9180917029\"}]}", + """ + {"heos": {"command": "player/get_players", "result": "success", "message": ""}, "payload": [\ + {"name": "Kantoor HEOS 3", "pid": -831584083, "model": "HEOS 3", "version": "1.520.200", "ip": "192.168.1.230", "network": "wired", "lineout": 0, "serial": "ACNG9180110887"}, \ + {"name": "HEOS Bar", "pid": 1958912779, "model": "HEOS Bar", "version": "1.520.200", "ip": "192.168.1.195", "network": "wired", "lineout": 0, "serial": "ADAG9180917029"}]}\ + """, Player[].class); assertEquals(HeosCommandGroup.PLAYER, response.heosCommand.commandGroup); @@ -194,8 +196,10 @@ public class HeosJsonParserResponseTest { @Test public void get_now_playing_media() { HeosResponseObject response = subject.parseResponse( - "{\"heos\": {\"command\": \"player/get_now_playing_media\", \"result\": \"success\", \"message\": \"pid=1958912779\"}, \"payload\": " - + "{\"type\": \"song\", \"song\": \"Solo (feat. Demi Lovato)\", \"album\": \"What Is Love? (Deluxe)\", \"artist\": \"Clean Bandit\", \"image_url\": \"http://192.168.1.230:8015//m-browsableMediaUri/getImageFromTag/mnt/326C72A3E307501E47DE2B0F47D90EB8/Clean%20Bandit/What%20Is%20Love_%20(Deluxe)/03%20Solo%20(feat.%20Demi%20Lovato).m4a\", \"album_id\": \"\", \"mid\": \"http://192.168.1.230:8015/m-1c176905-f6c7-d168-dc35-86b4735c5976/Clean+Bandit/What+Is+Love_+(Deluxe)/03+Solo+(feat.+Demi+Lovato).m4a\", \"qid\": 1, \"sid\": 1024}, \"options\": []}\n", + """ + {"heos": {"command": "player/get_now_playing_media", "result": "success", "message": "pid=1958912779"}, "payload": \ + {"type": "song", "song": "Solo (feat. Demi Lovato)", "album": "What Is Love? (Deluxe)", "artist": "Clean Bandit", "image_url": "http://192.168.1.230:8015//m-browsableMediaUri/getImageFromTag/mnt/326C72A3E307501E47DE2B0F47D90EB8/Clean%20Bandit/What%20Is%20Love_%20(Deluxe)/03%20Solo%20(feat.%20Demi%20Lovato).m4a", "album_id": "", "mid": "http://192.168.1.230:8015/m-1c176905-f6c7-d168-dc35-86b4735c5976/Clean+Bandit/What+Is+Love_+(Deluxe)/03+Solo+(feat.+Demi+Lovato).m4a", "qid": 1, "sid": 1024}, "options": []} + """, Media.class); assertEquals(HeosCommandGroup.PLAYER, response.heosCommand.commandGroup); @@ -222,13 +226,15 @@ public class HeosJsonParserResponseTest { @Test public void browse_playlist() { HeosResponseObject response = subject.parseResponse( - "{\"heos\": {\"command\": \"browse/browse\", \"result\": \"success\", \"message\": \"sid=1025&returned=6&count=6\"}, \"payload\": [" - + "{\"container\": \"yes\", \"type\": \"playlist\", \"cid\": \"132562\", \"playable\": \"yes\", \"name\": \"Maaike Ouboter - En hoe het dan ook weer dag wordt\", \"image_url\": \"\"}, " - + "{\"container\": \"yes\", \"type\": \"playlist\", \"cid\": \"132563\", \"playable\": \"yes\", \"name\": \"Maaike Ouboter - Vanaf nu is het van jou\", \"image_url\": \"\"}, " - + "{\"container\": \"yes\", \"type\": \"playlist\", \"cid\": \"162887\", \"playable\": \"yes\", \"name\": \"Easy listening\", \"image_url\": \"\"}, " - + "{\"container\": \"yes\", \"type\": \"playlist\", \"cid\": \"174461\", \"playable\": \"yes\", \"name\": \"Nieuwe muziek 5-2019\", \"image_url\": \"\"}, " - + "{\"container\": \"yes\", \"type\": \"playlist\", \"cid\": \"194000\", \"playable\": \"yes\", \"name\": \"Nieuwe muziek 2019-05\", \"image_url\": \"\"}, " - + "{\"container\": \"yes\", \"type\": \"playlist\", \"cid\": \"194001\", \"playable\": \"yes\", \"name\": \"Clean Bandit\", \"image_url\": \"\"}]}", + """ + {"heos": {"command": "browse/browse", "result": "success", "message": "sid=1025&returned=6&count=6"}, "payload": [\ + {"container": "yes", "type": "playlist", "cid": "132562", "playable": "yes", "name": "Maaike Ouboter - En hoe het dan ook weer dag wordt", "image_url": ""}, \ + {"container": "yes", "type": "playlist", "cid": "132563", "playable": "yes", "name": "Maaike Ouboter - Vanaf nu is het van jou", "image_url": ""}, \ + {"container": "yes", "type": "playlist", "cid": "162887", "playable": "yes", "name": "Easy listening", "image_url": ""}, \ + {"container": "yes", "type": "playlist", "cid": "174461", "playable": "yes", "name": "Nieuwe muziek 5-2019", "image_url": ""}, \ + {"container": "yes", "type": "playlist", "cid": "194000", "playable": "yes", "name": "Nieuwe muziek 2019-05", "image_url": ""}, \ + {"container": "yes", "type": "playlist", "cid": "194001", "playable": "yes", "name": "Clean Bandit", "image_url": ""}]}\ + """, BrowseResult[].class); assertEquals(HeosCommandGroup.BROWSE, response.heosCommand.commandGroup); @@ -252,11 +258,13 @@ public class HeosJsonParserResponseTest { @Test public void browse_favorites() { HeosResponseObject response = subject.parseResponse( - "{\"heos\": {\"command\": \"browse/browse\", \"result\": \"success\", \"message\": \"sid=1028&returned=3&count=3\"}, \"payload\": [" - + "{\"container\": \"no\", \"mid\": \"s6707\", \"type\": \"station\", \"playable\": \"yes\", \"name\": \"NPO 3FM 96.8 (Top 40 %26 Pop Music)\", \"image_url\": \"http://cdn-profiles.tunein.com/s6707/images/logoq.png?t=636268\"}, " - + "{\"container\": \"no\", \"mid\": \"s2967\", \"type\": \"station\", \"playable\": \"yes\", \"name\": \"Classic FM Nederland (Classical Music)\", \"image_url\": \"http://cdn-radiotime-logos.tunein.com/s2967q.png\"}, " - + "{\"container\": \"no\", \"mid\": \"s1993\", \"type\": \"station\", \"playable\": \"yes\", \"name\": \"BNR Nieuwsradio\", \"image_url\": \"http://cdn-radiotime-logos.tunein.com/s1993q.png\"}], " - + "\"options\": [{\"browse\": [{\"id\": 20, \"name\": \"Remove from HEOS Favorites\"}]}]}", + """ + {"heos": {"command": "browse/browse", "result": "success", "message": "sid=1028&returned=3&count=3"}, "payload": [\ + {"container": "no", "mid": "s6707", "type": "station", "playable": "yes", "name": "NPO 3FM 96.8 (Top 40 %26 Pop Music)", "image_url": "http://cdn-profiles.tunein.com/s6707/images/logoq.png?t=636268"}, \ + {"container": "no", "mid": "s2967", "type": "station", "playable": "yes", "name": "Classic FM Nederland (Classical Music)", "image_url": "http://cdn-radiotime-logos.tunein.com/s2967q.png"}, \ + {"container": "no", "mid": "s1993", "type": "station", "playable": "yes", "name": "BNR Nieuwsradio", "image_url": "http://cdn-radiotime-logos.tunein.com/s1993q.png"}], \ + "options": [{"browse": [{"id": 20, "name": "Remove from HEOS Favorites"}]}]}\ + """, BrowseResult[].class); assertEquals(HeosCommandGroup.BROWSE, response.heosCommand.commandGroup); @@ -282,9 +290,11 @@ public class HeosJsonParserResponseTest { @Test public void get_groups() { HeosResponseObject response = subject.parseResponse( - "{\"heos\": {\"command\": \"group/get_groups\", \"result\": \"success\", \"message\": \"\"}, \"payload\": [ " - + "{\"name\": \"Group 1\", \"gid\": \"214243242\", \"players\": [ {\"name\": \"HEOS 1\", \"pid\": \"2142443242\", \"role\": \"leader\"}, {\"name\": \"HEOS 3\", \"pid\": \"32432423432\", \"role\": \"member\"}, {\"name\": \"HEOS 5\", \"pid\": \"342423564\", \"role\": \"member\"}]}, " - + "{\"name\": \"Group 2\", \"gid\": \"2142432342\", \"players\": [ {\"name\": \"HEOS 3\", \"pid\": \"32432423432\", \"role\": \"member\"}, {\"name\": \"HEOS 5\", \"pid\": \"342423564\", \"role\": \"member\"}]}]}", + """ + {"heos": {"command": "group/get_groups", "result": "success", "message": ""}, "payload": [ \ + {"name": "Group 1", "gid": "214243242", "players": [ {"name": "HEOS 1", "pid": "2142443242", "role": "leader"}, {"name": "HEOS 3", "pid": "32432423432", "role": "member"}, {"name": "HEOS 5", "pid": "342423564", "role": "member"}]}, \ + {"name": "Group 2", "gid": "2142432342", "players": [ {"name": "HEOS 3", "pid": "32432423432", "role": "member"}, {"name": "HEOS 5", "pid": "342423564", "role": "member"}]}]}\ + """, Group[].class); assertEquals(HeosCommandGroup.GROUP, response.heosCommand.commandGroup); diff --git a/bundles/org.openhab.binding.herzborg/src/main/java/org/openhab/binding/herzborg/internal/CurtainHandler.java b/bundles/org.openhab.binding.herzborg/src/main/java/org/openhab/binding/herzborg/internal/CurtainHandler.java index cd70bbe19..fc706c934 100644 --- a/bundles/org.openhab.binding.herzborg/src/main/java/org/openhab/binding/herzborg/internal/CurtainHandler.java +++ b/bundles/org.openhab.binding.herzborg/src/main/java/org/openhab/binding/herzborg/internal/CurtainHandler.java @@ -74,8 +74,8 @@ public class CurtainHandler extends BaseThingHandler { (command == UpDownType.UP) ? ControlAddress.OPEN : ControlAddress.CLOSE); } else if (command instanceof StopMoveType) { pkt = buildPacket(Function.CONTROL, ControlAddress.STOP); - } else if (command instanceof DecimalType) { - pkt = buildPacket(Function.CONTROL, ControlAddress.PERCENT, ((DecimalType) command).byteValue()); + } else if (command instanceof DecimalType decimalCommand) { + pkt = buildPacket(Function.CONTROL, ControlAddress.PERCENT, decimalCommand.byteValue()); } break; case CHANNEL_REVERSE: diff --git a/bundles/org.openhab.binding.homeconnect/src/main/java/org/openhab/binding/homeconnect/internal/client/HomeConnectApiClient.java b/bundles/org.openhab.binding.homeconnect/src/main/java/org/openhab/binding/homeconnect/internal/client/HomeConnectApiClient.java index 27fef700b..c54dcc2ca 100644 --- a/bundles/org.openhab.binding.homeconnect/src/main/java/org/openhab/binding/homeconnect/internal/client/HomeConnectApiClient.java +++ b/bundles/org.openhab.binding.homeconnect/src/main/java/org/openhab/binding/homeconnect/internal/client/HomeConnectApiClient.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.homeconnect.internal.client; -import static java.util.Collections.singletonList; import static org.openhab.binding.homeconnect.internal.HomeConnectBindingConstants.*; import static org.openhab.binding.homeconnect.internal.client.HttpHelper.*; @@ -880,7 +879,7 @@ public class HomeConnectApiClient { private void checkResponseCode(int desiredCode, Request request, ContentResponse response, @Nullable String haId, @Nullable String requestPayload) throws CommunicationException, AuthorizationException, ApplianceOfflineException { - checkResponseCode(singletonList(desiredCode), request, response, haId, requestPayload); + checkResponseCode(List.of(desiredCode), request, response, haId, requestPayload); } private void checkResponseCode(List desiredCodes, Request request, ContentResponse response, diff --git a/bundles/org.openhab.binding.homeconnect/src/main/java/org/openhab/binding/homeconnect/internal/discovery/HomeConnectDiscoveryService.java b/bundles/org.openhab.binding.homeconnect/src/main/java/org/openhab/binding/homeconnect/internal/discovery/HomeConnectDiscoveryService.java index a22c9bb71..9a6c46158 100644 --- a/bundles/org.openhab.binding.homeconnect/src/main/java/org/openhab/binding/homeconnect/internal/discovery/HomeConnectDiscoveryService.java +++ b/bundles/org.openhab.binding.homeconnect/src/main/java/org/openhab/binding/homeconnect/internal/discovery/HomeConnectDiscoveryService.java @@ -60,8 +60,8 @@ public class HomeConnectDiscoveryService extends AbstractDiscoveryService @Override public void setThingHandler(ThingHandler handler) { - if (handler instanceof HomeConnectBridgeHandler) { - this.bridgeHandler = (HomeConnectBridgeHandler) handler; + if (handler instanceof HomeConnectBridgeHandler homeConnectBridgeHandler) { + this.bridgeHandler = homeConnectBridgeHandler; } } diff --git a/bundles/org.openhab.binding.homeconnect/src/main/java/org/openhab/binding/homeconnect/internal/handler/AbstractHomeConnectThingHandler.java b/bundles/org.openhab.binding.homeconnect/src/main/java/org/openhab/binding/homeconnect/internal/handler/AbstractHomeConnectThingHandler.java index d6cd23ea5..69bb4aa01 100644 --- a/bundles/org.openhab.binding.homeconnect/src/main/java/org/openhab/binding/homeconnect/internal/handler/AbstractHomeConnectThingHandler.java +++ b/bundles/org.openhab.binding.homeconnect/src/main/java/org/openhab/binding/homeconnect/internal/handler/AbstractHomeConnectThingHandler.java @@ -453,8 +453,8 @@ public abstract class AbstractHomeConnectThingHandler extends BaseThingHandler i Bridge bridge = getBridge(); if (bridge != null) { BridgeHandler bridgeHandler = bridge.getHandler(); - if (bridgeHandler instanceof HomeConnectBridgeHandler) { - return Optional.of((HomeConnectBridgeHandler) bridgeHandler); + if (bridgeHandler instanceof HomeConnectBridgeHandler homeConnectBridgeHandler) { + return Optional.of(homeConnectBridgeHandler); } } return Optional.empty(); @@ -537,7 +537,7 @@ public abstract class AbstractHomeConnectThingHandler extends BaseThingHandler i * @param channelUID channel UID */ protected void updateChannel(ChannelUID channelUID) { - if (!getApiClient().isPresent()) { + if (getApiClient().isEmpty()) { logger.error("Cannot update channel. No instance of api client found! thing={}, haId={}", getThingLabel(), getThingHaId()); return; @@ -1206,23 +1206,23 @@ public abstract class AbstractHomeConnectThingHandler extends BaseThingHandler i protected void handleTemperatureCommand(final ChannelUID channelUID, final Command command, final HomeConnectApiClient apiClient) throws CommunicationException, AuthorizationException, ApplianceOfflineException { - if (command instanceof QuantityType) { - QuantityType quantity = (QuantityType) command; - + if (command instanceof QuantityType quantityCommand) { String value; String unit; try { - if (quantity.getUnit().equals(SIUnits.CELSIUS) || quantity.getUnit().equals(ImperialUnits.FAHRENHEIT)) { - unit = quantity.getUnit().toString(); - value = String.valueOf(quantity.intValue()); + if (quantityCommand.getUnit().equals(SIUnits.CELSIUS) + || quantityCommand.getUnit().equals(ImperialUnits.FAHRENHEIT)) { + unit = quantityCommand.getUnit().toString(); + value = String.valueOf(quantityCommand.intValue()); } else { logger.debug("Converting target temperature from {}{} to °C value. thing={}, haId={}", - quantity.intValue(), quantity.getUnit().toString(), getThingLabel(), getThingHaId()); + quantityCommand.intValue(), quantityCommand.getUnit().toString(), getThingLabel(), + getThingHaId()); unit = "°C"; - var celsius = quantity.toUnit(SIUnits.CELSIUS); + var celsius = quantityCommand.toUnit(SIUnits.CELSIUS); if (celsius == null) { - logger.warn("Converting temperature to celsius failed! quantity={}", quantity); + logger.warn("Converting temperature to celsius failed! quantity={}", quantityCommand); value = null; } else { value = String.valueOf(celsius.intValue()); @@ -1272,10 +1272,10 @@ public abstract class AbstractHomeConnectThingHandler extends BaseThingHandler i } else { newBrightness = currentBrightness - BRIGHTNESS_DIM_STEP; } - } else if (command instanceof PercentType) { - newBrightness = (int) Math.floor(((PercentType) command).doubleValue()); - } else if (command instanceof DecimalType) { - newBrightness = ((DecimalType) command).intValue(); + } else if (command instanceof PercentType percentCommand) { + newBrightness = (int) Math.floor(percentCommand.doubleValue()); + } else if (command instanceof DecimalType decimalCommand) { + newBrightness = decimalCommand.intValue(); } // check in in range @@ -1308,8 +1308,8 @@ public abstract class AbstractHomeConnectThingHandler extends BaseThingHandler i apiClient.setAmbientLightColorState(getThingHaId(), STATE_AMBIENT_LIGHT_COLOR_CUSTOM_COLOR); } - if (command instanceof HSBType) { - apiClient.setAmbientLightCustomColorState(getThingHaId(), mapColor((HSBType) command)); + if (command instanceof HSBType hsbCommand) { + apiClient.setAmbientLightCustomColorState(getThingHaId(), mapColor(hsbCommand)); } else if (command instanceof StringType) { apiClient.setAmbientLightCustomColorState(getThingHaId(), command.toFullString()); } @@ -1546,9 +1546,9 @@ public abstract class AbstractHomeConnectThingHandler extends BaseThingHandler i .filter(option -> OPTION_DRYER_DRYING_TARGET.equals(option.getKey())).findFirst(); // Save options in cache only if we got options for all expected channels - if (cacheToSet && (!channelSpinSpeed.isPresent() || optionsSpinSpeed.isPresent()) - && (!channelTemperature.isPresent() || optionsTemperature.isPresent()) - && (!channelDryingTarget.isPresent() || optionsDryingTarget.isPresent())) { + if (cacheToSet && (channelSpinSpeed.isEmpty() || optionsSpinSpeed.isPresent()) + && (channelTemperature.isEmpty() || optionsTemperature.isPresent()) + && (channelDryingTarget.isEmpty() || optionsDryingTarget.isPresent())) { logger.debug("Saving options in cache for program '{}'.", programKey); availableProgramOptionsCache.put(programKey, availableProgramOptions); } @@ -1673,7 +1673,7 @@ public abstract class AbstractHomeConnectThingHandler extends BaseThingHandler i private boolean addUnsupportedProgramInCache(String programKey) { Optional prog = programsCache.stream().filter(program -> programKey.equals(program.getKey())) .findFirst(); - if (!prog.isPresent()) { + if (prog.isEmpty()) { programsCache.add(new AvailableProgram(programKey, false)); logger.debug("{} added in programs cache as an unsupported program", programKey); return true; diff --git a/bundles/org.openhab.binding.homeconnect/src/main/java/org/openhab/binding/homeconnect/internal/handler/HomeConnectBridgeHandler.java b/bundles/org.openhab.binding.homeconnect/src/main/java/org/openhab/binding/homeconnect/internal/handler/HomeConnectBridgeHandler.java index db483b3b1..240c2f25b 100644 --- a/bundles/org.openhab.binding.homeconnect/src/main/java/org/openhab/binding/homeconnect/internal/handler/HomeConnectBridgeHandler.java +++ b/bundles/org.openhab.binding.homeconnect/src/main/java/org/openhab/binding/homeconnect/internal/handler/HomeConnectBridgeHandler.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.List; import java.util.Map; import java.util.Map.Entry; +import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @@ -232,7 +232,7 @@ public class HomeConnectBridgeHandler extends BaseBridgeHandler { @Override public Collection> getServices() { - return Collections.singleton(HomeConnectDiscoveryService.class); + return Set.of(HomeConnectDiscoveryService.class); } /** diff --git a/bundles/org.openhab.binding.homeconnect/src/main/java/org/openhab/binding/homeconnect/internal/handler/HomeConnectHoodHandler.java b/bundles/org.openhab.binding.homeconnect/src/main/java/org/openhab/binding/homeconnect/internal/handler/HomeConnectHoodHandler.java index ebff3c1be..a7efb5dd6 100644 --- a/bundles/org.openhab.binding.homeconnect/src/main/java/org/openhab/binding/homeconnect/internal/handler/HomeConnectHoodHandler.java +++ b/bundles/org.openhab.binding.homeconnect/src/main/java/org/openhab/binding/homeconnect/internal/handler/HomeConnectHoodHandler.java @@ -49,15 +49,35 @@ import org.slf4j.LoggerFactory; @NonNullByDefault public class HomeConnectHoodHandler extends AbstractHomeConnectThingHandler { - private static final String START_VENTING_INTENSIVE_STAGE_PAYLOAD_TEMPLATE = "\n" + "{\n" + " \"data\": {\n" - + " \"key\": \"Cooking.Common.Program.Hood.Venting\",\n" + " \"options\": [\n" - + " {\n" + " \"key\": \"Cooking.Common.Option.Hood.IntensiveLevel\",\n" - + " \"value\": \"%s\"\n" + " }\n" + " ]\n" + " }\n" + "}"; + private static final String START_VENTING_INTENSIVE_STAGE_PAYLOAD_TEMPLATE = """ - private static final String START_VENTING_STAGE_PAYLOAD_TEMPLATE = "\n" + "{\n" + " \"data\": {\n" - + " \"key\": \"Cooking.Common.Program.Hood.Venting\",\n" + " \"options\": [\n" - + " {\n" + " \"key\": \"Cooking.Common.Option.Hood.VentingLevel\",\n" - + " \"value\": \"%s\"\n" + " }\n" + " ]\n" + " }\n" + "}"; + { + "data": { + "key": "Cooking.Common.Program.Hood.Venting", + "options": [ + { + "key": "Cooking.Common.Option.Hood.IntensiveLevel", + "value": "%s" + } + ] + } + }\ + """; + + private static final String START_VENTING_STAGE_PAYLOAD_TEMPLATE = """ + + { + "data": { + "key": "Cooking.Common.Program.Hood.Venting", + "options": [ + { + "key": "Cooking.Common.Option.Hood.VentingLevel", + "value": "%s" + } + ] + } + }\ + """; private final Logger logger = LoggerFactory.getLogger(HomeConnectHoodHandler.class); diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/common/HomematicConfig.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/common/HomematicConfig.java index 022e11339..e4ad10af7 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/common/HomematicConfig.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/common/HomematicConfig.java @@ -394,12 +394,12 @@ public class HomematicConfig { @Override public String toString() { - return String.format( - "%s[gatewayAddress=%s,callbackHost=%s,xmlCallbackPort=%d,binCallbackPort=%d," - + "gatewayType=%s,rfPort=%d,wiredPort=%d,hmIpPort=%d,cuxdPort=%d,groupPort=%d,timeout=%d," - + "discoveryTimeToLive=%d,installModeDuration=%d,socketMaxAlive=%d]", - getClass().getSimpleName(), gatewayAddress, callbackHost, xmlCallbackPort, binCallbackPort, gatewayType, - getRfPort(), getWiredPort(), getHmIpPort(), getCuxdPort(), getGroupPort(), timeout, discoveryTimeToLive, - installModeDuration, socketMaxAlive); + return String.format(""" + %s[gatewayAddress=%s,callbackHost=%s,xmlCallbackPort=%d,binCallbackPort=%d,\ + gatewayType=%s,rfPort=%d,wiredPort=%d,hmIpPort=%d,cuxdPort=%d,groupPort=%d,timeout=%d,\ + discoveryTimeToLive=%d,installModeDuration=%d,socketMaxAlive=%d]\ + """, getClass().getSimpleName(), gatewayAddress, callbackHost, xmlCallbackPort, binCallbackPort, + gatewayType, getRfPort(), getWiredPort(), getHmIpPort(), getCuxdPort(), getGroupPort(), timeout, + discoveryTimeToLive, installModeDuration, socketMaxAlive); } } diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/client/XmlRpcClient.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/client/XmlRpcClient.java index db27828c6..c74457aa4 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/client/XmlRpcClient.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/client/XmlRpcClient.java @@ -84,8 +84,7 @@ public class XmlRpcClient extends RpcClient { } catch (IOException ex) { reason = ex; // no retries for "init" request or if connection is refused - if ("init".equals(request.getMethodName()) - || ex.getCause() != null && ex.getCause() instanceof ExecutionException) { + if ("init".equals(request.getMethodName()) || ex.getCause() instanceof ExecutionException) { break; } logger.debug("XmlRpcMessage failed({}), sending message again {}/{}", ex.getMessage(), rpcRetryCounter, diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/message/BinRpcMessage.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/message/BinRpcMessage.java index 839846ce3..31e63c50c 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/message/BinRpcMessage.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/message/BinRpcMessage.java @@ -47,7 +47,7 @@ public class BinRpcMessage implements RpcRequest, RpcResponse { } private Object[] messageData; - private byte binRpcData[]; + private byte[] binRpcData; private int offset; private String methodName; @@ -74,7 +74,7 @@ public class BinRpcMessage implements RpcRequest, RpcResponse { */ public BinRpcMessage(InputStream is, boolean methodHeader, Charset encoding) throws IOException { this.encoding = encoding; - byte sig[] = new byte[8]; + byte[] sig = new byte[8]; int length = is.read(sig, 0, 4); if (length != 4) { throw new EOFException("Only " + length + " bytes received reading signature"); @@ -85,7 +85,7 @@ public class BinRpcMessage implements RpcRequest, RpcResponse { throw new EOFException("Only " + length + " bytes received reading message length"); } int datasize = (new BigInteger(Arrays.copyOfRange(sig, 4, 8))).intValue(); - byte payload[] = new byte[datasize]; + byte[] payload = new byte[datasize]; int offset = 0; int currentLength; @@ -201,14 +201,14 @@ public class BinRpcMessage implements RpcRequest, RpcResponse { // read rpc values private int readInt() { - byte bi[] = new byte[4]; + byte[] bi = new byte[4]; System.arraycopy(binRpcData, offset, bi, 0, 4); offset += 4; return (new BigInteger(bi)).intValue(); } private long readInt64() { - byte bi[] = new byte[8]; + byte[] bi = new byte[8]; System.arraycopy(binRpcData, offset, bi, 0, 8); offset += 8; return (new BigInteger(bi)).longValue(); @@ -274,7 +274,7 @@ public class BinRpcMessage implements RpcRequest, RpcResponse { private void addByte(byte b) { if (offset == binRpcData.length) { - byte newdata[] = new byte[binRpcData.length * 2]; + byte[] newdata = new byte[binRpcData.length * 2]; System.arraycopy(binRpcData, 0, newdata, 0, binRpcData.length); binRpcData = newdata; } @@ -311,7 +311,7 @@ public class BinRpcMessage implements RpcRequest, RpcResponse { } private void addString(String string) { - byte sd[] = string.getBytes(encoding); + byte[] sd = string.getBytes(encoding); for (byte ch : sd) { addByte(ch); } @@ -351,13 +351,11 @@ public class BinRpcMessage implements RpcRequest, RpcResponse { } else if (object.getClass() == Date.class) { addInt(5); addInt((int) ((Date) object).getTime() / 1000); - } else if (object instanceof List) { - Collection list = (Collection) object; + } else if (object instanceof List list) { addInt(0x100); addInt(list.size()); addList(list); - } else if (object instanceof Map) { - Map map = (Map) object; + } else if (object instanceof Map map) { addInt(0x101); addInt(map.size()); for (Map.Entry entry : map.entrySet()) { diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/message/RpcUtils.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/message/RpcUtils.java index 10a4d6102..461d43388 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/message/RpcUtils.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/message/RpcUtils.java @@ -42,10 +42,10 @@ public class RpcUtils { sb.append("[\n"); } for (Object o : c) { - if (o instanceof Map) { - dumpMap((Map) o, sb, indent + 1); - } else if (o instanceof Object[]) { - dumpCollection((Object[]) o, sb, indent + 1); + if (o instanceof Map map) { + dumpMap(map, sb, indent + 1); + } else if (o instanceof Object[] objects) { + dumpCollection(objects, sb, indent + 1); } else { for (int in = 0; in < indent; in++) { sb.append('\t'); @@ -76,12 +76,12 @@ public class RpcUtils { } sb.append(me.getKey()); sb.append('='); - if (o instanceof Map) { + if (o instanceof Map map) { sb.append("\n"); - dumpMap((Map) o, sb, indent + 1); - } else if (o instanceof Object[]) { + dumpMap(map, sb, indent + 1); + } else if (o instanceof Object[] objects) { sb.append("\n"); - dumpCollection((Object[]) o, sb, indent + 1); + dumpCollection(objects, sb, indent + 1); } else { sb.append(o); sb.append('\n'); diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/message/XmlRpcRequest.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/message/XmlRpcRequest.java index d30873df3..05ea0fe4f 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/message/XmlRpcRequest.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/message/XmlRpcRequest.java @@ -136,16 +136,16 @@ public class XmlRpcRequest implements RpcRequest { tag("boolean", ((Boolean) value).booleanValue() ? "1" : "0"); } else if (clazz == Date.class) { tag("dateTime.iso8601", xmlRpcDateFormat.format(((Date) value))); - } else if (value instanceof Calendar) { - generateValue(((Calendar) value).getTime()); - } else if (value instanceof byte[]) { - tag("base64", Base64.getEncoder().encodeToString((byte[]) value)); + } else if (value instanceof Calendar calendar) { + generateValue(calendar.getTime()); + } else if (value instanceof byte[] bytes) { + tag("base64", Base64.getEncoder().encodeToString(bytes)); } else if (clazz.isArray() || value instanceof List) { sb.append(""); Object[] array = null; - if (value instanceof List) { - array = ((List) value).toArray(); + if (value instanceof List list) { + array = list.toArray(); } else { array = (Object[]) value; } diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/message/XmlRpcResponse.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/message/XmlRpcResponse.java index 4df30c0cb..ae5aa4f2f 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/message/XmlRpcResponse.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/message/XmlRpcResponse.java @@ -97,10 +97,10 @@ public class XmlRpcResponse implements RpcResponse { public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { String tag = qName.toLowerCase(); - if (tag.equals("array") || tag.equals("struct")) { + if ("array".equals(tag) || "struct".equals(tag)) { currentDataObject.addLast(new ArrayList<>()); } - isValueTag = tag.equals("value"); + isValueTag = "value".equals(tag); tagValue = new StringBuilder(); } diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/parser/CommonRpcParser.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/parser/CommonRpcParser.java index 2323d5225..d5f20a3a8 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/parser/CommonRpcParser.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/parser/CommonRpcParser.java @@ -105,8 +105,7 @@ public abstract class CommonRpcParser implements RpcParser { * Converts the object to a string array. */ protected String[] toOptionList(Object optionList) { - if (optionList != null && optionList instanceof Object[]) { - Object[] vl = (Object[]) optionList; + if (optionList != null && optionList instanceof Object[] vl) { String[] stringArray = new String[vl.length]; for (int i = 0; i < vl.length; i++) { stringArray[i] = vl[i].toString(); @@ -232,9 +231,9 @@ public abstract class CommonRpcParser implements RpcParser { if (value == null || value.isBlank()) { return null; } - if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("on")) { + if ("true".equalsIgnoreCase(value) || "on".equalsIgnoreCase(value)) { return (Boolean.TRUE); - } else if (value.equalsIgnoreCase("false") || value.equalsIgnoreCase("off")) { + } else if ("false".equalsIgnoreCase(value) || "off".equalsIgnoreCase(value)) { return (Boolean.FALSE); } else if (value.matches("(-|\\+)?[0-9]+")) { return (Integer.valueOf(value)); diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/parser/GetParamsetParser.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/parser/GetParamsetParser.java index c60e3e73c..5254b2f58 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/parser/GetParamsetParser.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/parser/GetParamsetParser.java @@ -58,7 +58,7 @@ public class GetParamsetParser extends CommonRpcParser { // suppress warning for this datapoint due wrong CCU metadata String deviceType = channel.getDevice().getType(); - boolean isHmSenMdirNextTrans = dpInfo.getName().equals("NEXT_TRANSMISSION") + boolean isHmSenMdirNextTrans = "NEXT_TRANSMISSION".equals(dpInfo.getName()) && (deviceType.startsWith("HM-Sen-MDIR-O") || deviceType.startsWith("HM-Sen-MDIR-WM55") || deviceType.startsWith("HM-Sec-MDIR-2")); if (!isHmSenMdirNextTrans) { diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/server/BinRpcNetworkService.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/server/BinRpcNetworkService.java index c0081fa15..b40eaacad 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/server/BinRpcNetworkService.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/server/BinRpcNetworkService.java @@ -28,9 +28,9 @@ import org.openhab.core.common.ThreadPoolManager; * @author Gerhard Riegler - Initial contribution */ public class BinRpcNetworkService implements Runnable { - private static final byte BIN_EMPTY_STRING[] = { 'B', 'i', 'n', 1, 0, 0, 0, 8, 0, 0, 0, 3, 0, 0, 0, 0 }; - private static final byte BIN_EMPTY_ARRAY[] = { 'B', 'i', 'n', 1, 0, 0, 0, 8, 0, 0, 1, 0, 0, 0, 0, 0 }; - private static final byte BIN_EMPTY_EVENT_LIST[] = { 'B', 'i', 'n', 1, 0, 0, 0, 21, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, + private static final byte[] BIN_EMPTY_STRING = { 'B', 'i', 'n', 1, 0, 0, 0, 8, 0, 0, 0, 3, 0, 0, 0, 0 }; + private static final byte[] BIN_EMPTY_ARRAY = { 'B', 'i', 'n', 1, 0, 0, 0, 8, 0, 0, 1, 0, 0, 0, 0, 0 }; + private static final byte[] BIN_EMPTY_EVENT_LIST = { 'B', 'i', 'n', 1, 0, 0, 0, 21, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 5, 'e', 'v', 'e', 'n', 't' }; private static final String RPC_POOL_NAME = "homematicRpc"; diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/virtual/DeleteDeviceModeVirtualDatapointHandler.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/virtual/DeleteDeviceModeVirtualDatapointHandler.java index 6badfa157..f7d0d6bac 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/virtual/DeleteDeviceModeVirtualDatapointHandler.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/virtual/DeleteDeviceModeVirtualDatapointHandler.java @@ -43,7 +43,7 @@ public class DeleteDeviceModeVirtualDatapointHandler extends AbstractVirtualData @Override public void initialize(HmDevice device) { - if (!device.isGatewayExtras() && !(device.getHmInterface() == HmInterface.CUXD)) { + if (!device.isGatewayExtras() && device.getHmInterface() != HmInterface.CUXD) { HmDatapoint dp = addDatapoint(device, 0, getName(), HmValueType.ENUM, 0, false); dp.setOptions(new String[] { MODE_LOCKED, MODE_RESET, MODE_FORCE, MODE_DEFER }); dp.setMinValue(0); diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/virtual/DeleteDeviceVirtualDatapointHandler.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/virtual/DeleteDeviceVirtualDatapointHandler.java index 8005fc36b..24855e773 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/virtual/DeleteDeviceVirtualDatapointHandler.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/virtual/DeleteDeviceVirtualDatapointHandler.java @@ -44,7 +44,7 @@ public class DeleteDeviceVirtualDatapointHandler extends AbstractVirtualDatapoin @Override public void initialize(HmDevice device) { - if (!device.isGatewayExtras() && !(device.getHmInterface() == HmInterface.CUXD)) { + if (!device.isGatewayExtras() && device.getHmInterface() != HmInterface.CUXD) { addDatapoint(device, 0, getName(), HmValueType.BOOL, Boolean.FALSE, false); } } diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/virtual/DisplayOptionsVirtualDatapointHandler.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/virtual/DisplayOptionsVirtualDatapointHandler.java index 9c4097ebd..5ad741de7 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/virtual/DisplayOptionsVirtualDatapointHandler.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/virtual/DisplayOptionsVirtualDatapointHandler.java @@ -40,8 +40,7 @@ public class DisplayOptionsVirtualDatapointHandler extends AbstractVirtualDatapo @Override public void initialize(HmDevice device) { - if (device.getType().startsWith(DEVICE_TYPE_19_REMOTE_CONTROL) - && !(device.getHmInterface() == HmInterface.CUXD)) { + if (device.getType().startsWith(DEVICE_TYPE_19_REMOTE_CONTROL) && device.getHmInterface() != HmInterface.CUXD) { addDatapoint(device, 18, getName(), HmValueType.STRING, null, false); } } diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/virtual/OnTimeAutomaticVirtualDatapointHandler.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/virtual/OnTimeAutomaticVirtualDatapointHandler.java index 919e7bef3..7e42e5a47 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/virtual/OnTimeAutomaticVirtualDatapointHandler.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/virtual/OnTimeAutomaticVirtualDatapointHandler.java @@ -62,8 +62,8 @@ public class OnTimeAutomaticVirtualDatapointHandler extends AbstractVirtualDatap @Override public boolean canHandleCommand(HmDatapoint dp, Object value) { - boolean isLevel = DATAPOINT_NAME_LEVEL.equals(dp.getName()) && value != null && value instanceof Number - && ((Number) value).doubleValue() > 0.0; + boolean isLevel = DATAPOINT_NAME_LEVEL.equals(dp.getName()) && value != null + && value instanceof Number numberCommand && numberCommand.doubleValue() > 0.0; boolean isState = DATAPOINT_NAME_STATE.equals(dp.getName()) && MiscUtils.isTrueValue(value); return ((isLevel || isState) && getVirtualDatapointValue(dp.getChannel()) > 0.0) diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/discovery/CcuDiscoveryService.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/discovery/CcuDiscoveryService.java index 8b18fe65a..b6d7a69a7 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/discovery/CcuDiscoveryService.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/discovery/CcuDiscoveryService.java @@ -19,7 +19,7 @@ import java.net.DatagramPacket; import java.net.InetAddress; import java.net.MulticastSocket; import java.net.SocketTimeoutException; -import java.util.Collections; +import java.util.Set; import java.util.concurrent.Future; import org.openhab.binding.homematic.internal.discovery.eq3udp.Eq3UdpRequest; @@ -50,7 +50,7 @@ public class CcuDiscoveryService extends AbstractDiscoveryService { private NetworkAddressService networkAddressService; public CcuDiscoveryService() { - super(Collections.singleton(THING_TYPE_BRIDGE), 5, true); + super(Set.of(THING_TYPE_BRIDGE), 5, true); } @Override diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/discovery/HomegearDiscoveryParticipant.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/discovery/HomegearDiscoveryParticipant.java index 7e61eb669..22eae0964 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/discovery/HomegearDiscoveryParticipant.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/discovery/HomegearDiscoveryParticipant.java @@ -14,7 +14,6 @@ package org.openhab.binding.homematic.internal.discovery; import static org.openhab.binding.homematic.internal.HomematicBindingConstants.THING_TYPE_BRIDGE; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -41,7 +40,7 @@ public class HomegearDiscoveryParticipant implements UpnpDiscoveryParticipant { @Override public Set getSupportedThingTypeUIDs() { - return Collections.singleton(THING_TYPE_BRIDGE); + return Set.of(THING_TYPE_BRIDGE); } @Override diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/discovery/HomematicDeviceDiscoveryService.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/discovery/HomematicDeviceDiscoveryService.java index 22693d615..ced1ab103 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/discovery/HomematicDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/discovery/HomematicDeviceDiscoveryService.java @@ -14,7 +14,7 @@ package org.openhab.binding.homematic.internal.discovery; import static org.openhab.binding.homematic.internal.HomematicBindingConstants.BINDING_ID; -import java.util.Collections; +import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; @@ -54,13 +54,13 @@ public class HomematicDeviceDiscoveryService extends AbstractDiscoveryService private volatile Object installModeSync = new Object(); public HomematicDeviceDiscoveryService() { - super(Collections.singleton(new ThingTypeUID(BINDING_ID, "-")), DISCOVER_TIMEOUT_SECONDS, false); + super(Set.of(new ThingTypeUID(BINDING_ID, "-")), DISCOVER_TIMEOUT_SECONDS, false); } @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof HomematicBridgeHandler) { - this.bridgeHandler = (HomematicBridgeHandler) handler; + if (handler instanceof HomematicBridgeHandler homematicBridgeHandler) { + this.bridgeHandler = homematicBridgeHandler; this.bridgeHandler.setDiscoveryService(this); } } diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/handler/HomematicBridgeHandler.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/handler/HomematicBridgeHandler.java index aefa58005..c19e6efe0 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/handler/HomematicBridgeHandler.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/handler/HomematicBridgeHandler.java @@ -17,8 +17,8 @@ import static org.openhab.core.thing.Thing.*; import java.io.IOException; import java.util.Collection; -import java.util.Collections; import java.util.Map; +import java.util.Set; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; @@ -229,7 +229,7 @@ public class HomematicBridgeHandler extends BaseBridgeHandler implements Homemat @Override public Collection> getServices() { - return Collections.singleton(HomematicDeviceDiscoveryService.class); + return Set.of(HomematicDeviceDiscoveryService.class); } @Override diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/handler/HomematicThingHandler.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/handler/HomematicThingHandler.java index 542fac807..de3b66aa4 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/handler/HomematicThingHandler.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/handler/HomematicThingHandler.java @@ -594,15 +594,14 @@ public class HomematicThingHandler extends BaseThingHandler { if (dp != null) { try { if (newValue != null) { - if (newValue instanceof BigDecimal) { - final BigDecimal decimal = (BigDecimal) newValue; + if (newValue instanceof BigDecimal decimal) { if (dp.isIntegerType()) { newValue = decimal.intValue(); } else if (dp.isFloatType()) { newValue = decimal.doubleValue(); } - } else if (newValue instanceof String && dp.isEnumType()) { - newValue = dp.getOptionIndex((String) newValue); + } else if (newValue instanceof String string && dp.isEnumType()) { + newValue = dp.getOptionIndex(string); } if (!Objects.equals(dp.getValue(), newValue)) { sendDatapoint(dp, new HmDatapointConfig(), newValue); diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/model/HmDatapoint.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/model/HmDatapoint.java index dfbea5d65..c5446ef01 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/model/HmDatapoint.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/model/HmDatapoint.java @@ -426,9 +426,10 @@ public class HmDatapoint implements Cloneable { @Override public String toString() { - return String.format("%s[name=%s,value=%s,defaultValue=%s,type=%s,minValue=%s,maxValue=%s,options=%s," - + "readOnly=%b,readable=%b,unit=%s,description=%s,info=%s,paramsetType=%s,virtual=%b,trigger=%b]", - getClass().getSimpleName(), name, value, defaultValue, type, minValue, maxValue, + return String.format(""" + %s[name=%s,value=%s,defaultValue=%s,type=%s,minValue=%s,maxValue=%s,options=%s,\ + readOnly=%b,readable=%b,unit=%s,description=%s,info=%s,paramsetType=%s,virtual=%b,trigger=%b]\ + """, getClass().getSimpleName(), name, value, defaultValue, type, minValue, maxValue, (options == null ? null : String.join(";", options)), readOnly, readable, unit, description, info, paramsetType, virtual, trigger); } diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/model/HmDatapointInfo.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/model/HmDatapointInfo.java index 905e6ed71..e6cd7a89d 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/model/HmDatapointInfo.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/model/HmDatapointInfo.java @@ -96,7 +96,7 @@ public class HmDatapointInfo { @Override public boolean equals(Object obj) { - if (obj == null || !(obj instanceof HmDatapointInfo)) { + if (!(obj instanceof HmDatapointInfo)) { return false; } HmDatapointInfo comp = (HmDatapointInfo) obj; diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/model/HmDevice.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/model/HmDevice.java index 1bfc46e7d..6c7262e73 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/model/HmDevice.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/model/HmDevice.java @@ -213,7 +213,7 @@ public class HmDevice { @Override public boolean equals(Object obj) { - if (obj == null || !(obj instanceof HmDevice)) { + if (!(obj instanceof HmDevice)) { return false; } HmDevice comp = (HmDevice) obj; diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/type/HomematicTypeGeneratorImpl.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/type/HomematicTypeGeneratorImpl.java index a572a4f50..a088fc5f6 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/type/HomematicTypeGeneratorImpl.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/type/HomematicTypeGeneratorImpl.java @@ -189,11 +189,11 @@ public class HomematicTypeGeneratorImpl implements HomematicTypeGenerator { for (String deviceType : firmwaresByType.keySet()) { Set firmwares = firmwaresByType.get(deviceType); if (firmwares.size() > 1) { - logger.info( - "Multiple firmware versions for device type '{}' found ({}). " - + "Make sure, all devices of the same type have the same firmware version, " - + "otherwise you MAY have channel and/or datapoint errors in the logfile", - deviceType, String.join(", ", firmwares)); + logger.info(""" + Multiple firmware versions for device type '{}' found ({}). \ + Make sure, all devices of the same type have the same firmware version, \ + otherwise you MAY have channel and/or datapoint errors in the logfile\ + """, deviceType, String.join(", ", firmwares)); } } } @@ -387,7 +387,7 @@ public class HomematicTypeGeneratorImpl implements HomematicTypeGenerator { */ public static boolean isIgnoredDatapoint(HmDatapoint dp) { for (String testValue : IGNORE_DATAPOINT_NAMES) { - if (dp.getName().indexOf(testValue) > -1) { + if (dp.getName().contains(testValue)) { return true; } } diff --git a/bundles/org.openhab.binding.homewizard/src/main/java/org/openhab/binding/homewizard/internal/P1Payload.java b/bundles/org.openhab.binding.homewizard/src/main/java/org/openhab/binding/homewizard/internal/P1Payload.java index 7cea60ed8..27ce39f46 100644 --- a/bundles/org.openhab.binding.homewizard/src/main/java/org/openhab/binding/homewizard/internal/P1Payload.java +++ b/bundles/org.openhab.binding.homewizard/src/main/java/org/openhab/binding/homewizard/internal/P1Payload.java @@ -299,8 +299,11 @@ public class P1Payload { @Override public String toString() { - return String.format("P1 [version: %d model: %s ssid: %s signal: %d" - + " imp1: %f imp2: %f exp1: %f exp2: %f active: %f active1: %f active2: %f active3: %f gas: %f timestamp: %.0f]", + return String.format( + """ + P1 [version: %d model: %s ssid: %s signal: %d\ + imp1: %f imp2: %f exp1: %f exp2: %f active: %f active1: %f active2: %f active3: %f gas: %f timestamp: %.0f]\ + """, smrVersion, meterModel, wifiSsid, wifiStrength, totalEnergyImportT1Kwh, totalEnergyImportT2Kwh, totalEnergyExportT1Kwh, totalEnergyExportT2Kwh, activePowerW, activePowerL1W, activePowerL2W, activePowerL3W, totalGasM3, gasTimestamp); diff --git a/bundles/org.openhab.binding.hpprinter/src/main/java/org/openhab/binding/hpprinter/internal/api/HPFeatures.java b/bundles/org.openhab.binding.hpprinter/src/main/java/org/openhab/binding/hpprinter/internal/api/HPFeatures.java index d725a7fc0..220ef5153 100644 --- a/bundles/org.openhab.binding.hpprinter/src/main/java/org/openhab/binding/hpprinter/internal/api/HPFeatures.java +++ b/bundles/org.openhab.binding.hpprinter/src/main/java/org/openhab/binding/hpprinter/internal/api/HPFeatures.java @@ -39,9 +39,7 @@ public class HPFeatures { boolean localScannerStatus = false; for (Node n = root.getFirstChild(); n != null; n = n.getNextSibling()) { - if (n instanceof Element) { - Element feature = (Element) n; - + if (n instanceof Element feature) { NodeList resourceType = feature.getElementsByTagName("dd:ResourceType"); if (resourceType.getLength() > 0) { diff --git a/bundles/org.openhab.binding.hpprinter/src/main/java/org/openhab/binding/hpprinter/internal/api/HPUsage.java b/bundles/org.openhab.binding.hpprinter/src/main/java/org/openhab/binding/hpprinter/internal/api/HPUsage.java index 2e3215e6a..be633a331 100644 --- a/bundles/org.openhab.binding.hpprinter/src/main/java/org/openhab/binding/hpprinter/internal/api/HPUsage.java +++ b/bundles/org.openhab.binding.hpprinter/src/main/java/org/openhab/binding/hpprinter/internal/api/HPUsage.java @@ -279,8 +279,7 @@ public class HPUsage { int value = 0; for (Node n = parentNode.getFirstChild(); n != null; n = n.getNextSibling()) { - if (n instanceof Element) { - Element nodeItem = (Element) n; + if (n instanceof Element nodeItem) { if (nodeItem.getElementsByTagName(collateTagName).item(0).getTextContent() .equalsIgnoreCase(collateTagNameValue)) { int nodeValue = Integer diff --git a/bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/Util.java b/bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/Util.java index 9fc3e42e2..4a9212935 100644 --- a/bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/Util.java +++ b/bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/Util.java @@ -45,11 +45,9 @@ public class Util { String contentString = contentProvider == null ? "null" : StreamSupport.stream(contentProvider.spliterator(), false) .map(b -> StandardCharsets.UTF_8.decode(b).toString()).collect(Collectors.joining(", ")); - String logString = "Method = {" + request.getMethod() + "}, Headers = {" + return "Method = {" + request.getMethod() + "}, Headers = {" + request.getHeaders().stream().map(HttpField::toString).collect(Collectors.joining(", ")) + "}, Content = {" + contentString + "}"; - - return logString; } /** diff --git a/bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/converter/ColorItemConverter.java b/bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/converter/ColorItemConverter.java index 272daf18d..2d53a7817 100644 --- a/bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/converter/ColorItemConverter.java +++ b/bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/converter/ColorItemConverter.java @@ -60,13 +60,11 @@ public class ColorItemConverter extends AbstractTransformingItemConverter { return string; } - if (command instanceof HSBType) { - HSBType newState = (HSBType) command; + if (command instanceof HSBType newState) { state = newState; return hsbToString(newState); - } else if (command instanceof PercentType && state instanceof HSBType) { - HSBType newState = new HSBType(((HSBType) state).getBrightness(), ((HSBType) state).getSaturation(), - (PercentType) command); + } else if (command instanceof PercentType percentCommand && state instanceof HSBType hsb) { + HSBType newState = new HSBType(hsb.getBrightness(), hsb.getSaturation(), percentCommand); state = newState; return hsbToString(newState); } @@ -78,32 +76,29 @@ public class ColorItemConverter extends AbstractTransformingItemConverter { public State toState(String string) { State newState = UnDefType.UNDEF; if (string.equals(channelConfig.onValue)) { - if (state instanceof HSBType) { - newState = new HSBType(((HSBType) state).getHue(), ((HSBType) state).getSaturation(), - PercentType.HUNDRED); + if (state instanceof HSBType hsb) { + newState = new HSBType(hsb.getHue(), hsb.getSaturation(), PercentType.HUNDRED); } else { newState = HSBType.WHITE; } } else if (string.equals(channelConfig.offValue)) { - if (state instanceof HSBType) { - newState = new HSBType(((HSBType) state).getHue(), ((HSBType) state).getSaturation(), PercentType.ZERO); + if (state instanceof HSBType hsb) { + newState = new HSBType(hsb.getHue(), hsb.getSaturation(), PercentType.ZERO); } else { newState = HSBType.BLACK; } - } else if (string.equals(channelConfig.increaseValue) && state instanceof HSBType) { - BigDecimal newBrightness = ((HSBType) state).getBrightness().toBigDecimal().add(channelConfig.step); + } else if (string.equals(channelConfig.increaseValue) && state instanceof HSBType hsb) { + BigDecimal newBrightness = hsb.getBrightness().toBigDecimal().add(channelConfig.step); if (HUNDRED.compareTo(newBrightness) < 0) { newBrightness = HUNDRED; } - newState = new HSBType(((HSBType) state).getHue(), ((HSBType) state).getSaturation(), - new PercentType(newBrightness)); - } else if (string.equals(channelConfig.decreaseValue) && state instanceof HSBType) { - BigDecimal newBrightness = ((HSBType) state).getBrightness().toBigDecimal().subtract(channelConfig.step); + newState = new HSBType(hsb.getHue(), hsb.getSaturation(), new PercentType(newBrightness)); + } else if (string.equals(channelConfig.decreaseValue) && state instanceof HSBType hsb) { + BigDecimal newBrightness = hsb.getBrightness().toBigDecimal().subtract(channelConfig.step); if (BigDecimal.ZERO.compareTo(newBrightness) > 0) { newBrightness = BigDecimal.ZERO; } - newState = new HSBType(((HSBType) state).getHue(), ((HSBType) state).getSaturation(), - new PercentType(newBrightness)); + newState = new HSBType(hsb.getHue(), hsb.getSaturation(), new PercentType(newBrightness)); } else { Matcher matcher = TRIPLE_MATCHER.matcher(string); if (matcher.matches()) { diff --git a/bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/converter/DimmerItemConverter.java b/bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/converter/DimmerItemConverter.java index 11a27e480..f46e50e78 100644 --- a/bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/converter/DimmerItemConverter.java +++ b/bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/converter/DimmerItemConverter.java @@ -55,8 +55,8 @@ public class DimmerItemConverter extends AbstractTransformingItemConverter { return string; } - if (command instanceof PercentType) { - return ((PercentType) command).toString(); + if (command instanceof PercentType percentCommand) { + return percentCommand.toString(); } throw new IllegalArgumentException("Command type '" + command.toString() + "' not supported"); @@ -70,14 +70,14 @@ public class DimmerItemConverter extends AbstractTransformingItemConverter { newState = PercentType.HUNDRED; } else if (string.equals(channelConfig.offValue)) { newState = PercentType.ZERO; - } else if (string.equals(channelConfig.increaseValue) && state instanceof PercentType) { - BigDecimal newBrightness = ((PercentType) state).toBigDecimal().add(channelConfig.step); + } else if (string.equals(channelConfig.increaseValue) && state instanceof PercentType brightnessState) { + BigDecimal newBrightness = brightnessState.toBigDecimal().add(channelConfig.step); if (HUNDRED.compareTo(newBrightness) < 0) { newBrightness = HUNDRED; } newState = new PercentType(newBrightness); - } else if (string.equals(channelConfig.decreaseValue) && state instanceof PercentType) { - BigDecimal newBrightness = ((PercentType) state).toBigDecimal().subtract(channelConfig.step); + } else if (string.equals(channelConfig.decreaseValue) && state instanceof PercentType brightnessState) { + BigDecimal newBrightness = brightnessState.toBigDecimal().subtract(channelConfig.step); if (BigDecimal.ZERO.compareTo(newBrightness) > 0) { newBrightness = BigDecimal.ZERO; } diff --git a/bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/converter/GenericItemConverter.java b/bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/converter/GenericItemConverter.java index 9112d138e..5831c6c6e 100644 --- a/bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/converter/GenericItemConverter.java +++ b/bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/converter/GenericItemConverter.java @@ -40,6 +40,7 @@ public class GenericItemConverter extends AbstractTransformingItemConverter { this.toState = toState; } + @Override protected State toState(String value) { try { return toState.apply(value); @@ -53,6 +54,7 @@ public class GenericItemConverter extends AbstractTransformingItemConverter { return null; } + @Override protected String toString(Command command) { return command.toString(); } diff --git a/bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/converter/RollershutterItemConverter.java b/bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/converter/RollershutterItemConverter.java index c5d333af9..1c5ba2685 100644 --- a/bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/converter/RollershutterItemConverter.java +++ b/bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/converter/RollershutterItemConverter.java @@ -51,7 +51,7 @@ public class RollershutterItemConverter extends AbstractTransformingItemConverte return string; } - if (command instanceof PercentType) { + if (command instanceof PercentType brightnessState) { final String downValue = channelConfig.downValue; final String upValue = channelConfig.upValue; if (command.equals(PercentType.HUNDRED) && downValue != null) { @@ -59,7 +59,7 @@ public class RollershutterItemConverter extends AbstractTransformingItemConverte } else if (command.equals(PercentType.ZERO) && upValue != null) { return upValue; } else { - return ((PercentType) command).toString(); + return brightnessState.toString(); } } diff --git a/bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/http/HttpResponseListener.java b/bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/http/HttpResponseListener.java index a9b0bee84..385cd4db8 100644 --- a/bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/http/HttpResponseListener.java +++ b/bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/http/HttpResponseListener.java @@ -83,9 +83,8 @@ public class HttpResponseListener extends BufferingResponseListener { } private String responseToLogString(Response response) { - String logString = "Code = {" + response.getStatus() + "}, Headers = {" + return "Code = {" + response.getStatus() + "}, Headers = {" + response.getHeaders().stream().map(HttpField::toString).collect(Collectors.joining(", ")) + "}, Content = {" + getContentAsString() + "}"; - return logString; } } diff --git a/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/api/graphql/HydrawiseGraphQLClient.java b/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/api/graphql/HydrawiseGraphQLClient.java index a3a5c7542..b19745b0e 100644 --- a/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/api/graphql/HydrawiseGraphQLClient.java +++ b/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/api/graphql/HydrawiseGraphQLClient.java @@ -264,8 +264,8 @@ public class HydrawiseGraphQLClient { private void sendGraphQLMutation(String content) throws HydrawiseConnectionException, HydrawiseAuthenticationException, HydrawiseCommandException { Mutation mutation = new Mutation(content); - logger.debug("Sending Mutation {}", gson.toJson(mutation).toString()); - String response = sendGraphQLRequest(gson.toJson(mutation).toString()); + logger.debug("Sending Mutation {}", gson.toJson(mutation)); + String response = sendGraphQLRequest(gson.toJson(mutation)); logger.debug("Mutation response {}", response); try { MutationResponse mResponse = gson.fromJson(response, MutationResponse.class); @@ -273,7 +273,7 @@ public class HydrawiseGraphQLClient { throw new HydrawiseCommandException("Malformed response: " + response); } Optional status = mResponse.data.values().stream().findFirst(); - if (!status.isPresent()) { + if (status.isEmpty()) { throw new HydrawiseCommandException("Unknown response: " + response); } if (status.get().status != StatusCode.OK) { diff --git a/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/api/graphql/dto/MutationResponse.java b/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/api/graphql/dto/MutationResponse.java index 50b8243d0..7cb3b6b0a 100644 --- a/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/api/graphql/dto/MutationResponse.java +++ b/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/api/graphql/dto/MutationResponse.java @@ -27,6 +27,6 @@ public class MutationResponse { public enum StatusCode { OK, WARNING, - ERROR; + ERROR } } diff --git a/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/api/local/HydrawiseLocalApiClient.java b/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/api/local/HydrawiseLocalApiClient.java index 530cbdd03..4d3a9ec3e 100644 --- a/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/api/local/HydrawiseLocalApiClient.java +++ b/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/api/local/HydrawiseLocalApiClient.java @@ -99,8 +99,7 @@ public class HydrawiseLocalApiClient { public LocalScheduleResponse getLocalSchedule() throws HydrawiseConnectionException, HydrawiseAuthenticationException { String json = doGet(localGetURL); - LocalScheduleResponse response = gson.fromJson(json, LocalScheduleResponse.class); - return response; + return gson.fromJson(json, LocalScheduleResponse.class); } /** @@ -191,7 +190,7 @@ public class HydrawiseLocalApiClient { throws HydrawiseConnectionException, HydrawiseAuthenticationException, HydrawiseCommandException { String json = doGet(url); SetZoneResponse response = gson.fromJson(json, SetZoneResponse.class); - if (response.messageType.equals("error")) { + if ("error".equals(response.messageType)) { throw new HydrawiseCommandException(response.message); } return response.message; diff --git a/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/discovery/HydrawiseCloudControllerDiscoveryService.java b/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/discovery/HydrawiseCloudControllerDiscoveryService.java index b370ef812..29102ddb6 100644 --- a/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/discovery/HydrawiseCloudControllerDiscoveryService.java +++ b/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/discovery/HydrawiseCloudControllerDiscoveryService.java @@ -12,9 +12,9 @@ */ package org.openhab.binding.hydrawise.internal.discovery; -import java.util.Collections; import java.util.Date; import java.util.List; +import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; @@ -46,7 +46,7 @@ public class HydrawiseCloudControllerDiscoveryService extends AbstractDiscoveryS HydrawiseAccountHandler handler; public HydrawiseCloudControllerDiscoveryService() { - super(Collections.singleton(HydrawiseBindingConstants.THING_TYPE_CONTROLLER), TIMEOUT, true); + super(Set.of(HydrawiseBindingConstants.THING_TYPE_CONTROLLER), TIMEOUT, true); } @Override @@ -103,8 +103,7 @@ public class HydrawiseCloudControllerDiscoveryService extends AbstractDiscoveryS String.valueOf(id)); thingDiscovered(DiscoveryResultBuilder.create(thingUID).withLabel(label).withBridge(bridgeUID) .withProperty(HydrawiseBindingConstants.CONFIG_CONTROLLER_ID, id) - .withRepresentationProperty(String.valueOf(HydrawiseBindingConstants.CONFIG_CONTROLLER_ID)) - .build()); + .withRepresentationProperty(HydrawiseBindingConstants.CONFIG_CONTROLLER_ID).build()); } } } diff --git a/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/handler/HydrawiseAccountHandler.java b/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/handler/HydrawiseAccountHandler.java index 44f8f3853..01940cd10 100644 --- a/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/handler/HydrawiseAccountHandler.java +++ b/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/handler/HydrawiseAccountHandler.java @@ -17,6 +17,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; @@ -122,7 +123,7 @@ public class HydrawiseAccountHandler extends BaseBridgeHandler implements Access @Override public Collection> getServices() { - return Collections.singleton(HydrawiseCloudControllerDiscoveryService.class); + return Set.of(HydrawiseCloudControllerDiscoveryService.class); } public void addControllerListeners(HydrawiseControllerListener listener) { @@ -209,7 +210,7 @@ public class HydrawiseAccountHandler extends BaseBridgeHandler implements Access if (response == null) { throw new HydrawiseConnectionException("Malformed response"); } - if (response.errors != null && response.errors.size() > 0) { + if (response.errors != null && !response.errors.isEmpty()) { throw new HydrawiseConnectionException(response.errors.stream().map(error -> error.message).reduce("", (messages, message) -> messages + message + ". ")); } diff --git a/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/handler/HydrawiseLocalHandler.java b/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/handler/HydrawiseLocalHandler.java index b5894934a..7fb078bf6 100644 --- a/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/handler/HydrawiseLocalHandler.java +++ b/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/handler/HydrawiseLocalHandler.java @@ -215,7 +215,7 @@ public class HydrawiseLocalHandler extends BaseThingHandler { } updateGroupState(CHANNEL_GROUP_ALLZONES, CHANNEL_ZONE_RUN, - status.running.size() > 0 ? OnOffType.ON : OnOffType.OFF); + !status.running.isEmpty() ? OnOffType.ON : OnOffType.OFF); }); } diff --git a/bundles/org.openhab.binding.hyperion/src/main/java/org/openhab/binding/hyperion/internal/HyperionDiscoveryParticipant.java b/bundles/org.openhab.binding.hyperion/src/main/java/org/openhab/binding/hyperion/internal/HyperionDiscoveryParticipant.java index 8a8cdee11..5b911bdb1 100644 --- a/bundles/org.openhab.binding.hyperion/src/main/java/org/openhab/binding/hyperion/internal/HyperionDiscoveryParticipant.java +++ b/bundles/org.openhab.binding.hyperion/src/main/java/org/openhab/binding/hyperion/internal/HyperionDiscoveryParticipant.java @@ -13,7 +13,6 @@ package org.openhab.binding.hyperion.internal; import java.math.BigDecimal; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -39,7 +38,7 @@ public class HyperionDiscoveryParticipant implements MDNSDiscoveryParticipant { @Override public Set getSupportedThingTypeUIDs() { - return Collections.singleton(HyperionBindingConstants.THING_TYPE_SERVER_NG); + return Set.of(HyperionBindingConstants.THING_TYPE_SERVER_NG); } @Override diff --git a/bundles/org.openhab.binding.hyperion/src/main/java/org/openhab/binding/hyperion/internal/connection/JsonTcpConnection.java b/bundles/org.openhab.binding.hyperion/src/main/java/org/openhab/binding/hyperion/internal/connection/JsonTcpConnection.java index 8e8596b35..25145471d 100644 --- a/bundles/org.openhab.binding.hyperion/src/main/java/org/openhab/binding/hyperion/internal/connection/JsonTcpConnection.java +++ b/bundles/org.openhab.binding.hyperion/src/main/java/org/openhab/binding/hyperion/internal/connection/JsonTcpConnection.java @@ -68,8 +68,6 @@ public class JsonTcpConnection { outToServer.writeBytes(json + System.lineSeparator()); outToServer.flush(); response = inFromServer.readLine(); - } catch (IOException e) { - throw e; } logger.debug("Received: {}", response); return response; diff --git a/bundles/org.openhab.binding.hyperion/src/main/java/org/openhab/binding/hyperion/internal/handler/HyperionHandler.java b/bundles/org.openhab.binding.hyperion/src/main/java/org/openhab/binding/hyperion/internal/handler/HyperionHandler.java index ff9dd2e7d..6f2059c8b 100644 --- a/bundles/org.openhab.binding.hyperion/src/main/java/org/openhab/binding/hyperion/internal/handler/HyperionHandler.java +++ b/bundles/org.openhab.binding.hyperion/src/main/java/org/openhab/binding/hyperion/internal/handler/HyperionHandler.java @@ -255,10 +255,9 @@ public class HyperionHandler extends BaseThingHandler { } private void handleBrightness(Command command) throws IOException, CommandUnsuccessfulException { - if (command instanceof PercentType) { - PercentType percent = (PercentType) command; + if (command instanceof PercentType percentCommand) { Transform transform = new Transform(); - transform.setLuminanceGain(percent.doubleValue() / 100); + transform.setLuminanceGain(percentCommand.doubleValue() / 100); TransformCommand transformCommand = new TransformCommand(transform); sendCommand(transformCommand); } else { @@ -267,9 +266,8 @@ public class HyperionHandler extends BaseThingHandler { } private void handleColor(Command command) throws IOException, CommandUnsuccessfulException { - if (command instanceof HSBType) { - HSBType color = (HSBType) command; - Color c = new Color(color.getRGB()); + if (command instanceof HSBType hsbCommand) { + Color c = new Color(hsbCommand.getRGB()); int r = c.getRed(); int g = c.getGreen(); int b = c.getBlue(); diff --git a/bundles/org.openhab.binding.hyperion/src/main/java/org/openhab/binding/hyperion/internal/handler/HyperionNgHandler.java b/bundles/org.openhab.binding.hyperion/src/main/java/org/openhab/binding/hyperion/internal/handler/HyperionNgHandler.java index 26aae96fd..9fc494230 100644 --- a/bundles/org.openhab.binding.hyperion/src/main/java/org/openhab/binding/hyperion/internal/handler/HyperionNgHandler.java +++ b/bundles/org.openhab.binding.hyperion/src/main/java/org/openhab/binding/hyperion/internal/handler/HyperionNgHandler.java @@ -176,7 +176,6 @@ public class HyperionNgHandler extends BaseThingHandler { // update Hyperion, older API compatibility Hyperion hyperion = info.getHyperion(); if (hyperion != null) { - updateHyperion(hyperion); } @@ -422,9 +421,8 @@ public class HyperionNgHandler extends BaseThingHandler { } private void handleBrightness(Command command) throws IOException, CommandUnsuccessfulException { - if (command instanceof PercentType) { - PercentType percent = (PercentType) command; - int brightnessValue = percent.intValue(); + if (command instanceof PercentType percentCommand) { + int brightnessValue = percentCommand.intValue(); Adjustment adjustment = new Adjustment(); adjustment.setBrightness(brightnessValue); @@ -437,9 +435,8 @@ public class HyperionNgHandler extends BaseThingHandler { } private void handleColor(Command command) throws IOException, CommandUnsuccessfulException { - if (command instanceof HSBType) { - HSBType color = (HSBType) command; - Color c = new Color(color.getRGB()); + if (command instanceof HSBType hsbCommand) { + Color c = new Color(hsbCommand.getRGB()); int r = c.getRed(); int g = c.getGreen(); int b = c.getBlue(); diff --git a/bundles/org.openhab.binding.iammeter/src/main/java/org/openhab/binding/iammeter/internal/Iammeter3080THandler.java b/bundles/org.openhab.binding.iammeter/src/main/java/org/openhab/binding/iammeter/internal/Iammeter3080THandler.java index f130c03c7..22c61ed22 100644 --- a/bundles/org.openhab.binding.iammeter/src/main/java/org/openhab/binding/iammeter/internal/Iammeter3080THandler.java +++ b/bundles/org.openhab.binding.iammeter/src/main/java/org/openhab/binding/iammeter/internal/Iammeter3080THandler.java @@ -45,7 +45,7 @@ public class Iammeter3080THandler extends IammeterBaseHandler { JsonObject iammeterData = iammeterDataElement.getAsJsonObject(); String keyWord = "Datas"; if (iammeterData.has("Datas") && iammeterData.has("SN")) { - String groups[] = { "powerPhaseA", "powerPhaseB", "powerPhaseC" }; + String[] groups = { "powerPhaseA", "powerPhaseB", "powerPhaseC" }; for (int row = 0; row < groups.length; row++) { String gpName = groups[row]; List chnList = getThing().getChannelsOfGroup(gpName); diff --git a/bundles/org.openhab.binding.iaqualink/src/main/java/org/openhab/binding/iaqualink/internal/handler/IAqualinkHandler.java b/bundles/org.openhab.binding.iaqualink/src/main/java/org/openhab/binding/iaqualink/internal/handler/IAqualinkHandler.java index 78f6a172e..3c854a353 100644 --- a/bundles/org.openhab.binding.iaqualink/src/main/java/org/openhab/binding/iaqualink/internal/handler/IAqualinkHandler.java +++ b/bundles/org.openhab.binding.iaqualink/src/main/java/org/openhab/binding/iaqualink/internal/handler/IAqualinkHandler.java @@ -200,13 +200,12 @@ public class IAqualinkHandler extends BaseThingHandler { : "on".equals(command.toString()) ? "1" : command.toString(); client.lightCommand(serialNumber, sessionId, auxId, cmd, AuxiliaryType.fromChannelTypeUID(getChannelTypeUID(channelUID)).getSubType()); - } else if (command instanceof OnOffType) { + } else if (command instanceof OnOffType onOffCommand) { // these are toggle commands and require we have the current state to turn on/off Auxiliary[] auxs = client.getAux(serialNumber, sessionId); Optional optional = Arrays.stream(auxs).filter(o -> o.getName().equals(channelName)) .findFirst(); if (optional.isPresent()) { - OnOffType onOffCommand = (OnOffType) command; State currentState = toState(channelName, "Switch", optional.get().getState()); if (!currentState.equals(onOffCommand)) { client.auxSetCommand(serialNumber, sessionId, channelName); @@ -226,8 +225,7 @@ public class IAqualinkHandler extends BaseThingHandler { client.setPoolTemp(serialNumber, sessionId, value.floatValue()); } } - } else if (command instanceof OnOffType) { - OnOffType onOffCommand = (OnOffType) command; + } else if (command instanceof OnOffType onOffCommand) { // these are toggle commands and require we have the current state to turn on/off if (channelName.startsWith("onetouch_")) { OneTouch[] ota = client.getOneTouch(serialNumber, sessionId); diff --git a/bundles/org.openhab.binding.icalendar/src/main/java/org/openhab/binding/icalendar/internal/ICalendarHandlerFactory.java b/bundles/org.openhab.binding.icalendar/src/main/java/org/openhab/binding/icalendar/internal/ICalendarHandlerFactory.java index bc02959dc..13c08ebd1 100644 --- a/bundles/org.openhab.binding.icalendar/src/main/java/org/openhab/binding/icalendar/internal/ICalendarHandlerFactory.java +++ b/bundles/org.openhab.binding.icalendar/src/main/java/org/openhab/binding/icalendar/internal/ICalendarHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.icalendar.internal; import static org.openhab.binding.icalendar.internal.ICalendarBindingConstants.*; -import java.util.Collections; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -52,8 +51,8 @@ import org.slf4j.LoggerFactory; public class ICalendarHandlerFactory extends BaseThingHandlerFactory { private static final Set SUPPORTED_THING_TYPES_UIDS = Stream - .of(Collections.singleton(THING_TYPE_CALENDAR), Collections.singleton(THING_TYPE_FILTERED_EVENTS)) - .flatMap(Set::stream).collect(Collectors.toSet()); + .of(Set.of(THING_TYPE_CALENDAR), Set.of(THING_TYPE_FILTERED_EVENTS)).flatMap(Set::stream) + .collect(Collectors.toSet()); private final Logger logger = LoggerFactory.getLogger(ICalendarHandlerFactory.class); private final HttpClient sharedHttpClient; @@ -81,8 +80,8 @@ public class ICalendarHandlerFactory extends BaseThingHandlerFactory { return null; } if (thingTypeUID.equals(THING_TYPE_CALENDAR)) { - if (thing instanceof Bridge) { - return new ICalendarHandler((Bridge) thing, sharedHttpClient, eventPublisher, tzProvider); + if (thing instanceof Bridge bridge) { + return new ICalendarHandler(bridge, sharedHttpClient, eventPublisher, tzProvider); } else { logger.warn( "The API of iCalendar has changed. You have to recreate the calendar according to the docs."); diff --git a/bundles/org.openhab.binding.icalendar/src/main/java/org/openhab/binding/icalendar/internal/handler/EventFilterHandler.java b/bundles/org.openhab.binding.icalendar/src/main/java/org/openhab/binding/icalendar/internal/handler/EventFilterHandler.java index bf98c4eee..2b32c9e59 100644 --- a/bundles/org.openhab.binding.icalendar/src/main/java/org/openhab/binding/icalendar/internal/handler/EventFilterHandler.java +++ b/bundles/org.openhab.binding.icalendar/src/main/java/org/openhab/binding/icalendar/internal/handler/EventFilterHandler.java @@ -232,18 +232,19 @@ public class EventFilterHandler extends BaseThingHandler implements CalendarUpda thingBuilder.withoutChannel(toDelete.getUID()); }); - resultChannels.stream().filter((ResultChannelSet current) -> { - return (getThing().getChannelsOfGroup(current.resultGroup.toString()).size() == 0); - }).forEach((ResultChannelSet current) -> { - for (ChannelBuilder builder : handlerCallback.createChannelBuilders(current.resultGroup, - GROUP_TYPE_UID)) { - Channel currentChannel = builder.build(); - Channel existingChannel = getThing().getChannel(currentChannel.getUID()); - if (existingChannel == null) { - thingBuilder.withChannel(currentChannel); - } - } - }); + resultChannels + .stream().filter((ResultChannelSet current) -> (getThing() + .getChannelsOfGroup(current.resultGroup.toString()).isEmpty())) + .forEach((ResultChannelSet current) -> { + for (ChannelBuilder builder : handlerCallback.createChannelBuilders(current.resultGroup, + GROUP_TYPE_UID)) { + Channel currentChannel = builder.build(); + Channel existingChannel = getThing().getChannel(currentChannel.getUID()); + if (existingChannel == null) { + thingBuilder.withChannel(currentChannel); + } + } + }); } updateThing(thingBuilder.build()); } diff --git a/bundles/org.openhab.binding.icalendar/src/main/java/org/openhab/binding/icalendar/internal/handler/ICalendarHandler.java b/bundles/org.openhab.binding.icalendar/src/main/java/org/openhab/binding/icalendar/internal/handler/ICalendarHandler.java index fa90d9775..51aca138d 100644 --- a/bundles/org.openhab.binding.icalendar/src/main/java/org/openhab/binding/icalendar/internal/handler/ICalendarHandler.java +++ b/bundles/org.openhab.binding.icalendar/src/main/java/org/openhab/binding/icalendar/internal/handler/ICalendarHandler.java @@ -451,10 +451,10 @@ public class ICalendarHandler extends BaseBridgeHandler implements CalendarUpdat * @param childHandler the handler to be updated */ private void updateChild(@Nullable ThingHandler childHandler) { - if (childHandler instanceof CalendarUpdateListener) { + if (childHandler instanceof CalendarUpdateListener updateListener) { logger.trace("Notifying {} about fresh calendar.", childHandler.getThing().getUID()); try { - ((CalendarUpdateListener) childHandler).onCalendarUpdated(); + updateListener.onCalendarUpdated(); } catch (Exception e) { logger.trace("The update of a child handler failed. Ignoring.", e); } diff --git a/bundles/org.openhab.binding.icalendar/src/main/java/org/openhab/binding/icalendar/internal/logic/EventTextFilter.java b/bundles/org.openhab.binding.icalendar/src/main/java/org/openhab/binding/icalendar/internal/logic/EventTextFilter.java index 07d73772f..de68b8862 100644 --- a/bundles/org.openhab.binding.icalendar/src/main/java/org/openhab/binding/icalendar/internal/logic/EventTextFilter.java +++ b/bundles/org.openhab.binding.icalendar/src/main/java/org/openhab/binding/icalendar/internal/logic/EventTextFilter.java @@ -21,12 +21,12 @@ import org.eclipse.jdt.annotation.NonNullByDefault; */ @NonNullByDefault public class EventTextFilter { - public static enum Type { + public enum Type { TEXT, REGEX } - public static enum Field { + public enum Field { SUMMARY, DESCRIPTION, COMMENT, diff --git a/bundles/org.openhab.binding.icloud/src/main/java/org/openhab/binding/icloud/internal/ICloudHandlerFactory.java b/bundles/org.openhab.binding.icloud/src/main/java/org/openhab/binding/icloud/internal/ICloudHandlerFactory.java index aacb828b9..5d89c4cb5 100644 --- a/bundles/org.openhab.binding.icloud/src/main/java/org/openhab/binding/icloud/internal/ICloudHandlerFactory.java +++ b/bundles/org.openhab.binding.icloud/src/main/java/org/openhab/binding/icloud/internal/ICloudHandlerFactory.java @@ -89,8 +89,8 @@ public class ICloudHandlerFactory extends BaseThingHandlerFactory { @Override protected void removeHandler(ThingHandler thingHandler) { - if (thingHandler instanceof ICloudAccountBridgeHandler) { - unregisterDeviceDiscoveryService((ICloudAccountBridgeHandler) thingHandler); + if (thingHandler instanceof ICloudAccountBridgeHandler iCloudAccountBridgeHandler) { + unregisterDeviceDiscoveryService(iCloudAccountBridgeHandler); } } diff --git a/bundles/org.openhab.binding.icloud/src/main/java/org/openhab/binding/icloud/internal/handler/ICloudAccountBridgeHandler.java b/bundles/org.openhab.binding.icloud/src/main/java/org/openhab/binding/icloud/internal/handler/ICloudAccountBridgeHandler.java index 79761b0c5..d507e57a3 100644 --- a/bundles/org.openhab.binding.icloud/src/main/java/org/openhab/binding/icloud/internal/handler/ICloudAccountBridgeHandler.java +++ b/bundles/org.openhab.binding.icloud/src/main/java/org/openhab/binding/icloud/internal/handler/ICloudAccountBridgeHandler.java @@ -112,16 +112,13 @@ public class ICloudAccountBridgeHandler extends BaseBridgeHandler { authState = AuthState.INITIAL; } - this.iCloudDeviceInformationCache = new ExpiringCache<>(CACHE_EXPIRY, () -> { - return callApiWithRetryAndExceptionHandling(() -> { + this.iCloudDeviceInformationCache = new ExpiringCache<>(CACHE_EXPIRY, + () -> callApiWithRetryAndExceptionHandling(() -> // callApiWithRetryAndExceptionHanlding ensures that iCloudService is not null when the following is // called. Cannot use method local iCloudService instance here, because instance may be replaced with a // new // one during retry. - return iCloudService.getDevices().refreshClient(); - }); - - }); + iCloudService.getDevices().refreshClient())); updateStatus(ThingStatus.UNKNOWN); diff --git a/bundles/org.openhab.binding.icloud/src/main/java/org/openhab/binding/icloud/internal/handler/ICloudDeviceHandler.java b/bundles/org.openhab.binding.icloud/src/main/java/org/openhab/binding/icloud/internal/handler/ICloudDeviceHandler.java index 30e9aa8f9..7ce10106d 100644 --- a/bundles/org.openhab.binding.icloud/src/main/java/org/openhab/binding/icloud/internal/handler/ICloudDeviceHandler.java +++ b/bundles/org.openhab.binding.icloud/src/main/java/org/openhab/binding/icloud/internal/handler/ICloudDeviceHandler.java @@ -160,8 +160,8 @@ public class ICloudDeviceHandler extends BaseThingHandler implements ICloudDevic Bridge bridge = getBridge(); if (bridge != null) { ThingHandler bridgeHandler = bridge.getHandler(); - if (bridgeHandler instanceof ICloudAccountBridgeHandler) { - ((ICloudAccountBridgeHandler) bridgeHandler).unregisterListener(this); + if (bridgeHandler instanceof ICloudAccountBridgeHandler iCloudAccountBridgeHandler) { + iCloudAccountBridgeHandler.unregisterListener(this); } } super.dispose(); diff --git a/bundles/org.openhab.binding.icloud/src/test/java/org/openhab/binding/icloud/TestICloud.java b/bundles/org.openhab.binding.icloud/src/test/java/org/openhab/binding/icloud/TestICloud.java index da9af630c..86c9a238c 100644 --- a/bundles/org.openhab.binding.icloud/src/test/java/org/openhab/binding/icloud/TestICloud.java +++ b/bundles/org.openhab.binding.icloud/src/test/java/org/openhab/binding/icloud/TestICloud.java @@ -74,8 +74,8 @@ public class TestICloud { @BeforeEach public void setUp() { final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); - if (logger instanceof ch.qos.logback.classic.Logger) { - ((ch.qos.logback.classic.Logger) logger).setLevel(ch.qos.logback.classic.Level.DEBUG); + if (logger instanceof ch.qos.logback.classic.Logger qLogger) { + qLogger.setLevel(ch.qos.logback.classic.Level.DEBUG); } } @@ -122,7 +122,6 @@ public class TestICloud { @Test @EnabledIfSystemProperty(named = "icloud.test.email", matches = ".*", disabledReason = "Only for manual execution.") public void testDiscovery() { - String icloudDeviceRespond = """ { "userInfo": { diff --git a/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/handler/IhcHandler.java b/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/handler/IhcHandler.java index db1ebe05a..a312479bd 100644 --- a/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/handler/IhcHandler.java +++ b/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/handler/IhcHandler.java @@ -411,8 +411,8 @@ public class IhcHandler extends BaseThingHandler implements IhcEventListener { } private List getEnumValues(WSResourceValue value) { - if (value instanceof WSEnumValue) { - return enumDictionary.getEnumValues(((WSEnumValue) value).definitionTypeID); + if (value instanceof WSEnumValue enumValue) { + return enumDictionary.getEnumValues(enumValue.definitionTypeID); } return null; } @@ -764,8 +764,8 @@ public class IhcHandler extends BaseThingHandler implements IhcEventListener { } private void checkPotentialButtonPresses(WSResourceValue value) { - if (value instanceof WSBooleanValue) { - if (((WSBooleanValue) value).value) { + if (value instanceof WSBooleanValue booleanValue) { + if (booleanValue.value) { // potential button press lastUpdate.put(value.resourceID, LocalDateTime.now()); updateTriggers(value.resourceID, Duration.ZERO); diff --git a/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/profiles/PushButtonToCommandProfile.java b/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/profiles/PushButtonToCommandProfile.java index e5e74026e..8a34a975d 100644 --- a/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/profiles/PushButtonToCommandProfile.java +++ b/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/profiles/PushButtonToCommandProfile.java @@ -96,8 +96,8 @@ public class PushButtonToCommandProfile implements TriggerProfile { long retval; Object paramValue = context.getConfiguration().get(param); logger.debug("Configuring profile with {} parameter '{}'", param, paramValue); - if (paramValue instanceof BigDecimal) { - retval = ((BigDecimal) paramValue).longValue(); + if (paramValue instanceof BigDecimal decimalParam) { + retval = decimalParam.longValue(); } else { logger.debug("Parameter '{}' is not of type BigDecimal, using default value '{}'", param, defValue); retval = defValue; diff --git a/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/ws/http/IhcConnectionPool.java b/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/ws/http/IhcConnectionPool.java index 9554ee4f8..b02301101 100644 --- a/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/ws/http/IhcConnectionPool.java +++ b/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/ws/http/IhcConnectionPool.java @@ -76,7 +76,6 @@ public class IhcConnectionPool { private void init() throws IhcFatalExecption { try { - // Create a local instance of cookie store cookieStore = new BasicCookieStore(); diff --git a/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/ws/projectfile/ProjectFileUtils.java b/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/ws/projectfile/ProjectFileUtils.java index c44bf7b83..242254b9d 100644 --- a/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/ws/projectfile/ProjectFileUtils.java +++ b/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/ws/projectfile/ProjectFileUtils.java @@ -60,8 +60,7 @@ public class ProjectFileUtils { dbFactory.setXIncludeAware(false); dbFactory.setExpandEntityReferences(false); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); - Document doc = dBuilder.parse(fXmlFile); - return doc; + return dBuilder.parse(fXmlFile); } catch (IOException | ParserConfigurationException | SAXException e) { throw new IhcExecption(e); } diff --git a/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/ws/services/IhcAuthenticationService.java b/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/ws/services/IhcAuthenticationService.java index 24b7b8557..bcacc8b4e 100644 --- a/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/ws/services/IhcAuthenticationService.java +++ b/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/ws/services/IhcAuthenticationService.java @@ -39,16 +39,18 @@ public class IhcAuthenticationService extends IhcBaseService { // @formatter:off final String soapQuery = - "\n" - + "\n" - + " \n" - + " \n" - + " %s\n" - + " %s\n" - + " %s\n" - + " \n" - + " \n" - + ""; + """ + + + + + %s + %s + %s + + + \ + """; // @formatter:on String query = String.format(soapQuery, password, username, application); diff --git a/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/ws/services/IhcBaseService.java b/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/ws/services/IhcBaseService.java index 4547528f5..459906e57 100644 --- a/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/ws/services/IhcBaseService.java +++ b/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/ws/services/IhcBaseService.java @@ -29,11 +29,13 @@ public abstract class IhcBaseService extends IhcHttpsClient { // @formatter:off protected static final String EMPTY_QUERY = - "\n" - + "\n" - + " \n" - + " \n" - + ""; + """ + + + + + \ + """; // @formatter:on private String url; diff --git a/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/ws/services/IhcControllerService.java b/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/ws/services/IhcControllerService.java index 6146b2c22..083cb0e35 100644 --- a/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/ws/services/IhcControllerService.java +++ b/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/ws/services/IhcControllerService.java @@ -79,14 +79,16 @@ public class IhcControllerService extends IhcBaseService { public synchronized WSFile getProjectSegment(int index, int major, int minor) throws IhcExecption { // @formatter:off final String soapQuery = - "\n" - + "\n" - + " \n" - + " %s\n" - + " %s\n" - + " %s\n" - + " \n" - + ""; + """ + + + + %s + %s + %s + + \ + """; // @formatter:on String query = String.format(soapQuery, index, major, minor); @@ -117,15 +119,17 @@ public class IhcControllerService extends IhcBaseService { int timeoutInSeconds) throws IhcExecption { // @formatter:off final String soapQuery = - "\n" - + "\n" - + " \n" - + " \n" - + " %s\n" - + " \n" - + " %s\n" - + " \n" - + ""; + """ + + + + + %s + + %s + + \ + """; // @formatter:on String query = String.format(soapQuery, previousState.getState(), timeoutInSeconds); diff --git a/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/ws/services/IhcResourceInteractionService.java b/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/ws/services/IhcResourceInteractionService.java index 913c3b7ad..cc21456d2 100644 --- a/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/ws/services/IhcResourceInteractionService.java +++ b/bundles/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/internal/ws/services/IhcResourceInteractionService.java @@ -57,12 +57,14 @@ public class IhcResourceInteractionService extends IhcBaseService { public WSResourceValue resourceQuery(int resoureId) throws IhcExecption { // @formatter:off final String soapQuery = - "\n" - + "\n" - + " \n" - + " %s\n" - + " \n" - + ""; + """ + + + + %s + + \ + """; // @formatter:on String query = String.format(soapQuery, String.valueOf(resoureId)); @@ -173,22 +175,22 @@ public class IhcResourceInteractionService extends IhcBaseService { public boolean resourceUpdate(WSResourceValue value) throws IhcExecption { boolean retval = false; - if (value instanceof WSFloatingPointValue) { - retval = resourceUpdate((WSFloatingPointValue) value); - } else if (value instanceof WSBooleanValue) { - retval = resourceUpdate((WSBooleanValue) value); - } else if (value instanceof WSIntegerValue) { - retval = resourceUpdate((WSIntegerValue) value); - } else if (value instanceof WSTimerValue) { - retval = resourceUpdate((WSTimerValue) value); - } else if (value instanceof WSWeekdayValue) { - retval = resourceUpdate((WSWeekdayValue) value); - } else if (value instanceof WSEnumValue) { - retval = resourceUpdate((WSEnumValue) value); - } else if (value instanceof WSTimeValue) { - retval = resourceUpdate((WSTimeValue) value); - } else if (value instanceof WSDateValue) { - retval = resourceUpdate((WSDateValue) value); + if (value instanceof WSFloatingPointValue pointValue) { + retval = resourceUpdate(pointValue); + } else if (value instanceof WSBooleanValue booleanValue) { + retval = resourceUpdate(booleanValue); + } else if (value instanceof WSIntegerValue integerValue) { + retval = resourceUpdate(integerValue); + } else if (value instanceof WSTimerValue timerValue) { + retval = resourceUpdate(timerValue); + } else if (value instanceof WSWeekdayValue weekdayValue) { + retval = resourceUpdate(weekdayValue); + } else if (value instanceof WSEnumValue enumValue) { + retval = resourceUpdate(enumValue); + } else if (value instanceof WSTimeValue timeValue) { + retval = resourceUpdate(timeValue); + } else if (value instanceof WSDateValue dateValue) { + retval = resourceUpdate(dateValue); } else { throw new IhcExecption("Unsupported value type " + value.getClass().toString()); } @@ -199,18 +201,20 @@ public class IhcResourceInteractionService extends IhcBaseService { public boolean resourceUpdate(WSBooleanValue value) throws IhcExecption { // @formatter:off final String soapQuery = - "\n" - + "\n" - + " \n" - + " \n" - + " \n" - + " %s\n" - + " \n" - + " %s\n" - + " true\n" - + " \n" - + " \n" - + ""; + """ + + + + + + %s + + %s + true + + + \ + """; // @formatter:on String query = String.format(soapQuery, value.value ? "true" : "false", value.resourceID); @@ -220,20 +224,22 @@ public class IhcResourceInteractionService extends IhcBaseService { public boolean resourceUpdate(WSFloatingPointValue value) throws IhcExecption { // @formatter:off final String soapQuery = - "\n" - + "\n" - + " \n" - + " \n" - + " \n" - + " %s\n" - + " %s\n" - + " %s\n" - + " \n" - + " %s\n" - + " true\n" - + " \n" - + " \n" - + ""; + """ + + + + + + %s + %s + %s + + %s + true + + + \ + """; // @formatter:on String query = String.format(soapQuery, value.maximumValue, value.minimumValue, value.value, value.resourceID); @@ -243,20 +249,22 @@ public class IhcResourceInteractionService extends IhcBaseService { public boolean resourceUpdate(WSIntegerValue value) throws IhcExecption { // @formatter:off final String soapQuery = - "\n" - + "\n" - + " \n" - + " \n" - + " \n" - + " %s\n" - + " %s\n" - + " %s\n" - + " \n" - + " %s\n" - + " true\n" - + " \n" - + " \n" - + ""; + """ + + + + + + %s + %s + %s + + %s + true + + + \ + """; // @formatter:on String query = String.format(soapQuery, value.maximumValue, value.minimumValue, value.value, value.resourceID); @@ -266,18 +274,20 @@ public class IhcResourceInteractionService extends IhcBaseService { public boolean resourceUpdate(WSTimerValue value) throws IhcExecption { // @formatter:off final String soapQuery = - "\n" - + "\n" - + " \n" - + " \n" - + " \n" - + " %s\n" - + " \n" - + " %s\n" - + " true\n" - + " \n" - + " \n" - + ""; + """ + + + + + + %s + + %s + true + + + \ + """; // @formatter:on String query = String.format(soapQuery, value.milliseconds, value.resourceID); @@ -287,18 +297,20 @@ public class IhcResourceInteractionService extends IhcBaseService { public boolean resourceUpdate(WSWeekdayValue value) throws IhcExecption { // @formatter:off final String soapQuery = - "\n" - + "\n" - + " \n" - + " \n" - + " \n" - + " %s\n" - + " \n" - + " %s\n" - + " true\n" - + " \n" - + " \n" - + ""; + """ + + + + + + %s + + %s + true + + + \ + """; // @formatter:on String query = String.format(soapQuery, value.weekdayNumber, value.resourceID); @@ -308,20 +320,22 @@ public class IhcResourceInteractionService extends IhcBaseService { public boolean resourceUpdate(WSEnumValue value) throws IhcExecption { // @formatter:off final String soapQuery = - "\n" - + "\n" - + " \n" - + " \n" - + " \n" - + " %s\n" - + " %s\n" - + " %s\n" - + " \n" - + " %s\n" - + " true\n" - + " \n" - + " \n" - + ""; + """ + + + + + + %s + %s + %s + + %s + true + + + \ + """; // @formatter:on String query = String.format(soapQuery, value.definitionTypeID, value.enumValueID, value.enumName, @@ -332,20 +346,22 @@ public class IhcResourceInteractionService extends IhcBaseService { public boolean resourceUpdate(WSTimeValue value) throws IhcExecption { // @formatter:off final String soapQuery = - "\n" - + "\n" - + " \n" - + " \n" - + " \n" - + " %s\n" - + " %s\n" - + " %s\n" - + " \n" - + " %s\n" - + " true\n" - + " \n" - + " \n" - + ""; + """ + + + + + + %s + %s + %s + + %s + true + + + \ + """; // @formatter:on String query = String.format(soapQuery, value.hours, value.minutes, value.seconds, value.resourceID); @@ -355,20 +371,22 @@ public class IhcResourceInteractionService extends IhcBaseService { public boolean resourceUpdate(WSDateValue value) throws IhcExecption { // @formatter:off final String soapQuery = - "\n" - + "\n" - + " \n" - + " \n" - + " \n" - + " %s\n" - + " %s\n" - + " %s\n" - + " \n" - + " %s\n" - + " true\n" - + " \n" - + " \n" - + ""; + """ + + + + + + %s + %s + %s + + %s + true + + + \ + """; // @formatter:on String query = String.format(soapQuery, value.month, value.year, value.day, value.resourceID); @@ -394,15 +412,19 @@ public class IhcResourceInteractionService extends IhcBaseService { public void enableRuntimeValueNotifications(Set resourceIdList) throws IhcExecption { // @formatter:off final String soapQueryPrefix = - "\n" - + "\n" - + " \n" - + " \n"; + """ + + + + + """; final String soapQuerySuffix = - " \n" - + " \n" - + ""; + """ + + + \ + """; // @formatter:on String query = soapQueryPrefix; @@ -427,12 +449,14 @@ public class IhcResourceInteractionService extends IhcBaseService { public List waitResourceValueNotifications(int timeoutInSeconds) throws IhcExecption { // @formatter:off final String soapQuery = - "\n" - + "\n" - + " \n" - + " %s\n" - + " \n" - + ""; + """ + + + + %s + + \ + """; // @formatter:on String query = String.format(soapQuery, timeoutInSeconds); diff --git a/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/CommandHandler.java b/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/CommandHandler.java index 10044a748..8f2626f75 100644 --- a/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/CommandHandler.java +++ b/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/CommandHandler.java @@ -299,8 +299,8 @@ public abstract class CommandHandler { @Override public void handleCommand(InsteonChannelConfiguration conf, Command cmd, InsteonDevice dev) { try { - if (cmd instanceof DecimalType) { - int v = ((DecimalType) cmd).intValue(); + if (cmd instanceof DecimalType decimalCommand) { + int v = decimalCommand.intValue(); int cmd1 = (v != 1) ? 0x17 : 0x18; // start or stop int cmd2 = (v == 2) ? 0x01 : 0; // up or down Msg m = dev.makeStandardMessage((byte) 0x0f, (byte) cmd1, (byte) cmd2, getGroup(conf)); diff --git a/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/DeviceFeature.java b/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/DeviceFeature.java index 03b80ec4d..6f7d60248 100644 --- a/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/DeviceFeature.java +++ b/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/DeviceFeature.java @@ -64,7 +64,7 @@ import org.slf4j.LoggerFactory; */ @NonNullByDefault public class DeviceFeature { - public static enum QueryStatus { + public enum QueryStatus { NEVER_QUERIED, QUERY_PENDING, QUERY_ANSWERED @@ -300,8 +300,7 @@ public class DeviceFeature { } logger.trace("{} making poll msg for {} using handler {}", getName(), getDevice().getAddress(), pollHandler.getClass().getSimpleName()); - Msg m = pollHandler.makeMsg(device); - return m; + return pollHandler.makeMsg(device); } /** diff --git a/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/DeviceTypeLoader.java b/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/DeviceTypeLoader.java index 2c6aff95e..82a42d136 100644 --- a/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/DeviceTypeLoader.java +++ b/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/DeviceTypeLoader.java @@ -90,7 +90,7 @@ public class DeviceTypeLoader { NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); - if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals("device")) { + if (node.getNodeType() == Node.ELEMENT_NODE && "device".equals(node.getNodeName())) { processDevice((Element) node); } } diff --git a/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/FeatureTemplateLoader.java b/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/FeatureTemplateLoader.java index 7b92f8221..294412c5b 100644 --- a/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/FeatureTemplateLoader.java +++ b/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/FeatureTemplateLoader.java @@ -85,7 +85,7 @@ public class FeatureTemplateLoader { private static FeatureTemplate parseFeature(Element e) throws ParsingException { String name = e.getAttribute("name"); - boolean statusFeature = e.getAttribute("statusFeature").equals("true"); + boolean statusFeature = "true".equals(e.getAttribute("statusFeature")); FeatureTemplate feature = new FeatureTemplate(name, statusFeature, e.getAttribute("timeout")); NodeList nodes = e.getChildNodes(); @@ -94,13 +94,13 @@ public class FeatureTemplateLoader { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element child = (Element) node; - if (child.getTagName().equals("message-handler")) { + if ("message-handler".equals(child.getTagName())) { parseMessageHandler(child, feature); - } else if (child.getTagName().equals("command-handler")) { + } else if ("command-handler".equals(child.getTagName())) { parseCommandHandler(child, feature); - } else if (child.getTagName().equals("message-dispatcher")) { + } else if ("message-dispatcher".equals(child.getTagName())) { parseMessageDispatcher(child, feature); - } else if (child.getTagName().equals("poll-handler")) { + } else if ("poll-handler".equals(child.getTagName())) { parsePollHandler(child, feature); } } diff --git a/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/GroupMessageStateMachine.java b/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/GroupMessageStateMachine.java index 0864ba373..f0de27238 100644 --- a/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/GroupMessageStateMachine.java +++ b/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/GroupMessageStateMachine.java @@ -89,7 +89,7 @@ public class GroupMessageStateMachine { enum GroupMessage { BCAST, CLEAN, - SUCCESS; + SUCCESS }; /** diff --git a/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/InsteonDevice.java b/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/InsteonDevice.java index 943c89a5e..9c056b74b 100644 --- a/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/InsteonDevice.java +++ b/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/InsteonDevice.java @@ -49,7 +49,7 @@ import org.slf4j.LoggerFactory; public class InsteonDevice { private final Logger logger = LoggerFactory.getLogger(InsteonDevice.class); - public static enum DeviceStatus { + public enum DeviceStatus { INITIALIZED, POLLING } diff --git a/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/MessageHandler.java b/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/MessageHandler.java index ff8ae8d55..f7568bd6d 100644 --- a/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/MessageHandler.java +++ b/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/MessageHandler.java @@ -170,8 +170,8 @@ public abstract class MessageHandler { protected boolean getBooleanDeviceConfig(String key, boolean def) { Object o = feature.getDevice().getDeviceConfigMap().get(key); if (o != null) { - if (o instanceof Boolean) { - return (Boolean) o; + if (o instanceof Boolean booleanValue) { + return booleanValue; } else { logger.warn("{} {}: The value for the '{}' key is not boolean in the device configuration parameter.", nm(), feature.getDevice().getAddress(), key); diff --git a/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/ModemDBBuilder.java b/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/ModemDBBuilder.java index faf3e57fe..500131884 100644 --- a/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/ModemDBBuilder.java +++ b/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/ModemDBBuilder.java @@ -73,8 +73,10 @@ public class ModemDBBuilder implements MsgListener { if (System.currentTimeMillis() - lastMessageTimestamp > MESSAGE_TIMEOUT) { String s = ""; if (messageCount == 0) { - s = " No messages were received, the PLM or hub might be broken. If this continues see " - + "'Known Limitations and Issues' in the Insteon binding documentation."; + s = """ + No messages were received, the PLM or hub might be broken. If this continues see \ + 'Known Limitations and Issues' in the Insteon binding documentation.\ + """; } logger.warn("Modem database download was unsuccessful, restarting!{}", s); startDownload(); diff --git a/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/handler/InsteonDeviceHandler.java b/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/handler/InsteonDeviceHandler.java index 6c67bcb5e..a74299ffd 100644 --- a/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/handler/InsteonDeviceHandler.java +++ b/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/handler/InsteonDeviceHandler.java @@ -252,7 +252,7 @@ public class InsteonDeviceHandler extends BaseThingHandler { feature = DATA; } } else if (productKey.equals(PLM_PRODUCT_KEY)) { - String parts[] = feature.split("#"); + String[] parts = feature.split("#"); if (parts.length == 2 && parts[0].equalsIgnoreCase(InsteonBindingConstants.BROADCAST_ON_OFF) && parts[1].matches("^\\d+$")) { feature = BROADCAST_ON_OFF; @@ -282,9 +282,9 @@ public class InsteonDeviceHandler extends BaseThingHandler { Object groups = deviceConfigMap.get(BROADCAST_GROUPS); if (groups != null) { boolean valid = false; - if (groups instanceof List) { + if (groups instanceof List list) { valid = true; - for (Object o : (List) groups) { + for (Object o : list) { if (o instanceof Double && (Double) o % 1 == 0) { String id = InsteonBindingConstants.BROADCAST_ON_OFF + "#" + ((Double) o).intValue(); @@ -444,10 +444,10 @@ public class InsteonDeviceHandler extends BaseThingHandler { Map channelProperties = channel.getConfiguration().getProperties(); for (String key : channelProperties.keySet()) { Object value = channelProperties.get(key); - if (value instanceof String) { - params.put(key, (String) value); - } else if (value instanceof BigDecimal) { - String s = ((BigDecimal) value).toPlainString(); + if (value instanceof String stringValue) { + params.put(key, stringValue); + } else if (value instanceof BigDecimal decimalValue) { + String s = decimalValue.toPlainString(); params.put(key, s); } else { logger.warn("not a string or big decimal value key '{}' value '{}' {}", key, value, @@ -493,7 +493,7 @@ public class InsteonDeviceHandler extends BaseThingHandler { feature = DATA; } } else if (productKey.equals(PLM_PRODUCT_KEY)) { - String parts[] = feature.split("#"); + String[] parts = feature.split("#"); if (parts.length == 2 && parts[0].equalsIgnoreCase(InsteonBindingConstants.BROADCAST_ON_OFF) && parts[1].matches("^\\d+$")) { params.put(GROUP, parts[1]); diff --git a/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/message/Field.java b/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/message/Field.java index 2a2f3889f..6de15c1b9 100644 --- a/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/message/Field.java +++ b/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/message/Field.java @@ -176,8 +176,7 @@ public final class Field { byte b2 = array[offset + 1]; byte b3 = array[offset + 2]; byte b4 = array[offset + 3]; - int value = ((b1 << 24) + (b2 << 16) + (b3 << 8) + (b4 << 0)); - return value; + return ((b1 << 24) + (b2 << 16) + (b3 << 8) + (b4 << 0)); } /** @@ -199,8 +198,7 @@ public final class Field { */ @Override public boolean equals(@Nullable Object o) { - if (o instanceof Field) { - Field f = (Field) o; + if (o instanceof Field f) { return (f.getName().equals(getName())) && (f.getOffset() == getOffset()); } else { return false; diff --git a/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/message/XMLMessageReader.java b/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/message/XMLMessageReader.java index 6398b47e5..08f07cf54 100644 --- a/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/message/XMLMessageReader.java +++ b/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/message/XMLMessageReader.java @@ -73,7 +73,7 @@ public class XMLMessageReader { for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { - if (node.getNodeName().equals("msg")) { + if ("msg".equals(node.getNodeName())) { Pair msgDef = readMessageDefinition((Element) node); messageMap.put(msgDef.getKey(), msgDef.getValue()); } @@ -106,7 +106,7 @@ public class XMLMessageReader { for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { - if (node.getNodeName().equals("header")) { + if ("header".equals(node.getNodeName())) { int o = readHeaderElement((Element) node, fieldMap); hlength = o; // Increment the offset by the header length @@ -158,8 +158,7 @@ public class XMLMessageReader { // Now we have field, only need value String sVal = field.getTextContent(); Object val = DataTypeParser.parseDataType(dType, sVal); - Pair pair = new Pair<>(f, val); - return pair; + return new Pair<>(f, val); } private static Msg createMsg(HashMap values, int length, int headerLength, Msg.Direction dir) @@ -173,7 +172,7 @@ public class XMLMessageReader { } else { throw new FieldException("data is null"); } - if (!f.getName().equals("")) { + if (!"".equals(f.getName())) { msg.addField(f); } } diff --git a/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/utils/Utils.java b/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/utils/Utils.java index 8ec905ddb..4df35148d 100644 --- a/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/utils/Utils.java +++ b/bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/utils/Utils.java @@ -26,8 +26,7 @@ import org.openhab.binding.insteon.internal.message.DataType; @NonNullByDefault public class Utils { public static String getHexString(int b) { - String result = String.format("%02X", b & 0xFF); - return result; + return String.format("%02X", b & 0xFF); } public static String getHexString(byte[] b) { @@ -86,7 +85,7 @@ public class Utils { } public static byte parseByte(@Nullable String val) { - if (val != null && !val.trim().equals("")) { + if (val != null && !"".equals(val.trim())) { return (byte) Utils.from0xHexString(val.trim()); } else { return 0x00; @@ -94,7 +93,7 @@ public class Utils { } public static int parseInt(@Nullable String val) { - if (val != null && !val.trim().equals("")) { + if (val != null && !"".equals(val.trim())) { return Integer.parseInt(val); } else { return 0x00; @@ -102,7 +101,7 @@ public class Utils { } public static float parseFloat(@Nullable String val) { - if (val != null && !val.trim().equals("")) { + if (val != null && !"".equals(val.trim())) { return Float.parseFloat(val.trim()); } else { return 0; @@ -110,7 +109,7 @@ public class Utils { } public static InsteonAddress parseAddress(@Nullable String val) { - if (val != null && !val.trim().equals("")) { + if (val != null && !"".equals(val.trim())) { return InsteonAddress.parseAddress(val.trim()); } else { return new InsteonAddress(); diff --git a/bundles/org.openhab.binding.intesis/src/main/java/org/openhab/binding/intesis/internal/handler/IntesisBoxHandler.java b/bundles/org.openhab.binding.intesis/src/main/java/org/openhab/binding/intesis/internal/handler/IntesisBoxHandler.java index 8de6e1af2..74758e50c 100644 --- a/bundles/org.openhab.binding.intesis/src/main/java/org/openhab/binding/intesis/internal/handler/IntesisBoxHandler.java +++ b/bundles/org.openhab.binding.intesis/src/main/java/org/openhab/binding/intesis/internal/handler/IntesisBoxHandler.java @@ -174,9 +174,8 @@ public class IntesisBoxHandler extends BaseThingHandler implements IntesisBoxCha } break; case CHANNEL_TYPE_TARGETTEMP: - if (command instanceof QuantityType) { - QuantityType celsiusTemperature = (QuantityType) command; - celsiusTemperature = celsiusTemperature.toUnit(SIUnits.CELSIUS); + if (command instanceof QuantityType quantityCommand) { + QuantityType celsiusTemperature = quantityCommand.toUnit(SIUnits.CELSIUS); if (celsiusTemperature != null) { double doubleValue = celsiusTemperature.doubleValue(); logger.trace("targetTemp double value = {}", doubleValue); diff --git a/bundles/org.openhab.binding.intesis/src/main/java/org/openhab/binding/intesis/internal/handler/IntesisHomeHandler.java b/bundles/org.openhab.binding.intesis/src/main/java/org/openhab/binding/intesis/internal/handler/IntesisHomeHandler.java index f352fc2a6..7599997f7 100644 --- a/bundles/org.openhab.binding.intesis/src/main/java/org/openhab/binding/intesis/internal/handler/IntesisHomeHandler.java +++ b/bundles/org.openhab.binding.intesis/src/main/java/org/openhab/binding/intesis/internal/handler/IntesisHomeHandler.java @@ -194,8 +194,7 @@ public class IntesisHomeHandler extends BaseThingHandler { break; case CHANNEL_TYPE_TARGETTEMP: uid = 9; - if (command instanceof QuantityType) { - QuantityType newVal = (QuantityType) command; + if (command instanceof QuantityType newVal) { newVal = newVal.toUnit(SIUnits.CELSIUS); if (newVal != null) { value = newVal.intValue() * 10; @@ -226,7 +225,7 @@ public class IntesisHomeHandler extends BaseThingHandler { if (data != null) { Id id = gson.fromJson(data.id, Id.class); if (id != null) { - sessionId[0] = id.sessionID.toString(); + sessionId[0] = id.sessionID; } } }); @@ -241,8 +240,7 @@ public class IntesisHomeHandler extends BaseThingHandler { public @Nullable String logout(String sessionId) { String contentString = "{\"command\":\"logout\",\"data\":{\"sessionID\":\"" + sessionId + "\"}}"; - String response = api.postRequest(config.ipAddress, contentString); - return response; + return api.postRequest(config.ipAddress, contentString); } public void populateProperties() { @@ -490,7 +488,7 @@ public class IntesisHomeHandler extends BaseThingHandler { switch (element.uid) { case 1: updateState(CHANNEL_TYPE_POWER, - String.valueOf(element.value).equals("0") ? OnOffType.OFF : OnOffType.ON); + "0".equals(String.valueOf(element.value)) ? OnOffType.OFF : OnOffType.ON); break; case 2: switch (element.value) { @@ -554,7 +552,7 @@ public class IntesisHomeHandler extends BaseThingHandler { break; case 14: updateState(CHANNEL_TYPE_ERRORSTATUS, - String.valueOf(element.value).equals("0") ? OnOffType.OFF : OnOffType.ON); + "0".equals(String.valueOf(element.value)) ? OnOffType.OFF : OnOffType.ON); break; case 15: updateState(CHANNEL_TYPE_ERRORCODE, StringType.valueOf(String.valueOf(element.value))); diff --git a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/AmcrestHandler.java b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/AmcrestHandler.java index 82e321aab..37509cd54 100644 --- a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/AmcrestHandler.java +++ b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/AmcrestHandler.java @@ -226,7 +226,6 @@ public class AmcrestHandler extends ChannelDuplexHandler { // If a camera does not need to poll a request as often as snapshots, it can be // added here. Binding steps through the list. public ArrayList getLowPriorityRequests() { - ArrayList lowPriorityRequests = new ArrayList(1); - return lowPriorityRequests; + return new ArrayList(1); } } diff --git a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/DoorBirdHandler.java b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/DoorBirdHandler.java index fb1a8c6c1..9d71eaba5 100644 --- a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/DoorBirdHandler.java +++ b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/DoorBirdHandler.java @@ -95,7 +95,6 @@ public class DoorBirdHandler extends ChannelDuplexHandler { // If a camera does not need to poll a request as often as snapshots, it can be // added here. Binding steps through the list. public ArrayList getLowPriorityRequests() { - ArrayList lowPriorityRequests = new ArrayList(1); - return lowPriorityRequests; + return new ArrayList(1); } } diff --git a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/Helper.java b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/Helper.java index 1a2e641e7..5dc407f2f 100644 --- a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/Helper.java +++ b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/Helper.java @@ -123,9 +123,9 @@ public class Helper { for (Enumeration enumIpAddr = networkInterface.getInetAddresses(); enumIpAddr .hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); - if (!inetAddress.isLoopbackAddress() && inetAddress.getHostAddress().toString().length() < 18 + if (!inetAddress.isLoopbackAddress() && inetAddress.getHostAddress().length() < 18 && inetAddress.isSiteLocalAddress()) { - ipAddress = inetAddress.getHostAddress().toString(); + ipAddress = inetAddress.getHostAddress(); } } } diff --git a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/InstarHandler.java b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/InstarHandler.java index 0aaee77ec..1c4c0bd34 100644 --- a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/InstarHandler.java +++ b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/InstarHandler.java @@ -197,8 +197,8 @@ public class InstarHandler extends ChannelDuplexHandler { ipCameraHandler.sendHttpGET("/param.cgi?cmd=setaudioalarmattr&enable=0"); } else if (OnOffType.ON.equals(command)) { ipCameraHandler.sendHttpGET("/param.cgi?cmd=setaudioalarmattr&enable=1"); - } else if (command instanceof PercentType) { - int value = ((PercentType) command).toBigDecimal().divide(BigDecimal.TEN).intValue(); + } else if (command instanceof PercentType percentCommand) { + int value = percentCommand.toBigDecimal().divide(BigDecimal.TEN).intValue(); ipCameraHandler.sendHttpGET("/param.cgi?cmd=setaudioalarmattr&enable=1&threshold=" + value); } return; @@ -253,8 +253,8 @@ public class InstarHandler extends ChannelDuplexHandler { ipCameraHandler.sendHttpGET("/cgi-bin/hi3510/param.cgi?cmd=setaudioalarmattr&-aa_enable=0"); } else if (OnOffType.ON.equals(command)) { ipCameraHandler.sendHttpGET("/cgi-bin/hi3510/param.cgi?cmd=setaudioalarmattr&-aa_enable=1"); - } else if (command instanceof PercentType) { - int value = ((PercentType) command).toBigDecimal().divide(BigDecimal.TEN).intValue(); + } else if (command instanceof PercentType percentCommand) { + int value = percentCommand.toBigDecimal().divide(BigDecimal.TEN).intValue(); ipCameraHandler.sendHttpGET( "/cgi-bin/hi3510/param.cgi?cmd=setaudioalarmattr&-aa_enable=1&-aa_value=" + value * 10); } diff --git a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/IpCameraBindingConstants.java b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/IpCameraBindingConstants.java index af72ae036..4d9d96fd2 100644 --- a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/IpCameraBindingConstants.java +++ b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/IpCameraBindingConstants.java @@ -35,7 +35,7 @@ public class IpCameraBindingConstants { public static final String INSTAR_HANDLER = "instarHandler"; public static final String REOLINK_HANDLER = "reolinkHandler"; - public static enum FFmpegFormat { + public enum FFmpegFormat { HLS, GIF, RECORD, diff --git a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/MyNettyAuthHandler.java b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/MyNettyAuthHandler.java index 1fa75c9ee..096551c69 100644 --- a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/MyNettyAuthHandler.java +++ b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/MyNettyAuthHandler.java @@ -145,15 +145,14 @@ public class MyNettyAuthHandler extends ChannelDuplexHandler { if (msg == null || ctx == null) { return; } - if (msg instanceof HttpResponse) { - HttpResponse response = (HttpResponse) msg; + if (msg instanceof HttpResponse response) { if (response.status().code() == 401) { ctx.close(); if (!response.headers().isEmpty()) { String authenticate = ""; for (CharSequence name : response.headers().names()) { for (CharSequence value : response.headers().getAll(name)) { - if (name.toString().equalsIgnoreCase("WWW-Authenticate")) { + if ("WWW-Authenticate".equalsIgnoreCase(name.toString())) { authenticate = value.toString(); } } diff --git a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/ReolinkHandler.java b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/ReolinkHandler.java index b3fa10d37..3dffcf725 100644 --- a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/ReolinkHandler.java +++ b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/ReolinkHandler.java @@ -242,8 +242,8 @@ public class ReolinkHandler extends ChannelDuplexHandler { ipCameraHandler.sendHttpPOST("/api.cgi?cmd=SetWhiteLed" + ipCameraHandler.reolinkAuth, "[{\"cmd\": \"SetWhiteLed\",\"param\": {\"WhiteLed\": {\"state\": 1,\"channel\": " + ipCameraHandler.cameraConfig.getNvrChannel() + ",\"mode\": 1}}}]"); - } else if (command instanceof PercentType) { - int value = ((PercentType) command).toBigDecimal().intValue(); + } else if (command instanceof PercentType percentCommand) { + int value = percentCommand.toBigDecimal().intValue(); ipCameraHandler.sendHttpPOST("/api.cgi?cmd=SetWhiteLed" + ipCameraHandler.reolinkAuth, "[{\"cmd\": \"SetWhiteLed\",\"param\": {\"WhiteLed\": {\"state\": 1,\"channel\": " + ipCameraHandler.cameraConfig.getNvrChannel() + ",\"mode\": 1,\"bright\": " + value diff --git a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/handler/IpCameraHandler.java b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/handler/IpCameraHandler.java index ad380b0f0..e5f1702d8 100644 --- a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/handler/IpCameraHandler.java +++ b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/handler/IpCameraHandler.java @@ -28,10 +28,10 @@ import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.Future; @@ -218,8 +218,7 @@ public class IpCameraHandler extends BaseThingHandler { return; } try { - if (msg instanceof HttpResponse) { - HttpResponse response = (HttpResponse) msg; + if (msg instanceof HttpResponse response) { if (response.status().code() == 200) { if (!response.headers().isEmpty()) { for (String name : response.headers().names()) { @@ -264,8 +263,7 @@ public class IpCameraHandler extends BaseThingHandler { return; } } - if (msg instanceof HttpContent) { - HttpContent content = (HttpContent) msg; + if (msg instanceof HttpContent content) { if (mjpegUri.equals(requestUrl) && !(content instanceof LastHttpContent)) { // multiple MJPEG stream packets come back as this. byte[] chunkedFrame = new byte[content.content().readableBytes()]; @@ -368,8 +366,7 @@ public class IpCameraHandler extends BaseThingHandler { if (ctx == null) { return; } - if (evt instanceof IdleStateEvent) { - IdleStateEvent e = (IdleStateEvent) evt; + if (evt instanceof IdleStateEvent e) { // If camera does not use the channel for X amount of time it will close. if (e.state() == IdleState.READER_IDLE) { String urlToKeepOpen = ""; @@ -1154,9 +1151,9 @@ public class IpCameraHandler extends BaseThingHandler { } else if (OnOffType.OFF.equals(command) || DecimalType.ZERO.equals(command)) { ffmpegMotionAlarmEnabled = false; noMotionDetected(CHANNEL_FFMPEG_MOTION_ALARM); - } else if (command instanceof PercentType) { + } else if (command instanceof PercentType percentCommand) { ffmpegMotionAlarmEnabled = true; - motionThreshold = ((PercentType) command).toBigDecimal(); + motionThreshold = percentCommand.toBigDecimal(); } setupFfmpegFormat(FFmpegFormat.RTSP_ALARMS); return; @@ -1887,6 +1884,6 @@ public class IpCameraHandler extends BaseThingHandler { @Override public Collection> getServices() { - return Collections.singleton(IpCameraActions.class); + return Set.of(IpCameraActions.class); } } diff --git a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/onvif/OnvifCodec.java b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/onvif/OnvifCodec.java index e9eb38a08..378a6b2e0 100644 --- a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/onvif/OnvifCodec.java +++ b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/onvif/OnvifCodec.java @@ -46,8 +46,7 @@ public class OnvifCodec extends ChannelDuplexHandler { return; } try { - if (msg instanceof HttpContent) { - HttpContent content = (HttpContent) msg; + if (msg instanceof HttpContent content) { incomingMessage += content.content().toString(CharsetUtil.UTF_8); } if (msg instanceof LastHttpContent) { diff --git a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/onvif/OnvifConnection.java b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/onvif/OnvifConnection.java index 948852571..9725dfcc6 100644 --- a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/onvif/OnvifConnection.java +++ b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/onvif/OnvifConnection.java @@ -72,7 +72,7 @@ import io.netty.handler.timeout.IdleStateHandler; @NonNullByDefault public class OnvifConnection { - public static enum RequestType { + public enum RequestType { AbsoluteMove, AddPTZConfiguration, ContinuousMoveLeft, diff --git a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/onvif/OnvifDiscovery.java b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/onvif/OnvifDiscovery.java index dc49bf3bd..7dbaf9242 100644 --- a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/onvif/OnvifDiscovery.java +++ b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/onvif/OnvifDiscovery.java @@ -86,7 +86,7 @@ public class OnvifDiscovery { for (Enumeration enumIpAddr = networkInterface.getInetAddresses(); enumIpAddr .hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); - if (!inetAddress.isLoopbackAddress() && inetAddress.getHostAddress().toString().length() < 18 + if (!inetAddress.isLoopbackAddress() && inetAddress.getHostAddress().length() < 18 && inetAddress.isSiteLocalAddress()) { if (inetAddress.getHostAddress().equals(primaryHostAddress)) { results.add(networkInterface); diff --git a/bundles/org.openhab.binding.ipobserver/src/main/java/org/openhab/binding/ipobserver/internal/IpObserverDiscoveryService.java b/bundles/org.openhab.binding.ipobserver/src/main/java/org/openhab/binding/ipobserver/internal/IpObserverDiscoveryService.java index 63068c1ee..6cc0cca66 100644 --- a/bundles/org.openhab.binding.ipobserver/src/main/java/org/openhab/binding/ipobserver/internal/IpObserverDiscoveryService.java +++ b/bundles/org.openhab.binding.ipobserver/src/main/java/org/openhab/binding/ipobserver/internal/IpObserverDiscoveryService.java @@ -98,7 +98,7 @@ public class IpObserverDiscoveryService 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 IpObserverDiscoveryJob(this, host)); } diff --git a/bundles/org.openhab.binding.ipp/src/main/java/org/openhab/binding/ipp/internal/handler/IppPrinterHandler.java b/bundles/org.openhab.binding.ipp/src/main/java/org/openhab/binding/ipp/internal/handler/IppPrinterHandler.java index e4f429cfe..4325d42d2 100644 --- a/bundles/org.openhab.binding.ipp/src/main/java/org/openhab/binding/ipp/internal/handler/IppPrinterHandler.java +++ b/bundles/org.openhab.binding.ipp/src/main/java/org/openhab/binding/ipp/internal/handler/IppPrinterHandler.java @@ -77,10 +77,10 @@ public class IppPrinterHandler extends BaseThingHandler implements DiscoveryList String name = (String) config.get(PRINTER_PARAMETER_NAME); try { Object obj = config.get(PRINTER_PARAMETER_URL); - if (obj instanceof URL) { - url = (URL) obj; - } else if (obj instanceof String) { - url = new URL((String) obj); + if (obj instanceof URL newUrl) { + url = newUrl; + } else if (obj instanceof String urlString) { + url = new URL(urlString); } printer = new CupsPrinter(null, url, name); } catch (MalformedURLException e) { diff --git a/bundles/org.openhab.binding.irobot/src/main/java/org/openhab/binding/irobot/internal/IRobotHandlerFactory.java b/bundles/org.openhab.binding.irobot/src/main/java/org/openhab/binding/irobot/internal/IRobotHandlerFactory.java index d55fa758f..36b083f0a 100644 --- a/bundles/org.openhab.binding.irobot/src/main/java/org/openhab/binding/irobot/internal/IRobotHandlerFactory.java +++ b/bundles/org.openhab.binding.irobot/src/main/java/org/openhab/binding/irobot/internal/IRobotHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.irobot.internal; import static org.openhab.binding.irobot.internal.IRobotBindingConstants.THING_TYPE_ROOMBA; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -38,7 +37,7 @@ import org.osgi.service.component.annotations.Component; @NonNullByDefault public class IRobotHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_ROOMBA); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_ROOMBA); @Override public boolean supportsThingType(ThingTypeUID thingTypeUID) { diff --git a/bundles/org.openhab.binding.irobot/src/main/java/org/openhab/binding/irobot/internal/dto/MQTTProtocol.java b/bundles/org.openhab.binding.irobot/src/main/java/org/openhab/binding/irobot/internal/dto/MQTTProtocol.java index 1265af0be..8e4ca5a50 100644 --- a/bundles/org.openhab.binding.irobot/src/main/java/org/openhab/binding/irobot/internal/dto/MQTTProtocol.java +++ b/bundles/org.openhab.binding.irobot/src/main/java/org/openhab/binding/irobot/internal/dto/MQTTProtocol.java @@ -128,7 +128,7 @@ public class MQTTProtocol { } public boolean cycleEnabled(int i) { - return cycle[i].equals("start"); + return "start".equals(cycle[i]); } public void enableCycle(int i, boolean enable) { diff --git a/bundles/org.openhab.binding.irtrans/src/main/java/org/openhab/binding/irtrans/internal/IrCommand.java b/bundles/org.openhab.binding.irtrans/src/main/java/org/openhab/binding/irtrans/internal/IrCommand.java index 47bfed76d..b1497e8aa 100644 --- a/bundles/org.openhab.binding.irtrans/src/main/java/org/openhab/binding/irtrans/internal/IrCommand.java +++ b/bundles/org.openhab.binding.irtrans/src/main/java/org/openhab/binding/irtrans/internal/IrCommand.java @@ -315,7 +315,7 @@ public class IrCommand { * @return the byte buffer in Hex format */ public ByteBuffer toHEXByteBuffer() { - byte hexDigit[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + byte[] hexDigit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; ByteBuffer byteBuffer = toByteBuffer(); byte[] toConvert = new byte[byteBuffer.limit()]; diff --git a/bundles/org.openhab.binding.jablotron/src/main/java/org/openhab/binding/jablotron/internal/discovery/JablotronDiscoveryService.java b/bundles/org.openhab.binding.jablotron/src/main/java/org/openhab/binding/jablotron/internal/discovery/JablotronDiscoveryService.java index 747a3fb8d..751eae40f 100644 --- a/bundles/org.openhab.binding.jablotron/src/main/java/org/openhab/binding/jablotron/internal/discovery/JablotronDiscoveryService.java +++ b/bundles/org.openhab.binding.jablotron/src/main/java/org/openhab/binding/jablotron/internal/discovery/JablotronDiscoveryService.java @@ -65,8 +65,8 @@ public class JablotronDiscoveryService extends AbstractDiscoveryService @Override public void setThingHandler(@Nullable ThingHandler thingHandler) { - if (thingHandler instanceof JablotronBridgeHandler) { - bridgeHandler = (JablotronBridgeHandler) thingHandler; + if (thingHandler instanceof JablotronBridgeHandler bridgeHandler) { + this.bridgeHandler = bridgeHandler; } } diff --git a/bundles/org.openhab.binding.jablotron/src/main/java/org/openhab/binding/jablotron/internal/handler/JablotronBridgeHandler.java b/bundles/org.openhab.binding.jablotron/src/main/java/org/openhab/binding/jablotron/internal/handler/JablotronBridgeHandler.java index 4055e93c8..8b7d4734e 100644 --- a/bundles/org.openhab.binding.jablotron/src/main/java/org/openhab/binding/jablotron/internal/handler/JablotronBridgeHandler.java +++ b/bundles/org.openhab.binding.jablotron/src/main/java/org/openhab/binding/jablotron/internal/handler/JablotronBridgeHandler.java @@ -15,8 +15,8 @@ package org.openhab.binding.jablotron.internal.handler; import static org.openhab.binding.jablotron.JablotronBindingConstants.*; import java.util.Collection; -import java.util.Collections; import java.util.List; +import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -85,7 +85,7 @@ public class JablotronBridgeHandler extends BaseBridgeHandler { @Override public Collection> getServices() { - return Collections.singleton(JablotronDiscoveryService.class); + return Set.of(JablotronDiscoveryService.class); } @Override diff --git a/bundles/org.openhab.binding.jeelink/src/main/java/org/openhab/binding/jeelink/internal/ec3k/Ec3kReadingConverter.java b/bundles/org.openhab.binding.jeelink/src/main/java/org/openhab/binding/jeelink/internal/ec3k/Ec3kReadingConverter.java index ef6575030..0910804fd 100644 --- a/bundles/org.openhab.binding.jeelink/src/main/java/org/openhab/binding/jeelink/internal/ec3k/Ec3kReadingConverter.java +++ b/bundles/org.openhab.binding.jeelink/src/main/java/org/openhab/binding/jeelink/internal/ec3k/Ec3kReadingConverter.java @@ -23,10 +23,11 @@ import org.openhab.binding.jeelink.internal.JeeLinkReadingConverter; * @author Volker Bier - Initial contribution */ public class Ec3kReadingConverter implements JeeLinkReadingConverter { - private static final Pattern LINE_P = Pattern - .compile("OK\\s+22\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)" - + "\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)" - + "\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)"); + private static final Pattern LINE_P = Pattern.compile(""" + OK\\s+22\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\ + \\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\ + \\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\ + """); @Override public Ec3kReading createReading(String inputLine) { diff --git a/bundles/org.openhab.binding.jeelink/src/main/java/org/openhab/binding/jeelink/internal/lacrosse/LgwSensorHandler.java b/bundles/org.openhab.binding.jeelink/src/main/java/org/openhab/binding/jeelink/internal/lacrosse/LgwSensorHandler.java index c6422ed6c..3ad324bd0 100644 --- a/bundles/org.openhab.binding.jeelink/src/main/java/org/openhab/binding/jeelink/internal/lacrosse/LgwSensorHandler.java +++ b/bundles/org.openhab.binding.jeelink/src/main/java/org/openhab/binding/jeelink/internal/lacrosse/LgwSensorHandler.java @@ -59,7 +59,7 @@ public class LgwSensorHandler extends JeeLinkSensorHandler { @Override public ReadingPublisher createPublisher() { - ReadingPublisher publisher = new ReadingPublisher() { + return new ReadingPublisher() { @Override public void publish(LgwReading reading) { if (reading != null && getThing().getStatus() == ThingStatus.ONLINE) { @@ -109,7 +109,5 @@ public class LgwSensorHandler extends JeeLinkSensorHandler { public void dispose() { } }; - - return publisher; } } diff --git a/bundles/org.openhab.binding.jeelink/src/main/java/org/openhab/binding/jeelink/internal/lacrosse/Tx22SensorHandler.java b/bundles/org.openhab.binding.jeelink/src/main/java/org/openhab/binding/jeelink/internal/lacrosse/Tx22SensorHandler.java index 642ed2ace..3260b4c20 100644 --- a/bundles/org.openhab.binding.jeelink/src/main/java/org/openhab/binding/jeelink/internal/lacrosse/Tx22SensorHandler.java +++ b/bundles/org.openhab.binding.jeelink/src/main/java/org/openhab/binding/jeelink/internal/lacrosse/Tx22SensorHandler.java @@ -48,7 +48,7 @@ public class Tx22SensorHandler extends JeeLinkSensorHandler { @Override public ReadingPublisher createPublisher() { - ReadingPublisher publisher = new ReadingPublisher() { + return new ReadingPublisher() { @Override public void publish(Tx22Reading reading) { if (reading != null && getThing().getStatus() == ThingStatus.ONLINE) { @@ -90,7 +90,5 @@ public class Tx22SensorHandler extends JeeLinkSensorHandler { public void dispose() { } }; - - return publisher; } } diff --git a/bundles/org.openhab.binding.jeelink/src/main/java/org/openhab/binding/jeelink/internal/pca301/Pca301SensorHandler.java b/bundles/org.openhab.binding.jeelink/src/main/java/org/openhab/binding/jeelink/internal/pca301/Pca301SensorHandler.java index 9419f68be..a386c3a49 100644 --- a/bundles/org.openhab.binding.jeelink/src/main/java/org/openhab/binding/jeelink/internal/pca301/Pca301SensorHandler.java +++ b/bundles/org.openhab.binding.jeelink/src/main/java/org/openhab/binding/jeelink/internal/pca301/Pca301SensorHandler.java @@ -83,8 +83,8 @@ public class Pca301SensorHandler extends JeeLinkSensorHandler { command); if (channelUid.getIdWithoutGroup().equals(SWITCHING_STATE_CHANNEL)) { - if (command instanceof OnOffType) { - sendCommandRetry((OnOffType) command); + if (command instanceof OnOffType onOffCommand) { + sendCommandRetry(onOffCommand); } else { sendCommand(command); } diff --git a/bundles/org.openhab.binding.jeelink/src/main/java/org/openhab/binding/jeelink/internal/revolt/RevoltReadingConverter.java b/bundles/org.openhab.binding.jeelink/src/main/java/org/openhab/binding/jeelink/internal/revolt/RevoltReadingConverter.java index 3bc804980..501c22c08 100644 --- a/bundles/org.openhab.binding.jeelink/src/main/java/org/openhab/binding/jeelink/internal/revolt/RevoltReadingConverter.java +++ b/bundles/org.openhab.binding.jeelink/src/main/java/org/openhab/binding/jeelink/internal/revolt/RevoltReadingConverter.java @@ -23,9 +23,10 @@ import org.openhab.binding.jeelink.internal.JeeLinkReadingConverter; * @author Volker Bier - Initial contribution */ public class RevoltReadingConverter implements JeeLinkReadingConverter { - private static final Pattern LINE_P = Pattern - .compile("r([0-9A-Za-z]{4})([0-9A-Za-z]{2})([0-9A-Za-z]{4})([0-9A-Za-z]{2})([0-9A-Za-z]{4})" - + "([0-9A-Za-z]{2})([0-9A-Za-z]{4})[0-9A-Za-z][0-9A-Za-z]"); + private static final Pattern LINE_P = Pattern.compile(""" + r([0-9A-Za-z]{4})([0-9A-Za-z]{2})([0-9A-Za-z]{4})([0-9A-Za-z]{2})([0-9A-Za-z]{4})\ + ([0-9A-Za-z]{2})([0-9A-Za-z]{4})[0-9A-Za-z][0-9A-Za-z]\ + """); @Override public RevoltReading createReading(String inputLine) { diff --git a/bundles/org.openhab.binding.jeelink/src/main/java/org/openhab/binding/jeelink/internal/revolt/RevoltSensorHandler.java b/bundles/org.openhab.binding.jeelink/src/main/java/org/openhab/binding/jeelink/internal/revolt/RevoltSensorHandler.java index b2cbc3fde..a1055d9c0 100644 --- a/bundles/org.openhab.binding.jeelink/src/main/java/org/openhab/binding/jeelink/internal/revolt/RevoltSensorHandler.java +++ b/bundles/org.openhab.binding.jeelink/src/main/java/org/openhab/binding/jeelink/internal/revolt/RevoltSensorHandler.java @@ -46,7 +46,7 @@ public class RevoltSensorHandler extends JeeLinkSensorHandler { @Override public ReadingPublisher createPublisher() { - ReadingPublisher publisher = new ReadingPublisher() { + return new ReadingPublisher() { @Override public void publish(RevoltReading reading) { if (reading != null && getThing().getStatus() == ThingStatus.ONLINE) { @@ -73,7 +73,5 @@ public class RevoltSensorHandler extends JeeLinkSensorHandler { public void dispose() { } }; - - return publisher; } } diff --git a/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/JellyfinHandlerFactory.java b/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/JellyfinHandlerFactory.java index d1d5dd1f4..bd3c6dca0 100644 --- a/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/JellyfinHandlerFactory.java +++ b/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/JellyfinHandlerFactory.java @@ -81,8 +81,7 @@ public class JellyfinHandlerFactory extends BaseThingHandlerFactory { @Override protected synchronized void removeHandler(ThingHandler thingHandler) { - if (thingHandler instanceof JellyfinServerHandler) { - var serverHandler = (JellyfinServerHandler) thingHandler; + if (thingHandler instanceof JellyfinServerHandler serverHandler) { unregisterAuthenticationServlet(serverHandler); } super.removeHandler(thingHandler); diff --git a/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/discovery/JellyfinClientDiscoveryService.java b/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/discovery/JellyfinClientDiscoveryService.java index 1b4c877a7..a658afef5 100644 --- a/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/discovery/JellyfinClientDiscoveryService.java +++ b/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/discovery/JellyfinClientDiscoveryService.java @@ -105,8 +105,8 @@ public class JellyfinClientDiscoveryService extends AbstractDiscoveryService imp @Override public void setThingHandler(ThingHandler thingHandler) { - if (thingHandler instanceof JellyfinServerHandler) { - bridgeHandler = (JellyfinServerHandler) thingHandler; + if (thingHandler instanceof JellyfinServerHandler bridgeHandler) { + this.bridgeHandler = bridgeHandler; } } @@ -115,6 +115,7 @@ public class JellyfinClientDiscoveryService extends AbstractDiscoveryService imp return null; } + @Override public void activate() { activate(new HashMap<>()); } diff --git a/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/discovery/JellyfinServerDiscoveryService.java b/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/discovery/JellyfinServerDiscoveryService.java index b265781a4..1221bd32a 100644 --- a/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/discovery/JellyfinServerDiscoveryService.java +++ b/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/discovery/JellyfinServerDiscoveryService.java @@ -107,7 +107,7 @@ public class JellyfinServerDiscoveryService extends AbstractDiscoveryService { new SystemApi(jellyClient).getPublicSystemInfo(asyncResponse); try { var publicSystemInfo = asyncResponse.awaitContent(); - discoverServer(uri.getHost(), uri.getPort(), uri.getScheme().equalsIgnoreCase("https"), uri.getPath(), + discoverServer(uri.getHost(), uri.getPort(), "https".equalsIgnoreCase(uri.getScheme()), uri.getPath(), publicSystemInfo); } catch (SyncCallback.SyncCallbackError | ApiClientException e) { logger.warn("Discovery error: {}", e.getMessage()); diff --git a/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/handler/JellyfinClientHandler.java b/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/handler/JellyfinClientHandler.java index 21b876d0f..50172b34d 100644 --- a/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/handler/JellyfinClientHandler.java +++ b/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/handler/JellyfinClientHandler.java @@ -243,9 +243,8 @@ public class JellyfinClientHandler extends BaseThingHandler { private UUID parseItemUUID(Command command) throws NumberFormatException { var itemId = command.toFullString().replace("-", ""); - UUID itemUUID = new UUID(new BigInteger(itemId.substring(0, 16), 16).longValue(), + return new UUID(new BigInteger(itemId.substring(0, 16), 16).longValue(), new BigInteger(itemId.substring(16), 16).longValue()); - return itemUUID; } @Override @@ -385,9 +384,9 @@ public class JellyfinClientHandler extends BaseThingHandler { var typeMatcher = typeSearchPattern.matcher(terms); boolean searchByTypeEnabled = typeMatcher.matches(); var type = searchByTypeEnabled ? typeMatcher.group("type") : ""; - boolean movieSearchEnabled = !searchByTypeEnabled || type.equals("movie"); - boolean seriesSearchEnabled = !searchByTypeEnabled || type.equals("series"); - boolean episodeSearchEnabled = !searchByTypeEnabled || type.equals("episode"); + boolean movieSearchEnabled = !searchByTypeEnabled || "movie".equals(type); + boolean seriesSearchEnabled = !searchByTypeEnabled || "series".equals(type); + boolean episodeSearchEnabled = !searchByTypeEnabled || "episode".equals(type); var searchTerms = searchByTypeEnabled ? typeMatcher.group("terms") : terms; runItemSearchByType(searchTerms, playCommand, movieSearchEnabled, seriesSearchEnabled, episodeSearchEnabled); } diff --git a/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/handler/JellyfinServerHandler.java b/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/handler/JellyfinServerHandler.java index 989a8987e..75cb3025e 100644 --- a/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/handler/JellyfinServerHandler.java +++ b/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/handler/JellyfinServerHandler.java @@ -15,9 +15,9 @@ package org.openhab.binding.jellyfin.internal.handler; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.Collection; -import java.util.Collections; import java.util.List; import java.util.Objects; +import java.util.Set; import java.util.UUID; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -118,7 +118,7 @@ public class JellyfinServerHandler extends BaseBridgeHandler { @Override public Collection> getServices() { - return Collections.singleton(JellyfinClientDiscoveryService.class); + return Set.of(JellyfinClientDiscoveryService.class); } public String getServerUrl() { @@ -225,8 +225,8 @@ public class JellyfinServerHandler extends BaseBridgeHandler { logger.warn("Api error: {}", e.getMessage()); var cause = e.getCause(); boolean unauthenticated = false; - if (cause instanceof InvalidStatusException) { - var status = ((InvalidStatusException) cause).getStatus(); + if (cause instanceof InvalidStatusException invalidStatusException) { + var status = invalidStatusException.getStatus(); if (status == 401) { unauthenticated = true; } @@ -398,8 +398,8 @@ public class JellyfinServerHandler extends BaseBridgeHandler { if (handler == null) { return; } - if (handler instanceof JellyfinClientHandler) { - updateClientState((JellyfinClientHandler) handler, sessions); + if (handler instanceof JellyfinClientHandler clientHandler) { + updateClientState(clientHandler, sessions); } else { logger.warn("Found unknown thing-handler instance: {}", handler); } diff --git a/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/util/SyncResponse.java b/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/util/SyncResponse.java index b2db6b86d..4a7a7b8a0 100644 --- a/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/util/SyncResponse.java +++ b/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/util/SyncResponse.java @@ -28,8 +28,8 @@ public class SyncResponse extends SyncCallback> { return awaitResult(); } catch (SyncCallbackError e) { var cause = e.getCause(); - if (cause instanceof ApiClientException) { - throw (ApiClientException) cause; + if (cause instanceof ApiClientException apiClientException) { + throw apiClientException; } throw e; } diff --git a/bundles/org.openhab.binding.juicenet/src/main/java/org/openhab/binding/juicenet/internal/discovery/JuiceNetDiscoveryService.java b/bundles/org.openhab.binding.juicenet/src/main/java/org/openhab/binding/juicenet/internal/discovery/JuiceNetDiscoveryService.java index 9f190e654..182302412 100644 --- a/bundles/org.openhab.binding.juicenet/src/main/java/org/openhab/binding/juicenet/internal/discovery/JuiceNetDiscoveryService.java +++ b/bundles/org.openhab.binding.juicenet/src/main/java/org/openhab/binding/juicenet/internal/discovery/JuiceNetDiscoveryService.java @@ -68,8 +68,7 @@ public class JuiceNetDiscoveryService extends AbstractDiscoveryService @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof JuiceNetBridgeHandler) { - JuiceNetBridgeHandler bridgeHandler = (JuiceNetBridgeHandler) handler; + if (handler instanceof JuiceNetBridgeHandler bridgeHandler) { bridgeHandler.setDiscoveryService(this); this.bridgeHandler = bridgeHandler; } else { diff --git a/bundles/org.openhab.binding.juicenet/src/main/java/org/openhab/binding/juicenet/internal/handler/JuiceNetBridgeHandler.java b/bundles/org.openhab.binding.juicenet/src/main/java/org/openhab/binding/juicenet/internal/handler/JuiceNetBridgeHandler.java index c0b75fca4..30c918fda 100644 --- a/bundles/org.openhab.binding.juicenet/src/main/java/org/openhab/binding/juicenet/internal/handler/JuiceNetBridgeHandler.java +++ b/bundles/org.openhab.binding.juicenet/src/main/java/org/openhab/binding/juicenet/internal/handler/JuiceNetBridgeHandler.java @@ -15,9 +15,9 @@ package org.openhab.binding.juicenet.internal.handler; import static org.openhab.binding.juicenet.internal.JuiceNetBindingConstants.*; import java.util.Collection; -import java.util.Collections; import java.util.List; import java.util.Objects; +import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -116,7 +116,7 @@ public class JuiceNetBridgeHandler extends BaseBridgeHandler { */ @Override public Collection> getServices() { - return Collections.singleton(JuiceNetDiscoveryService.class); + return Set.of(JuiceNetDiscoveryService.class); } public void handleApiException(Exception e) { diff --git a/bundles/org.openhab.binding.kaleidescape/src/main/java/org/openhab/binding/kaleidescape/internal/discovery/KaleidescapeDiscoveryService.java b/bundles/org.openhab.binding.kaleidescape/src/main/java/org/openhab/binding/kaleidescape/internal/discovery/KaleidescapeDiscoveryService.java index efd18427b..97883a2b0 100644 --- a/bundles/org.openhab.binding.kaleidescape/src/main/java/org/openhab/binding/kaleidescape/internal/discovery/KaleidescapeDiscoveryService.java +++ b/bundles/org.openhab.binding.kaleidescape/src/main/java/org/openhab/binding/kaleidescape/internal/discovery/KaleidescapeDiscoveryService.java @@ -281,7 +281,6 @@ public class KaleidescapeDiscoveryService extends AbstractDiscoveryService { input.close(); writer.close(); output.close(); - socket.close(); } catch (IOException e) { logger.debug("isKaleidescapeDevice() IOException: {}", e.getMessage()); } diff --git a/bundles/org.openhab.binding.kaleidescape/src/main/java/org/openhab/binding/kaleidescape/internal/handler/KaleidescapeHandler.java b/bundles/org.openhab.binding.kaleidescape/src/main/java/org/openhab/binding/kaleidescape/internal/handler/KaleidescapeHandler.java index 7ba530ac7..98ba12d86 100644 --- a/bundles/org.openhab.binding.kaleidescape/src/main/java/org/openhab/binding/kaleidescape/internal/handler/KaleidescapeHandler.java +++ b/bundles/org.openhab.binding.kaleidescape/src/main/java/org/openhab/binding/kaleidescape/internal/handler/KaleidescapeHandler.java @@ -16,9 +16,9 @@ import static org.openhab.binding.kaleidescape.internal.KaleidescapeBindingConst import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ScheduledFuture; @@ -189,7 +189,7 @@ public class KaleidescapeHandler extends BaseThingHandler implements Kaleidescap @Override public Collection> getServices() { - return Collections.singletonList(KaleidescapeThingActions.class); + return List.of(KaleidescapeThingActions.class); } public void handleRawCommand(@Nullable String command) { @@ -229,8 +229,8 @@ public class KaleidescapeHandler extends BaseThingHandler implements Kaleidescap } break; case VOLUME: - if (command instanceof PercentType) { - this.volume = (int) ((PercentType) command).doubleValue(); + if (command instanceof PercentType percentCommand) { + this.volume = (int) percentCommand.doubleValue(); logger.debug("Got volume command {}", this.volume); connector.sendCommand(SEND_EVENT_VOLUME_LEVEL_EQ + this.volume); } diff --git a/bundles/org.openhab.binding.keba/src/main/java/org/openhab/binding/keba/internal/KebaHandlerFactory.java b/bundles/org.openhab.binding.keba/src/main/java/org/openhab/binding/keba/internal/KebaHandlerFactory.java index 643f0d50c..452b4916e 100644 --- a/bundles/org.openhab.binding.keba/src/main/java/org/openhab/binding/keba/internal/KebaHandlerFactory.java +++ b/bundles/org.openhab.binding.keba/src/main/java/org/openhab/binding/keba/internal/KebaHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.keba.internal; import static org.openhab.binding.keba.internal.KebaBindingConstants.THING_TYPE_KECONTACTP20; -import java.util.Collections; import java.util.Set; import org.openhab.binding.keba.internal.handler.KeContactHandler; @@ -35,7 +34,7 @@ import org.osgi.service.component.annotations.Component; @Component(service = ThingHandlerFactory.class, configurationPid = "binding.keba") public class KebaHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_KECONTACTP20); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_KECONTACTP20); private final KeContactTransceiver transceiver = new KeContactTransceiver(); diff --git a/bundles/org.openhab.binding.keba/src/main/java/org/openhab/binding/keba/internal/handler/KeContactHandler.java b/bundles/org.openhab.binding.keba/src/main/java/org/openhab/binding/keba/internal/handler/KeContactHandler.java index f67adc89b..a16abfd30 100644 --- a/bundles/org.openhab.binding.keba/src/main/java/org/openhab/binding/keba/internal/handler/KeContactHandler.java +++ b/bundles/org.openhab.binding.keba/src/main/java/org/openhab/binding/keba/internal/handler/KeContactHandler.java @@ -342,7 +342,7 @@ public class KeContactHandler extends BaseThingHandler { updateState(CHANNEL_MAX_SYSTEM_CURRENT, newState); if (maxSystemCurrent != 0) { if (maxSystemCurrent < maxPresetCurrent) { - transceiver.send("curr " + String.valueOf(maxSystemCurrent), this); + transceiver.send("curr " + maxSystemCurrent, this); updateState(CHANNEL_MAX_PRESET_CURRENT, new QuantityType(maxSystemCurrent / 1000.0, Units.AMPERE)); updateState(CHANNEL_MAX_PRESET_CURRENT_RANGE, new QuantityType( @@ -528,12 +528,10 @@ public class KeContactHandler extends BaseThingHandler { } else { switch (channelUID.getId()) { case CHANNEL_MAX_PRESET_CURRENT: { - if (command instanceof QuantityType) { - QuantityType value = ((QuantityType) command).toUnit("mA"); + if (command instanceof QuantityType quantityCommand) { + QuantityType value = quantityCommand.toUnit("mA"); - transceiver.send( - "curr " + String.valueOf(Math.min(Math.max(6000, value.intValue()), maxSystemCurrent)), - this); + transceiver.send("curr " + Math.min(Math.max(6000, value.intValue()), maxSystemCurrent), this); } break; } @@ -549,13 +547,13 @@ public class KeContactHandler extends BaseThingHandler { newValue = maxSystemCurrent; } else if (command == OnOffType.OFF) { newValue = 6000; - } else if (command instanceof QuantityType) { - QuantityType value = ((QuantityType) command).toUnit("%"); + } else if (command instanceof QuantityType quantityCommand) { + QuantityType value = quantityCommand.toUnit("%"); newValue = Math.round(6000 + (maxSystemCurrent - 6000) * value.doubleValue() / 100.0); } else { return; } - transceiver.send("curr " + String.valueOf(newValue), this); + transceiver.send("curr " + newValue, this); } break; } @@ -596,11 +594,10 @@ public class KeContactHandler extends BaseThingHandler { break; } case CHANNEL_SETENERGY: { - if (command instanceof QuantityType) { - QuantityType value = ((QuantityType) command).toUnit(Units.WATT_HOUR); + if (command instanceof QuantityType quantityCommand) { + QuantityType value = quantityCommand.toUnit(Units.WATT_HOUR); transceiver.send( - "setenergy " + String.valueOf( - Math.min(Math.max(0, Math.round(value.doubleValue() * 10.0)), 999999999)), + "setenergy " + Math.min(Math.max(0, Math.round(value.doubleValue() * 10.0)), 999999999), this); } break; diff --git a/bundles/org.openhab.binding.keba/src/main/java/org/openhab/binding/keba/internal/handler/KeContactTransceiver.java b/bundles/org.openhab.binding.keba/src/main/java/org/openhab/binding/keba/internal/handler/KeContactTransceiver.java index 4a3eb1e00..4b9826b36 100644 --- a/bundles/org.openhab.binding.keba/src/main/java/org/openhab/binding/keba/internal/handler/KeContactTransceiver.java +++ b/bundles/org.openhab.binding.keba/src/main/java/org/openhab/binding/keba/internal/handler/KeContactTransceiver.java @@ -405,7 +405,7 @@ public class KeContactTransceiver { private void establishConnection(KeContactHandler handler) { String ipAddress = handler.getIPAddress(); if (handler.getThing().getStatusInfo().getStatusDetail() != ThingStatusDetail.CONFIGURATION_ERROR - && !ipAddress.equals("")) { + && !"".equals(ipAddress)) { logger.debug("Establishing the connection to the KEBA KeContact '{}'", handler.getThing().getUID()); DatagramChannel datagramChannel = null; diff --git a/bundles/org.openhab.binding.km200/src/main/java/org/openhab/binding/km200/internal/KM200Device.java b/bundles/org.openhab.binding.km200/src/main/java/org/openhab/binding/km200/internal/KM200Device.java index 408816dbc..ff9f3568f 100644 --- a/bundles/org.openhab.binding.km200/src/main/java/org/openhab/binding/km200/internal/KM200Device.java +++ b/bundles/org.openhab.binding.km200/src/main/java/org/openhab/binding/km200/internal/KM200Device.java @@ -332,7 +332,7 @@ public class KM200Device { String decodedData = null; JsonObject nodeRoot = null; logger.debug("{}: trying to query information.", service); - byte[] recData = deviceCommunicator.getDataFromService(service.toString()); + byte[] recData = deviceCommunicator.getDataFromService(service); try { if (recData == null) { logger.debug("Communication to {} is not possible!", service); @@ -361,7 +361,7 @@ public class KM200Device { logger.warn("{}: SERVICE NOT AVAILABLE", service); return null; } else { - logger.debug("{}: trying to parse {}", service, decodedData.toString()); + logger.debug("{}: trying to parse {}", service, decodedData); nodeRoot = (JsonObject) JsonParser.parseString(decodedData); } } else { diff --git a/bundles/org.openhab.binding.km200/src/main/java/org/openhab/binding/km200/internal/handler/KM200DataHandler.java b/bundles/org.openhab.binding.km200/src/main/java/org/openhab/binding/km200/internal/handler/KM200DataHandler.java index 8a8de8367..511a92d53 100644 --- a/bundles/org.openhab.binding.km200/src/main/java/org/openhab/binding/km200/internal/handler/KM200DataHandler.java +++ b/bundles/org.openhab.binding.km200/src/main/java/org/openhab/binding/km200/internal/handler/KM200DataHandler.java @@ -150,7 +150,7 @@ public class KM200DataHandler { } switch (type) { case DATA_TYPE_STRING_VALUE: /* Check whether the type is a single value containing a string value */ - logger.debug("parseJSONData type string value: {} Type: {}", nodeRoot, itemType.toString()); + logger.debug("parseJSONData type string value: {} Type: {}", nodeRoot, itemType); String sVal = nodeRoot.get("value").getAsString(); object.setValue(sVal); /* Switch Binding */ diff --git a/bundles/org.openhab.binding.km200/src/main/java/org/openhab/binding/km200/internal/handler/KM200GatewayHandler.java b/bundles/org.openhab.binding.km200/src/main/java/org/openhab/binding/km200/internal/handler/KM200GatewayHandler.java index 1f2da882e..90129b072 100644 --- a/bundles/org.openhab.binding.km200/src/main/java/org/openhab/binding/km200/internal/handler/KM200GatewayHandler.java +++ b/bundles/org.openhab.binding.km200/src/main/java/org/openhab/binding/km200/internal/handler/KM200GatewayHandler.java @@ -73,7 +73,7 @@ public class KM200GatewayHandler extends BaseBridgeHandler { private final Logger logger = LoggerFactory.getLogger(KM200GatewayHandler.class); - public static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_KMDEVICE); + public static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_KMDEVICE); private final Map sendMap = Collections.synchronizedMap(new LinkedHashMap<>()); diff --git a/bundles/org.openhab.binding.knx/src/main/java/org/openhab/binding/knx/internal/dpt/ValueDecoder.java b/bundles/org.openhab.binding.knx/src/main/java/org/openhab/binding/knx/internal/dpt/ValueDecoder.java index 6364aeba3..a54490ca3 100644 --- a/bundles/org.openhab.binding.knx/src/main/java/org/openhab/binding/knx/internal/dpt/ValueDecoder.java +++ b/bundles/org.openhab.binding.knx/src/main/java/org/openhab/binding/knx/internal/dpt/ValueDecoder.java @@ -215,11 +215,7 @@ public class ValueDecoder { try { date = new SimpleDateFormat(TIME_DAY_FORMAT, Locale.US).parse(value); } catch (ParseException pe) { - try { - date = new SimpleDateFormat(TIME_FORMAT, Locale.US).parse(value); - } catch (ParseException pe2) { - throw pe2; - } + date = new SimpleDateFormat(TIME_FORMAT, Locale.US).parse(value); } return DateTimeType.valueOf(new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(date)); } diff --git a/bundles/org.openhab.binding.knx/src/main/java/org/openhab/binding/knx/internal/handler/DeviceThingHandler.java b/bundles/org.openhab.binding.knx/src/main/java/org/openhab/binding/knx/internal/handler/DeviceThingHandler.java index 2b6402529..0f684320c 100644 --- a/bundles/org.openhab.binding.knx/src/main/java/org/openhab/binding/knx/internal/handler/DeviceThingHandler.java +++ b/bundles/org.openhab.binding.knx/src/main/java/org/openhab/binding/knx/internal/handler/DeviceThingHandler.java @@ -414,9 +414,10 @@ public class DeviceThingHandler extends BaseThingHandler implements GroupAddress if (oldFuture != null) { oldFuture.cancel(true); } - if (value instanceof IncreaseDecreaseType type) { - channelFutures.put(channelUID, scheduler.scheduleWithFixedDelay( - () -> postCommand(channelUID, type), 0, frequency, TimeUnit.MILLISECONDS)); + if (value instanceof IncreaseDecreaseType increaseDecreaseCommand) { + channelFutures.put(channelUID, + scheduler.scheduleWithFixedDelay(() -> postCommand(channelUID, increaseDecreaseCommand), + 0, frequency, TimeUnit.MILLISECONDS)); } } else { if (value instanceof Command command) { diff --git a/bundles/org.openhab.binding.kodi/src/main/java/org/openhab/binding/kodi/internal/KodiAudioSink.java b/bundles/org.openhab.binding.kodi/src/main/java/org/openhab/binding/kodi/internal/KodiAudioSink.java index 996926275..46a758923 100644 --- a/bundles/org.openhab.binding.kodi/src/main/java/org/openhab/binding/kodi/internal/KodiAudioSink.java +++ b/bundles/org.openhab.binding.kodi/src/main/java/org/openhab/binding/kodi/internal/KodiAudioSink.java @@ -75,10 +75,10 @@ public class KodiAudioSink extends AudioSinkSync { public @NonNull CompletableFuture<@Nullable Void> processAndComplete(@Nullable AudioStream audioStream) { // we override this method to intercept URLAudioStream and handle it asynchronously. We won't wait for it to // play through the end as it can be very long - if (audioStream instanceof URLAudioStream) { + if (audioStream instanceof URLAudioStream stream) { // Asynchronous handling for URLAudioStream. Id it is an external URL, the speaker can access it itself and // play it. There will be no volume restoration or call to dispose / complete, but there is no need to. - String url = ((URLAudioStream) audioStream).getURL(); + String url = stream.getURL(); AudioFormat format = audioStream.getFormat(); logger.trace("Processing audioStream URL {} of format {}.", url, format); handler.playURI(new StringType(url)); diff --git a/bundles/org.openhab.binding.kodi/src/main/java/org/openhab/binding/kodi/internal/KodiBindingConstants.java b/bundles/org.openhab.binding.kodi/src/main/java/org/openhab/binding/kodi/internal/KodiBindingConstants.java index a029e5d7c..624a719fb 100644 --- a/bundles/org.openhab.binding.kodi/src/main/java/org/openhab/binding/kodi/internal/KodiBindingConstants.java +++ b/bundles/org.openhab.binding.kodi/src/main/java/org/openhab/binding/kodi/internal/KodiBindingConstants.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.kodi.internal; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -34,7 +33,7 @@ public class KodiBindingConstants { // List of all Thing Type UIDs public static final ThingTypeUID THING_TYPE_KODI = new ThingTypeUID(BINDING_ID, "kodi"); - public static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_KODI); + public static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_KODI); // List of thing parameters names public static final String HOST_PARAMETER = "ipAddress"; diff --git a/bundles/org.openhab.binding.kodi/src/main/java/org/openhab/binding/kodi/internal/discovery/KodiUpnpDiscoveryParticipant.java b/bundles/org.openhab.binding.kodi/src/main/java/org/openhab/binding/kodi/internal/discovery/KodiUpnpDiscoveryParticipant.java index 297e60e30..45291bc66 100644 --- a/bundles/org.openhab.binding.kodi/src/main/java/org/openhab/binding/kodi/internal/discovery/KodiUpnpDiscoveryParticipant.java +++ b/bundles/org.openhab.binding.kodi/src/main/java/org/openhab/binding/kodi/internal/discovery/KodiUpnpDiscoveryParticipant.java @@ -82,10 +82,8 @@ public class KodiUpnpDiscoveryParticipant implements UpnpDiscoveryParticipant { Map properties = new HashMap<>(); properties.put(HOST_PARAMETER, device.getIdentity().getDescriptorURL().getHost()); - DiscoveryResult result = DiscoveryResultBuilder.create(thingUid).withLabel(label) - .withProperties(properties).withRepresentationProperty(HOST_PARAMETER).build(); - - return result; + return DiscoveryResultBuilder.create(thingUid).withLabel(label).withProperties(properties) + .withRepresentationProperty(HOST_PARAMETER).build(); } } return null; diff --git a/bundles/org.openhab.binding.kodi/src/main/java/org/openhab/binding/kodi/internal/handler/KodiHandler.java b/bundles/org.openhab.binding.kodi/src/main/java/org/openhab/binding/kodi/internal/handler/KodiHandler.java index 494904127..be5f908ce 100644 --- a/bundles/org.openhab.binding.kodi/src/main/java/org/openhab/binding/kodi/internal/handler/KodiHandler.java +++ b/bundles/org.openhab.binding.kodi/src/main/java/org/openhab/binding/kodi/internal/handler/KodiHandler.java @@ -134,8 +134,8 @@ public class KodiHandler extends BaseThingHandler implements KodiEventListener { private int getIntConfigParameter(String key, int defaultValue) { Object obj = this.getConfig().get(key); - if (obj instanceof Number) { - return ((Number) obj).intValue(); + if (obj instanceof Number numberValue) { + return numberValue.intValue(); } else if (obj instanceof String) { return Integer.parseInt(obj.toString()); } @@ -160,8 +160,8 @@ public class KodiHandler extends BaseThingHandler implements KodiEventListener { } break; case CHANNEL_VOLUME: - if (command instanceof PercentType) { - connection.setVolume(((PercentType) command).intValue()); + if (command instanceof PercentType percentCommand) { + connection.setVolume(percentCommand.intValue()); } else if (command.equals(IncreaseDecreaseType.INCREASE)) { connection.increaseVolume(); } else if (command.equals(IncreaseDecreaseType.DECREASE)) { @@ -213,8 +213,8 @@ public class KodiHandler extends BaseThingHandler implements KodiEventListener { } break; case CHANNEL_PLAYNOTIFICATION: - if (command instanceof StringType) { - playNotificationSoundURI((StringType) command, true); + if (command instanceof StringType stringCommand) { + playNotificationSoundURI(stringCommand, true); updateState(CHANNEL_PLAYNOTIFICATION, UnDefType.UNDEF); } else if (command.equals(RefreshType.REFRESH)) { updateState(CHANNEL_PLAYNOTIFICATION, UnDefType.UNDEF); @@ -307,14 +307,14 @@ public class KodiHandler extends BaseThingHandler implements KodiEventListener { case CHANNEL_AUDIO_CODEC: break; case CHANNEL_AUDIO_INDEX: - if (command instanceof DecimalType) { - connection.setAudioStream(((DecimalType) command).intValue()); + if (command instanceof DecimalType decimalCommand) { + connection.setAudioStream(decimalCommand.intValue()); } break; case CHANNEL_VIDEO_CODEC: case CHANNEL_VIDEO_INDEX: - if (command instanceof DecimalType) { - connection.setVideoStream(((DecimalType) command).intValue()); + if (command instanceof DecimalType decimalCommand) { + connection.setVideoStream(decimalCommand.intValue()); } break; case CHANNEL_SUBTITLE_ENABLED: @@ -325,13 +325,13 @@ public class KodiHandler extends BaseThingHandler implements KodiEventListener { } break; case CHANNEL_SUBTITLE_INDEX: - if (command instanceof DecimalType) { - connection.setSubtitle(((DecimalType) command).intValue()); + if (command instanceof DecimalType decimalCommand) { + connection.setSubtitle(decimalCommand.intValue()); } break; case CHANNEL_CURRENTTIME: - if (command instanceof QuantityType) { - connection.setTime(((QuantityType) command).intValue()); + if (command instanceof QuantityType quantityCommand) { + connection.setTime(quantityCommand.intValue()); } break; case CHANNEL_CURRENTTIMEPERCENTAGE: diff --git a/bundles/org.openhab.binding.kodi/src/main/java/org/openhab/binding/kodi/internal/protocol/KodiConnection.java b/bundles/org.openhab.binding.kodi/src/main/java/org/openhab/binding/kodi/internal/protocol/KodiConnection.java index 12fdff2b8..e92930512 100644 --- a/bundles/org.openhab.binding.kodi/src/main/java/org/openhab/binding/kodi/internal/protocol/KodiConnection.java +++ b/bundles/org.openhab.binding.kodi/src/main/java/org/openhab/binding/kodi/internal/protocol/KodiConnection.java @@ -184,9 +184,7 @@ public class KodiConnection implements KodiClientSocketEventListener { private synchronized JsonArray getPlaylistsInternal() { String method = "Playlist.GetPlaylists"; String hash = hostname + '#' + method; - JsonElement response = REQUEST_CACHE.putIfAbsentAndGet(hash, () -> { - return socket.callMethod(method); - }); + JsonElement response = REQUEST_CACHE.putIfAbsentAndGet(hash, () -> socket.callMethod(method)); if (response instanceof JsonArray) { return response.getAsJsonArray(); diff --git a/bundles/org.openhab.binding.konnected/src/main/java/org/openhab/binding/konnected/internal/KonnectedHandlerFactory.java b/bundles/org.openhab.binding.konnected/src/main/java/org/openhab/binding/konnected/internal/KonnectedHandlerFactory.java index 4e71401b2..27657adc4 100644 --- a/bundles/org.openhab.binding.konnected/src/main/java/org/openhab/binding/konnected/internal/KonnectedHandlerFactory.java +++ b/bundles/org.openhab.binding.konnected/src/main/java/org/openhab/binding/konnected/internal/KonnectedHandlerFactory.java @@ -82,7 +82,6 @@ public class KonnectedHandlerFactory extends BaseThingHandlerFactory { @Override protected @Nullable ThingHandler createHandler(Thing thing) { - KonnectedHandler thingHandler = new KonnectedHandler(thing, getCallbackUrl()); if (servlet != null) { logger.debug("Adding thinghandler for thing {} to webhook.", thing.getUID().getId()); diff --git a/bundles/org.openhab.binding.konnected/src/main/java/org/openhab/binding/konnected/internal/discovery/KonnectedUPnPServer.java b/bundles/org.openhab.binding.konnected/src/main/java/org/openhab/binding/konnected/internal/discovery/KonnectedUPnPServer.java index 666155497..52249bf27 100644 --- a/bundles/org.openhab.binding.konnected/src/main/java/org/openhab/binding/konnected/internal/discovery/KonnectedUPnPServer.java +++ b/bundles/org.openhab.binding.konnected/src/main/java/org/openhab/binding/konnected/internal/discovery/KonnectedUPnPServer.java @@ -62,9 +62,8 @@ public class KonnectedUPnPServer implements UpnpDiscoveryParticipant { Map properties = new HashMap<>(); properties.put(BASE_URL, device.getDetails().getBaseURL()); properties.put(MAC_ADDR, device.getDetails().getSerialNumber()); - DiscoveryResult result = DiscoveryResultBuilder.create(uid).withProperties(properties) + return DiscoveryResultBuilder.create(uid).withProperties(properties) .withLabel(device.getDetails().getFriendlyName()).withRepresentationProperty(MAC_ADDR).build(); - return result; } else { return null; } diff --git a/bundles/org.openhab.binding.konnected/src/main/java/org/openhab/binding/konnected/internal/handler/KonnectedHandler.java b/bundles/org.openhab.binding.konnected/src/main/java/org/openhab/binding/konnected/internal/handler/KonnectedHandler.java index 1816c0c33..271b696b2 100644 --- a/bundles/org.openhab.binding.konnected/src/main/java/org/openhab/binding/konnected/internal/handler/KonnectedHandler.java +++ b/bundles/org.openhab.binding.konnected/src/main/java/org/openhab/binding/konnected/internal/handler/KonnectedHandler.java @@ -88,11 +88,11 @@ public class KonnectedHandler extends BaseThingHandler { String zone = zoneConfig.zone; logger.debug("The channelUID is: {} and the zone is : {}", channelUID.getAsString(), zone); // if the command is OnOfftype - if (command instanceof OnOffType) { + if (command instanceof OnOffType onOffCommand) { if (channelType.contains(CHANNEL_SWITCH)) { logger.debug("A command was sent to a sensor type so we are ignoring the command"); } else { - sendActuatorCommand((OnOffType) command, zone, channelUID); + sendActuatorCommand(onOffCommand, zone, channelUID); } } else if (command instanceof RefreshType) { // check to see if handler has been initialized before attempting to get state of pin, else wait one minute @@ -227,7 +227,7 @@ public class KonnectedHandler extends BaseThingHandler { // https://github.com/eclipse/smarthome/issues/3484 has been implemented in the framework String[] cfg = configurationParameter.getKey().split("_"); if ("controller".equals(cfg[0])) { - if (cfg[1].equals("softreset") && value instanceof Boolean && (Boolean) value) { + if ("softreset".equals(cfg[1]) && value instanceof Boolean bool && bool) { scheduler.execute(() -> { try { http.doGet(baseUrl + "/settings?restart=true", null, retryCount); @@ -235,7 +235,7 @@ public class KonnectedHandler extends BaseThingHandler { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); } }); - } else if (cfg[1].equals("removewifi") && value instanceof Boolean && (Boolean) value) { + } else if ("removewifi".equals(cfg[1]) && value instanceof Boolean bool && bool) { scheduler.execute(() -> { try { http.doGet(baseUrl + "/settings?restore=true", null, retryCount); @@ -243,7 +243,7 @@ public class KonnectedHandler extends BaseThingHandler { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); } }); - } else if (cfg[1].equals("sendConfig") && value instanceof Boolean && (Boolean) value) { + } else if ("sendConfig".equals(cfg[1]) && value instanceof Boolean bool && bool) { scheduler.execute(() -> { try { String response = updateKonnectedModule(); @@ -444,7 +444,7 @@ public class KonnectedHandler extends BaseThingHandler { private void getSwitchState(String zone, ChannelUID channelId) { Channel channel = getThing().getChannel(channelId.getId()); - if (!(channel == null)) { + if (channel != null) { logger.debug("getasstring: {} getID: {} getGroupId: {} toString:{}", channelId.getAsString(), channelId.getId(), channelId.getGroupId(), channelId); KonnectedModuleGson payload = new KonnectedModuleGson(); diff --git a/bundles/org.openhab.binding.kostalinverter/src/main/java/org/openhab/binding/kostalinverter/internal/secondgeneration/SecondGenerationConfigurationHandler.java b/bundles/org.openhab.binding.kostalinverter/src/main/java/org/openhab/binding/kostalinverter/internal/secondgeneration/SecondGenerationConfigurationHandler.java index 75661c325..df282ea0e 100644 --- a/bundles/org.openhab.binding.kostalinverter/src/main/java/org/openhab/binding/kostalinverter/internal/secondgeneration/SecondGenerationConfigurationHandler.java +++ b/bundles/org.openhab.binding.kostalinverter/src/main/java/org/openhab/binding/kostalinverter/internal/secondgeneration/SecondGenerationConfigurationHandler.java @@ -59,8 +59,7 @@ public class SecondGenerationConfigurationHandler { sessionId = extractSessionId(getAuthenticateResponseJsonObject); - JsonObject authenticateJsonObject = JsonParser.parseString(getAuthenticateResponse.toString()) - .getAsJsonObject(); + JsonObject authenticateJsonObject = JsonParser.parseString(getAuthenticateResponse).getAsJsonObject(); salt = authenticateJsonObject.get("salt").getAsString(); String saltedPassword = new StringBuilder(password).append(salt).toString(); @@ -120,9 +119,7 @@ public class SecondGenerationConfigurationHandler { int codeStartPosition = jsonResponse.indexOf("code"); transformStringBuilder.insert(codeStartPosition + 11, ']'); - String transformJsonObject = transformStringBuilder.toString(); - - return transformJsonObject; + return transformStringBuilder.toString(); } // Method extractSessionId extracts sessionId from JsonObject diff --git a/bundles/org.openhab.binding.kostalinverter/src/main/java/org/openhab/binding/kostalinverter/internal/secondgeneration/SecondGenerationHandler.java b/bundles/org.openhab.binding.kostalinverter/src/main/java/org/openhab/binding/kostalinverter/internal/secondgeneration/SecondGenerationHandler.java index 58d96ad40..7dfc60619 100644 --- a/bundles/org.openhab.binding.kostalinverter/src/main/java/org/openhab/binding/kostalinverter/internal/secondgeneration/SecondGenerationHandler.java +++ b/bundles/org.openhab.binding.kostalinverter/src/main/java/org/openhab/binding/kostalinverter/internal/secondgeneration/SecondGenerationHandler.java @@ -103,10 +103,10 @@ public class SecondGenerationHandler extends BaseThingHandler { valueConfiguration); break; case SecondGenerationBindingConstants.CHANNEL_SMARTBATTERYCONTROLSET: - if (command.toString().equals("ON")) { + if ("ON".equals(command.toString())) { valueConfiguration = "true"; } - if (command.toString().equals("OFF")) { + if ("OFF".equals(command.toString())) { valueConfiguration = "false"; } dxsEntriesConf = "33556484"; @@ -288,10 +288,10 @@ public class SecondGenerationHandler extends BaseThingHandler { String channel = cConfig.id; String value = channelPostsConfigurable[channelValuesCounterConfigurable]; int dxsEntriesCheckCounter = 3; - if (cConfig.dxsEntries.equals("33556484")) { + if ("33556484".equals(cConfig.dxsEntries)) { dxsEntriesCheckCounter = 1; } - if (cConfig.dxsEntries.equals("33556482")) { + if ("33556482".equals(cConfig.dxsEntries)) { dxsEntriesCheckCounter = 2; } switch (dxsEntriesCheckCounter) { diff --git a/bundles/org.openhab.binding.kvv/src/main/java/org/openhab/binding/kvv/internal/KVVBridgeHandler.java b/bundles/org.openhab.binding.kvv/src/main/java/org/openhab/binding/kvv/internal/KVVBridgeHandler.java index bfb070f3a..3644e89eb 100644 --- a/bundles/org.openhab.binding.kvv/src/main/java/org/openhab/binding/kvv/internal/KVVBridgeHandler.java +++ b/bundles/org.openhab.binding.kvv/src/main/java/org/openhab/binding/kvv/internal/KVVBridgeHandler.java @@ -76,7 +76,6 @@ public class KVVBridgeHandler extends BaseBridgeHandler { * @return the latest {@link DepartureResult}. */ public synchronized @Nullable DepartureResult queryKVV(final KVVStopConfig stopConfig) { - // is there an up-to-date value in the cache? final DepartureResult cr = this.cache.get(stopConfig.stopId); if (cr != null) { diff --git a/bundles/org.openhab.binding.lametrictime/src/3rdparty/java/org/openhab/binding/lametrictime/internal/api/authentication/HttpAuthenticationFeature.java b/bundles/org.openhab.binding.lametrictime/src/3rdparty/java/org/openhab/binding/lametrictime/internal/api/authentication/HttpAuthenticationFeature.java index bc40e815b..c758e1eea 100644 --- a/bundles/org.openhab.binding.lametrictime/src/3rdparty/java/org/openhab/binding/lametrictime/internal/api/authentication/HttpAuthenticationFeature.java +++ b/bundles/org.openhab.binding.lametrictime/src/3rdparty/java/org/openhab/binding/lametrictime/internal/api/authentication/HttpAuthenticationFeature.java @@ -139,7 +139,7 @@ public class HttpAuthenticationFeature implements Feature { /** * Feature authentication mode. */ - static enum Mode { + enum Mode { /** * Basic preemptive. **/ diff --git a/bundles/org.openhab.binding.lametrictime/src/3rdparty/java/org/openhab/binding/lametrictime/internal/api/authentication/HttpAuthenticationFilter.java b/bundles/org.openhab.binding.lametrictime/src/3rdparty/java/org/openhab/binding/lametrictime/internal/api/authentication/HttpAuthenticationFilter.java index f457624d8..68cb7884c 100644 --- a/bundles/org.openhab.binding.lametrictime/src/3rdparty/java/org/openhab/binding/lametrictime/internal/api/authentication/HttpAuthenticationFilter.java +++ b/bundles/org.openhab.binding.lametrictime/src/3rdparty/java/org/openhab/binding/lametrictime/internal/api/authentication/HttpAuthenticationFilter.java @@ -305,13 +305,13 @@ class HttpAuthenticationFilter implements ClientRequestFilter, ClientResponseFil } String userName = (String) request.getProperty(usernameKey); - if (userName != null && !userName.equals("")) { + if (userName != null && !"".equals(userName)) { byte[] pwdBytes; Object password = request.getProperty(passwordKey); - if (password instanceof byte[]) { - pwdBytes = ((byte[]) password); - } else if (password instanceof String) { - pwdBytes = ((String) password).getBytes(CHARACTER_SET); + if (password instanceof byte[] bytes) { + pwdBytes = bytes; + } else if (password instanceof String stringValue) { + pwdBytes = stringValue.getBytes(CHARACTER_SET); } else { throw new RequestAuthenticationException("Passwort invalid."); } diff --git a/bundles/org.openhab.binding.lametrictime/src/main/java/org/openhab/binding/lametrictime/internal/discovery/LaMetricTimeDiscoveryParticipant.java b/bundles/org.openhab.binding.lametrictime/src/main/java/org/openhab/binding/lametrictime/internal/discovery/LaMetricTimeDiscoveryParticipant.java index a961051dc..61e3d965e 100644 --- a/bundles/org.openhab.binding.lametrictime/src/main/java/org/openhab/binding/lametrictime/internal/discovery/LaMetricTimeDiscoveryParticipant.java +++ b/bundles/org.openhab.binding.lametrictime/src/main/java/org/openhab/binding/lametrictime/internal/discovery/LaMetricTimeDiscoveryParticipant.java @@ -15,7 +15,6 @@ package org.openhab.binding.lametrictime.internal.discovery; import static org.openhab.binding.lametrictime.internal.LaMetricTimeBindingConstants.THING_TYPE_DEVICE; import static org.openhab.binding.lametrictime.internal.config.LaMetricTimeConfiguration.HOST; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -46,7 +45,7 @@ public class LaMetricTimeDiscoveryParticipant implements UpnpDiscoveryParticipan @Override public Set getSupportedThingTypeUIDs() { - return Collections.singleton(THING_TYPE_DEVICE); + return Set.of(THING_TYPE_DEVICE); } @Override diff --git a/bundles/org.openhab.binding.lametrictime/src/main/java/org/openhab/binding/lametrictime/internal/handler/LaMetricTimeHandler.java b/bundles/org.openhab.binding.lametrictime/src/main/java/org/openhab/binding/lametrictime/internal/handler/LaMetricTimeHandler.java index 26690b652..e116ff690 100644 --- a/bundles/org.openhab.binding.lametrictime/src/main/java/org/openhab/binding/lametrictime/internal/handler/LaMetricTimeHandler.java +++ b/bundles/org.openhab.binding.lametrictime/src/main/java/org/openhab/binding/lametrictime/internal/handler/LaMetricTimeHandler.java @@ -214,9 +214,8 @@ public class LaMetricTimeHandler extends ConfigStatusBridgeHandler { Audio audio = clock.getLocalApi().getAudio(); if (command instanceof RefreshType) { updateState(channelUID, new PercentType(audio.getVolume())); - } else if (command instanceof PercentType) { + } else if (command instanceof PercentType percentTypeCommand) { try { - PercentType percentTypeCommand = (PercentType) command; int volume = percentTypeCommand.intValue(); if (volume >= 0 && volume != audio.getVolume()) { audio.setVolume(volume); @@ -256,8 +255,7 @@ public class LaMetricTimeHandler extends ConfigStatusBridgeHandler { private void updateBluetoothValue(ChannelUID channelUID, Command command, Bluetooth bluetooth) { try { - if (command instanceof OnOffType && channelUID.getId().equals(CHANNEL_BLUETOOTH_ACTIVE)) { - OnOffType onOffCommand = (OnOffType) command; + if (command instanceof OnOffType onOffCommand && channelUID.getId().equals(CHANNEL_BLUETOOTH_ACTIVE)) { if (onOffCommand == OnOffType.ON && !bluetooth.isActive()) { bluetooth.setActive(true); clock.getLocalApi().updateBluetooth(bluetooth); @@ -296,8 +294,8 @@ public class LaMetricTimeHandler extends ConfigStatusBridgeHandler { private void updateDisplayValue(ChannelUID channelUID, Command command) { try { if (channelUID.getId().equals(CHANNEL_DISPLAY_BRIGHTNESS)) { - if (command instanceof PercentType) { - int brightness = ((PercentType) command).intValue(); + if (command instanceof PercentType percentCommand) { + int brightness = percentCommand.intValue(); logger.debug("Set Brightness to {}.", brightness); Display newDisplay = clock.setBrightness(brightness); updateState(CHANNEL_DISPLAY_BRIGHTNESS_MODE, new StringType(newDisplay.getBrightnessMode())); diff --git a/bundles/org.openhab.binding.lametrictime/src/main/java/org/openhab/binding/lametrictime/internal/handler/RadioAppHandler.java b/bundles/org.openhab.binding.lametrictime/src/main/java/org/openhab/binding/lametrictime/internal/handler/RadioAppHandler.java index a34b5980e..3d5c288a1 100644 --- a/bundles/org.openhab.binding.lametrictime/src/main/java/org/openhab/binding/lametrictime/internal/handler/RadioAppHandler.java +++ b/bundles/org.openhab.binding.lametrictime/src/main/java/org/openhab/binding/lametrictime/internal/handler/RadioAppHandler.java @@ -64,8 +64,8 @@ public class RadioAppHandler extends AbstractLaMetricTimeAppHandler { } private void handleControl(final Command command) throws ApplicationActionException { - if (command instanceof PlayPauseType) { - switch ((PlayPauseType) command) { + if (command instanceof PlayPauseType playCommand) { + switch (playCommand) { case PLAY: play(); return; @@ -78,8 +78,8 @@ public class RadioAppHandler extends AbstractLaMetricTimeAppHandler { } } - if (command instanceof NextPreviousType) { - switch ((NextPreviousType) command) { + if (command instanceof NextPreviousType nextCommand) { + switch (nextCommand) { case NEXT: next(); return; diff --git a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/DimmerOutputProfile.java b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/DimmerOutputProfile.java index 203ba4d17..5f866a872 100644 --- a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/DimmerOutputProfile.java +++ b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/DimmerOutputProfile.java @@ -52,8 +52,8 @@ public class DimmerOutputProfile implements StateProfile { Optional outputs12 = getConfig(profileContext, "controlOutputs12"); ramp.ifPresent(b -> { - if (b instanceof BigDecimal) { - rampMs = (int) (((BigDecimal) b).doubleValue() * 1000); + if (b instanceof BigDecimal decimalValue) { + rampMs = (int) (decimalValue.doubleValue() * 1000); } else { logger.warn("Could not parse 'ramp', unexpected type, should be float: {}", ramp); } @@ -86,10 +86,10 @@ public class DimmerOutputProfile implements StateProfile { logger.warn("Unsupported 'ramp' setting. Will be forced to 250ms: {}", rampMs); } BigDecimal value; - if (command instanceof DecimalType) { - value = ((DecimalType) command).toBigDecimal(); - } else if (command instanceof OnOffType) { - value = ((OnOffType) command) == OnOffType.ON ? BigDecimal.valueOf(100) : BigDecimal.ZERO; + if (command instanceof DecimalType decimalCommand) { + value = decimalCommand.toBigDecimal(); + } else if (command instanceof OnOffType onOffCommand) { + value = onOffCommand == OnOffType.ON ? BigDecimal.valueOf(100) : BigDecimal.ZERO; } else { logger.warn("Unsupported type: {}", command.toFullString()); return; diff --git a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/LcnModuleDiscoveryService.java b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/LcnModuleDiscoveryService.java index 4fc011c1f..87402fbcd 100644 --- a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/LcnModuleDiscoveryService.java +++ b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/LcnModuleDiscoveryService.java @@ -82,8 +82,8 @@ public class LcnModuleDiscoveryService extends AbstractDiscoveryService @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof PckGatewayHandler) { - this.bridgeHandler = (PckGatewayHandler) handler; + if (handler instanceof PckGatewayHandler gatewayHandler) { + this.bridgeHandler = gatewayHandler; } } diff --git a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/LcnModuleHandler.java b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/LcnModuleHandler.java index 5cf844888..5d105cd60 100644 --- a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/LcnModuleHandler.java +++ b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/LcnModuleHandler.java @@ -14,12 +14,12 @@ package org.openhab.binding.lcn.internal; 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.NoSuchElementException; import java.util.Optional; +import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; @@ -117,8 +117,8 @@ public class LcnModuleHandler extends BaseThingHandler { Object invertUpDown = channel.getConfiguration().get("invertUpDown"); // Initialize value converters - if (unitObject instanceof String) { - switch ((String) unitObject) { + if (unitObject instanceof String stringValue) { + switch (stringValue) { case "power": case "energy": converters.put(channel.getUID(), new S0Converter(parameterObject)); @@ -207,35 +207,33 @@ public class LcnModuleHandler extends BaseThingHandler { if (command instanceof RefreshType) { number.ifPresent(n -> subHandler.handleRefresh(channelGroup, n)); subHandler.handleRefresh(channelUid.getIdWithoutGroup()); - } else if (command instanceof OnOffType) { - subHandler.handleCommandOnOff((OnOffType) command, channelGroup, number.get()); - } else if (command instanceof DimmerOutputCommand) { - subHandler.handleCommandDimmerOutput((DimmerOutputCommand) command, number.get()); - } else if (command instanceof PercentType && number.isPresent()) { - subHandler.handleCommandPercent((PercentType) command, channelGroup, number.get()); - } else if (command instanceof HSBType) { - subHandler.handleCommandHsb((HSBType) command, channelUid.getIdWithoutGroup()); - } else if (command instanceof PercentType) { - subHandler.handleCommandPercent((PercentType) command, channelGroup, channelUid.getIdWithoutGroup()); - } else if (command instanceof StringType) { - subHandler.handleCommandString((StringType) command, number.orElse(0)); - } else if (command instanceof DecimalType) { - DecimalType decimalType = (DecimalType) command; - DecimalType nativeValue = getConverter(channelUid).onCommandFromItem(decimalType.doubleValue()); + } else if (command instanceof OnOffType onOffCommand) { + subHandler.handleCommandOnOff(onOffCommand, channelGroup, number.get()); + } else if (command instanceof DimmerOutputCommand outputCommand) { + subHandler.handleCommandDimmerOutput(outputCommand, number.get()); + } else if (command instanceof PercentType percentCommand && number.isPresent()) { + subHandler.handleCommandPercent(percentCommand, channelGroup, number.get()); + } else if (command instanceof HSBType hsbCommand) { + subHandler.handleCommandHsb(hsbCommand, channelUid.getIdWithoutGroup()); + } else if (command instanceof PercentType percentCommand) { + subHandler.handleCommandPercent(percentCommand, channelGroup, channelUid.getIdWithoutGroup()); + } else if (command instanceof StringType stringCommand) { + subHandler.handleCommandString(stringCommand, number.orElse(0)); + } else if (command instanceof DecimalType decimalCommand) { + DecimalType nativeValue = getConverter(channelUid).onCommandFromItem(decimalCommand.doubleValue()); subHandler.handleCommandDecimal(nativeValue, channelGroup, number.get()); - } else if (command instanceof QuantityType) { - QuantityType quantityType = (QuantityType) command; - DecimalType nativeValue = getConverter(channelUid).onCommandFromItem(quantityType); + } else if (command instanceof QuantityType quantityCommand) { + DecimalType nativeValue = getConverter(channelUid).onCommandFromItem(quantityCommand); subHandler.handleCommandDecimal(nativeValue, channelGroup, number.get()); - } else if (command instanceof UpDownType) { + } else if (command instanceof UpDownType upDownCommand) { Channel channel = thing.getChannel(channelUid); if (channel != null) { Object invertConfig = channel.getConfiguration().get("invertUpDown"); - boolean invertUpDown = invertConfig instanceof Boolean && (boolean) invertConfig; - subHandler.handleCommandUpDown((UpDownType) command, channelGroup, number.get(), invertUpDown); + boolean invertUpDown = invertConfig instanceof Boolean bool && bool; + subHandler.handleCommandUpDown(upDownCommand, channelGroup, number.get(), invertUpDown); } - } else if (command instanceof StopMoveType) { - subHandler.handleCommandStopMove((StopMoveType) command, channelGroup, number.get()); + } else if (command instanceof StopMoveType stopMoveCommand) { + subHandler.handleCommandStopMove(stopMoveCommand, channelGroup, number.get()); } else { throw new LcnException("Unsupported command type"); } @@ -397,7 +395,7 @@ public class LcnModuleHandler extends BaseThingHandler { @Override public Collection> getServices() { - return Collections.singleton(LcnModuleActions.class); + return Set.of(LcnModuleActions.class); } /** diff --git a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/LcnProfileFactory.java b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/LcnProfileFactory.java index d519c18d6..e455b3efa 100644 --- a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/LcnProfileFactory.java +++ b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/LcnProfileFactory.java @@ -13,8 +13,8 @@ package org.openhab.binding.lcn.internal; import java.util.Collection; -import java.util.Collections; import java.util.Locale; +import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; @@ -46,12 +46,12 @@ public class LcnProfileFactory implements ProfileFactory, ProfileTypeProvider { @Override public Collection getSupportedProfileTypeUIDs() { - return Collections.singleton(DimmerOutputProfile.UID); + return Set.of(DimmerOutputProfile.UID); } @Override public Collection getProfileTypes(@Nullable Locale locale) { - return Collections.singleton(ProfileTypeBuilder.newState(DimmerOutputProfile.UID, "Dimmer Output (%)") + return Set.of(ProfileTypeBuilder.newState(DimmerOutputProfile.UID, "Dimmer Output (%)") .withSupportedItemTypes(CoreItemFactory.DIMMER, CoreItemFactory.COLOR) .withSupportedChannelTypeUIDs( new ChannelTypeUID(LcnBindingConstants.BINDING_ID, LcnChannelGroup.OUTPUT.name().toLowerCase())) diff --git a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/PckGatewayHandler.java b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/PckGatewayHandler.java index 38529c556..7c5f25aaf 100644 --- a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/PckGatewayHandler.java +++ b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/PckGatewayHandler.java @@ -13,8 +13,8 @@ package org.openhab.binding.lcn.internal; import java.util.Collection; -import java.util.Collections; import java.util.Optional; +import java.util.Set; import java.util.function.Consumer; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -114,7 +114,7 @@ public class PckGatewayHandler extends BaseBridgeHandler { @Override public Collection> getServices() { - return Collections.singleton(LcnModuleDiscoveryService.class); + return Set.of(LcnModuleDiscoveryService.class); } @Override diff --git a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/common/LcnDefs.java b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/common/LcnDefs.java index 7f711ba9e..75a623f52 100644 --- a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/common/LcnDefs.java +++ b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/common/LcnDefs.java @@ -86,14 +86,14 @@ public final class LcnDefs { OFF, ON, BLINK, - FLICKER; + FLICKER } /** Possible states for LCN logic-operations. */ public enum LogicOpStatus { NOT, OR, // Note: Actually not correct since AND won't be OR also - AND; + AND } /** Time units used for several LCN commands. */ @@ -101,7 +101,7 @@ public final class LcnDefs { SECONDS, MINUTES, HOURS, - DAYS; + DAYS } /** Relay-state modifiers used in LCN commands. */ diff --git a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/connection/Connection.java b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/connection/Connection.java index 6ffc5264f..58657cd36 100644 --- a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/connection/Connection.java +++ b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/connection/Connection.java @@ -251,7 +251,7 @@ public class Connection { writeInProgress = false; - if (sendQueue.size() > 0) { + if (!sendQueue.isEmpty()) { /** * This could lead to stack overflows, since the CompletionHandler may run in * the same Thread as triggerWriteToSocket() is invoked (see diff --git a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/converter/S0Converter.java b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/converter/S0Converter.java index 82770678a..7964694ee 100644 --- a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/converter/S0Converter.java +++ b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/converter/S0Converter.java @@ -36,8 +36,8 @@ public class S0Converter extends ValueConverter { if (parameter == null) { pulsesPerKwh = 1000; logger.debug("Pulses per kWh not set. Assuming 1000 imp./kWh."); - } else if (parameter instanceof BigDecimal) { - pulsesPerKwh = ((BigDecimal) parameter).doubleValue(); + } else if (parameter instanceof BigDecimal decimalValue) { + pulsesPerKwh = decimalValue.doubleValue(); } else { logger.warn("Could not parse 'pulses', unexpected type, should be float or integer: {}", parameter); } diff --git a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/converter/ValueConverter.java b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/converter/ValueConverter.java index f51090698..925fff97f 100644 --- a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/converter/ValueConverter.java +++ b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/converter/ValueConverter.java @@ -103,10 +103,10 @@ public class ValueConverter extends Converter { */ @Override public State onStateUpdateFromHandler(State state) throws LcnException { - if (state instanceof DecimalType) { + if (state instanceof DecimalType decimalValue) { Unit localUnit = unit; if (localUnit != null) { - return QuantityType.valueOf(toHumanReadable(((DecimalType) state).longValue()), localUnit); + return QuantityType.valueOf(toHumanReadable(decimalValue.longValue()), localUnit); } return state; diff --git a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/AbstractLcnModuleRollershutterRelaySubHandler.java b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/AbstractLcnModuleRollershutterRelaySubHandler.java index 2c75e2a82..d11855045 100644 --- a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/AbstractLcnModuleRollershutterRelaySubHandler.java +++ b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/AbstractLcnModuleRollershutterRelaySubHandler.java @@ -13,7 +13,7 @@ package org.openhab.binding.lcn.internal.subhandler; import java.util.Collection; -import java.util.Collections; +import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -90,6 +90,6 @@ public abstract class AbstractLcnModuleRollershutterRelaySubHandler extends Abst @Override public Collection getPckStatusMessagePatterns() { - return Collections.singleton(PATTERN); + return Set.of(PATTERN); } } diff --git a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleBinarySensorSubHandler.java b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleBinarySensorSubHandler.java index 9b9adb724..37e0b4672 100644 --- a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleBinarySensorSubHandler.java +++ b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleBinarySensorSubHandler.java @@ -13,7 +13,7 @@ package org.openhab.binding.lcn.internal.subhandler; import java.util.Collection; -import java.util.Collections; +import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.IntStream; @@ -57,6 +57,6 @@ public class LcnModuleBinarySensorSubHandler extends AbstractLcnModuleSubHandler @Override public Collection getPckStatusMessagePatterns() { - return Collections.singleton(PATTERN); + return Set.of(PATTERN); } } diff --git a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleHostCommandSubHandler.java b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleHostCommandSubHandler.java index 5737f5625..02f796e26 100644 --- a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleHostCommandSubHandler.java +++ b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleHostCommandSubHandler.java @@ -13,7 +13,7 @@ package org.openhab.binding.lcn.internal.subhandler; import java.util.Collection; -import java.util.Collections; +import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -73,6 +73,6 @@ public class LcnModuleHostCommandSubHandler extends AbstractLcnModuleSubHandler @Override public Collection getPckStatusMessagePatterns() { - return Collections.singleton(SEND_KEY_PATTERN); + return Set.of(SEND_KEY_PATTERN); } } diff --git a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleKeyLockTableSubHandler.java b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleKeyLockTableSubHandler.java index a73581c87..db831f7c4 100644 --- a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleKeyLockTableSubHandler.java +++ b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleKeyLockTableSubHandler.java @@ -14,7 +14,7 @@ package org.openhab.binding.lcn.internal.subhandler; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; +import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.IntStream; @@ -90,6 +90,6 @@ public class LcnModuleKeyLockTableSubHandler extends AbstractLcnModuleSubHandler @Override public Collection getPckStatusMessagePatterns() { - return Collections.singleton(PATTERN); + return Set.of(PATTERN); } } diff --git a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleMetaFirmwareSubHandler.java b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleMetaFirmwareSubHandler.java index 52273db6f..8e7ad6f8a 100644 --- a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleMetaFirmwareSubHandler.java +++ b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleMetaFirmwareSubHandler.java @@ -13,7 +13,7 @@ package org.openhab.binding.lcn.internal.subhandler; import java.util.Collection; -import java.util.Collections; +import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -52,6 +52,6 @@ public class LcnModuleMetaFirmwareSubHandler extends AbstractLcnModuleSubHandler @Override public Collection getPckStatusMessagePatterns() { - return Collections.singleton(PATTERN); + return Set.of(PATTERN); } } diff --git a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleRelaySubHandler.java b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleRelaySubHandler.java index 0d8e3ab28..a948ea748 100644 --- a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleRelaySubHandler.java +++ b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleRelaySubHandler.java @@ -13,7 +13,7 @@ package org.openhab.binding.lcn.internal.subhandler; import java.util.Collection; -import java.util.Collections; +import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.IntStream; @@ -81,6 +81,6 @@ public class LcnModuleRelaySubHandler extends AbstractLcnModuleSubHandler { @Override public Collection getPckStatusMessagePatterns() { - return Collections.singleton(PATTERN); + return Set.of(PATTERN); } } diff --git a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleS0CounterSubHandler.java b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleS0CounterSubHandler.java index 26885e334..c42bcea0b 100644 --- a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleS0CounterSubHandler.java +++ b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleS0CounterSubHandler.java @@ -13,7 +13,7 @@ package org.openhab.binding.lcn.internal.subhandler; import java.util.Collection; -import java.util.Collections; +import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -53,6 +53,6 @@ public class LcnModuleS0CounterSubHandler extends AbstractLcnModuleVariableSubHa @Override public Collection getPckStatusMessagePatterns() { - return Collections.singleton(PATTERN); + return Set.of(PATTERN); } } diff --git a/bundles/org.openhab.binding.leapmotion/src/main/java/org/openhab/binding/leapmotion/internal/LeapMotionColorProfile.java b/bundles/org.openhab.binding.leapmotion/src/main/java/org/openhab/binding/leapmotion/internal/LeapMotionColorProfile.java index 53e499d69..114d9ab1f 100644 --- a/bundles/org.openhab.binding.leapmotion/src/main/java/org/openhab/binding/leapmotion/internal/LeapMotionColorProfile.java +++ b/bundles/org.openhab.binding.leapmotion/src/main/java/org/openhab/binding/leapmotion/internal/LeapMotionColorProfile.java @@ -48,8 +48,8 @@ public class LeapMotionColorProfile implements TriggerProfile { @Override public void onStateUpdateFromItem(State state) { - if (state instanceof HSBType) { - lastState = (HSBType) state; + if (state instanceof HSBType hsbState) { + lastState = hsbState; } else { PercentType currentBrightness = state.as(PercentType.class); if (currentBrightness != null) { @@ -94,7 +94,6 @@ public class LeapMotionColorProfile implements TriggerProfile { int hue = clockwise ? (color.getHue().toBigDecimal().intValue() - 20 + 360) % 360 : (color.getHue().toBigDecimal().intValue() + 20 + 360) % 360; logger.debug("New hue value: {}", hue); - HSBType newState = new HSBType(new DecimalType(hue), color.getSaturation(), color.getBrightness()); - return newState; + return new HSBType(new DecimalType(hue), color.getSaturation(), color.getBrightness()); } } diff --git a/bundles/org.openhab.binding.leapmotion/src/main/java/org/openhab/binding/leapmotion/internal/LeapMotionHandlerFactory.java b/bundles/org.openhab.binding.leapmotion/src/main/java/org/openhab/binding/leapmotion/internal/LeapMotionHandlerFactory.java index 1559f1817..b520a81a3 100644 --- a/bundles/org.openhab.binding.leapmotion/src/main/java/org/openhab/binding/leapmotion/internal/LeapMotionHandlerFactory.java +++ b/bundles/org.openhab.binding.leapmotion/src/main/java/org/openhab/binding/leapmotion/internal/LeapMotionHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.leapmotion.internal; import static org.openhab.binding.leapmotion.internal.LeapMotionBindingConstants.THING_TYPE_CONTROLLER; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -36,7 +35,7 @@ import org.osgi.service.component.annotations.Component; @NonNullByDefault public class LeapMotionHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_CONTROLLER); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_CONTROLLER); @Override public boolean supportsThingType(ThingTypeUID thingTypeUID) { diff --git a/bundles/org.openhab.binding.leapmotion/src/main/java/org/openhab/binding/leapmotion/internal/discovery/LeapMotionDiscoveryService.java b/bundles/org.openhab.binding.leapmotion/src/main/java/org/openhab/binding/leapmotion/internal/discovery/LeapMotionDiscoveryService.java index acc62d12b..9c47695c4 100644 --- a/bundles/org.openhab.binding.leapmotion/src/main/java/org/openhab/binding/leapmotion/internal/discovery/LeapMotionDiscoveryService.java +++ b/bundles/org.openhab.binding.leapmotion/src/main/java/org/openhab/binding/leapmotion/internal/discovery/LeapMotionDiscoveryService.java @@ -12,8 +12,8 @@ */ package org.openhab.binding.leapmotion.internal.discovery; -import java.util.Collections; import java.util.Map; +import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; @@ -42,7 +42,7 @@ public class LeapMotionDiscoveryService extends AbstractDiscoveryService { private @NonNullByDefault({}) Listener listener; public LeapMotionDiscoveryService() throws IllegalArgumentException { - super(Collections.singleton(LeapMotionBindingConstants.THING_TYPE_CONTROLLER), 10, true); + super(Set.of(LeapMotionBindingConstants.THING_TYPE_CONTROLLER), 10, true); } @Override diff --git a/bundles/org.openhab.binding.lghombot/src/main/java/org/openhab/binding/lghombot/internal/LGHomBotBindingConstants.java b/bundles/org.openhab.binding.lghombot/src/main/java/org/openhab/binding/lghombot/internal/LGHomBotBindingConstants.java index db4b5ef2e..c0dd2f13f 100644 --- a/bundles/org.openhab.binding.lghombot/src/main/java/org/openhab/binding/lghombot/internal/LGHomBotBindingConstants.java +++ b/bundles/org.openhab.binding.lghombot/src/main/java/org/openhab/binding/lghombot/internal/LGHomBotBindingConstants.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.lghombot.internal; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -32,7 +31,7 @@ public final class LGHomBotBindingConstants { // List of all Thing Type UIDs public static final ThingTypeUID THING_TYPE_LGHOMBOT = new ThingTypeUID(BINDING_ID, "LGHomBot"); - public static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_LGHOMBOT); + public static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_LGHOMBOT); // List of all Channel ids static final String CHANNEL_STATE = "state"; diff --git a/bundles/org.openhab.binding.lghombot/src/main/java/org/openhab/binding/lghombot/internal/LGHomBotHandlerFactory.java b/bundles/org.openhab.binding.lghombot/src/main/java/org/openhab/binding/lghombot/internal/LGHomBotHandlerFactory.java index 94d537aa0..0765b9b61 100644 --- a/bundles/org.openhab.binding.lghombot/src/main/java/org/openhab/binding/lghombot/internal/LGHomBotHandlerFactory.java +++ b/bundles/org.openhab.binding.lghombot/src/main/java/org/openhab/binding/lghombot/internal/LGHomBotHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.lghombot.internal; import static org.openhab.binding.lghombot.internal.LGHomBotBindingConstants.THING_TYPE_LGHOMBOT; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -36,7 +35,7 @@ import org.osgi.service.component.annotations.Component; @Component(configurationPid = "binding.lghombot", service = ThingHandlerFactory.class) public class LGHomBotHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_LGHOMBOT); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_LGHOMBOT); @Override public boolean supportsThingType(ThingTypeUID thingTypeUID) { diff --git a/bundles/org.openhab.binding.lghombot/src/main/java/org/openhab/binding/lghombot/internal/discovery/LGHomBotDiscovery.java b/bundles/org.openhab.binding.lghombot/src/main/java/org/openhab/binding/lghombot/internal/discovery/LGHomBotDiscovery.java index a41ae5470..59ab1bef0 100644 --- a/bundles/org.openhab.binding.lghombot/src/main/java/org/openhab/binding/lghombot/internal/discovery/LGHomBotDiscovery.java +++ b/bundles/org.openhab.binding.lghombot/src/main/java/org/openhab/binding/lghombot/internal/discovery/LGHomBotDiscovery.java @@ -236,12 +236,12 @@ public class LGHomBotDiscovery extends AbstractDiscoveryService { if (idx > 0) { String name = msg.substring(0, idx); - if (name.equalsIgnoreCase("JSON_NICKNAME")) { - nickName = msg.substring(idx + 1).trim().replaceAll("\"", ""); - } else if (name.equalsIgnoreCase("JSON_VERSION")) { - fwVersion = msg.substring(idx + 1).trim().replaceAll("\"", ""); - } else if (name.equalsIgnoreCase("LGSRV_VERSION")) { - srvVersion = msg.substring(idx + 1).trim().replaceAll("\"", ""); + if ("JSON_NICKNAME".equalsIgnoreCase(name)) { + nickName = msg.substring(idx + 1).trim().replace("\"", ""); + } else if ("JSON_VERSION".equalsIgnoreCase(name)) { + fwVersion = msg.substring(idx + 1).trim().replace("\"", ""); + } else if ("LGSRV_VERSION".equalsIgnoreCase(name)) { + srvVersion = msg.substring(idx + 1).trim().replace("\"", ""); } } diff --git a/bundles/org.openhab.binding.lgtvserial/src/main/java/org/openhab/binding/lgtvserial/internal/protocol/serial/responses/OnOffResponse.java b/bundles/org.openhab.binding.lgtvserial/src/main/java/org/openhab/binding/lgtvserial/internal/protocol/serial/responses/OnOffResponse.java index 5f41b0177..ea8905f9e 100644 --- a/bundles/org.openhab.binding.lgtvserial/src/main/java/org/openhab/binding/lgtvserial/internal/protocol/serial/responses/OnOffResponse.java +++ b/bundles/org.openhab.binding.lgtvserial/src/main/java/org/openhab/binding/lgtvserial/internal/protocol/serial/responses/OnOffResponse.java @@ -36,7 +36,7 @@ public class OnOffResponse implements LGSerialResponse { this.success = success; if (success) { - state = data.equals("01") ? OnOffType.ON : OnOffType.OFF; + state = "01".equals(data) ? OnOffType.ON : OnOffType.OFF; } else { state = new StringType(data); } diff --git a/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/LGWebOSBindingConstants.java b/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/LGWebOSBindingConstants.java index c033ff8b7..cfbfc954e 100644 --- a/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/LGWebOSBindingConstants.java +++ b/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/LGWebOSBindingConstants.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.lgwebos.internal; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -31,7 +30,7 @@ public class LGWebOSBindingConstants { public static final ThingTypeUID THING_TYPE_WEBOSTV = new ThingTypeUID(BINDING_ID, "WebOSTV"); - public static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_WEBOSTV); + public static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_WEBOSTV); public static final ServiceType UPNP_SERVICE_TYPE = new ServiceType("lge-com", "webos-second-screen", 1); diff --git a/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/PowerControlPower.java b/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/PowerControlPower.java index ed2e2a60f..eda9b69cc 100644 --- a/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/PowerControlPower.java +++ b/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/PowerControlPower.java @@ -64,9 +64,11 @@ public class PowerControlPower extends BaseChannelHandler { case DISCONNECTED: String macAddress = configProvider.getMacAddress(); if (macAddress.isEmpty()) { - logger.debug("Received ON - Turning TV on via API is not supported by LG WebOS TVs. " - + "You may succeed using wake on lan (WOL). " - + "Please set the macAddress config value in Thing configuration to enable this."); + logger.debug(""" + Received ON - Turning TV on via API is not supported by LG WebOS TVs. \ + You may succeed using wake on lan (WOL). \ + Please set the macAddress config value in Thing configuration to enable this.\ + """); handler.postUpdate(channelId, OnOffType.OFF); } else { for (int i = 0; i < WOL_PACKET_RETRY_COUNT; i++) { diff --git a/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/VolumeControlVolume.java b/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/VolumeControlVolume.java index 737ab4587..7cdaf395e 100644 --- a/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/VolumeControlVolume.java +++ b/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/VolumeControlVolume.java @@ -49,12 +49,12 @@ public class VolumeControlVolume extends BaseChannelHandler { handler.getSocket().getVolume(createResponseListener(channelId, handler)); return; } - if (command instanceof PercentType) { - percent = (PercentType) command; - } else if (command instanceof DecimalType) { - percent = new PercentType(((DecimalType) command).toBigDecimal()); - } else if (command instanceof StringType) { - percent = new PercentType(((StringType) command).toString()); + if (command instanceof PercentType percentCommand) { + percent = percentCommand; + } else if (command instanceof DecimalType decimalCommand) { + percent = new PercentType(decimalCommand.toBigDecimal()); + } else if (command instanceof StringType stringCommand) { + percent = new PercentType(stringCommand.toString()); } else { percent = null; } diff --git a/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/WakeOnLanUtility.java b/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/WakeOnLanUtility.java index 9381660a7..426c191dc 100644 --- a/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/WakeOnLanUtility.java +++ b/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/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.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/action/LGWebOSActions.java b/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/action/LGWebOSActions.java index 6164e065b..8ee09e4ac 100644 --- a/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/action/LGWebOSActions.java +++ b/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/action/LGWebOSActions.java @@ -115,7 +115,7 @@ public class LGWebOSActions implements ThingActions { private List getAppInfos() { LGWebOSHandler lgWebOSHandler = getLGWebOSHandler(); - if (!this.getConnectedSocket().isPresent()) { + if (this.getConnectedSocket().isEmpty()) { return Collections.emptyList(); } diff --git a/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/console/LGWebOSCommandExtension.java b/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/console/LGWebOSCommandExtension.java index 4f2b7c908..d316470ed 100644 --- a/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/console/LGWebOSCommandExtension.java +++ b/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/console/LGWebOSCommandExtension.java @@ -65,8 +65,8 @@ public class LGWebOSCommandExtension extends AbstractConsoleCommandExtension imp LGWebOSHandler handler = null; if (thing != null) { thingHandler = thing.getHandler(); - if (thingHandler instanceof LGWebOSHandler) { - handler = (LGWebOSHandler) thingHandler; + if (thingHandler instanceof LGWebOSHandler webOSHandler) { + handler = webOSHandler; } } if (thing == null) { diff --git a/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/handler/LGWebOSHandler.java b/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/handler/LGWebOSHandler.java index c7f326534..8be697da8 100644 --- a/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/handler/LGWebOSHandler.java +++ b/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/handler/LGWebOSHandler.java @@ -21,6 +21,7 @@ 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; @@ -373,7 +374,7 @@ public class LGWebOSHandler extends BaseThingHandler @Override public Collection> getServices() { - return Collections.singleton(LGWebOSActions.class); + return Set.of(LGWebOSActions.class); } /** diff --git a/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/LifxLightCommunicationHandler.java b/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/LifxLightCommunicationHandler.java index 00350626f..f1a8282f8 100644 --- a/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/LifxLightCommunicationHandler.java +++ b/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/LifxLightCommunicationHandler.java @@ -189,8 +189,7 @@ public class LifxLightCommunicationHandler { new Object[] { logId, packet.getClass().getSimpleName(), address.toString(), packet.getTarget().getHex(), packet.getSequence(), Long.toString(packet.getSource(), 16) }); - if (packet instanceof StateServiceResponse) { - StateServiceResponse response = (StateServiceResponse) packet; + if (packet instanceof StateServiceResponse response) { MACAddress discoveredAddress = response.getTarget(); if (packetFromConfiguredHost && macAddress == null) { macAddress = discoveredAddress; diff --git a/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/LifxLightCurrentStateUpdater.java b/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/LifxLightCurrentStateUpdater.java index b83229afb..f890571f3 100644 --- a/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/LifxLightCurrentStateUpdater.java +++ b/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/LifxLightCurrentStateUpdater.java @@ -157,22 +157,22 @@ public class LifxLightCurrentStateUpdater { try { lock.lock(); - if (packet instanceof StateResponse) { - handleLightStatus((StateResponse) packet); - } else if (packet instanceof StatePowerResponse) { - handlePowerStatus((StatePowerResponse) packet); - } else if (packet instanceof StateLightPowerResponse) { - handleLightPowerStatus((StateLightPowerResponse) packet); - } else if (packet instanceof StateHevCycleResponse) { - handleHevCycleStatus((StateHevCycleResponse) packet); - } else if (packet instanceof StateLightInfraredResponse) { - handleInfraredStatus((StateLightInfraredResponse) packet); - } else if (packet instanceof StateMultiZoneResponse) { - handleMultiZoneStatus((StateMultiZoneResponse) packet); - } else if (packet instanceof StateTileEffectResponse) { - handleTileEffectStatus((StateTileEffectResponse) packet); - } else if (packet instanceof StateWifiInfoResponse) { - handleWifiInfoStatus((StateWifiInfoResponse) packet); + if (packet instanceof StateResponse response) { + handleLightStatus(response); + } else if (packet instanceof StatePowerResponse response) { + handlePowerStatus(response); + } else if (packet instanceof StateLightPowerResponse response) { + handleLightPowerStatus(response); + } else if (packet instanceof StateHevCycleResponse response) { + handleHevCycleStatus(response); + } else if (packet instanceof StateLightInfraredResponse response) { + handleInfraredStatus(response); + } else if (packet instanceof StateMultiZoneResponse response) { + handleMultiZoneStatus(response); + } else if (packet instanceof StateTileEffectResponse response) { + handleTileEffectStatus(response); + } else if (packet instanceof StateWifiInfoResponse response) { + handleWifiInfoStatus(response); } currentLightState.setOnline(); diff --git a/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/LifxLightDiscovery.java b/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/LifxLightDiscovery.java index 5d3bbe27b..e54cfa9ca 100644 --- a/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/LifxLightDiscovery.java +++ b/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/LifxLightDiscovery.java @@ -269,8 +269,8 @@ public class LifxLightDiscovery extends AbstractDiscoveryService { MACAddress macAddress = packet.getTarget(); DiscoveredLight light = discoveredLights.get(macAddress); - if (packet instanceof StateServiceResponse) { - int port = (int) ((StateServiceResponse) packet).getPort(); + if (packet instanceof StateServiceResponse response) { + int port = (int) response.getPort(); if (port != 0) { try { InetSocketAddress socketAddress = new InetSocketAddress(address.getAddress(), port); @@ -294,14 +294,13 @@ public class LifxLightDiscovery extends AbstractDiscoveryService { } } } else if (light != null) { - if (packet instanceof StateLabelResponse) { - light.label = ((StateLabelResponse) packet).getLabel().trim(); - } else if (packet instanceof StateVersionResponse) { + if (packet instanceof StateLabelResponse response) { + light.label = response.getLabel().trim(); + } else if (packet instanceof StateVersionResponse response) { try { - LifxProduct product = LifxProduct - .getProductFromProductID(((StateVersionResponse) packet).getProduct()); + LifxProduct product = LifxProduct.getProductFromProductID(response.getProduct()); light.product = product; - light.productVersion = ((StateVersionResponse) packet).getVersion(); + light.productVersion = response.getVersion(); light.supportedProduct = product.isLight(); } catch (IllegalArgumentException e) { logger.debug("Discovered an unsupported light ({}): {}", light.macAddress.getAsLabel(), diff --git a/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/LifxLightPropertiesUpdater.java b/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/LifxLightPropertiesUpdater.java index 163dc1216..634f65109 100644 --- a/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/LifxLightPropertiesUpdater.java +++ b/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/LifxLightPropertiesUpdater.java @@ -148,11 +148,11 @@ public class LifxLightPropertiesUpdater { return; } - if (packet instanceof StateVersionResponse) { - long productId = ((StateVersionResponse) packet).getProduct(); + if (packet instanceof StateVersionResponse response) { + long productId = response.getProduct(); properties.put(LifxBindingConstants.PROPERTY_PRODUCT_ID, Long.toString(productId)); - long productVersion = ((StateVersionResponse) packet).getVersion(); + long productVersion = response.getVersion(); properties.put(LifxBindingConstants.PROPERTY_PRODUCT_VERSION, Long.toString(productVersion)); try { @@ -165,12 +165,12 @@ public class LifxLightPropertiesUpdater { } receivedPacketTypes.add(packet.getPacketType()); - } else if (packet instanceof StateHostFirmwareResponse) { - String hostVersion = ((StateHostFirmwareResponse) packet).getVersion().toString(); + } else if (packet instanceof StateHostFirmwareResponse response) { + String hostVersion = response.getVersion().toString(); properties.put(LifxBindingConstants.PROPERTY_HOST_VERSION, hostVersion); receivedPacketTypes.add(packet.getPacketType()); - } else if (packet instanceof StateWifiFirmwareResponse) { - String wifiVersion = ((StateWifiFirmwareResponse) packet).getVersion().toString(); + } else if (packet instanceof StateWifiFirmwareResponse response) { + String wifiVersion = response.getVersion().toString(); properties.put(LifxBindingConstants.PROPERTY_WIFI_VERSION, wifiVersion); receivedPacketTypes.add(packet.getPacketType()); } diff --git a/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/LifxSequenceNumberSupplier.java b/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/LifxSequenceNumberSupplier.java index 4c6e5cfba..5906d8efb 100644 --- a/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/LifxSequenceNumberSupplier.java +++ b/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/LifxSequenceNumberSupplier.java @@ -30,8 +30,6 @@ public class LifxSequenceNumberSupplier implements Supplier { @Override public Integer get() { - return sequenceNumber.getAndUpdate((value) -> { - return (value + 1) % SEQUENCE_NUMBER_DIVISOR; - }); + return sequenceNumber.getAndUpdate((value) -> (value + 1) % SEQUENCE_NUMBER_DIVISOR); } } diff --git a/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/dto/LightLastHevCycleResult.java b/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/dto/LightLastHevCycleResult.java index a4c4f949f..4b05aa3d1 100644 --- a/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/dto/LightLastHevCycleResult.java +++ b/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/dto/LightLastHevCycleResult.java @@ -41,7 +41,7 @@ public enum LightLastHevCycleResult { Optional result = Arrays.stream(values()).filter((value) -> value.type == type) .findFirst(); - if (!result.isPresent()) { + if (result.isEmpty()) { throw new IllegalArgumentException("Invalid LightLastHevCycleResult type: " + type); } diff --git a/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/fields/LittleField.java b/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/fields/LittleField.java index 07de7e342..b157788ad 100644 --- a/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/fields/LittleField.java +++ b/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/fields/LittleField.java @@ -44,9 +44,7 @@ public class LittleField extends Field { ByteBuffer flipped = flip(ByteBuffer.wrap(field)); - T value = wrapped.value(flipped); - - return value; + return wrapped.value(flipped); } @Override diff --git a/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/handler/LifxLightHandler.java b/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/handler/LifxLightHandler.java index 8a1a361d5..5f52c5616 100644 --- a/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/handler/LifxLightHandler.java +++ b/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/handler/LifxLightHandler.java @@ -561,68 +561,67 @@ public class LifxLightHandler extends BaseThingHandler { switch (channelUID.getId()) { case CHANNEL_ABS_TEMPERATURE: case CHANNEL_TEMPERATURE: - if (command instanceof DecimalType || (command instanceof QuantityType - && ((QuantityType) command).toInvertibleUnit(Units.KELVIN) != null)) { + if (command instanceof DecimalType || (command instanceof QuantityType quantityCommand + && quantityCommand.toInvertibleUnit(Units.KELVIN) != null)) { return () -> handleTemperatureCommand(command); - } else if (command instanceof IncreaseDecreaseType) { - return () -> handleIncreaseDecreaseTemperatureCommand((IncreaseDecreaseType) command); + } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) { + return () -> handleIncreaseDecreaseTemperatureCommand(increaseDecreaseCommand); } case CHANNEL_BRIGHTNESS: - if (command instanceof PercentType) { - return () -> handlePercentCommand((PercentType) command); - } else if (command instanceof OnOffType) { - return () -> handleOnOffCommand((OnOffType) command); - } else if (command instanceof IncreaseDecreaseType) { - return () -> handleIncreaseDecreaseCommand((IncreaseDecreaseType) command); + if (command instanceof PercentType percentCommand) { + return () -> handlePercentCommand(percentCommand); + } else if (command instanceof OnOffType onOffCommand) { + return () -> handleOnOffCommand(onOffCommand); + } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) { + return () -> handleIncreaseDecreaseCommand(increaseDecreaseCommand); } case CHANNEL_COLOR: - if (command instanceof HSBType) { - return () -> handleHSBCommand((HSBType) command); - } else if (command instanceof PercentType) { - return () -> handlePercentCommand((PercentType) command); - } else if (command instanceof OnOffType) { - return () -> handleOnOffCommand((OnOffType) command); - } else if (command instanceof IncreaseDecreaseType) { - return () -> handleIncreaseDecreaseCommand((IncreaseDecreaseType) command); + if (command instanceof HSBType hsbCommand) { + return () -> handleHSBCommand(hsbCommand); + } else if (command instanceof PercentType percentCommand) { + return () -> handlePercentCommand(percentCommand); + } else if (command instanceof OnOffType onOffCommand) { + return () -> handleOnOffCommand(onOffCommand); + } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) { + return () -> handleIncreaseDecreaseCommand(increaseDecreaseCommand); } case CHANNEL_EFFECT: - if (command instanceof StringType && features.hasFeature(TILE_EFFECT)) { - return () -> handleTileEffectCommand((StringType) command); + if (command instanceof StringType stringCommand && features.hasFeature(TILE_EFFECT)) { + return () -> handleTileEffectCommand(stringCommand); } case CHANNEL_HEV_CYCLE: - if (command instanceof OnOffType) { - return () -> handleHevCycleCommand((OnOffType) command); + if (command instanceof OnOffType onOffCommand) { + return () -> handleHevCycleCommand(onOffCommand); } case CHANNEL_INFRARED: - if (command instanceof PercentType) { - return () -> handleInfraredCommand((PercentType) command); - } else if (command instanceof IncreaseDecreaseType) { - return () -> handleIncreaseDecreaseInfraredCommand((IncreaseDecreaseType) command); + if (command instanceof PercentType percentCommand) { + return () -> handleInfraredCommand(percentCommand); + } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) { + return () -> handleIncreaseDecreaseInfraredCommand(increaseDecreaseCommand); } default: try { if (channelUID.getId().startsWith(CHANNEL_ABS_TEMPERATURE_ZONE)) { int zoneIndex = Integer.parseInt(channelUID.getId().replace(CHANNEL_ABS_TEMPERATURE_ZONE, "")); - if (command instanceof DecimalType || (command instanceof QuantityType - && ((QuantityType) command).toInvertibleUnit(Units.KELVIN) != null)) { + if (command instanceof DecimalType || (command instanceof QuantityType quantityCommand + && quantityCommand.toInvertibleUnit(Units.KELVIN) != null)) { return () -> handleTemperatureCommand(command, zoneIndex); } } else if (channelUID.getId().startsWith(CHANNEL_COLOR_ZONE)) { int zoneIndex = Integer.parseInt(channelUID.getId().replace(CHANNEL_COLOR_ZONE, "")); - if (command instanceof HSBType) { - return () -> handleHSBCommand((HSBType) command, zoneIndex); - } else if (command instanceof PercentType) { - return () -> handlePercentCommand((PercentType) command, zoneIndex); - } else if (command instanceof IncreaseDecreaseType) { - return () -> handleIncreaseDecreaseCommand((IncreaseDecreaseType) command, zoneIndex); + if (command instanceof HSBType hsbCommand) { + return () -> handleHSBCommand(hsbCommand, zoneIndex); + } else if (command instanceof PercentType percentCommand) { + return () -> handlePercentCommand(percentCommand, zoneIndex); + } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) { + return () -> handleIncreaseDecreaseCommand(increaseDecreaseCommand, zoneIndex); } } else if (channelUID.getId().startsWith(CHANNEL_TEMPERATURE_ZONE)) { int zoneIndex = Integer.parseInt(channelUID.getId().replace(CHANNEL_TEMPERATURE_ZONE, "")); - if (command instanceof PercentType) { - return () -> handleTemperatureCommand((PercentType) command, zoneIndex); - } else if (command instanceof IncreaseDecreaseType) { - return () -> handleIncreaseDecreaseTemperatureCommand((IncreaseDecreaseType) command, - zoneIndex); + if (command instanceof PercentType percentCommand) { + return () -> handleTemperatureCommand(percentCommand, zoneIndex); + } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) { + return () -> handleIncreaseDecreaseTemperatureCommand(increaseDecreaseCommand, zoneIndex); } } } catch (NumberFormatException e) { diff --git a/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/util/LifxMessageUtil.java b/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/util/LifxMessageUtil.java index 701e6d642..d4a88d682 100644 --- a/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/util/LifxMessageUtil.java +++ b/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/util/LifxMessageUtil.java @@ -106,12 +106,12 @@ public final class LifxMessageUtil { } public static int commandToKelvin(Command temperature, TemperatureRange temperatureRange) { - if (temperature instanceof PercentType) { - return percentTypeToKelvin((PercentType) temperature, temperatureRange); - } else if (temperature instanceof QuantityType) { - return quantityTypeToKelvin((QuantityType) temperature, temperatureRange); - } else if (temperature instanceof DecimalType) { - return decimalTypeToKelvin((DecimalType) temperature, temperatureRange); + if (temperature instanceof PercentType percentValue) { + return percentTypeToKelvin(percentValue, temperatureRange); + } else if (temperature instanceof QuantityType quantityValue) { + return quantityTypeToKelvin(quantityValue, temperatureRange); + } else if (temperature instanceof DecimalType decimalValue) { + return decimalTypeToKelvin(decimalValue, temperatureRange); } else { throw new IllegalStateException( "Unexpected command type " + temperature.getClass().getName() + " for color temperature command."); diff --git a/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/util/LifxNetworkUtil.java b/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/util/LifxNetworkUtil.java index 59c05ed36..0f600ff4c 100644 --- a/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/util/LifxNetworkUtil.java +++ b/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/util/LifxNetworkUtil.java @@ -131,9 +131,7 @@ public final class LifxNetworkUtil { } public static int getNewBroadcastPort() { - int offset = BROADCAST_PORT_COUNTER.getAndUpdate((value) -> { - return (value + 1) % Integer.MAX_VALUE; - }); + int offset = BROADCAST_PORT_COUNTER.getAndUpdate((value) -> (value + 1) % Integer.MAX_VALUE); return BROADCAST_PORT + (offset % (PORT_MAX - BROADCAST_PORT)); } } diff --git a/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/util/LifxSelectorUtil.java b/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/util/LifxSelectorUtil.java index 24c53a286..200dbc8fb 100644 --- a/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/util/LifxSelectorUtil.java +++ b/bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/util/LifxSelectorUtil.java @@ -160,8 +160,8 @@ public class LifxSelectorUtil { readBuffer.rewind(); try { - if (channel instanceof DatagramChannel) { - InetSocketAddress address = (InetSocketAddress) ((DatagramChannel) channel).receive(readBuffer); + if (channel instanceof DatagramChannel datagramChannel) { + InetSocketAddress address = (InetSocketAddress) datagramChannel.receive(readBuffer); if (address == null) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("{} : No datagram is available", logId); @@ -169,9 +169,9 @@ public class LifxSelectorUtil { } else if (isRemoteAddress(address.getAddress())) { supplyParsedPacketToConsumer(readBuffer, address, packetConsumer, logId); } - } else if (channel instanceof SocketChannel) { - ((SocketChannel) channel).read(readBuffer); - InetSocketAddress address = (InetSocketAddress) ((SocketChannel) channel).getRemoteAddress(); + } else if (channel instanceof SocketChannel socketChannel) { + socketChannel.read(readBuffer); + InetSocketAddress address = (InetSocketAddress) socketChannel.getRemoteAddress(); if (address == null) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("{} : Channel socket is not connected", logId); @@ -292,20 +292,19 @@ public class LifxSelectorUtil { if (key.isValid() && key.isWritable() && key.equals(castKey)) { SelectableChannel channel = key.channel(); - if (channel instanceof DatagramChannel) { + if (channel instanceof DatagramChannel datagramChannel) { if (LOGGER.isTraceEnabled()) { LOGGER.trace( "{} : Sending packet type '{}' from '{}' to '{}' for '{}' with sequence '{}' and source '{}'", new Object[] { context.getLogId(), packet.getClass().getSimpleName(), - ((InetSocketAddress) ((DatagramChannel) channel).getLocalAddress()) - .toString(), + ((InetSocketAddress) datagramChannel.getLocalAddress()).toString(), address.toString(), packet.getTarget().getHex(), packet.getSequence(), Long.toString(packet.getSource(), 16) }); } - ((DatagramChannel) channel).send(packet.bytes(), address); + datagramChannel.send(packet.bytes(), address); return true; - } else if (channel instanceof SocketChannel) { - ((SocketChannel) channel).write(packet.bytes()); + } else if (channel instanceof SocketChannel socketChannel) { + socketChannel.write(packet.bytes()); return true; } } diff --git a/bundles/org.openhab.binding.linky/src/main/java/org/openhab/binding/linky/internal/console/LinkyCommandExtension.java b/bundles/org.openhab.binding.linky/src/main/java/org/openhab/binding/linky/internal/console/LinkyCommandExtension.java index 3da31b36a..8ebd32748 100644 --- a/bundles/org.openhab.binding.linky/src/main/java/org/openhab/binding/linky/internal/console/LinkyCommandExtension.java +++ b/bundles/org.openhab.binding.linky/src/main/java/org/openhab/binding/linky/internal/console/LinkyCommandExtension.java @@ -65,8 +65,8 @@ public class LinkyCommandExtension extends AbstractConsoleCommandExtension imple LinkyHandler handler = null; if (thing != null) { thingHandler = thing.getHandler(); - if (thingHandler instanceof LinkyHandler) { - handler = (LinkyHandler) thingHandler; + if (thingHandler instanceof LinkyHandler linkyHandler) { + handler = linkyHandler; } } if (thing == null) { diff --git a/bundles/org.openhab.binding.linky/src/main/java/org/openhab/binding/linky/internal/dto/AuthData.java b/bundles/org.openhab.binding.linky/src/main/java/org/openhab/binding/linky/internal/dto/AuthData.java index 5cb66b538..14cf52b7a 100644 --- a/bundles/org.openhab.binding.linky/src/main/java/org/openhab/binding/linky/internal/dto/AuthData.java +++ b/bundles/org.openhab.binding.linky/src/main/java/org/openhab/binding/linky/internal/dto/AuthData.java @@ -30,7 +30,7 @@ public class AuthData { public @Nullable Object value; public @Nullable String valueAsString() { - return (value instanceof String) ? (String) value : null; + return (value instanceof String stringValue) ? stringValue : null; } } diff --git a/bundles/org.openhab.binding.linky/src/main/java/org/openhab/binding/linky/internal/handler/LinkyHandler.java b/bundles/org.openhab.binding.linky/src/main/java/org/openhab/binding/linky/internal/handler/LinkyHandler.java index 23b2d0568..feecaded2 100644 --- a/bundles/org.openhab.binding.linky/src/main/java/org/openhab/binding/linky/internal/handler/LinkyHandler.java +++ b/bundles/org.openhab.binding.linky/src/main/java/org/openhab/binding/linky/internal/handler/LinkyHandler.java @@ -472,25 +472,25 @@ public class LinkyHandler extends BaseThingHandler { } private void checkData(Consumption consumption) throws LinkyException { - if (consumption.aggregats.days.periodes.size() == 0) { + if (consumption.aggregats.days.periodes.isEmpty()) { throw new LinkyException("Invalid consumptions data: no day period"); } if (consumption.aggregats.days.periodes.size() != consumption.aggregats.days.datas.size()) { throw new LinkyException("Invalid consumptions data: not any data for each day period"); } - if (consumption.aggregats.weeks.periodes.size() == 0) { + if (consumption.aggregats.weeks.periodes.isEmpty()) { throw new LinkyException("Invalid consumptions data: no week period"); } if (consumption.aggregats.weeks.periodes.size() != consumption.aggregats.weeks.datas.size()) { throw new LinkyException("Invalid consumptions data: not any data for each week period"); } - if (consumption.aggregats.months.periodes.size() == 0) { + if (consumption.aggregats.months.periodes.isEmpty()) { throw new LinkyException("Invalid consumptions data: no month period"); } if (consumption.aggregats.months.periodes.size() != consumption.aggregats.months.datas.size()) { throw new LinkyException("Invalid consumptions data: not any data for each month period"); } - if (consumption.aggregats.years.periodes.size() == 0) { + if (consumption.aggregats.years.periodes.isEmpty()) { throw new LinkyException("Invalid consumptions data: no year period"); } if (consumption.aggregats.years.periodes.size() != consumption.aggregats.years.datas.size()) { @@ -501,13 +501,13 @@ public class LinkyHandler extends BaseThingHandler { private boolean isDataFirstDayAvailable(Consumption consumption) { Aggregate days = consumption.aggregats.days; logData(days, "First day", false, DateTimeFormatter.ISO_LOCAL_DATE, Target.FIRST); - return days.datas != null && days.datas.size() > 0 && !days.datas.get(0).isNaN(); + return days.datas != null && !days.datas.isEmpty() && !days.datas.get(0).isNaN(); } private boolean isDataLastDayAvailable(Consumption consumption) { Aggregate days = consumption.aggregats.days; logData(days, "Last day", false, DateTimeFormatter.ISO_LOCAL_DATE, Target.LAST); - return days.datas != null && days.datas.size() > 0 && !days.datas.get(days.datas.size() - 1).isNaN(); + return days.datas != null && !days.datas.isEmpty() && !days.datas.get(days.datas.size() - 1).isNaN(); } private void logData(Aggregate aggregate, String title, boolean withDateFin, DateTimeFormatter dateTimeFormatter, diff --git a/bundles/org.openhab.binding.linuxinput/src/main/java/org/openhab/binding/linuxinput/internal/LinuxInputDiscoveryService.java b/bundles/org.openhab.binding.linuxinput/src/main/java/org/openhab/binding/linuxinput/internal/LinuxInputDiscoveryService.java index 1b62827ba..88ea6ac99 100644 --- a/bundles/org.openhab.binding.linuxinput/src/main/java/org/openhab/binding/linuxinput/internal/LinuxInputDiscoveryService.java +++ b/bundles/org.openhab.binding.linuxinput/src/main/java/org/openhab/binding/linuxinput/internal/LinuxInputDiscoveryService.java @@ -22,7 +22,7 @@ import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.time.Duration; -import java.util.Collections; +import java.util.Set; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; @@ -59,7 +59,7 @@ public class LinuxInputDiscoveryService extends AbstractDiscoveryService { private @NonNullByDefault({}) Future discoveryJob; public LinuxInputDiscoveryService() { - super(Collections.singleton(THING_TYPE_DEVICE), (int) TIMEOUT.getSeconds(), true); + super(Set.of(THING_TYPE_DEVICE), (int) TIMEOUT.getSeconds(), true); } @Override diff --git a/bundles/org.openhab.binding.linuxinput/src/main/java/org/openhab/binding/linuxinput/internal/LinuxInputHandler.java b/bundles/org.openhab.binding.linuxinput/src/main/java/org/openhab/binding/linuxinput/internal/LinuxInputHandler.java index 1648fc594..c543f6196 100644 --- a/bundles/org.openhab.binding.linuxinput/src/main/java/org/openhab/binding/linuxinput/internal/LinuxInputHandler.java +++ b/bundles/org.openhab.binding.linuxinput/src/main/java/org/openhab/binding/linuxinput/internal/LinuxInputHandler.java @@ -166,7 +166,7 @@ public final class LinuxInputHandler extends DeviceReadingHandler { if (selector.selectedKeys().remove(evdevReady)) { while (true) { Optional ev = currentDevice.nextEvent(); - if (!ev.isPresent()) { + if (ev.isEmpty()) { break; } handleEvent(ev.get()); diff --git a/bundles/org.openhab.binding.linuxinput/src/main/java/org/openhab/binding/linuxinput/internal/LinuxInputHandlerFactory.java b/bundles/org.openhab.binding.linuxinput/src/main/java/org/openhab/binding/linuxinput/internal/LinuxInputHandlerFactory.java index bec914342..30c59d4b8 100644 --- a/bundles/org.openhab.binding.linuxinput/src/main/java/org/openhab/binding/linuxinput/internal/LinuxInputHandlerFactory.java +++ b/bundles/org.openhab.binding.linuxinput/src/main/java/org/openhab/binding/linuxinput/internal/LinuxInputHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.linuxinput.internal; import static org.openhab.binding.linuxinput.internal.LinuxInputBindingConstants.THING_TYPE_DEVICE; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -34,7 +33,7 @@ import org.osgi.service.component.annotations.Component; @NonNullByDefault @Component(configurationPid = "binding.linuxinput", service = ThingHandlerFactory.class) public class LinuxInputHandlerFactory extends BaseThingHandlerFactory { - 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); @Override public boolean supportsThingType(ThingTypeUID thingTypeUID) { diff --git a/bundles/org.openhab.binding.liquidcheck/src/main/java/org/openhab/binding/liquidcheck/internal/LiquidCheckHandler.java b/bundles/org.openhab.binding.liquidcheck/src/main/java/org/openhab/binding/liquidcheck/internal/LiquidCheckHandler.java index 82709680a..3edb89995 100644 --- a/bundles/org.openhab.binding.liquidcheck/src/main/java/org/openhab/binding/liquidcheck/internal/LiquidCheckHandler.java +++ b/bundles/org.openhab.binding.liquidcheck/src/main/java/org/openhab/binding/liquidcheck/internal/LiquidCheckHandler.java @@ -84,7 +84,7 @@ public class LiquidCheckHandler extends BaseThingHandler { if (client != null && client.isConnected()) { String response = client.measureCommand(); CommData commandResponse = new Gson().fromJson(response, CommData.class); - if (commandResponse != null && !commandResponse.header.name.equals("")) { + if (commandResponse != null && !"".equals(commandResponse.header.name)) { if (!"success".equals(commandResponse.context.status)) { logger.warn("Starting the measurement was not successful!"); } @@ -136,7 +136,7 @@ public class LiquidCheckHandler extends BaseThingHandler { try { String jsonString = client.pollData(); CommData response = new Gson().fromJson(jsonString, CommData.class); - if (response != null && !response.header.messageId.equals("")) { + if (response != null && !"".equals(response.header.messageId)) { Map properties = response.createPropertyMap(); if (!oldProps.equals(properties)) { oldProps = properties; diff --git a/bundles/org.openhab.binding.lirc/src/main/java/org/openhab/binding/lirc/internal/LIRCBindingConstants.java b/bundles/org.openhab.binding.lirc/src/main/java/org/openhab/binding/lirc/internal/LIRCBindingConstants.java index 8e1d73d69..c974d2cac 100644 --- a/bundles/org.openhab.binding.lirc/src/main/java/org/openhab/binding/lirc/internal/LIRCBindingConstants.java +++ b/bundles/org.openhab.binding.lirc/src/main/java/org/openhab/binding/lirc/internal/LIRCBindingConstants.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.lirc.internal; -import java.util.Collections; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -39,8 +38,8 @@ public class LIRCBindingConstants { public static final String CHANNEL_TRANSMIT = "transmit"; // List of all supported thing types - public static final Set SUPPORTED_DEVICE_TYPES = Collections.singleton(THING_TYPE_REMOTE); - public static final Set SUPPORTED_BRIDGE_TYPES = Collections.singleton(THING_TYPE_BRIDGE); + public static final Set SUPPORTED_DEVICE_TYPES = Set.of(THING_TYPE_REMOTE); + public static final Set SUPPORTED_BRIDGE_TYPES = Set.of(THING_TYPE_BRIDGE); public static final Set SUPPORTED_THING_TYPES = Stream.of(THING_TYPE_REMOTE, THING_TYPE_BRIDGE) .collect(Collectors.toSet()); diff --git a/bundles/org.openhab.binding.livisismarthome/src/main/java/org/openhab/binding/livisismarthome/internal/discovery/LivisiDeviceDiscoveryService.java b/bundles/org.openhab.binding.livisismarthome/src/main/java/org/openhab/binding/livisismarthome/internal/discovery/LivisiDeviceDiscoveryService.java index d10c25435..a7533a480 100644 --- a/bundles/org.openhab.binding.livisismarthome/src/main/java/org/openhab/binding/livisismarthome/internal/discovery/LivisiDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.livisismarthome/src/main/java/org/openhab/binding/livisismarthome/internal/discovery/LivisiDeviceDiscoveryService.java @@ -160,8 +160,8 @@ public class LivisiDeviceDiscoveryService extends AbstractDiscoveryService @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof LivisiBridgeHandler) { - bridgeHandler = (LivisiBridgeHandler) handler; + if (handler instanceof LivisiBridgeHandler livisiBridgeHandler) { + bridgeHandler = livisiBridgeHandler; } } diff --git a/bundles/org.openhab.binding.livisismarthome/src/main/java/org/openhab/binding/livisismarthome/internal/handler/LivisiBridgeHandler.java b/bundles/org.openhab.binding.livisismarthome/src/main/java/org/openhab/binding/livisismarthome/internal/handler/LivisiBridgeHandler.java index 393755c44..462370c7f 100644 --- a/bundles/org.openhab.binding.livisismarthome/src/main/java/org/openhab/binding/livisismarthome/internal/handler/LivisiBridgeHandler.java +++ b/bundles/org.openhab.binding.livisismarthome/src/main/java/org/openhab/binding/livisismarthome/internal/handler/LivisiBridgeHandler.java @@ -20,10 +20,10 @@ import java.net.URI; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; import java.util.Collection; -import java.util.Collections; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledExecutorService; @@ -137,7 +137,7 @@ public class LivisiBridgeHandler extends BaseBridgeHandler @Override public Collection> getServices() { - return Collections.singleton(LivisiDeviceDiscoveryService.class); + return Set.of(LivisiDeviceDiscoveryService.class); } @Override @@ -564,8 +564,8 @@ public class LivisiBridgeHandler extends BaseBridgeHandler @Override public void onError(final Throwable cause) { - if (cause instanceof Exception) { - handleClientException((Exception) cause); + if (cause instanceof Exception exception) { + handleClientException(exception); } } diff --git a/bundles/org.openhab.binding.livisismarthome/src/main/java/org/openhab/binding/livisismarthome/internal/handler/LivisiDeviceHandler.java b/bundles/org.openhab.binding.livisismarthome/src/main/java/org/openhab/binding/livisismarthome/internal/handler/LivisiDeviceHandler.java index fb3c6ffa7..8d6a2167f 100644 --- a/bundles/org.openhab.binding.livisismarthome/src/main/java/org/openhab/binding/livisismarthome/internal/handler/LivisiDeviceHandler.java +++ b/bundles/org.openhab.binding.livisismarthome/src/main/java/org/openhab/binding/livisismarthome/internal/handler/LivisiDeviceHandler.java @@ -132,8 +132,7 @@ public class LivisiDeviceHandler extends BaseThingHandler implements DeviceStatu } private void commandSetDimLevel(Command command, LivisiBridgeHandler bridgeHandler) { - if (command instanceof DecimalType) { - final DecimalType dimLevel = (DecimalType) command; + if (command instanceof DecimalType dimLevel) { bridgeHandler.commandSetDimLevel(deviceId, dimLevel.intValue()); } else if (command instanceof OnOffType) { if (OnOffType.ON.equals(command)) { @@ -145,8 +144,7 @@ public class LivisiDeviceHandler extends BaseThingHandler implements DeviceStatu } private void commandRollerShutter(Command command, LivisiBridgeHandler bridgeHandler) { - if (command instanceof DecimalType) { - final DecimalType rollerShutterLevel = (DecimalType) command; + if (command instanceof DecimalType rollerShutterLevel) { bridgeHandler.commandSetRollerShutterLevel(deviceId, invertRollerShutterValueIfConfigured(rollerShutterLevel.intValue())); } else if (command instanceof OnOffType) { @@ -169,13 +167,13 @@ public class LivisiDeviceHandler extends BaseThingHandler implements DeviceStatu } private void commandUpdatePointTemperature(Command command, LivisiBridgeHandler bridgeHandler) { - if (command instanceof QuantityType) { - final QuantityType pointTemperatureCommand = ((QuantityType) command).toUnit(SIUnits.CELSIUS); + if (command instanceof QuantityType temperatureCommand) { + final QuantityType pointTemperatureCommand = temperatureCommand.toUnit(SIUnits.CELSIUS); if (pointTemperatureCommand != null) { commandUpdatePointTemperature(pointTemperatureCommand.doubleValue(), bridgeHandler); } - } else if (command instanceof DecimalType) { - commandUpdatePointTemperature(((DecimalType) command).doubleValue(), bridgeHandler); + } else if (command instanceof DecimalType temperatureCommand) { + commandUpdatePointTemperature(temperatureCommand.doubleValue(), bridgeHandler); } } @@ -991,8 +989,7 @@ public class LivisiDeviceHandler extends BaseThingHandler implements DeviceStatu } @Nullable final ThingHandler handler = bridge.getHandler(); - if (handler instanceof LivisiBridgeHandler) { - LivisiBridgeHandler bridgeHandler = (LivisiBridgeHandler) handler; + if (handler instanceof LivisiBridgeHandler bridgeHandler) { bridgeHandler.registerDeviceStatusListener(deviceId, this); this.bridgeHandler = bridgeHandler; } else { diff --git a/bundles/org.openhab.binding.livisismarthome/src/test/java/org/openhab/binding/livisismarthome/internal/client/LivisiClientTest.java b/bundles/org.openhab.binding.livisismarthome/src/test/java/org/openhab/binding/livisismarthome/internal/client/LivisiClientTest.java index 33713f1b7..0a1391234 100644 --- a/bundles/org.openhab.binding.livisismarthome/src/test/java/org/openhab/binding/livisismarthome/internal/client/LivisiClientTest.java +++ b/bundles/org.openhab.binding.livisismarthome/src/test/java/org/openhab/binding/livisismarthome/internal/client/LivisiClientTest.java @@ -69,14 +69,15 @@ public class LivisiClientTest { @Test public void testRefreshStatusSHC2() throws Exception { - mockRequest(STATUS_URL, - "{\"gateway\": {\"serialNumber\": \"123\"," - + "\"appVersion\": \"1.2.37.430\",\"osVersion\": \"8.17\",\"configVersion\": 1200," - + "\"operationStatus\": \"active\",\"network\": " - + "{\"ethCableAttached\": true,\"inUseAdapter\": \"eth\",\"hotspotActive\": false," - + "\"wpsActive\": false,\"backendAvailable\": true,\"ethMacAddress\": " - + "[{\"id\": \"456\",\"config\": {\"name\": \"Arbeitszimmer\",\"type\": \"Other\"}," - + "\"desc\": \"/desc/location\"}]}}}"); + mockRequest(STATUS_URL, """ + {"gateway": {"serialNumber": "123",\ + "appVersion": "1.2.37.430","osVersion": "8.17","configVersion": 1200,\ + "operationStatus": "active","network": \ + {"ethCableAttached": true,"inUseAdapter": "eth","hotspotActive": false,\ + "wpsActive": false,"backendAvailable": true,"ethMacAddress": \ + [{"id": "456","config": {"name": "Arbeitszimmer","type": "Other"},\ + "desc": "/desc/location"}]}}}\ + """); assertEquals("1200", client.refreshStatus()); } diff --git a/bundles/org.openhab.binding.livisismarthome/src/test/java/org/openhab/binding/livisismarthome/internal/client/entity/device/DeviceDTOTest.java b/bundles/org.openhab.binding.livisismarthome/src/test/java/org/openhab/binding/livisismarthome/internal/client/entity/device/DeviceDTOTest.java index 3fd8c50d4..75972f93b 100644 --- a/bundles/org.openhab.binding.livisismarthome/src/test/java/org/openhab/binding/livisismarthome/internal/client/entity/device/DeviceDTOTest.java +++ b/bundles/org.openhab.binding.livisismarthome/src/test/java/org/openhab/binding/livisismarthome/internal/client/entity/device/DeviceDTOTest.java @@ -39,7 +39,7 @@ public class DeviceDTOTest { assertTrue(device.isReachable()); assertFalse(device.hasLowBattery()); - device.setMessageList(Collections.singletonList(createMessage(MessageDTO.TYPE_DEVICE_LOW_BATTERY))); + device.setMessageList(List.of(createMessage(MessageDTO.TYPE_DEVICE_LOW_BATTERY))); assertTrue(device.isReachable()); assertTrue(device.hasLowBattery()); @@ -52,7 +52,7 @@ public class DeviceDTOTest { assertTrue(device.isReachable()); assertFalse(device.hasLowBattery()); - device.setMessageList(Collections.singletonList(createMessage(MessageDTO.TYPE_DEVICE_UNREACHABLE))); + device.setMessageList(List.of(createMessage(MessageDTO.TYPE_DEVICE_UNREACHABLE))); assertFalse(device.isReachable()); assertFalse(device.hasLowBattery()); @@ -126,7 +126,7 @@ public class DeviceDTOTest { assertFalse(device.isReachable()); assertTrue(device.hasLowBattery()); - messages = Collections.singletonList(createMessage("UNKNOWN")); + messages = List.of(createMessage("UNKNOWN")); device.setMessageList(messages); // Nothing should get changed. @@ -144,7 +144,7 @@ public class DeviceDTOTest { assertTrue(device.isReachable()); assertFalse(device.hasLowBattery()); - device.setMessageList(Collections.singletonList(createMessage("UNKNOWN"))); + device.setMessageList(List.of(createMessage("UNKNOWN"))); assertTrue(device.isReachable()); assertFalse(device.hasLowBattery()); diff --git a/bundles/org.openhab.binding.livisismarthome/src/test/java/org/openhab/binding/livisismarthome/internal/handler/LivisiBridgeHandlerTest.java b/bundles/org.openhab.binding.livisismarthome/src/test/java/org/openhab/binding/livisismarthome/internal/handler/LivisiBridgeHandlerTest.java index 51f611c61..90eccc7e5 100644 --- a/bundles/org.openhab.binding.livisismarthome/src/test/java/org/openhab/binding/livisismarthome/internal/handler/LivisiBridgeHandlerTest.java +++ b/bundles/org.openhab.binding.livisismarthome/src/test/java/org/openhab/binding/livisismarthome/internal/handler/LivisiBridgeHandlerTest.java @@ -18,9 +18,9 @@ import static org.openhab.binding.livisismarthome.internal.LivisiBindingConstant import static org.openhab.binding.livisismarthome.internal.client.api.entity.link.LinkDTO.LINK_TYPE_DEVICE; import java.io.IOException; -import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; @@ -363,7 +363,7 @@ public class LivisiBridgeHandlerTest { livisiClientMock = mock(LivisiClient.class); fullDeviceManagerMock = mock(FullDeviceManager.class); - when(fullDeviceManagerMock.getFullDevices()).thenReturn(Collections.singletonList(bridgeDevice)); + when(fullDeviceManagerMock.getFullDevices()).thenReturn(List.of(bridgeDevice)); schedulerMock = mock(ScheduledExecutorService.class); diff --git a/bundles/org.openhab.binding.livisismarthome/src/test/java/org/openhab/binding/livisismarthome/internal/handler/LivisiDeviceHandlerTest.java b/bundles/org.openhab.binding.livisismarthome/src/test/java/org/openhab/binding/livisismarthome/internal/handler/LivisiDeviceHandlerTest.java index f03aab91f..4f39d1667 100644 --- a/bundles/org.openhab.binding.livisismarthome/src/test/java/org/openhab/binding/livisismarthome/internal/handler/LivisiDeviceHandlerTest.java +++ b/bundles/org.openhab.binding.livisismarthome/src/test/java/org/openhab/binding/livisismarthome/internal/handler/LivisiDeviceHandlerTest.java @@ -1754,7 +1754,7 @@ public class LivisiDeviceHandlerTest { ThingUID thingUID = new ThingUID(thingTypeUID, device.getId()); Configuration thingConfiguration = new Configuration(); - thingConfiguration.setProperties(Collections.singletonMap(PROPERTY_ID, device.getId())); + thingConfiguration.setProperties(Map.of(PROPERTY_ID, device.getId())); Thing thingMock = mock(Thing.class); when(thingMock.getBridgeUID()).thenReturn(bridgeThingUID); diff --git a/bundles/org.openhab.binding.logreader/src/3rdparty/java/org/apache/commons/io/input/Tailer.java b/bundles/org.openhab.binding.logreader/src/3rdparty/java/org/apache/commons/io/input/Tailer.java index 22f0d80f5..fcfa4eb21 100644 --- a/bundles/org.openhab.binding.logreader/src/3rdparty/java/org/apache/commons/io/input/Tailer.java +++ b/bundles/org.openhab.binding.logreader/src/3rdparty/java/org/apache/commons/io/input/Tailer.java @@ -149,7 +149,7 @@ public class Tailer implements Runnable { /** * Buffer on top of RandomAccessFile. */ - private final byte inbuf[]; + private final byte[] inbuf; /** * The file which will be tailed. diff --git a/bundles/org.openhab.binding.logreader/src/main/java/org/openhab/binding/logreader/internal/handler/LogHandler.java b/bundles/org.openhab.binding.logreader/src/main/java/org/openhab/binding/logreader/internal/handler/LogHandler.java index 935ffef8e..595d2fec3 100644 --- a/bundles/org.openhab.binding.logreader/src/main/java/org/openhab/binding/logreader/internal/handler/LogHandler.java +++ b/bundles/org.openhab.binding.logreader/src/main/java/org/openhab/binding/logreader/internal/handler/LogHandler.java @@ -184,7 +184,7 @@ public class LogHandler extends BaseThingHandler implements FileReaderListener { return; } - if (!(thing.getStatus() == ThingStatus.ONLINE)) { + if (thing.getStatus() != ThingStatus.ONLINE) { updateStatus(ThingStatus.ONLINE); } diff --git a/bundles/org.openhab.binding.logreader/src/main/java/org/openhab/binding/logreader/internal/searchengine/SearchEngine.java b/bundles/org.openhab.binding.logreader/src/main/java/org/openhab/binding/logreader/internal/searchengine/SearchEngine.java index 3d8ac1298..b4ba401e7 100644 --- a/bundles/org.openhab.binding.logreader/src/main/java/org/openhab/binding/logreader/internal/searchengine/SearchEngine.java +++ b/bundles/org.openhab.binding.logreader/src/main/java/org/openhab/binding/logreader/internal/searchengine/SearchEngine.java @@ -83,7 +83,7 @@ public class SearchEngine { private List compilePatterns(@Nullable String patterns) throws PatternSyntaxException { List patternsList = new ArrayList<>(); if (patterns != null && !patterns.isEmpty()) { - String list[] = patterns.split("\\|"); + String[] list = patterns.split("\\|"); if (list.length > 0) { for (String patternStr : list) { patternsList.add(Pattern.compile(patternStr)); diff --git a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/LxHandlerFactory.java b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/LxHandlerFactory.java index 7f4720a1d..cb9795c3f 100644 --- a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/LxHandlerFactory.java +++ b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/LxHandlerFactory.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.loxone.internal; -import java.util.Collections; import java.util.Set; import org.openhab.core.thing.Thing; @@ -31,8 +30,7 @@ import org.osgi.service.component.annotations.Reference; @Component(service = ThingHandlerFactory.class, configurationPid = "binding.loxone") public class LxHandlerFactory extends BaseThingHandlerFactory { - public static final Set SUPPORTED_THING_TYPES_UIDS = Collections - .singleton(LxBindingConstants.THING_TYPE_MINISERVER); + public static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(LxBindingConstants.THING_TYPE_MINISERVER); private LxDynamicStateDescriptionProvider dynamicStateDescriptionProvider; @@ -45,8 +43,7 @@ public class LxHandlerFactory extends BaseThingHandlerFactory { protected ThingHandler createHandler(Thing thing) { ThingTypeUID uid = thing.getThingTypeUID(); if (uid.equals(LxBindingConstants.THING_TYPE_MINISERVER)) { - LxServerHandler handler = new LxServerHandler(thing, dynamicStateDescriptionProvider); - return handler; + return new LxServerHandler(thing, dynamicStateDescriptionProvider); } return null; } diff --git a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/LxServerHandler.java b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/LxServerHandler.java index d89eb5b5e..1829c190c 100644 --- a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/LxServerHandler.java +++ b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/LxServerHandler.java @@ -19,7 +19,6 @@ import java.net.UnknownHostException; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -106,8 +105,7 @@ public class LxServerHandler extends BaseThingHandler implements LxServerHandler private final Logger logger = LoggerFactory.getLogger(LxServerHandler.class); private static AtomicInteger staticDebugId = new AtomicInteger(1); - static final Set SUPPORTED_THING_TYPES_UIDS = Collections - .singleton(LxBindingConstants.THING_TYPE_MINISERVER); + static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(LxBindingConstants.THING_TYPE_MINISERVER); private QueuedThreadPool jettyThreadPool; @@ -324,7 +322,7 @@ public class LxServerHandler extends BaseThingHandler implements LxServerHandler @Override public String getSetting(String name) { Object value = getConfig().get(name); - return (value instanceof String) ? (String) value : null; + return (value instanceof String s) ? s : null; } /* diff --git a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/LxWebSocket.java b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/LxWebSocket.java index 201065450..3483827e1 100644 --- a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/LxWebSocket.java +++ b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/LxWebSocket.java @@ -207,7 +207,7 @@ public class LxWebSocket { } @OnWebSocketMessage - public void onBinaryMessage(byte data[], int msgOffset, int msgLength) { + public void onBinaryMessage(byte[] data, int msgOffset, int msgLength) { int offset = msgOffset; int length = msgLength; if (logger.isTraceEnabled()) { diff --git a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControl.java b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControl.java index 51500f013..868c67e00 100644 --- a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControl.java +++ b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControl.java @@ -617,8 +617,8 @@ public class LxControl { LxState state = states.get(name); if (state != null) { Object value = state.getStateValue(); - if (value instanceof String) { - return (String) value; + if (value instanceof String str) { + return str; } } return null; diff --git a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlAlarm.java b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlAlarm.java index 4c7132898..9ce84e92d 100644 --- a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlAlarm.java +++ b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlAlarm.java @@ -188,9 +188,9 @@ class LxControlAlarm extends LxControl { if (STATE_START_TIME.equals(stateName)) { startTime = UnDefType.UNDEF; Object obj = state.getStateValue(); - if (obj instanceof String && !((String) obj).isEmpty()) { + if (obj instanceof String str && !str.isEmpty()) { try { - LocalDateTime ldt = LocalDateTime.parse((String) obj, dateTimeFormatter); + LocalDateTime ldt = LocalDateTime.parse(str, dateTimeFormatter); ZonedDateTime dt = ldt.atZone(ZoneId.systemDefault()); startTime = new DateTimeType(dt); } catch (DateTimeParseException e) { diff --git a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlColorPickerV2.java b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlColorPickerV2.java index 0be247e3d..f47d9a258 100644 --- a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlColorPickerV2.java +++ b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlColorPickerV2.java @@ -70,20 +70,20 @@ class LxControlColorPickerV2 extends LxControl { } private void handleCommands(Command command) throws IOException { - if (command instanceof HSBType) { - setColor((HSBType) command); + if (command instanceof HSBType hsbCommand) { + setColor(hsbCommand); } else if (command instanceof OnOffType) { if (command == OnOffType.ON) { on(); } else { off(); } - } else if (command instanceof DecimalType) { - setBrightness((DecimalType) command); - } else if (command instanceof PercentType) { - setBrightness((PercentType) command); - } else if (command instanceof IncreaseDecreaseType) { - if (((IncreaseDecreaseType) command).equals(IncreaseDecreaseType.INCREASE)) { + } else if (command instanceof DecimalType decimalCommand) { + setBrightness(decimalCommand); + } else if (command instanceof PercentType percentCommand) { + setBrightness(percentCommand); + } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) { + if (increaseDecreaseCommand.equals(IncreaseDecreaseType.INCREASE)) { increaseDecreaseBrightness(1); } else { increaseDecreaseBrightness(-1); diff --git a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlEIBDimmer.java b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlEIBDimmer.java index 36c061398..e21b3ffd6 100644 --- a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlEIBDimmer.java +++ b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlEIBDimmer.java @@ -99,16 +99,15 @@ class LxControlEIBDimmer extends LxControl { } else { sendAction(CMD_OFF); } - } else if (command instanceof PercentType) { - PercentType percentCmd = (PercentType) command; - setPosition(percentCmd.doubleValue()); - } else if (command instanceof IncreaseDecreaseType) { + } else if (command instanceof PercentType percentCommand) { + setPosition(percentCommand.doubleValue()); + } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) { Double value = getStateDoubleValue(STATE_POSITION); Double min = getMin(); Double max = getMax(); Double step = getStep(); if (value != null && max != null && min != null && step != null && min >= 0 && max >= 0 && max > min) { - if ((IncreaseDecreaseType) command == IncreaseDecreaseType.INCREASE) { + if (increaseDecreaseCommand == IncreaseDecreaseType.INCREASE) { value += step; if (value > max) { value = max; @@ -169,8 +168,8 @@ class LxControlEIBDimmer extends LxControl { Double max = getMax(); Double min = getMin(); if (max != null && min != null) { - double value = min + ohValue * (max - min) / 100; - return value; // no rounding to integer value is needed as loxone is accepting floating point values + return min + ohValue * (max - min) / 100; // no rounding to integer value is needed as loxone is + // accepting floating point values } } return null; diff --git a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlIRoomControllerV2.java b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlIRoomControllerV2.java index 255d7fc99..79d7fbf71 100644 --- a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlIRoomControllerV2.java +++ b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlIRoomControllerV2.java @@ -163,16 +163,14 @@ class LxControlIRoomControllerV2 extends LxControl { } private void setOperatingMode(Command command) throws IOException { - if (command instanceof DecimalType) { - DecimalType mode = (DecimalType) command; - sendAction(CMD_SET_OPERATING_MODE + String.valueOf(mode.intValue())); + if (command instanceof DecimalType mode) { + sendAction(CMD_SET_OPERATING_MODE + mode.intValue()); } } private void setTemperature(Command command, String prefix) throws IOException { - if (command instanceof DecimalType) { - DecimalType temp = (DecimalType) command; - sendAction(prefix + String.valueOf(temp.doubleValue())); + if (command instanceof DecimalType temp) { + sendAction(prefix + temp.doubleValue()); } } } diff --git a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlJalousie.java b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlJalousie.java index 86856bb1f..a759c19e9 100644 --- a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlJalousie.java +++ b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlJalousie.java @@ -132,22 +132,22 @@ class LxControlJalousie extends LxControl { private void handleOperateCommands(Command command) throws IOException { logger.debug("Command input {}", command); - if (command instanceof PercentType) { + if (command instanceof PercentType percentCommand) { if (PercentType.ZERO.equals(command)) { sendAction(CMD_FULL_UP); } else if (PercentType.HUNDRED.equals(command)) { sendAction(CMD_FULL_DOWN); } else { - moveToPosition(((PercentType) command).doubleValue() / 100); + moveToPosition(percentCommand.doubleValue() / 100); } - } else if (command instanceof UpDownType) { - if ((UpDownType) command == UpDownType.UP) { + } else if (command instanceof UpDownType upDownCommand) { + if (upDownCommand == UpDownType.UP) { sendAction(CMD_FULL_UP); } else { sendAction(CMD_FULL_DOWN); } - } else if (command instanceof StopMoveType) { - if ((StopMoveType) command == StopMoveType.STOP) { + } else if (command instanceof StopMoveType stopMoveCommand) { + if (stopMoveCommand == StopMoveType.STOP) { sendAction(CMD_STOP); } } @@ -169,16 +169,16 @@ class LxControlJalousie extends LxControl { } private void handleShadeCommands(Command command) throws IOException { - if (command instanceof OnOffType) { - if ((OnOffType) command == OnOffType.ON) { + if (command instanceof OnOffType onOffCommand) { + if (onOffCommand == OnOffType.ON) { sendAction(CMD_SHADE); } } } private void handleAutoShadeCommands(Command command) throws IOException { - if (command instanceof OnOffType) { - if ((OnOffType) command == OnOffType.ON) { + if (command instanceof OnOffType onOffCommand) { + if (onOffCommand == OnOffType.ON) { sendAction(CMD_AUTO); } else { sendAction(CMD_NO_AUTO); diff --git a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlLightController.java b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlLightController.java index 818387c43..18879df87 100644 --- a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlLightController.java +++ b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlLightController.java @@ -105,20 +105,20 @@ class LxControlLightController extends LxControl { } private void handleCommands(Command command) throws IOException { - if (command instanceof OnOffType) { - if ((OnOffType) command == OnOffType.ON) { + if (command instanceof OnOffType onOffCommand) { + if (onOffCommand == OnOffType.ON) { sendAction(CMD_ON); } else { sendAction(CMD_OFF); } - } else if (command instanceof UpDownType) { - if ((UpDownType) command == UpDownType.UP) { + } else if (command instanceof UpDownType upDownCommand) { + if (upDownCommand == UpDownType.UP) { sendAction(CMD_NEXT_SCENE); } else { sendAction(CMD_PREVIOUS_SCENE); } - } else if (command instanceof DecimalType) { - int scene = ((DecimalType) command).intValue(); + } else if (command instanceof DecimalType decimalCommand) { + int scene = decimalCommand.intValue(); if (scene == SCENE_ALL_ON) { sendAction(CMD_ON); } else if (scene >= 0 && scene < NUM_OF_SCENES) { @@ -142,11 +142,11 @@ class LxControlLightController extends LxControl { public void onStateChange(LxState state) { if (STATE_SCENE_LIST.equals(state.getName()) && channelId != null) { Object value = state.getStateValue(); - if (value instanceof String) { + if (value instanceof String str) { sceneNames.clear(); - String[] scenes = ((String) value).split(","); + String[] scenes = str.split(","); for (String line : scenes) { - line = line.replaceAll("\"", ""); + line = line.replace("\"", ""); String[] params = line.split("="); if (params.length == 2) { sceneNames.add(new StateOption(params[0], params[1])); diff --git a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlLightControllerV2.java b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlLightControllerV2.java index 2954b9a21..fffad2992 100644 --- a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlLightControllerV2.java +++ b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlLightControllerV2.java @@ -125,14 +125,14 @@ class LxControlLightControllerV2 extends LxControl { } private void handleCommands(Command command) throws IOException { - if (command instanceof UpDownType) { - if ((UpDownType) command == UpDownType.UP) { + if (command instanceof UpDownType upDownCommand) { + if (upDownCommand == UpDownType.UP) { sendAction(CMD_NEXT_MOOD); } else { sendAction(CMD_PREVIOUS_MOOD); } - } else if (command instanceof DecimalType) { - int moodId = ((DecimalType) command).intValue(); + } else if (command instanceof DecimalType decimalCommand) { + int moodId = decimalCommand.intValue(); if (isMoodOk(moodId)) { sendAction(CMD_CHANGE_TO_MOOD + "/" + moodId); } @@ -160,11 +160,11 @@ class LxControlLightControllerV2 extends LxControl { String stateName = state.getName(); Object value = state.getStateValue(); try { - if (STATE_MOODS_LIST.equals(stateName) && value instanceof String) { - onMoodsListChange((String) value); - } else if (STATE_ACTIVE_MOODS_LIST.equals(stateName) && value instanceof String) { + if (STATE_MOODS_LIST.equals(stateName) && value instanceof String string) { + onMoodsListChange(string); + } else if (STATE_ACTIVE_MOODS_LIST.equals(stateName) && value instanceof String string) { // this state can be received before list of moods, but it contains a valid list of IDs - Integer[] array = getGson().fromJson((String) value, Integer[].class); + Integer[] array = getGson().fromJson(string, Integer[].class); activeMoods = Arrays.asList(array).stream().filter(id -> isMoodOk(id)).collect(Collectors.toList()); // update all moods states - this will force update of channels too moodList.values().forEach(mood -> mood.onStateChange(null)); diff --git a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlMeter.java b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlMeter.java index 9bc44eb67..8c5d9aad4 100644 --- a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlMeter.java +++ b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlMeter.java @@ -94,7 +94,7 @@ class LxControlMeter extends LxControl { } private void handleResetCommands(Command command) throws IOException { - if (command instanceof OnOffType && (OnOffType) command == OnOffType.ON) { + if (command instanceof OnOffType onOffCommand && onOffCommand == OnOffType.ON) { sendAction(CMD_RESET); } } diff --git a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlPushbutton.java b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlPushbutton.java index 6497ba021..28470a1f5 100644 --- a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlPushbutton.java +++ b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlPushbutton.java @@ -51,8 +51,8 @@ class LxControlPushbutton extends LxControlSwitch { @Override void handleSwitchCommands(Command command) throws IOException { - if (command instanceof OnOffType) { - if ((OnOffType) command == OnOffType.ON) { + if (command instanceof OnOffType onOffCommand) { + if (onOffCommand == OnOffType.ON) { sendAction(CMD_PULSE); } else { off(); diff --git a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlRadio.java b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlRadio.java index a18d2610f..81b1acc68 100644 --- a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlRadio.java +++ b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlRadio.java @@ -97,11 +97,10 @@ class LxControlRadio extends LxControl { } private void handleCommands(Command command) throws IOException { - if (((command instanceof OnOffType && (OnOffType) command == OnOffType.OFF) || DecimalType.ZERO.equals(command)) - && outputsMap.containsKey("0")) { + if (((command instanceof OnOffType onOffCommand && onOffCommand == OnOffType.OFF) + || DecimalType.ZERO.equals(command)) && outputsMap.containsKey("0")) { sendAction(CMD_RESET); - } else if (command instanceof DecimalType) { - DecimalType output = (DecimalType) command; + } else if (command instanceof DecimalType output) { if (outputsMap.containsKey(output.toString())) { sendAction(String.valueOf(output.intValue())); } diff --git a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlSauna.java b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlSauna.java index 72f147679..7b4854e75 100644 --- a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlSauna.java +++ b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlSauna.java @@ -139,8 +139,8 @@ class LxControlSauna extends LxControl { } private void handleSaunaActivateCommands(Command command) throws IOException { - if (command instanceof OnOffType) { - if ((OnOffType) command == OnOffType.ON) { + if (command instanceof OnOffType onOffCommand) { + if (onOffCommand == OnOffType.ON) { sendAction(CMD_ON); } else { sendAction(CMD_OFF); @@ -149,15 +149,15 @@ class LxControlSauna extends LxControl { } private void handleSetNumberCommands(Command command, String prefix) throws IOException { - if (command instanceof DecimalType) { - Double value = ((DecimalType) command).doubleValue(); + if (command instanceof DecimalType decimalCommand) { + Double value = decimalCommand.doubleValue(); sendAction(prefix + value.toString()); } } private void handleFanCommands(Command command) throws IOException { - if (command instanceof OnOffType) { - if ((OnOffType) command == OnOffType.ON) { + if (command instanceof OnOffType onOffCommand) { + if (onOffCommand == OnOffType.ON) { sendAction(CMD_FAN_ON); } else { sendAction(CMD_FAN_OFF); @@ -166,14 +166,14 @@ class LxControlSauna extends LxControl { } private void handleTriggerCommands(Command command, String prefix) throws IOException { - if (command instanceof OnOffType && (OnOffType) command == OnOffType.ON) { + if (command instanceof OnOffType onOffCommand && onOffCommand == OnOffType.ON) { sendAction(prefix); } } private void handleModeCommands(Command command) throws IOException { - if (command instanceof DecimalType) { - Double value = ((DecimalType) command).doubleValue(); + if (command instanceof DecimalType decimalCommand) { + Double value = decimalCommand.doubleValue(); // per API there are 7 evaporator modes selected with number 0-6 if (value % 1 == 0 && value >= 0.0 && value <= 6.0) { sendAction(CMD_SET_EVAPORATOR_MODE + value.toString()); diff --git a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlSwitch.java b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlSwitch.java index 251a07b2e..4dbb97ac8 100644 --- a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlSwitch.java +++ b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlSwitch.java @@ -83,8 +83,8 @@ class LxControlSwitch extends LxControl { } void handleSwitchCommands(Command command) throws IOException { - if (command instanceof OnOffType) { - if ((OnOffType) command == OnOffType.ON) { + if (command instanceof OnOffType onOffCommand) { + if (onOffCommand == OnOffType.ON) { on(); } else { off(); diff --git a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlUpDownAnalog.java b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlUpDownAnalog.java index 7d5bc2a0c..e0f43eb6d 100644 --- a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlUpDownAnalog.java +++ b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlUpDownAnalog.java @@ -91,8 +91,8 @@ class LxControlUpDownAnalog extends LxControl { } private void handleCommands(Command command) throws IOException { - if (command instanceof DecimalType) { - Double value = ((DecimalType) command).doubleValue(); + if (command instanceof DecimalType decimalCommand) { + Double value = decimalCommand.doubleValue(); if (minValue != null && maxValue != null && value >= minValue && value <= maxValue) { sendAction(value.toString()); } else { diff --git a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlUpDownDigital.java b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlUpDownDigital.java index 1f54bfd19..9fd42231b 100644 --- a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlUpDownDigital.java +++ b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlUpDownDigital.java @@ -81,8 +81,8 @@ class LxControlUpDownDigital extends LxControl { } private void handleUpCommands(Command command) throws IOException { - if (command instanceof OnOffType) { - if ((OnOffType) command == OnOffType.ON && upState == OnOffType.OFF) { + if (command instanceof OnOffType onOffCommand) { + if (onOffCommand == OnOffType.ON && upState == OnOffType.OFF) { setStates(OnOffType.ON, OnOffType.OFF); sendAction(CMD_UP_ON); } else if (upState == OnOffType.ON) { @@ -93,8 +93,8 @@ class LxControlUpDownDigital extends LxControl { } private void handleDownCommands(Command command) throws IOException { - if (command instanceof OnOffType) { - if ((OnOffType) command == OnOffType.ON && downState == OnOffType.OFF) { + if (command instanceof OnOffType onOffCommand) { + if (onOffCommand == OnOffType.ON && downState == OnOffType.OFF) { setStates(OnOffType.OFF, OnOffType.ON); sendAction(CMD_DOWN_ON); } else if (downState == OnOffType.ON) { diff --git a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlValueSelector.java b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlValueSelector.java index 153e7afd2..0ad680821 100644 --- a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlValueSelector.java +++ b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/controls/LxControlValueSelector.java @@ -96,25 +96,25 @@ class LxControlValueSelector extends LxControl { logger.debug("Value selector min or max value missing or min>max."); return; } - if (command instanceof OnOffType) { - if ((OnOffType) command == OnOffType.ON) { + if (command instanceof OnOffType onOffCommand) { + if (onOffCommand == OnOffType.ON) { sendAction(maxValue.toString()); } else { sendAction(minValue.toString()); } - } else if (command instanceof IncreaseDecreaseType) { + } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) { if (stepValue == null) { logger.debug("Value selector step value missing."); return; } - IncreaseDecreaseType type = (IncreaseDecreaseType) command; - if (increaseOnly != null && type == IncreaseDecreaseType.DECREASE && increaseOnly) { + if (increaseOnly != null && increaseDecreaseCommand == IncreaseDecreaseType.DECREASE && increaseOnly) { logger.debug("Value selector configured to allow increase only."); return; } Double currentValue = getStateDoubleValue(STATE_VALUE); if (currentValue != null) { - Double nextValue = currentValue + (type == IncreaseDecreaseType.INCREASE ? stepValue : -stepValue); + Double nextValue = currentValue + + (increaseDecreaseCommand == IncreaseDecreaseType.INCREASE ? stepValue : -stepValue); if (nextValue > maxValue) { nextValue = maxValue; } @@ -123,8 +123,8 @@ class LxControlValueSelector extends LxControl { } sendAction(nextValue.toString()); } - } else if (command instanceof PercentType) { - Double value = ((PercentType) command).doubleValue() * (maxValue - minValue) / 100.0 + minValue; + } else if (command instanceof PercentType percentCommand) { + Double value = percentCommand.doubleValue() * (maxValue - minValue) / 100.0 + minValue; sendAction(value.toString()); } } @@ -134,8 +134,8 @@ class LxControlValueSelector extends LxControl { logger.debug("Value selector min or max value missing or min>max."); return; } - if (command instanceof DecimalType) { - Double value = ((DecimalType) command).doubleValue(); + if (command instanceof DecimalType decimalCommand) { + Double value = decimalCommand.doubleValue(); if (value < minValue || value > maxValue) { logger.debug("Value {} out of {}-{} range", value, minValue, maxValue); return; diff --git a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/types/LxTags.java b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/types/LxTags.java index 8df468b5b..4fb94e7b1 100644 --- a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/types/LxTags.java +++ b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/types/LxTags.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.loxone.internal.types; -import java.util.Collections; import java.util.Set; import org.openhab.binding.loxone.internal.controls.LxControl; @@ -24,8 +23,8 @@ import org.openhab.binding.loxone.internal.controls.LxControl; * */ public class LxTags { - public static final Set SCENE = Collections.singleton("Scene"); - public static final Set LIGHTING = Collections.singleton("Lighting"); - public static final Set SWITCHABLE = Collections.singleton("Switchable"); - public static final Set TEMPERATURE = Collections.singleton("CurrentTemperature"); + public static final Set SCENE = Set.of("Scene"); + public static final Set LIGHTING = Set.of("Lighting"); + public static final Set SWITCHABLE = Set.of("Switchable"); + public static final Set TEMPERATURE = Set.of("CurrentTemperature"); } diff --git a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/types/LxUuid.java b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/types/LxUuid.java index 33b9a03a0..9447ead18 100644 --- a/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/types/LxUuid.java +++ b/bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/types/LxUuid.java @@ -56,7 +56,7 @@ public class LxUuid { this.uuid = init(uuid); } - public LxUuid(byte data[], int offset) { + public LxUuid(byte[] data, int offset) { String id = String.format("%08x-%04x-%04x-%02x%02x%02x%02x%02x%02x%02x%02x", ByteBuffer.wrap(data, offset, 4).order(ByteOrder.LITTLE_ENDIAN).getInt(), ByteBuffer.wrap(data, offset + 4, 2).order(ByteOrder.LITTLE_ENDIAN).getShort(), diff --git a/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlAlarmNoPresenceTest.java b/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlAlarmNoPresenceTest.java index d42070afa..470ffeb53 100644 --- a/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlAlarmNoPresenceTest.java +++ b/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlAlarmNoPresenceTest.java @@ -47,7 +47,7 @@ public class LxControlAlarmNoPresenceTest extends LxControlTest { static final String SENSORS_CHANNEL = " / Sensors"; static final String QUIT_CHANNEL = " / Acknowledge"; - private static final String NUMBER_CHANNELS[] = { NEXT_LEVEL_CHANNEL, NEXT_LEVEL_DELAY_CHANNEL, + private static final String[] NUMBER_CHANNELS = { NEXT_LEVEL_CHANNEL, NEXT_LEVEL_DELAY_CHANNEL, NEXT_LEVEL_DELAY_TOTAL_CHANNEL, LEVEL_CHANNEL, ARMED_DELAY_CHANNEL, ARMED_TOTAL_DELAY_CHANNEL }; @BeforeEach diff --git a/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlInfoOnlyAnalogTempTagTest.java b/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlInfoOnlyAnalogTempTagTest.java index 99c18f0d5..5de4a00a8 100644 --- a/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlInfoOnlyAnalogTempTagTest.java +++ b/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlInfoOnlyAnalogTempTagTest.java @@ -12,7 +12,7 @@ */ package org.openhab.binding.loxone.internal.controls; -import java.util.Collections; +import java.util.Set; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -37,6 +37,6 @@ public class LxControlInfoOnlyAnalogTempTagTest extends LxControlTest { @Test public void testChannels() { - testChannel("Number", null, null, null, null, "%.1f", true, null, Collections.singleton("CurrentTemperature")); + testChannel("Number", null, null, null, null, "%.1f", true, null, Set.of("CurrentTemperature")); } } diff --git a/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlJalousieTest.java b/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlJalousieTest.java index 1f6fe2255..1c96531c3 100644 --- a/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlJalousieTest.java +++ b/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlJalousieTest.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.loxone.internal.controls; -import java.util.Collections; import java.util.Set; import org.junit.jupiter.api.BeforeEach; @@ -48,8 +47,8 @@ public class LxControlJalousieTest extends LxControlTest { @Test public void testChannels() { - testChannel("Rollershutter", Collections.singleton("Blinds")); - Set tags = Collections.singleton("Switchable"); + testChannel("Rollershutter", Set.of("Blinds")); + Set tags = Set.of("Switchable"); testChannel("Switch", SHADE_CHANNEL, tags); testChannel("Switch", AUTO_SHADE_CHANNEL, tags); } diff --git a/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlLightControllerV2Test.java b/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlLightControllerV2Test.java index 0ffc01d6a..45f64ea9c 100644 --- a/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlLightControllerV2Test.java +++ b/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlLightControllerV2Test.java @@ -21,8 +21,8 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigDecimal; import java.util.ArrayList; -import java.util.Collections; import java.util.List; +import java.util.Set; import java.util.stream.Collectors; import org.junit.jupiter.api.BeforeEach; @@ -59,7 +59,7 @@ public class LxControlLightControllerV2Test extends LxControlTest { @Test public void testChannels() { - testChannel("Number", Collections.singleton("Scene")); + testChannel("Number", Set.of("Scene")); } @Test @@ -234,7 +234,7 @@ public class LxControlLightControllerV2Test extends LxControlTest { assertNotNull(min); assertNotNull(max); testChannel("Number", null, new BigDecimal(min), new BigDecimal(max), BigDecimal.ONE, null, false, options, - Collections.singleton("Scene")); + Set.of("Scene")); } private void testMood(String name, String id, boolean isStatic) { @@ -247,7 +247,7 @@ public class LxControlLightControllerV2Test extends LxControlTest { assertEquals(0, mood.getChannels().size()); } else { assertEquals(1, mood.getChannels().size()); - testChannel(mood, "Switch", Collections.singleton("Lighting")); + testChannel(mood, "Switch", Set.of("Lighting")); } } diff --git a/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlPushbuttonTest.java b/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlPushbuttonTest.java index 15d8ea4b6..5c80963e3 100644 --- a/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlPushbuttonTest.java +++ b/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlPushbuttonTest.java @@ -12,7 +12,7 @@ */ package org.openhab.binding.loxone.internal.controls; -import java.util.Collections; +import java.util.Set; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -43,7 +43,7 @@ public class LxControlPushbuttonTest extends LxControlSwitchTest { @Override @Test public void testChannels() { - testChannel("Switch", Collections.singleton("Switchable")); + testChannel("Switch", Set.of("Switchable")); } @Override diff --git a/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlSwitchTest.java b/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlSwitchTest.java index 688561867..199d97eb7 100644 --- a/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlSwitchTest.java +++ b/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlSwitchTest.java @@ -12,7 +12,7 @@ */ package org.openhab.binding.loxone.internal.controls; -import java.util.Collections; +import java.util.Set; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -41,7 +41,7 @@ public class LxControlSwitchTest extends LxControlTest { @Test public void testChannels() { - testChannel("Switch", Collections.singleton("Lighting")); + testChannel("Switch", Set.of("Lighting")); } @Test diff --git a/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlTimedSwitchTest.java b/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlTimedSwitchTest.java index cce385893..bc2a7af79 100644 --- a/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlTimedSwitchTest.java +++ b/bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlTimedSwitchTest.java @@ -13,7 +13,7 @@ package org.openhab.binding.loxone.internal.controls; import java.math.BigDecimal; -import java.util.Collections; +import java.util.Set; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -42,7 +42,7 @@ public class LxControlTimedSwitchTest extends LxControlTest { @Test public void testChannels() { - testChannel("Switch", Collections.singleton("Switchable")); + testChannel("Switch", Set.of("Switchable")); testChannel("Number", DELAY_CHANNEL, new BigDecimal(-1), null, null, null, true, null); } diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/LutronHandlerFactory.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/LutronHandlerFactory.java index 0e7de3746..0339ff3f1 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/LutronHandlerFactory.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/LutronHandlerFactory.java @@ -100,7 +100,7 @@ public class LutronHandlerFactory extends BaseThingHandlerFactory { // Used by the HwDiscoveryService public static final Set HW_DISCOVERABLE_DEVICE_TYPES_UIDS = Collections - .unmodifiableSet(Collections.singleton(HwConstants.THING_TYPE_HWDIMMER)); + .unmodifiableSet(Set.of(HwConstants.THING_TYPE_HWDIMMER)); // Other types that can be initiated but not discovered private static final Set SUPPORTED_THING_TYPES_UIDS = Collections @@ -143,8 +143,7 @@ public class LutronHandlerFactory extends BaseThingHandlerFactory { registerDiscoveryService(bridgeHandler); return bridgeHandler; } else if (thingTypeUID.equals(THING_TYPE_LEAPBRIDGE)) { - LeapBridgeHandler bridgeHandler = new LeapBridgeHandler((Bridge) thing); - return bridgeHandler; + return new LeapBridgeHandler((Bridge) thing); } else if (thingTypeUID.equals(THING_TYPE_DIMMER)) { return new DimmerHandler(thing); } else if (thingTypeUID.equals(THING_TYPE_SHADE)) { diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/action/DimmerActions.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/action/DimmerActions.java index 19e287f5f..a084c520b 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/action/DimmerActions.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/action/DimmerActions.java @@ -45,8 +45,8 @@ public class DimmerActions implements ThingActions { @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof DimmerHandler) { - this.handler = (DimmerHandler) handler; + if (handler instanceof DimmerHandler dimmerHandler) { + this.handler = dimmerHandler; } } diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/discovery/LeapDeviceDiscoveryService.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/discovery/LeapDeviceDiscoveryService.java index 3ea2add76..97edabcea 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/discovery/LeapDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/discovery/LeapDeviceDiscoveryService.java @@ -61,8 +61,8 @@ public class LeapDeviceDiscoveryService extends AbstractDiscoveryService @Override public void setThingHandler(ThingHandler handler) { - if (handler instanceof LeapBridgeHandler) { - bridgeHandler = (LeapBridgeHandler) handler; + if (handler instanceof LeapBridgeHandler leapBridgeHandler) { + bridgeHandler = leapBridgeHandler; bridgeHandler.setDiscoveryService(this); } } diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/discovery/LutronDeviceDiscoveryService.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/discovery/LutronDeviceDiscoveryService.java index 59b51f198..0e00a9924 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/discovery/LutronDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/discovery/LutronDeviceDiscoveryService.java @@ -240,10 +240,10 @@ public class LutronDeviceDiscoveryService extends AbstractDiscoveryService { context.push(area.getName()); for (DeviceNode deviceNode : area.getDeviceNodes()) { - if (deviceNode instanceof DeviceGroup) { - processDeviceGroup(area, (DeviceGroup) deviceNode, context); - } else if (deviceNode instanceof Device) { - processDevice(area, (Device) deviceNode, context); + if (deviceNode instanceof DeviceGroup group) { + processDeviceGroup(area, group, context); + } else if (deviceNode instanceof Device device) { + processDevice(area, device, context); } } diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/discovery/LutronMcastBridgeDiscoveryService.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/discovery/LutronMcastBridgeDiscoveryService.java index 4a0475236..0cedb5701 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/discovery/LutronMcastBridgeDiscoveryService.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/discovery/LutronMcastBridgeDiscoveryService.java @@ -20,7 +20,6 @@ import java.net.InetAddress; import java.net.MulticastSocket; import java.net.SocketTimeoutException; import java.nio.charset.StandardCharsets; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -56,7 +55,7 @@ public class LutronMcastBridgeDiscoveryService extends AbstractDiscoveryService private static final int SCAN_INTERVAL_MINUTES = 30; private static final int SCAN_TIMEOUT_MS = 2000; - private static final Set BRIDGE_TYPE_UID = Collections.singleton(THING_TYPE_IPBRIDGE); + private static final Set BRIDGE_TYPE_UID = Set.of(THING_TYPE_IPBRIDGE); private static final String GROUP_ADDRESS = "224.0.37.42"; private static final byte[] QUERY_DATA = "".getBytes(StandardCharsets.US_ASCII); diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/discovery/LutronMdnsBridgeDiscoveryService.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/discovery/LutronMdnsBridgeDiscoveryService.java index 55c8dd1de..182a3a4f8 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/discovery/LutronMdnsBridgeDiscoveryService.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/discovery/LutronMdnsBridgeDiscoveryService.java @@ -15,7 +15,6 @@ package org.openhab.binding.lutron.internal.discovery; import static org.openhab.binding.lutron.internal.LutronBindingConstants.*; import java.net.InetAddress; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -72,7 +71,7 @@ public class LutronMdnsBridgeDiscoveryService implements MDNSDiscoveryParticipan @Override public Set getSupportedThingTypeUIDs() { - return Collections.singleton(THING_TYPE_IPBRIDGE); + return Set.of(THING_TYPE_IPBRIDGE); } @Override diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/grxprg/GrafikEyeHandler.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/grxprg/GrafikEyeHandler.java index 9a735f20d..f160eb079 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/grxprg/GrafikEyeHandler.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/grxprg/GrafikEyeHandler.java @@ -106,8 +106,8 @@ public class GrafikEyeHandler extends BaseThingHandler { } if (id.equals(PrgConstants.CHANNEL_SCENE)) { - if (command instanceof DecimalType) { - final int scene = ((DecimalType) command).intValue(); + if (command instanceof DecimalType sceneCommand) { + final int scene = sceneCommand.intValue(); getProtocolHandler().selectScene(config.getControlUnit(), scene); } else { logger.error("Received a SCENE command with a non DecimalType: {}", command); @@ -143,8 +143,8 @@ public class GrafikEyeHandler extends BaseThingHandler { getProtocolHandler().setZoneRaise(config.getControlUnit(), zone); } } else if (id.equals(PrgConstants.CHANNEL_ZONEFADE)) { - if (command instanceof DecimalType) { - setFade(((DecimalType) command).intValue()); + if (command instanceof DecimalType zoneFade) { + setFade(zoneFade.intValue()); } else { logger.error("Received a ZONEFADE command with a non DecimalType: {}", command); } @@ -152,8 +152,8 @@ public class GrafikEyeHandler extends BaseThingHandler { final Integer zone = getTrailingNbr(id, PrgConstants.CHANNEL_ZONEINTENSITY); if (zone != null) { - if (command instanceof PercentType) { - final int intensity = ((PercentType) command).intValue(); + if (command instanceof PercentType intensityPercent) { + final int intensity = intensityPercent.intValue(); getProtocolHandler().setZoneIntensity(config.getControlUnit(), zone, fade, intensity); } else if (command instanceof OnOffType) { getProtocolHandler().setZoneIntensity(config.getControlUnit(), zone, fade, diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/grxprg/PrgBridgeHandler.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/grxprg/PrgBridgeHandler.java index b5421716c..a7b903eeb 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/grxprg/PrgBridgeHandler.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/grxprg/PrgBridgeHandler.java @@ -165,15 +165,15 @@ public class PrgBridgeHandler extends BaseBridgeHandler { } else if (id.equals(PrgConstants.CHANNEL_ZONERAISESTOP)) { protocolHandler.setZoneRaiseStop(); } else if (id.equals(PrgConstants.CHANNEL_TIMECLOCK)) { - if (command instanceof DateTimeType) { - final ZonedDateTime zdt = ((DateTimeType) command).getZonedDateTime(); + if (command instanceof DateTimeType dateTime) { + final ZonedDateTime zdt = dateTime.getZonedDateTime(); protocolHandler.setTime(GregorianCalendar.from(zdt)); } else { logger.error("Received a TIMECLOCK channel command with a non DateTimeType: {}", command); } } else if (id.startsWith(PrgConstants.CHANNEL_SCHEDULE)) { - if (command instanceof DecimalType) { - final int schedule = ((DecimalType) command).intValue(); + if (command instanceof DecimalType scheduleCommand) { + final int schedule = scheduleCommand.intValue(); protocolHandler.selectSchedule(schedule); } else { logger.error("Received a SCHEDULE channel command with a non DecimalType: {}", command); diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/grxprg/PrgProtocolHandler.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/grxprg/PrgProtocolHandler.java index 6154205c1..25ed07ed8 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/grxprg/PrgProtocolHandler.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/grxprg/PrgProtocolHandler.java @@ -283,7 +283,7 @@ class PrgProtocolHandler { session.setCallback(callback); String response = callback.getResponse(); - if (response.equals("login")) { + if ("login".equals(response)) { session.sendCommand(username); } else { return "Protocol violation - wasn't initially a command failure or login prompt: " + response; @@ -293,7 +293,7 @@ class PrgProtocolHandler { response = callback.getResponse(); // Burn the empty response if we got one ( - if (response.equals("")) { + if ("".equals(response)) { response = callback.getResponse(); } @@ -928,7 +928,7 @@ class PrgProtocolHandler { throw new IllegalArgumentException("m (matcher) cannot be null"); } if (m.groupCount() == 5) { - if (m.group(1).equals("255")) { + if ("255".equals(m.group(1))) { logger.warn("Sunrise/Sunset needs to be enabled via Liason Software"); return; } @@ -995,7 +995,7 @@ class PrgProtocolHandler { final int controlUnit = Integer.parseInt(m.group(1)); for (int z = 1; z <= 8; z++) { final String zi = m.group(z + 1); - if (zi.equals("*") || zi.equals(Integer.toString(z - 1))) { + if ("*".equals(zi) || zi.equals(Integer.toString(z - 1))) { continue; // not present } final int zid = convertIntensity(controlUnit, z, zi); @@ -1196,10 +1196,10 @@ class PrgProtocolHandler { */ String getResponse() throws Exception { final Object lastResponse = responses.poll(5, TimeUnit.SECONDS); - if (lastResponse instanceof String) { - return (String) lastResponse; - } else if (lastResponse instanceof Exception) { - throw (Exception) lastResponse; + if (lastResponse instanceof String str) { + return str; + } else if (lastResponse instanceof Exception exception) { + throw exception; } else if (lastResponse == null) { throw new Exception("Didn't receive response in time"); } else { diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/grxprg/SocketSession.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/grxprg/SocketSession.java index 42d3a58ef..d86093b2c 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/grxprg/SocketSession.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/grxprg/SocketSession.java @@ -361,16 +361,16 @@ public class SocketSession { final Object response = responsesQueue.poll(1, TimeUnit.SECONDS); if (response != null) { - if (response instanceof String) { + if (response instanceof String str) { try { logger.debug("Dispatching response: {}", response); - ssCallback.responseReceived((String) response); + ssCallback.responseReceived(str); } catch (Exception e) { logger.warn("Exception occurred processing the response '{}': ", response, e); } - } else if (response instanceof Exception) { + } else if (response instanceof Exception exception) { logger.debug("Dispatching exception: {}", response); - ssCallback.responseException((Exception) response); + ssCallback.responseException(exception); } else { logger.error("Unknown response class: {}", response); } diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/BlindHandler.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/BlindHandler.java index c206f3cdc..c8b307635 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/BlindHandler.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/BlindHandler.java @@ -116,8 +116,8 @@ public class BlindHandler extends LutronHandler { } private void handleLiftCommand(Command command) { - if (command instanceof PercentType) { - int level = ((PercentType) command).intValue(); + if (command instanceof PercentType liftPercent) { + int level = liftPercent.intValue(); output(TargetType.BLIND, OutputCommand.ACTION_LIFTLEVEL, level, null, null); } else if (command.equals(UpDownType.UP)) { output(TargetType.BLIND, OutputCommand.ACTION_STARTRAISINGLIFT, null, null, null); @@ -131,8 +131,8 @@ public class BlindHandler extends LutronHandler { } private void handleTiltCommand(Command command) { - if (command instanceof PercentType) { - int level = ((PercentType) command).intValue(); + if (command instanceof PercentType tiltPercent) { + int level = tiltPercent.intValue(); output(TargetType.BLIND, OutputCommand.ACTION_TILTLEVEL, Math.min(level, tiltMax), null, null); } else if (command.equals(UpDownType.UP)) { output(TargetType.BLIND, OutputCommand.ACTION_STARTRAISINGTILT, null, null, null); diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/DimmerHandler.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/DimmerHandler.java index 3c8afd4c6..9fc40e9f9 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/DimmerHandler.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/DimmerHandler.java @@ -16,7 +16,7 @@ import static org.openhab.binding.lutron.internal.LutronBindingConstants.CHANNEL import java.math.BigDecimal; import java.util.Collection; -import java.util.Collections; +import java.util.List; import java.util.concurrent.atomic.AtomicReference; import org.openhab.binding.lutron.internal.action.DimmerActions; @@ -56,7 +56,7 @@ public class DimmerHandler extends LutronHandler { @Override public Collection> getServices() { - return Collections.singletonList(DimmerActions.class); + return List.of(DimmerActions.class); } @Override @@ -109,8 +109,8 @@ public class DimmerHandler extends LutronHandler { @Override public void handleCommand(ChannelUID channelUID, Command command) { if (channelUID.getId().equals(CHANNEL_LIGHTLEVEL)) { - if (command instanceof Number) { - int level = ((Number) command).intValue(); + if (command instanceof Number number) { + int level = number.intValue(); output(TargetType.DIMMER, OutputCommand.ACTION_ZONELEVEL, level, new LutronDuration("0.25"), null); } else if (command.equals(OnOffType.ON)) { if (config.onToLast) { diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/FanHandler.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/FanHandler.java index 819e430f7..dde63685c 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/FanHandler.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/FanHandler.java @@ -97,8 +97,8 @@ public class FanHandler extends LutronHandler { @Override public void handleCommand(ChannelUID channelUID, Command command) { if (channelUID.getId().equals(CHANNEL_FANLEVEL)) { - if (command instanceof Number) { - int level = ((Number) command).intValue(); + if (command instanceof Number number) { + int level = number.intValue(); FanSpeedType speed = FanSpeedType.toFanSpeedType(level); // output(TargetType.FAN, LutronCommand.ACTION_ZONELEVEL, level, null, null); sendCommand(new OutputCommand(TargetType.FAN, LutronOperation.EXECUTE, getIntegrationId(), diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/GreenModeHandler.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/GreenModeHandler.java index 10191f7e2..24ec7e143 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/GreenModeHandler.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/GreenModeHandler.java @@ -141,8 +141,8 @@ public class GreenModeHandler extends LutronHandler { greenMode(ModeCommand.ACTION_STEP, 2); } else if (command == OnOffType.OFF) { greenMode(ModeCommand.ACTION_STEP, 1); - } else if (command instanceof Number) { - Integer step = ((Number) command).intValue(); + } else if (command instanceof Number number) { + Integer step = number.intValue(); if (step.intValue() >= GREENSTEP_MIN) { greenMode(ModeCommand.ACTION_STEP, step); } diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/IPBridgeHandler.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/IPBridgeHandler.java index d5222bf4d..6b78dcc43 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/IPBridgeHandler.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/IPBridgeHandler.java @@ -344,7 +344,7 @@ public class IPBridgeHandler extends LutronBridgeHandler { String scrubbedLine; for (String line : this.session.readLines()) { - if (line.trim().equals("")) { + if ("".equals(line.trim())) { // Sometimes we get an empty line (possibly only when prompts are disabled). Ignore them. continue; } diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/QSIOHandler.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/QSIOHandler.java index 97dc98994..97e7a40ac 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/QSIOHandler.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/QSIOHandler.java @@ -30,7 +30,7 @@ import org.slf4j.LoggerFactory; @NonNullByDefault public class QSIOHandler extends BaseKeypadHandler { - private static enum Component implements KeypadComponent { + private enum Component implements KeypadComponent { CCI1(1, "cci1", "CCI 1", ComponentType.CCI), CCI2(2, "cci2", "CCI 2", ComponentType.CCI), CCI3(3, "cci3", "CCI 3", ComponentType.CCI), diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/ShadeHandler.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/ShadeHandler.java index 8becfdfbf..8a841e8f6 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/ShadeHandler.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/ShadeHandler.java @@ -100,8 +100,8 @@ public class ShadeHandler extends LutronHandler { @Override public void handleCommand(ChannelUID channelUID, Command command) { if (channelUID.getId().equals(CHANNEL_SHADELEVEL)) { - if (command instanceof PercentType) { - int level = ((PercentType) command).intValue(); + if (command instanceof PercentType shadePercent) { + int level = shadePercent.intValue(); output(TargetType.SHADE, OutputCommand.ACTION_ZONELEVEL, level, null, null); if (leap) { // LEAP may not send back a position update diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/SysvarHandler.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/SysvarHandler.java index 4c1c431bd..888a84e4e 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/SysvarHandler.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/SysvarHandler.java @@ -97,8 +97,8 @@ public class SysvarHandler extends LutronHandler { @Override public void handleCommand(ChannelUID channelUID, Command command) { if (channelUID.getId().equals(CHANNEL_VARSTATE)) { - if (command instanceof Number) { - int state = ((Number) command).intValue(); + if (command instanceof Number number) { + int state = number.intValue(); sysvar(SysvarCommand.ACTION_GETSETSYSVAR, state); } } diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/TimeclockHandler.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/TimeclockHandler.java index 4651426e3..093a32d5b 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/TimeclockHandler.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/TimeclockHandler.java @@ -95,8 +95,8 @@ public class TimeclockHandler extends LutronHandler { logger.debug("Handling timeclock command {} on channel {}", command, channelID); if (channelUID.getId().equals(CHANNEL_CLOCKMODE)) { - if (command instanceof DecimalType) { - Integer mode = ((DecimalType) command).intValue(); + if (command instanceof DecimalType decimalCommand) { + Integer mode = decimalCommand.intValue(); timeclock(TimeclockCommand.ACTION_CLOCKMODE, mode, null); } else if (command instanceof RefreshType) { queryTimeclock(TimeclockCommand.ACTION_CLOCKMODE); @@ -104,8 +104,8 @@ public class TimeclockHandler extends LutronHandler { logger.debug("Invalid command type for clockmode channnel"); } } else if (channelUID.getId().equals(CHANNEL_EXECEVENT)) { - if (command instanceof DecimalType) { - Integer index = ((DecimalType) command).intValue(); + if (command instanceof DecimalType decimalCommand) { + Integer index = decimalCommand.intValue(); timeclock(TimeclockCommand.ACTION_EXECEVENT, index, null); } else { logger.debug("Invalid command type for execevent channnel"); @@ -123,15 +123,15 @@ public class TimeclockHandler extends LutronHandler { logger.debug("Invalid command type for sunset channnel"); } } else if (channelUID.getId().equals(CHANNEL_ENABLEEVENT)) { - if (command instanceof DecimalType) { - Integer index = ((DecimalType) command).intValue(); + if (command instanceof DecimalType decimalCommand) { + Integer index = decimalCommand.intValue(); timeclock(TimeclockCommand.ACTION_SETEVENT, index, true); } else { logger.debug("Invalid command type for enableevent channnel"); } } else if (channelUID.getId().equals(CHANNEL_DISABLEEVENT)) { - if (command instanceof DecimalType) { - Integer index = ((DecimalType) command).intValue(); + if (command instanceof DecimalType decimalCommand) { + Integer index = decimalCommand.intValue(); timeclock(TimeclockCommand.ACTION_SETEVENT, index, false); } else { logger.debug("Invalid command type for disableevent channnel"); diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/VcrxHandler.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/VcrxHandler.java index 38c101c3d..f83a0525a 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/VcrxHandler.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/VcrxHandler.java @@ -31,7 +31,7 @@ import org.slf4j.LoggerFactory; @NonNullByDefault public class VcrxHandler extends BaseKeypadHandler { - private static enum Component implements KeypadComponent { + private enum Component implements KeypadComponent { BUTTON1(1, "button1", "Button 1", ComponentType.BUTTON), BUTTON2(2, "button2", "Button 2", ComponentType.BUTTON), BUTTON3(3, "button3", "Button 3", ComponentType.BUTTON), diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/WciHandler.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/WciHandler.java index f3fabb631..d4ac8d2df 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/WciHandler.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/handler/WciHandler.java @@ -31,7 +31,7 @@ import org.slf4j.LoggerFactory; @NonNullByDefault public class WciHandler extends BaseKeypadHandler { - private static enum Component implements KeypadComponent { + private enum Component implements KeypadComponent { BUTTON1(1, "button1", "Button 1", ComponentType.BUTTON), BUTTON2(2, "button2", "Button 2", ComponentType.BUTTON), BUTTON3(3, "button3", "Button 3", ComponentType.BUTTON), diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/hw/HwDimmerHandler.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/hw/HwDimmerHandler.java index 6fa2e682a..38cb575ee 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/hw/HwDimmerHandler.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/hw/HwDimmerHandler.java @@ -68,8 +68,8 @@ public class HwDimmerHandler extends BaseThingHandler { @Override public void handleCommand(ChannelUID channelUID, Command command) { if (channelUID.getId().equals(CHANNEL_LIGHTLEVEL)) { - if (command instanceof Number) { - int level = ((Number) command).intValue(); + if (command instanceof Number number) { + int level = number.intValue(); outputLevel(level); } else if (command.equals(OnOffType.ON)) { outputLevel(defaultLevel); diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/hw/HwDiscoveryService.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/hw/HwDiscoveryService.java index ab1f12f5d..cd27c2bbe 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/hw/HwDiscoveryService.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/hw/HwDiscoveryService.java @@ -51,8 +51,8 @@ public class HwDiscoveryService extends AbstractDiscoveryService implements Disc @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof HwSerialBridgeHandler) { - this.handler = (HwSerialBridgeHandler) handler; + if (handler instanceof HwSerialBridgeHandler bridgeHandler) { + this.handler = bridgeHandler; this.handler.setDiscoveryService(this); } } @@ -102,7 +102,7 @@ public class HwDiscoveryService extends AbstractDiscoveryService implements Disc logger.info("Discovered HomeWorks dimmer with no address"); return; } - String addressUid = address.replaceAll("[\\[\\]]", "").replaceAll(":", "-"); + String addressUid = address.replaceAll("[\\[\\]]", "").replace(":", "-"); ThingUID bridgeUID = this.handler.getThing().getUID(); ThingUID uid = new ThingUID(HwConstants.THING_TYPE_HWDIMMER, bridgeUID, addressUid); diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/hw/HwSerialBridgeHandler.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/hw/HwSerialBridgeHandler.java index 07076a029..63e96b7b5 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/hw/HwSerialBridgeHandler.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/hw/HwSerialBridgeHandler.java @@ -19,7 +19,7 @@ import java.io.OutputStreamWriter; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Collection; -import java.util.Collections; +import java.util.Set; import java.util.TooManyListenersException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -175,7 +175,7 @@ public class HwSerialBridgeHandler extends BaseBridgeHandler implements SerialPo @Override public Collection> getServices() { - return Collections.singleton(HwDiscoveryService.class); + return Set.of(HwDiscoveryService.class); } @Override diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfig.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfig.java index ac23e728b..7b7d218f5 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfig.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfig.java @@ -133,7 +133,7 @@ public abstract class KeypadConfig { * @return Concatenated list */ @SafeVarargs - protected static final List combinedList(final List... lists) { + protected static List combinedList(final List... lists) { List newlist = new LinkedList<>(); for (List list : lists) { newlist.addAll(list); diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfigGrafikEye.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfigGrafikEye.java index 1dbed5f85..a2a110817 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfigGrafikEye.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfigGrafikEye.java @@ -27,7 +27,7 @@ import org.openhab.binding.lutron.internal.discovery.project.ComponentType; @NonNullByDefault public final class KeypadConfigGrafikEye extends KeypadConfig { - private static enum Component implements KeypadComponent { + private enum Component implements KeypadComponent { BUTTON1(70, "button1", "Button 1", ComponentType.BUTTON), // Scene button 1 BUTTON2(71, "button2", "Button 2", ComponentType.BUTTON), // Scene button 2 BUTTON3(76, "button3", "Button 3", ComponentType.BUTTON), // Scene button 3 diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfigIntlSeetouch.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfigIntlSeetouch.java index 606d4fee1..c26f0b213 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfigIntlSeetouch.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfigIntlSeetouch.java @@ -26,7 +26,7 @@ import org.openhab.binding.lutron.internal.discovery.project.ComponentType; @NonNullByDefault public final class KeypadConfigIntlSeetouch extends KeypadConfig { - private static enum Component implements KeypadComponent { + private enum Component implements KeypadComponent { BUTTON1(1, "button1", "Button 1", ComponentType.BUTTON), BUTTON2(2, "button2", "Button 2", ComponentType.BUTTON), BUTTON3(3, "button3", "Button 3", ComponentType.BUTTON), diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfigPalladiom.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfigPalladiom.java index 875ef4fcf..8a86e5409 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfigPalladiom.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfigPalladiom.java @@ -26,7 +26,7 @@ import org.openhab.binding.lutron.internal.discovery.project.ComponentType; @NonNullByDefault public final class KeypadConfigPalladiom extends KeypadConfig { - private static enum Component implements KeypadComponent { + private enum Component implements KeypadComponent { BUTTON1(1, "button1", "Button 1", ComponentType.BUTTON), BUTTON2(2, "button2", "Button 2", ComponentType.BUTTON), BUTTON3(3, "button3", "Button 3", ComponentType.BUTTON), diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfigPico.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfigPico.java index b2ad68175..6193f74f5 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfigPico.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfigPico.java @@ -34,7 +34,7 @@ public final class KeypadConfigPico extends KeypadConfig { public static final Map LEAPBUTTONS_4B = Map.of(8, 1, 9, 2, 10, 3, 11, 4); public static final Map LEAPBUTTONS_3BRL = Map.of(2, 1, 3, 2, 4, 3, 5, 4, 6, 5); - private static enum Component implements KeypadComponent { + private enum Component implements KeypadComponent { // Buttons for 2B, 2BRL, 3B, and 3BRL models BUTTON1(2, "button1", "Button 1", ComponentType.BUTTON), BUTTON2(3, "button2", "Button 2", ComponentType.BUTTON), diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfigSeetouch.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfigSeetouch.java index 0c359da00..863a3edc5 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfigSeetouch.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfigSeetouch.java @@ -26,7 +26,7 @@ import org.openhab.binding.lutron.internal.discovery.project.ComponentType; @NonNullByDefault public final class KeypadConfigSeetouch extends KeypadConfig { - private static enum Component implements KeypadComponent { + private enum Component implements KeypadComponent { BUTTON1(1, "button1", "Button 1", ComponentType.BUTTON), BUTTON2(2, "button2", "Button 2", ComponentType.BUTTON), BUTTON3(3, "button3", "Button 3", ComponentType.BUTTON), diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfigTabletopSeetouch.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfigTabletopSeetouch.java index f2fa5826b..91aad39d5 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfigTabletopSeetouch.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/keypadconfig/KeypadConfigTabletopSeetouch.java @@ -27,7 +27,7 @@ import org.openhab.binding.lutron.internal.discovery.project.ComponentType; @NonNullByDefault public final class KeypadConfigTabletopSeetouch extends KeypadConfig { - private static enum Component implements KeypadComponent { + private enum Component implements KeypadComponent { BUTTON1(1, "button1", "Button 1", ComponentType.BUTTON), BUTTON2(2, "button2", "Button 2", ComponentType.BUTTON), BUTTON3(3, "button3", "Button 3", ComponentType.BUTTON), diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/protocol/LIPCommand.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/protocol/LIPCommand.java index 39946c8e5..9997ca97e 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/protocol/LIPCommand.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/protocol/LIPCommand.java @@ -61,8 +61,7 @@ public class LIPCommand extends LutronCommandNew { } public int getNumberParameter(int position) { - if (parameters.length > position && parameters[position] instanceof Number) { - Number num = (Number) parameters[position]; + if (parameters.length > position && parameters[position] instanceof Number num) { return num.intValue(); } else { throw new IllegalArgumentException("Invalid command parameter"); diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/protocol/leap/LeapMessageParser.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/protocol/leap/LeapMessageParser.java index 8c9fe5a54..5bcbae934 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/protocol/leap/LeapMessageParser.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/protocol/leap/LeapMessageParser.java @@ -70,7 +70,7 @@ public class LeapMessageParser { * @param msg String containing the LEAP message */ public void handleMessage(String msg) { - if (msg.trim().equals("")) { + if ("".equals(msg.trim())) { return; // Ignore empty lines } logger.trace("Received message: {}", msg); diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/protocol/leap/Request.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/protocol/leap/Request.java index 8078b6619..f8681abc0 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/protocol/leap/Request.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/protocol/leap/Request.java @@ -25,56 +25,76 @@ public class Request { public static final String BUTTON_GROUP_URL = "/buttongroup"; public static String goToLevel(int zone, int value) { - String request = "{\"CommuniqueType\": \"CreateRequest\"," - + "\"Header\": {\"Url\": \"/zone/%d/commandprocessor\"}," + "\"Body\": {" + "\"Command\": {" - + "\"CommandType\": \"GoToLevel\"," + "\"Parameter\": [{\"Type\": \"Level\", \"Value\": %d}]}}}"; + String request = """ + {"CommuniqueType": "CreateRequest",\ + "Header": {"Url": "/zone/%d/commandprocessor"},\ + "Body": {\ + "Command": {\ + "CommandType": "GoToLevel",\ + "Parameter": [{"Type": "Level", "Value": %d}]}}}\ + """; return String.format(request, zone, value); } /** fadeTime must be in the format hh:mm:ss **/ public static String goToDimmedLevel(int zone, int value, String fadeTime) { - String request = "{\"CommuniqueType\": \"CreateRequest\"," - + "\"Header\": {\"Url\": \"/zone/%d/commandprocessor\"},\"Body\": {\"Command\": {" - + "\"CommandType\": \"GoToDimmedLevel\"," - + "\"DimmedLevelParameters\": {\"Level\": %d, \"FadeTime\": \"%s\"}}}}"; + String request = """ + {"CommuniqueType": "CreateRequest",\ + "Header": {"Url": "/zone/%d/commandprocessor"},"Body": {"Command": {\ + "CommandType": "GoToDimmedLevel",\ + "DimmedLevelParameters": {"Level": %d, "FadeTime": "%s"}}}}\ + """; return String.format(request, zone, value, fadeTime); } /** fadeTime and delayTime must be in the format hh:mm:ss **/ public static String goToDimmedLevel(int zone, int value, String fadeTime, String delayTime) { - String request = "{\"CommuniqueType\": \"CreateRequest\"," - + "\"Header\": {\"Url\": \"/zone/%d/commandprocessor\"},\"Body\": {\"Command\": {" - + "\"CommandType\": \"GoToDimmedLevel\"," - + "\"DimmedLevelParameters\": {\"Level\": %d, \"FadeTime\": \"%s\", \"DelayTime\": \"%s\"}}}}"; + String request = """ + {"CommuniqueType": "CreateRequest",\ + "Header": {"Url": "/zone/%d/commandprocessor"},"Body": {"Command": {\ + "CommandType": "GoToDimmedLevel",\ + "DimmedLevelParameters": {"Level": %d, "FadeTime": "%s", "DelayTime": "%s"}}}}\ + """; return String.format(request, zone, value, fadeTime, delayTime); } public static String goToFanSpeed(int zone, FanSpeedType fanSpeed) { - String request = "{\"CommuniqueType\": \"CreateRequest\"," - + "\"Header\": {\"Url\": \"/zone/%d/commandprocessor\"}," + "\"Body\": {" - + "\"Command\": {\"CommandType\": \"GoToFanSpeed\"," - + "\"FanSpeedParameters\": {\"FanSpeed\": \"%s\"}}}}"; + String request = """ + {"CommuniqueType": "CreateRequest",\ + "Header": {"Url": "/zone/%d/commandprocessor"},\ + "Body": {\ + "Command": {"CommandType": "GoToFanSpeed",\ + "FanSpeedParameters": {"FanSpeed": "%s"}}}}\ + """; return String.format(request, zone, fanSpeed.leapValue()); } public static String buttonCommand(int button, CommandType command) { - String request = "{\"CommuniqueType\": \"CreateRequest\"," - + "\"Header\": {\"Url\": \"/button/%d/commandprocessor\"}," - + "\"Body\": {\"Command\": {\"CommandType\": \"%s\"}}}"; + String request = """ + {"CommuniqueType": "CreateRequest",\ + "Header": {"Url": "/button/%d/commandprocessor"},\ + "Body": {"Command": {"CommandType": "%s"}}}\ + """; return String.format(request, button, command.toString()); } public static String virtualButtonCommand(int virtualbutton, CommandType command) { - String request = "{\"CommuniqueType\": \"CreateRequest\"," - + "\"Header\": {\"Url\": \"/virtualbutton/%d/commandprocessor\"}," - + "\"Body\": {\"Command\": {\"CommandType\": \"%s\"}}}"; + String request = """ + {"CommuniqueType": "CreateRequest",\ + "Header": {"Url": "/virtualbutton/%d/commandprocessor"},\ + "Body": {"Command": {"CommandType": "%s"}}}\ + """; return String.format(request, virtualbutton, command.toString()); } public static String zoneCommand(int zone, CommandType commandType) { - String request = "{\"CommuniqueType\": \"CreateRequest\"," - + "\"Header\": {\"Url\": \"/zone/%d/commandprocessor\"}," + "\"Body\": {" + "\"Command\": {" - + "\"CommandType\": \"%s\"}}}"; + String request = """ + {"CommuniqueType": "CreateRequest",\ + "Header": {"Url": "/zone/%d/commandprocessor"},\ + "Body": {\ + "Command": {\ + "CommandType": "%s"}}}\ + """; return String.format(request, zone, commandType.toString()); } diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/protocol/lip/TargetType.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/protocol/lip/TargetType.java index d694e0298..facbca103 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/protocol/lip/TargetType.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/protocol/lip/TargetType.java @@ -33,5 +33,5 @@ public enum TargetType { SWITCH, SYSVAR, TIMECLOCK, - VIRTUALKEYPAD; + VIRTUALKEYPAD } diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/RS232Connection.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/RS232Connection.java index 967bf672e..1a3e5fed1 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/RS232Connection.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/RS232Connection.java @@ -82,7 +82,7 @@ public class RS232Connection implements RadioRAConnection, SerialPortEventListen @Override public void write(String command) { - logger.debug("Writing to serial port: {}", command.toString()); + logger.debug("Writing to serial port: {}", command); SerialPort serialPort = this.serialPort; try { diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/handler/DimmerHandler.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/handler/DimmerHandler.java index 1d92b781c..f231403b5 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/handler/DimmerHandler.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/handler/DimmerHandler.java @@ -65,8 +65,8 @@ public class DimmerHandler extends LutronHandler { } if (LutronBindingConstants.CHANNEL_LIGHTLEVEL.equals(channelUID.getId())) { - if (command instanceof PercentType) { - int intensity = ((PercentType) command).intValue(); + if (command instanceof PercentType percentCommand) { + int intensity = percentCommand.intValue(); SetDimmerLevelCommand cmd = new SetDimmerLevelCommand(config.getZoneNumber(), intensity, config.system); bridgeHandler.sendCommand(cmd); @@ -74,9 +74,7 @@ public class DimmerHandler extends LutronHandler { updateInternalState(intensity); } - if (command instanceof OnOffType) { - OnOffType onOffCmd = (OnOffType) command; - + if (command instanceof OnOffType onOffCmd) { SetSwitchLevelCommand cmd = new SetSwitchLevelCommand(config.getZoneNumber(), onOffCmd, config.system); bridgeHandler.sendCommand(cmd); @@ -87,10 +85,10 @@ public class DimmerHandler extends LutronHandler { @Override public void handleFeedback(RadioRAFeedback feedback) { - if (feedback instanceof LocalZoneChangeFeedback) { - handleLocalZoneChangeFeedback((LocalZoneChangeFeedback) feedback); - } else if (feedback instanceof ZoneMapFeedback) { - handleZoneMapFeedback((ZoneMapFeedback) feedback); + if (feedback instanceof LocalZoneChangeFeedback localZoneChangeFeedback) { + handleLocalZoneChangeFeedback(localZoneChangeFeedback); + } else if (feedback instanceof ZoneMapFeedback zoneMapFeedback) { + handleZoneMapFeedback(zoneMapFeedback); } } diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/handler/LutronHandler.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/handler/LutronHandler.java index af185ca69..3b35e74cb 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/handler/LutronHandler.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/handler/LutronHandler.java @@ -42,8 +42,8 @@ public abstract class LutronHandler extends BaseThingHandler { return null; } ThingHandler th = bridge.getHandler(); - if (th instanceof RS232Handler) { - return (RS232Handler) th; + if (th instanceof RS232Handler handler) { + return handler; } else { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Bridge not properly configured."); return null; diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/handler/PhantomButtonHandler.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/handler/PhantomButtonHandler.java index de8d7db84..dbe622406 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/handler/PhantomButtonHandler.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/handler/PhantomButtonHandler.java @@ -60,8 +60,8 @@ public class PhantomButtonHandler extends LutronHandler { @Override public void handleFeedback(RadioRAFeedback feedback) { - if (feedback instanceof LEDMapFeedback) { - handleLEDMapFeedback((LEDMapFeedback) feedback); + if (feedback instanceof LEDMapFeedback ledMapFeedback) { + handleLEDMapFeedback(ledMapFeedback); } } diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/handler/RS232Handler.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/handler/RS232Handler.java index dfa99e086..9e11fb182 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/handler/RS232Handler.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/handler/RS232Handler.java @@ -119,8 +119,8 @@ public class RS232Handler extends BaseBridgeHandler implements RadioRAFeedbackLi public void handleRadioRAFeedback(RadioRAFeedback feedback) { for (Thing thing : getThing().getThings()) { ThingHandler handler = thing.getHandler(); - if (handler instanceof LutronHandler) { - ((LutronHandler) handler).handleFeedback(feedback); + if (handler instanceof LutronHandler lutronHandler) { + lutronHandler.handleFeedback(feedback); } else { logger.debug("Unexpected - Thing {} is not a LutronHandler", thing.getClass()); } diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/handler/SwitchHandler.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/handler/SwitchHandler.java index 9f775234a..350233d2b 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/handler/SwitchHandler.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/handler/SwitchHandler.java @@ -52,8 +52,8 @@ public class SwitchHandler extends LutronHandler { public void handleCommand(ChannelUID channelUID, Command command) { RS232Handler bridgeHandler = getRS232Handler(); if (LutronBindingConstants.CHANNEL_SWITCH.equals(channelUID.getId())) { - if (command instanceof OnOffType) { - SetSwitchLevelCommand cmd = new SetSwitchLevelCommand(config.getZoneNumber(), (OnOffType) command, + if (command instanceof OnOffType onOffCommand) { + SetSwitchLevelCommand cmd = new SetSwitchLevelCommand(config.getZoneNumber(), onOffCommand, config.system); if (bridgeHandler != null) { @@ -65,10 +65,10 @@ public class SwitchHandler extends LutronHandler { @Override public void handleFeedback(RadioRAFeedback feedback) { - if (feedback instanceof LocalZoneChangeFeedback) { - handleLocalZoneChangeFeedback((LocalZoneChangeFeedback) feedback); - } else if (feedback instanceof ZoneMapFeedback) { - handleZoneMapFeedback((ZoneMapFeedback) feedback); + if (feedback instanceof LocalZoneChangeFeedback localZoneChangeFeedback) { + handleLocalZoneChangeFeedback(localZoneChangeFeedback); + } else if (feedback instanceof ZoneMapFeedback zoneMapFeedback) { + handleZoneMapFeedback(zoneMapFeedback); } } diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/protocol/ButtonPressCommand.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/protocol/ButtonPressCommand.java index cae1caa1f..c7e0c30d9 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/protocol/ButtonPressCommand.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/protocol/ButtonPressCommand.java @@ -65,7 +65,7 @@ public class ButtonPressCommand extends RadioRACommand { } if (system == 1 || system == 2) { - args.add("S" + String.valueOf(system)); + args.add("S" + system); } return args; diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/protocol/SetDimmerLevelCommand.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/protocol/SetDimmerLevelCommand.java index 08ee328d0..d964fd345 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/protocol/SetDimmerLevelCommand.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/protocol/SetDimmerLevelCommand.java @@ -59,7 +59,7 @@ public class SetDimmerLevelCommand extends RadioRACommand { } if (system == 1 || system == 2) { - args.add("S" + String.valueOf(system)); + args.add("S" + system); } return args; diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/protocol/SetSwitchLevelCommand.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/protocol/SetSwitchLevelCommand.java index 688f0774d..629d9291f 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/protocol/SetSwitchLevelCommand.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/radiora/protocol/SetSwitchLevelCommand.java @@ -60,7 +60,7 @@ public class SetSwitchLevelCommand extends RadioRACommand { } if (system == 1 || system == 2) { - args.add("S" + String.valueOf(system)); + args.add("S" + system); } return args; diff --git a/bundles/org.openhab.binding.luxom/src/main/java/org/openhab/binding/luxom/internal/handler/LuxomDimmerHandler.java b/bundles/org.openhab.binding.luxom/src/main/java/org/openhab/binding/luxom/internal/handler/LuxomDimmerHandler.java index 4ec91c004..32d7f465c 100644 --- a/bundles/org.openhab.binding.luxom/src/main/java/org/openhab/binding/luxom/internal/handler/LuxomDimmerHandler.java +++ b/bundles/org.openhab.binding.luxom/src/main/java/org/openhab/binding/luxom/internal/handler/LuxomDimmerHandler.java @@ -93,15 +93,14 @@ public class LuxomDimmerHandler extends LuxomThingHandler { clear(); } } else if (LuxomBindingConstants.CHANNEL_BRIGHTNESS.equals(channelUID.getId()) && config != null) { - if (command instanceof Number) { - int level = ((Number) command).intValue(); + if (command instanceof Number number) { + int level = number.intValue(); logger.trace("dimmer at address {} just setting dimmer level", getAddress()); dim(level); - } else if (command instanceof IncreaseDecreaseType) { - IncreaseDecreaseType s = (IncreaseDecreaseType) command; + } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) { int currentValue = lastLightLevel.get(); int newValue; - if (IncreaseDecreaseType.INCREASE.equals(s)) { + if (IncreaseDecreaseType.INCREASE.equals(increaseDecreaseCommand)) { newValue = currentValue + config.stepPercentage; // round down to step multiple newValue = newValue - newValue % config.stepPercentage; diff --git a/bundles/org.openhab.binding.luxom/src/main/java/org/openhab/binding/luxom/internal/handler/LuxomThingHandler.java b/bundles/org.openhab.binding.luxom/src/main/java/org/openhab/binding/luxom/internal/handler/LuxomThingHandler.java index 2aa13ddf9..c211b4e78 100644 --- a/bundles/org.openhab.binding.luxom/src/main/java/org/openhab/binding/luxom/internal/handler/LuxomThingHandler.java +++ b/bundles/org.openhab.binding.luxom/src/main/java/org/openhab/binding/luxom/internal/handler/LuxomThingHandler.java @@ -87,7 +87,6 @@ public abstract class LuxomThingHandler extends BaseThingHandler { if (bridgeStatusInfo.getStatus() == ThingStatus.ONLINE && getThing().getStatusInfo().getStatusDetail() == ThingStatusDetail.BRIDGE_OFFLINE) { initDeviceState(); - } else if (bridgeStatusInfo.getStatus() == ThingStatus.OFFLINE) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE); thingOfflineNotify(); diff --git a/bundles/org.openhab.binding.luxom/src/main/java/org/openhab/binding/luxom/internal/protocol/LuxomCommunication.java b/bundles/org.openhab.binding.luxom/src/main/java/org/openhab/binding/luxom/internal/protocol/LuxomCommunication.java index 05c318941..6e350ca94 100644 --- a/bundles/org.openhab.binding.luxom/src/main/java/org/openhab/binding/luxom/internal/protocol/LuxomCommunication.java +++ b/bundles/org.openhab.binding.luxom/src/main/java/org/openhab/binding/luxom/internal/protocol/LuxomCommunication.java @@ -68,7 +68,6 @@ public class LuxomCommunication { // IP-interface. (new Thread(this::runLuxomEvents, "OH-binding-" + bridgeHandler.getThing().getBridgeUID() + "-listen-for-events")).start(); - } catch (IOException | InterruptedException e) { throw new LuxomConnectionException(e); } diff --git a/bundles/org.openhab.binding.luxtronikheatpump/src/main/java/org/openhab/binding/luxtronikheatpump/internal/LuxtronikHeatpumpBindingConstants.java b/bundles/org.openhab.binding.luxtronikheatpump/src/main/java/org/openhab/binding/luxtronikheatpump/internal/LuxtronikHeatpumpBindingConstants.java index 171722f73..9f056dd2c 100644 --- a/bundles/org.openhab.binding.luxtronikheatpump/src/main/java/org/openhab/binding/luxtronikheatpump/internal/LuxtronikHeatpumpBindingConstants.java +++ b/bundles/org.openhab.binding.luxtronikheatpump/src/main/java/org/openhab/binding/luxtronikheatpump/internal/LuxtronikHeatpumpBindingConstants.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.luxtronikheatpump.internal; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -31,5 +30,5 @@ public class LuxtronikHeatpumpBindingConstants { public static final ThingTypeUID THING_TYPE_HEATPUMP = new ThingTypeUID(BINDING_ID, "heatpump"); - public static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_HEATPUMP); + public static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_HEATPUMP); } diff --git a/bundles/org.openhab.binding.luxtronikheatpump/src/main/java/org/openhab/binding/luxtronikheatpump/internal/LuxtronikHeatpumpHandler.java b/bundles/org.openhab.binding.luxtronikheatpump/src/main/java/org/openhab/binding/luxtronikheatpump/internal/LuxtronikHeatpumpHandler.java index f73c043f0..f07340566 100644 --- a/bundles/org.openhab.binding.luxtronikheatpump/src/main/java/org/openhab/binding/luxtronikheatpump/internal/LuxtronikHeatpumpHandler.java +++ b/bundles/org.openhab.binding.luxtronikheatpump/src/main/java/org/openhab/binding/luxtronikheatpump/internal/LuxtronikHeatpumpHandler.java @@ -112,9 +112,7 @@ public class LuxtronikHeatpumpHandler extends BaseThingHandler { return; } - if (command instanceof QuantityType) { - QuantityType value = (QuantityType) command; - + if (command instanceof QuantityType value) { Unit unit = channel.getUnit(); if (unit != null) { value = value.toUnit(unit); @@ -123,8 +121,8 @@ public class LuxtronikHeatpumpHandler extends BaseThingHandler { command = new DecimalType(value.floatValue()); } - if (command instanceof OnOffType) { - command = ((OnOffType) command) == OnOffType.ON ? new DecimalType(1) : DecimalType.ZERO; + if (command instanceof OnOffType onOffCommand) { + command = onOffCommand == OnOffType.ON ? new DecimalType(1) : DecimalType.ZERO; } if (!(command instanceof DecimalType)) { diff --git a/bundles/org.openhab.binding.luxtronikheatpump/src/main/java/org/openhab/binding/luxtronikheatpump/internal/enums/HeatpumpType.java b/bundles/org.openhab.binding.luxtronikheatpump/src/main/java/org/openhab/binding/luxtronikheatpump/internal/enums/HeatpumpType.java index d6f9b9a21..71165da69 100644 --- a/bundles/org.openhab.binding.luxtronikheatpump/src/main/java/org/openhab/binding/luxtronikheatpump/internal/enums/HeatpumpType.java +++ b/bundles/org.openhab.binding.luxtronikheatpump/src/main/java/org/openhab/binding/luxtronikheatpump/internal/enums/HeatpumpType.java @@ -109,7 +109,7 @@ public enum HeatpumpType { this.name = name; } - public static final HeatpumpType fromCode(Integer code) { + public static HeatpumpType fromCode(Integer code) { for (HeatpumpType error : HeatpumpType.values()) { if (error.code.equals(code)) { return error; diff --git a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/MagentaTVBindingConstants.java b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/MagentaTVBindingConstants.java index 8f0ca725b..ba659bb00 100644 --- a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/MagentaTVBindingConstants.java +++ b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/MagentaTVBindingConstants.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.magentatv.internal; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -33,7 +32,7 @@ public class MagentaTVBindingConstants { // List of all Thing Type UIDs public static final ThingTypeUID THING_TYPE_RECEIVER = new ThingTypeUID(BINDING_ID, "receiver"); - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_RECEIVER); + public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_RECEIVER); /** * Property names for config/status properties diff --git a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/config/MagentaTVDynamicConfig.java b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/config/MagentaTVDynamicConfig.java index 4c9ec14e5..5488dacb3 100644 --- a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/config/MagentaTVDynamicConfig.java +++ b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/config/MagentaTVDynamicConfig.java @@ -58,7 +58,7 @@ public class MagentaTVDynamicConfig extends MagentaTVThingConfiguration { } public void setPort(String port) { - if (modelId.contains(MODEL_MR400) && port.equals("49153")) { + if (modelId.contains(MODEL_MR400) && "49153".equals(port)) { // overwrite port returned by discovery (invalid for this model) this.port = MR400_DEF_REMOTE_PORT; } else { @@ -84,7 +84,7 @@ public class MagentaTVDynamicConfig extends MagentaTVThingConfiguration { public String getDescriptionUrl() { if (descriptionUrl.equals(MR400_DEF_DESCRIPTION_URL) - && !(port.equals(MR400_DEF_REMOTE_PORT) || port.equals("49153"))) { + && !(port.equals(MR400_DEF_REMOTE_PORT) || "49153".equals(port))) { // MR401B returns the wrong URL return MR401B_DEF_DESCRIPTION_URL; } diff --git a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/discovery/MagentaTVDiscoveryParticipant.java b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/discovery/MagentaTVDiscoveryParticipant.java index bc28e69ee..761e1a604 100644 --- a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/discovery/MagentaTVDiscoveryParticipant.java +++ b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/discovery/MagentaTVDiscoveryParticipant.java @@ -16,7 +16,6 @@ import static org.openhab.binding.magentatv.internal.MagentaTVBindingConstants.* import static org.openhab.binding.magentatv.internal.MagentaTVUtil.*; import static org.openhab.core.thing.Thing.*; -import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.TreeMap; @@ -46,7 +45,7 @@ public class MagentaTVDiscoveryParticipant implements UpnpDiscoveryParticipant { @Override public Set getSupportedThingTypeUIDs() { - return Collections.singleton(THING_TYPE_RECEIVER); + return Set.of(THING_TYPE_RECEIVER); } /** @@ -74,7 +73,7 @@ public class MagentaTVDiscoveryParticipant implements UpnpDiscoveryParticipant { .substring(device.getIdentity().getUdn().getIdentifierString().length() - 12); String mac = hex.substring(0, 2) + ":" + hex.substring(2, 4) + ":" + hex.substring(4, 6) + ":" + hex.substring(6, 8) + ":" + hex.substring(8, 10) + ":" + hex.substring(10, 12); - if (port.equals("49153")) { // MR400 reports the rong + if ("49153".equals(port)) { // MR400 reports the rong port = MR400_DEF_REMOTE_PORT; } properties.put(PROPERTY_VENDOR, VENDOR + "(" + manufacturer + ")"); diff --git a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/handler/MagentaTVControl.java b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/handler/MagentaTVControl.java index 0fce1cb97..eea050625 100644 --- a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/handler/MagentaTVControl.java +++ b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/handler/MagentaTVControl.java @@ -135,7 +135,7 @@ public class MagentaTVControl { if (result.contains("")) { String wol = substringBetween(result, "", ""); config.setWakeOnLAN(wol); - logger.debug("{}: Wake-on-LAN is {}", thingId, wol.equals("0") ? "disabled" : "enabled"); + logger.debug("{}: Wake-on-LAN is {}", thingId, "0".equals(wol) ? "disabled" : "enabled"); } if (result.contains("")) { String version; @@ -240,7 +240,7 @@ public class MagentaTVControl { } String result = substringBetween(response, "", ""); - if (!result.equals("0")) { + if (!"0".equals(result)) { throw new MagentaTVException("Pairing failed, result=" + result); } @@ -295,7 +295,7 @@ public class MagentaTVControl { } String result = getXmlValue(response, "pairingResult"); - if (!result.equals("0")) { + if (!"0".equals(result)) { logger.debug("{}: Pairing failed or pairing no longer valid, result={}", thingId, result); resetPairing(); // let the caller decide how to proceed diff --git a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/handler/MagentaTVHandler.java b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/handler/MagentaTVHandler.java index 759c517e7..b6e5133cf 100644 --- a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/handler/MagentaTVHandler.java +++ b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/handler/MagentaTVHandler.java @@ -223,7 +223,7 @@ public class MagentaTVHandler extends BaseThingHandler implements MagentaTVListe } try { - if (!isOnline() || command.toString().equalsIgnoreCase("PAIR")) { + if (!isOnline() || "PAIR".equalsIgnoreCase(command.toString())) { logger.debug("{}: Receiver {} is offline, try to (re-)connect", thingId, deviceName()); connectReceiver(); // reconnect to MR, throws an exception if this fails } @@ -273,7 +273,7 @@ public class MagentaTVHandler extends BaseThingHandler implements MagentaTVListe } break; case CHANNEL_KEY: - if (command.toString().equalsIgnoreCase("PAIR")) { // special key to re-pair receiver (already done + if ("PAIR".equalsIgnoreCase(command.toString())) { // special key to re-pair receiver (already done // above) logger.debug("{}: PAIRing key received, reconnect receiver {}", thingId, deviceName()); } else { diff --git a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVHttp.java b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVHttp.java index 6feb0f5a8..1ae9434e8 100644 --- a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVHttp.java +++ b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVHttp.java @@ -110,7 +110,6 @@ public class MagentaTVHttp { * @throws IOException */ public String sendData(String remoteIp, String remotePort, String data) throws MagentaTVException { - String errorMessage = ""; StringBuffer response = new StringBuffer(); try (Socket socket = new Socket()) { diff --git a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVNetwork.java b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVNetwork.java index 53125af5c..c4069d987 100644 --- a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVNetwork.java +++ b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVNetwork.java @@ -48,7 +48,7 @@ public class MagentaTVNetwork { */ public void initLocalNet(String localIP, String localPort) throws MagentaTVException { try { - if (localIP.isEmpty() || localIP.equals("0.0.0.0") || localIP.equals("127.0.0.1")) { + if (localIP.isEmpty() || "0.0.0.0".equals(localIP) || "127.0.0.1".equals(localIP)) { throw new MagentaTVException("Unable to detect local IP address!"); } this.localPort = localPort; diff --git a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVNotifyServlet.java b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVNotifyServlet.java index a9ac8648d..667408174 100644 --- a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVNotifyServlet.java +++ b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVNotifyServlet.java @@ -89,7 +89,6 @@ public class MagentaTVNotifyServlet extends HttpServlet { @Override protected void service(@Nullable HttpServletRequest request, @Nullable HttpServletResponse response) throws ServletException, IOException { - String data = inputStreamToString(request); try { if ((request == null) || (response == null)) { @@ -118,7 +117,7 @@ public class MagentaTVNotifyServlet extends HttpServlet { } } else { if (data.contains("STB_")) { - data = data.replaceAll(""", "\""); + data = data.replace(""", "\""); String stbMac = substringBetween(data, "", ""); String stbEvent = ""; if (data.contains("")) { diff --git a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVOAuth.java b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVOAuth.java index aa83aa5ca..498024cb6 100644 --- a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVOAuth.java +++ b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVOAuth.java @@ -120,9 +120,9 @@ public class MagentaTVOAuth { if (cred.sam3Para != null) { for (OauthKeyValue si : cred.sam3Para) { logger.trace("sam3Para.{} = {}", si.key, si.value); - if (si.key.equalsIgnoreCase("oAuthScope")) { + if ("oAuthScope".equalsIgnoreCase(si.key)) { oAuthScope = si.value; - } else if (si.key.equalsIgnoreCase("SAM3ServiceURL")) { + } else if ("SAM3ServiceURL".equalsIgnoreCase(si.key)) { oAuthService = si.value; } } @@ -242,7 +242,7 @@ public class MagentaTVOAuth { // validate response, API errors are reported as Json HttpFields responseHeaders = contentResponse.getHeaders(); for (HttpField f : responseHeaders) { - if (f.getName().equals("Set-Cookie")) { + if ("Set-Cookie".equals(f.getName())) { HttpCookie c = new HttpCookie(f.getName(), f.getValue()); cookies.add(c); } diff --git a/bundles/org.openhab.binding.mail/src/3rdparty/java/javax/activation/PatchedMailcapCommandMap.java b/bundles/org.openhab.binding.mail/src/3rdparty/java/javax/activation/PatchedMailcapCommandMap.java index eb46a0305..3d04d9e9b 100644 --- a/bundles/org.openhab.binding.mail/src/3rdparty/java/javax/activation/PatchedMailcapCommandMap.java +++ b/bundles/org.openhab.binding.mail/src/3rdparty/java/javax/activation/PatchedMailcapCommandMap.java @@ -168,8 +168,8 @@ public class PatchedMailcapCommandMap extends CommandMap { if (fieldName.startsWith("x-java-") && fieldName.length() > 7) { String command = fieldName.substring(7); value = value.trim(); - if (command.equals("fallback-entry")) { - if (value.equals("true")) { + if ("fallback-entry".equals(command)) { + if ("true".equals(value)) { fallback = true; } } diff --git a/bundles/org.openhab.binding.mail/src/main/java/org/openhab/binding/mail/internal/POP3IMAPHandler.java b/bundles/org.openhab.binding.mail/src/main/java/org/openhab/binding/mail/internal/POP3IMAPHandler.java index e92ef1878..a7cf802fc 100644 --- a/bundles/org.openhab.binding.mail/src/main/java/org/openhab/binding/mail/internal/POP3IMAPHandler.java +++ b/bundles/org.openhab.binding.mail/src/main/java/org/openhab/binding/mail/internal/POP3IMAPHandler.java @@ -169,9 +169,9 @@ public class POP3IMAPHandler extends BaseThingHandler { } Object rawContent = message.getContent(); String contentAsString; - if (rawContent instanceof String) { + if (rawContent instanceof String str) { logger.trace("Detected plain text message"); - contentAsString = (String) rawContent; + contentAsString = str; } else if (rawContent instanceof MimeMessage mimeMessage) { logger.trace("Detected MIME message"); try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { diff --git a/bundles/org.openhab.binding.mail/src/main/java/org/openhab/binding/mail/internal/SMTPHandler.java b/bundles/org.openhab.binding.mail/src/main/java/org/openhab/binding/mail/internal/SMTPHandler.java index f25afdbe3..072b11a6e 100644 --- a/bundles/org.openhab.binding.mail/src/main/java/org/openhab/binding/mail/internal/SMTPHandler.java +++ b/bundles/org.openhab.binding.mail/src/main/java/org/openhab/binding/mail/internal/SMTPHandler.java @@ -115,8 +115,7 @@ public class SMTPHandler extends BaseThingHandler { Field dataField = dataSource.getClass().getDeclaredField("data"); dataField.setAccessible(true); Object data = dataField.get(dataSource); - if (data instanceof MimeMultipart) { - MimeMultipart mimeMultipart = (MimeMultipart) data; + if (data instanceof MimeMultipart mimeMultipart) { for (int i = 0; i < mimeMultipart.getCount(); i++) { Part mimePart = mimeMultipart.getBodyPart(i); mimePart.getDataHandler().setCommandMap(commandMap); diff --git a/bundles/org.openhab.binding.mail/src/main/java/org/openhab/binding/mail/internal/action/SendMailActions.java b/bundles/org.openhab.binding.mail/src/main/java/org/openhab/binding/mail/internal/action/SendMailActions.java index 0894ebe6e..8c27b7343 100644 --- a/bundles/org.openhab.binding.mail/src/main/java/org/openhab/binding/mail/internal/action/SendMailActions.java +++ b/bundles/org.openhab.binding.mail/src/main/java/org/openhab/binding/mail/internal/action/SendMailActions.java @@ -230,8 +230,8 @@ public class SendMailActions implements ThingActions { @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof SMTPHandler) { - this.handler = (SMTPHandler) handler; + if (handler instanceof SMTPHandler smtpHandler) { + this.handler = smtpHandler; } } diff --git a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/Utils.java b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/Utils.java index 7001c40a2..38c42b842 100644 --- a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/Utils.java +++ b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/Utils.java @@ -33,7 +33,7 @@ public final class Utils { * the hex value to be parsed into an integer * @return the given hex value as integer */ - public static final int fromHex(String hex) { + public static int fromHex(String hex) { return Integer.parseInt(hex, 16); } @@ -44,7 +44,7 @@ public final class Utils { * the integer values to be converted into hexadecimal numbers * @return the given numbers as hexadecimal number */ - public static final String toHex(int... values) { + public static String toHex(int... values) { String returnValue = ""; for (int v : values) { returnValue += v < 16 ? "0" + Integer.toHexString(v).toUpperCase() : Integer.toHexString(v).toUpperCase(); @@ -60,7 +60,7 @@ public final class Utils { * hexadecimal numbers * @return the hexadecimal number */ - public static final String toHex(boolean[] bits) { + public static String toHex(boolean[] bits) { int retVal = 0; for (int i = 0; i < bits.length; ++i) { retVal |= (bits[i] ? 1 : 0) << i; @@ -76,7 +76,7 @@ public final class Utils { * the byte to be converted into its integer value * @return the integer value represented by the given byte */ - public static final int fromByte(byte b) { + public static int fromByte(byte b) { return b & 0xFF; } diff --git a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/actions/MaxCubeActions.java b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/actions/MaxCubeActions.java index 52f04fcb9..219f630c8 100644 --- a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/actions/MaxCubeActions.java +++ b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/actions/MaxCubeActions.java @@ -38,8 +38,8 @@ public class MaxCubeActions implements ThingActions { @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof MaxCubeBridgeHandler) { - this.handler = (MaxCubeBridgeHandler) handler; + if (handler instanceof MaxCubeBridgeHandler bridgeHandler) { + this.handler = bridgeHandler; } } diff --git a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/actions/MaxDevicesActions.java b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/actions/MaxDevicesActions.java index 1c4dd8727..e727f5828 100644 --- a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/actions/MaxDevicesActions.java +++ b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/actions/MaxDevicesActions.java @@ -38,8 +38,8 @@ public class MaxDevicesActions implements ThingActions { @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof MaxDevicesHandler) { - this.handler = (MaxDevicesHandler) handler; + if (handler instanceof MaxDevicesHandler devicesHandler) { + this.handler = devicesHandler; } } diff --git a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/command/CCommand.java b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/command/CCommand.java index 1a37e57bd..3e516637b 100644 --- a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/command/CCommand.java +++ b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/command/CCommand.java @@ -29,8 +29,7 @@ public class CCommand extends CubeCommand { @Override public String getCommandString() { - String cmd = "c:" + rfAddress + '\r' + '\n'; - return cmd; + return "c:" + rfAddress + '\r' + '\n'; } @Override diff --git a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/command/UdpCubeCommand.java b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/command/UdpCubeCommand.java index f917aaab7..d0c584a05 100644 --- a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/command/UdpCubeCommand.java +++ b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/command/UdpCubeCommand.java @@ -127,14 +127,14 @@ public class UdpCubeCommand { // Check if the message is correct if (message.startsWith("eQ3Max") && !message.equals(MAXCUBE_COMMAND_STRING)) { - commandResponse.put("maxCubeIP", receivePacket.getAddress().getHostAddress().toString()); + commandResponse.put("maxCubeIP", receivePacket.getAddress().getHostAddress()); commandResponse.put("maxCubeState", message.substring(0, 8)); commandResponse.put("serialNumber", message.substring(8, 18)); commandResponse.put("msgValidid", message.substring(18, 19)); String requestType = message.substring(19, 20); commandResponse.put("requestType", requestType); - if (requestType.equals("I")) { + if ("I".equals(requestType)) { commandResponse.put("rfAddress", Utils.getHex(message.substring(21, 24).getBytes(StandardCharsets.UTF_8)) .replace(" ", "").toLowerCase()); diff --git a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/discovery/MaxCubeBridgeDiscovery.java b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/discovery/MaxCubeBridgeDiscovery.java index fec78745c..5a8a19a2f 100644 --- a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/discovery/MaxCubeBridgeDiscovery.java +++ b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/discovery/MaxCubeBridgeDiscovery.java @@ -136,7 +136,7 @@ public class MaxCubeBridgeDiscovery extends AbstractDiscoveryService { logger.trace("Msg Valid : {}", msgValidid); logger.trace("Msg Type : {}", requestType); - if (requestType.equals("I")) { + if ("I".equals(requestType)) { rfAddress = Utils.getHex(Arrays.copyOfRange(messageBuf, 21, 24)).replace(" ", "").toLowerCase(); String firmwareVersion = Utils.getHex(Arrays.copyOfRange(messageBuf, 24, 26)).replace(" ", "."); logger.debug("RF Address: {}", rfAddress); diff --git a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/discovery/MaxDeviceDiscoveryService.java b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/discovery/MaxDeviceDiscoveryService.java index 26fcafdb4..c749b7ed7 100644 --- a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/discovery/MaxDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/discovery/MaxDeviceDiscoveryService.java @@ -55,8 +55,8 @@ public class MaxDeviceDiscoveryService extends AbstractDiscoveryService @Override public void setThingHandler(@NonNullByDefault({}) ThingHandler handler) { - if (handler instanceof MaxCubeBridgeHandler) { - this.maxCubeBridgeHandler = (MaxCubeBridgeHandler) handler; + if (handler instanceof MaxCubeBridgeHandler maxCubeBridgeHandler) { + this.maxCubeBridgeHandler = maxCubeBridgeHandler; } } diff --git a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/handler/MaxDevicesHandler.java b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/handler/MaxDevicesHandler.java index d9d3e07c6..8cadbcc72 100644 --- a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/handler/MaxDevicesHandler.java +++ b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/handler/MaxDevicesHandler.java @@ -20,10 +20,10 @@ import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; +import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -198,7 +198,7 @@ public class MaxDevicesHandler extends BaseThingHandler implements DeviceStatusL @Override public Collection> getServices() { - return Collections.singleton(MaxDevicesActions.class); + return Set.of(MaxDevicesActions.class); } private void sendPropertyUpdate(Map configurationParameters, Map deviceProperties) { @@ -543,8 +543,8 @@ public class MaxDevicesHandler extends BaseThingHandler implements DeviceStatusL configuration.put(PROPERTY_ROOMNAME, device.getRoomName()); config_changed = true; } - if (getConfig().get(PROPERTY_ROOMID) == null || !(new BigDecimal(device.getRoomId()) - .compareTo((BigDecimal) getConfig().get(PROPERTY_ROOMID)) == 0)) { + if (getConfig().get(PROPERTY_ROOMID) == null || new BigDecimal(device.getRoomId()) + .compareTo((BigDecimal) getConfig().get(PROPERTY_ROOMID)) != 0) { configuration.put(PROPERTY_ROOMID, new BigDecimal(device.getRoomId())); config_changed = true; } diff --git a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/handler/SendCommand.java b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/handler/SendCommand.java index 959937cf4..1ca1d4a40 100644 --- a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/handler/SendCommand.java +++ b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/handler/SendCommand.java @@ -68,8 +68,7 @@ public final class SendCommand { * This is can be used to find duplicated commands in the queue */ private static String getKey(String serialNumber, CubeCommand cubeCommand) { - String key = serialNumber + "-" + cubeCommand.getClass().getSimpleName(); - return key; + return serialNumber + "-" + cubeCommand.getClass().getSimpleName(); } /** diff --git a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/message/MessageProcessor.java b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/message/MessageProcessor.java index c3ea3e0eb..222add76d 100644 --- a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/message/MessageProcessor.java +++ b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/message/MessageProcessor.java @@ -171,7 +171,7 @@ public class MessageProcessor { } } } else { - if ((!counter.equals(this.numberOfRequiredLines)) || (!(index == this.receivedLines.size()))) { + if (!counter.equals(this.numberOfRequiredLines) || index != this.receivedLines.size()) { throw new IncorrectMultilineIndexException(); } diff --git a/bundles/org.openhab.binding.max/src/test/java/org/openhab/binding/max/internal/command/MCommandTest.java b/bundles/org.openhab.binding.max/src/test/java/org/openhab/binding/max/internal/command/MCommandTest.java index a1656c6d3..9f1a969ea 100644 --- a/bundles/org.openhab.binding.max/src/test/java/org/openhab/binding/max/internal/command/MCommandTest.java +++ b/bundles/org.openhab.binding.max/src/test/java/org/openhab/binding/max/internal/command/MCommandTest.java @@ -36,7 +36,7 @@ public class MCommandTest { private List devices = new ArrayList<>(); private List rooms = new ArrayList<>(); - String deviceCMsg[] = { + String[] deviceCMsg = { "C:0b0da3,0gsNowIBEABLRVEwNTQ0MjQyLCQ9CQcYAzAM/wBIYViRSP1ZFE0gTSBNIEUgRSBFIEUgRSBFIEhhWJFQ/VkVUSBRIFEgRSBFIEUgRSBFIEUgSFBYWkj+WRRNIE0gTSBFIEUgRSBFIEUgRSBIUFhaSP5ZFE0gTSBNIEUgRSBFIEUgRSBFIEhQWFpI/lkUTSBNIE0gRSBFIEUgRSBFIEUgSFBYWkj+WRRNIE0gTSBFIEUgRSBFIEUgRSBIUFhaSP5ZFE0gTSBNIEUgRSBFIEUgRSBFIA==", "C:08c1d6,0gjB1gEFGP9LRVEwNjQ5MzEyKyE9CQcYAzAM/wBEeFUgVSBVIFUgVSBVIEUgRSBFIEUgRSBFIER4VRZFIEUgRSBFIEUgRSBFIEUgRSBFIEUgRFFEYkTkTQ9FIEUgRSBFIEUgRSBFIEUgRSBEUURiRORND0UgRSBFIEUgRSBFIEUgRSBFIERRRGJE5E0PRSBFIEUgRSBFIEUgRSBFIEUgRFFEYkTkTQ9FIEUgRSBFIEUgRSBFIEUgRSBEUURiRORRGEUgRSBFIEUgRSBFIEUgRSBFIA==", "C:0e75f6,EQ519gQCEABLRVExMTA0Mzgw", diff --git a/bundles/org.openhab.binding.max/src/test/java/org/openhab/binding/max/internal/message/UtilsTest.java b/bundles/org.openhab.binding.max/src/test/java/org/openhab/binding/max/internal/message/UtilsTest.java index 8eba440c2..39150a9a7 100644 --- a/bundles/org.openhab.binding.max/src/test/java/org/openhab/binding/max/internal/message/UtilsTest.java +++ b/bundles/org.openhab.binding.max/src/test/java/org/openhab/binding/max/internal/message/UtilsTest.java @@ -93,14 +93,14 @@ public class UtilsTest { @Test public void getBitsTest() { - boolean b1[] = Utils.getBits(0xFF); + boolean[] b1 = Utils.getBits(0xFF); assertEquals(b1.length, 8); for (int i = 0; i < 8; i++) { assertEquals(true, b1[i]); } - boolean b2[] = Utils.getBits(0x5A); + boolean[] b2 = Utils.getBits(0x5A); assertEquals(b2.length, 8); assertEquals(false, b2[0]); diff --git a/bundles/org.openhab.binding.mcd/src/main/java/org/openhab/binding/mcd/internal/handler/SensorThingHandler.java b/bundles/org.openhab.binding.mcd/src/main/java/org/openhab/binding/mcd/internal/handler/SensorThingHandler.java index 669edcc9e..d4d058066 100644 --- a/bundles/org.openhab.binding.mcd/src/main/java/org/openhab/binding/mcd/internal/handler/SensorThingHandler.java +++ b/bundles/org.openhab.binding.mcd/src/main/java/org/openhab/binding/mcd/internal/handler/SensorThingHandler.java @@ -334,18 +334,22 @@ public class SensorThingHandler extends BaseThingHandler { JsonArray array = deviceInfo.getAsJsonArray("PatientDevices"); JsonObject patient = array.get(0).getAsJsonObject(); if (patient.has("UuidPerson") && !patient.get("UuidPerson").isJsonNull()) { - return "https://cunds-syncapi.azurewebsites.net/api/ApiSensor/GetLatestApiSensorEvents" - + "?UuidPatient=" + patient.get("UuidPerson").getAsString() + "&SerialNumber=" - + serialNumber + "&Count=1"; + return """ + https://cunds-syncapi.azurewebsites.net/api/ApiSensor/GetLatestApiSensorEvents\ + ?UuidPatient=\ + """ + patient.get("UuidPerson").getAsString() + "&SerialNumber=" + serialNumber + + "&Count=1"; } } else if (deviceInfo.has("OrganisationUnitDevices") && deviceInfo.getAsJsonArray("OrganisationUnitDevices").size() != 0) { JsonArray array = deviceInfo.getAsJsonArray("OrganisationUnitDevices"); JsonObject orgUnit = array.get(0).getAsJsonObject(); if (orgUnit.has("UuidOrganisationUnit") && !orgUnit.get("UuidOrganisationUnit").isJsonNull()) { - return "https://cunds-syncapi.azurewebsites.net/api/ApiSensor/GetLatestApiSensorEvents" - + "?UuidOrganisationUnit=" + orgUnit.get("UuidOrganisationUnit").getAsString() - + "&SerialNumber=" + serialNumber + "&Count=1"; + return """ + https://cunds-syncapi.azurewebsites.net/api/ApiSensor/GetLatestApiSensorEvents\ + ?UuidOrganisationUnit=\ + """ + orgUnit.get("UuidOrganisationUnit").getAsString() + "&SerialNumber=" + + serialNumber + "&Count=1"; } } } else { diff --git a/bundles/org.openhab.binding.mcd/src/test/java/org/openhab/binding/mcd/internal/handler/SensorThingHandlerTest.java b/bundles/org.openhab.binding.mcd/src/test/java/org/openhab/binding/mcd/internal/handler/SensorThingHandlerTest.java index b0204babc..1e331c345 100644 --- a/bundles/org.openhab.binding.mcd/src/test/java/org/openhab/binding/mcd/internal/handler/SensorThingHandlerTest.java +++ b/bundles/org.openhab.binding.mcd/src/test/java/org/openhab/binding/mcd/internal/handler/SensorThingHandlerTest.java @@ -35,20 +35,48 @@ public class SensorThingHandlerTest { @Test public void getLatestValueFromJsonObjectTest() { - String arrayString = "[\n" + " {\n" + " \"IdPatient\": 1,\n" + " \"LastName\": \"Mustermann\",\n" - + " \"FirstName\": \"Max\",\n" + " \"Devices\": [\n" + " {\n" + " \"IdDevice\": 2,\n" - + " \"SerialNumber\": \"001\",\n" + " \"Name\": \"Test Sitzkissen\",\n" - + " \"Events\": [\n" + " {\n" + " \"EventDef\": \"Alarm\",\n" - + " \"DateEntry\": \"2021-11-22T10:17:56.2866667\"\n" + " }\n" + " ]\n" - + " }\n" + " ]\n" + " }\n" + "]"; + String arrayString = """ + [ + { + "IdPatient": 1, + "LastName": "Mustermann", + "FirstName": "Max", + "Devices": [ + { + "IdDevice": 2, + "SerialNumber": "001", + "Name": "Test Sitzkissen", + "Events": [ + { + "EventDef": "Alarm", + "DateEntry": "2021-11-22T10:17:56.2866667" + } + ] + } + ] + } + ]\ + """; JsonArray array = gson.fromJson(arrayString, JsonArray.class); JsonObject object = SensorThingHandler.getLatestValueFromJsonArray(array); String string = object != null ? object.toString() : null; assertEquals("{\"EventDef\":\"Alarm\",\"DateEntry\":\"2021-11-22T10:17:56.2866667\"}", string); - arrayString = "[\n" + " {\n" + " \"IdPatient\": 1,\n" + " \"LastName\": \"Mustermann\",\n" - + " \"FirstName\": \"Max\",\n" + " \"Devices\": [\n" + " {\n" + " \"IdDevice\": 2,\n" - + " \"SerialNumber\": \"001\",\n" + " \"Name\": \"Test Sitzkissen\"\n" + " }\n" - + " ]\n" + " }\n" + "]"; + arrayString = """ + [ + { + "IdPatient": 1, + "LastName": "Mustermann", + "FirstName": "Max", + "Devices": [ + { + "IdDevice": 2, + "SerialNumber": "001", + "Name": "Test Sitzkissen" + } + ] + } + ]\ + """; array = gson.fromJson(arrayString, JsonArray.class); assertNull(SensorThingHandler.getLatestValueFromJsonArray(array)); } diff --git a/bundles/org.openhab.binding.mcp23017/src/main/java/org/openhab/binding/mcp23017/internal/Mcp23017HandlerFactory.java b/bundles/org.openhab.binding.mcp23017/src/main/java/org/openhab/binding/mcp23017/internal/Mcp23017HandlerFactory.java index 248cf0c77..abb0c615f 100644 --- a/bundles/org.openhab.binding.mcp23017/src/main/java/org/openhab/binding/mcp23017/internal/Mcp23017HandlerFactory.java +++ b/bundles/org.openhab.binding.mcp23017/src/main/java/org/openhab/binding/mcp23017/internal/Mcp23017HandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.mcp23017.internal; import static org.openhab.binding.mcp23017.internal.Mcp23017BindingConstants.THING_TYPE_MCP23017; -import java.util.Collections; import java.util.Set; import org.openhab.binding.mcp23017.internal.handler.Mcp23017Handler; @@ -36,7 +35,7 @@ import org.slf4j.LoggerFactory; @Component(service = ThingHandlerFactory.class, configurationPid = "binding.mcp23017") public class Mcp23017HandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_MCP23017); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_MCP23017); private final Logger logger = LoggerFactory.getLogger(Mcp23017HandlerFactory.class); @Override diff --git a/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/api/MeaterRestAPI.java b/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/api/MeaterRestAPI.java index 41a2cb64d..0832b4943 100644 --- a/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/api/MeaterRestAPI.java +++ b/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/api/MeaterRestAPI.java @@ -159,8 +159,8 @@ public class MeaterRestAPI { throw new MeaterException("Failed to fetch from API!"); } catch (ExecutionException e) { Throwable cause = e.getCause(); - if (cause != null && cause instanceof HttpResponseException) { - Response response = ((HttpResponseException) cause).getResponse(); + if (cause instanceof HttpResponseException httpResponseException) { + Response response = httpResponseException.getResponse(); if (response.getStatus() == HttpStatus.UNAUTHORIZED_401) { /* * When contextId is not valid, the service will respond with HTTP code 401 without diff --git a/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/console/MeaterCommandExtension.java b/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/console/MeaterCommandExtension.java index dc16db478..70629e9d7 100644 --- a/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/console/MeaterCommandExtension.java +++ b/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/console/MeaterCommandExtension.java @@ -60,9 +60,9 @@ public class MeaterCommandExtension extends AbstractConsoleCommandExtension impl for (Thing thing : thingRegistry.getAll()) { ThingHandler thingHandler = thing.getHandler(); - if (thingHandler instanceof MeaterBridgeHandler) { + if (thingHandler instanceof MeaterBridgeHandler bridgeHandler) { console.println("API bridge: " + thing.getLabel()); - ((MeaterBridgeHandler) thingHandler).getMeaterThings().entrySet().stream().forEach(t -> { + bridgeHandler.getMeaterThings().entrySet().stream().forEach(t -> { console.println(" - ID: " + t.getKey() + " (ambient temperature: " + t.getValue().temperature.ambient + ")"); }); diff --git a/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/discovery/MeaterDiscoveryService.java b/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/discovery/MeaterDiscoveryService.java index af61c6f2c..20d34e333 100644 --- a/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/discovery/MeaterDiscoveryService.java +++ b/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/discovery/MeaterDiscoveryService.java @@ -43,10 +43,10 @@ public class MeaterDiscoveryService extends AbstractDiscoveryService implements @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof MeaterBridgeHandler) { - this.handler = (MeaterBridgeHandler) handler; - i18nProvider = ((MeaterBridgeHandler) handler).getI18nProvider(); - localeProvider = ((MeaterBridgeHandler) handler).getLocaleProvider(); + if (handler instanceof MeaterBridgeHandler bridgeHandler) { + this.handler = bridgeHandler; + i18nProvider = bridgeHandler.getI18nProvider(); + localeProvider = bridgeHandler.getLocaleProvider(); } } diff --git a/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/handler/MeaterBridgeHandler.java b/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/handler/MeaterBridgeHandler.java index 932f45535..509e6b08d 100644 --- a/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/handler/MeaterBridgeHandler.java +++ b/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/handler/MeaterBridgeHandler.java @@ -15,7 +15,6 @@ package org.openhab.binding.meater.internal.handler; import static org.openhab.binding.meater.internal.MeaterBindingConstants.*; import java.util.Collection; -import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @@ -56,7 +55,7 @@ public class MeaterBridgeHandler extends BaseBridgeHandler { private final Logger logger = LoggerFactory.getLogger(MeaterBridgeHandler.class); - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_BRIDGE); + public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_BRIDGE); private final Gson gson; private final HttpClient httpClient; @@ -101,7 +100,7 @@ public class MeaterBridgeHandler extends BaseBridgeHandler { @Override public Collection> getServices() { - return Collections.singleton(MeaterDiscoveryService.class); + return Set.of(MeaterDiscoveryService.class); } @Override diff --git a/bundles/org.openhab.binding.melcloud/src/main/java/org/openhab/binding/melcloud/internal/MelCloudHandlerFactory.java b/bundles/org.openhab.binding.melcloud/src/main/java/org/openhab/binding/melcloud/internal/MelCloudHandlerFactory.java index f20258e0d..4a94c1413 100644 --- a/bundles/org.openhab.binding.melcloud/src/main/java/org/openhab/binding/melcloud/internal/MelCloudHandlerFactory.java +++ b/bundles/org.openhab.binding.melcloud/src/main/java/org/openhab/binding/melcloud/internal/MelCloudHandlerFactory.java @@ -46,14 +46,11 @@ public class MelCloudHandlerFactory extends BaseThingHandlerFactory { ThingTypeUID thingTypeUID = thing.getThingTypeUID(); if (THING_TYPE_MELCLOUD_ACCOUNT.equals(thingTypeUID)) { - MelCloudAccountHandler handler = new MelCloudAccountHandler((Bridge) thing); - return handler; + return new MelCloudAccountHandler((Bridge) thing); } else if (THING_TYPE_ACDEVICE.equals(thingTypeUID)) { - MelCloudDeviceHandler handler = new MelCloudDeviceHandler(thing); - return handler; + return new MelCloudDeviceHandler(thing); } else if (THING_TYPE_HEATPUMPDEVICE.equals(thingTypeUID)) { - MelCloudHeatpumpDeviceHandler handler = new MelCloudHeatpumpDeviceHandler(thing); - return handler; + return new MelCloudHeatpumpDeviceHandler(thing); } return null; diff --git a/bundles/org.openhab.binding.melcloud/src/main/java/org/openhab/binding/melcloud/internal/api/MelCloudConnection.java b/bundles/org.openhab.binding.melcloud/src/main/java/org/openhab/binding/melcloud/internal/api/MelCloudConnection.java index 6156f9dbd..9eea2f903 100644 --- a/bundles/org.openhab.binding.melcloud/src/main/java/org/openhab/binding/melcloud/internal/api/MelCloudConnection.java +++ b/bundles/org.openhab.binding.melcloud/src/main/java/org/openhab/binding/melcloud/internal/api/MelCloudConnection.java @@ -137,8 +137,7 @@ public class MelCloudConnection { try { String response = HttpUtil.executeUrl("GET", url, getHeaderProperties(), null, null, TIMEOUT_MILLISECONDS); logger.debug("Device status response: {}", response); - DeviceStatus deviceStatus = gson.fromJson(response, DeviceStatus.class); - return deviceStatus; + return gson.fromJson(response, DeviceStatus.class); } catch (IOException | JsonSyntaxException e) { setConnected(false); throw new MelCloudCommException("Error occurred during device status fetch", e); @@ -167,8 +166,7 @@ public class MelCloudConnection { try { String response = HttpUtil.executeUrl("GET", url, getHeaderProperties(), null, null, TIMEOUT_MILLISECONDS); logger.debug("Device heatpump status response: {}", response); - HeatpumpDeviceStatus heatpumpDeviceStatus = gson.fromJson(response, HeatpumpDeviceStatus.class); - return heatpumpDeviceStatus; + return gson.fromJson(response, HeatpumpDeviceStatus.class); } catch (IOException | JsonSyntaxException e) { setConnected(false); throw new MelCloudCommException("Error occurred during heatpump device status fetch", e); diff --git a/bundles/org.openhab.binding.melcloud/src/main/java/org/openhab/binding/melcloud/internal/discovery/MelCloudDiscoveryService.java b/bundles/org.openhab.binding.melcloud/src/main/java/org/openhab/binding/melcloud/internal/discovery/MelCloudDiscoveryService.java index 679d71a55..8faf3ff72 100644 --- a/bundles/org.openhab.binding.melcloud/src/main/java/org/openhab/binding/melcloud/internal/discovery/MelCloudDiscoveryService.java +++ b/bundles/org.openhab.binding.melcloud/src/main/java/org/openhab/binding/melcloud/internal/discovery/MelCloudDiscoveryService.java @@ -130,9 +130,9 @@ public class MelCloudDiscoveryService extends AbstractDiscoveryService Map deviceProperties = new HashMap<>(); deviceProperties.put(PROPERTY_DEVICE_ID, device.getDeviceID().toString()); - deviceProperties.put(Thing.PROPERTY_SERIAL_NUMBER, device.getSerialNumber().toString()); - deviceProperties.put(Thing.PROPERTY_MAC_ADDRESS, device.getMacAddress().toString()); - deviceProperties.put("deviceName", device.getDeviceName().toString()); + deviceProperties.put(Thing.PROPERTY_SERIAL_NUMBER, device.getSerialNumber()); + deviceProperties.put(Thing.PROPERTY_MAC_ADDRESS, device.getMacAddress()); + deviceProperties.put("deviceName", device.getDeviceName()); deviceProperties.put("buildingID", device.getBuildingID().toString()); String label = createLabel(device); @@ -158,7 +158,7 @@ public class MelCloudDiscoveryService extends AbstractDiscoveryService } else if (device.getType() == 1) { sb.append("Heatpump Device - "); } - if (device.getBuildingName() != null && device.getBuildingName() instanceof String) { + if (device.getBuildingName() instanceof String) { sb.append(device.getBuildingName()).append(" - "); } sb.append(device.getDeviceName()); @@ -167,8 +167,8 @@ public class MelCloudDiscoveryService extends AbstractDiscoveryService @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof MelCloudAccountHandler) { - melCloudHandler = (MelCloudAccountHandler) handler; + if (handler instanceof MelCloudAccountHandler accountHandler) { + melCloudHandler = accountHandler; } } diff --git a/bundles/org.openhab.binding.melcloud/src/main/java/org/openhab/binding/melcloud/internal/handler/MelCloudAccountHandler.java b/bundles/org.openhab.binding.melcloud/src/main/java/org/openhab/binding/melcloud/internal/handler/MelCloudAccountHandler.java index 284d59e51..e69640dfe 100644 --- a/bundles/org.openhab.binding.melcloud/src/main/java/org/openhab/binding/melcloud/internal/handler/MelCloudAccountHandler.java +++ b/bundles/org.openhab.binding.melcloud/src/main/java/org/openhab/binding/melcloud/internal/handler/MelCloudAccountHandler.java @@ -16,6 +16,7 @@ import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; +import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -61,7 +62,7 @@ public class MelCloudAccountHandler extends BaseBridgeHandler { @Override public Collection> getServices() { - return Collections.singleton(MelCloudDiscoveryService.class); + return Set.of(MelCloudDiscoveryService.class); } @Override diff --git a/bundles/org.openhab.binding.mercedesme/src/main/java/org/openhab/binding/mercedesme/internal/handler/AccountHandler.java b/bundles/org.openhab.binding.mercedesme/src/main/java/org/openhab/binding/mercedesme/internal/handler/AccountHandler.java index f47595d86..1b369d19a 100644 --- a/bundles/org.openhab.binding.mercedesme/src/main/java/org/openhab/binding/mercedesme/internal/handler/AccountHandler.java +++ b/bundles/org.openhab.binding.mercedesme/src/main/java/org/openhab/binding/mercedesme/internal/handler/AccountHandler.java @@ -122,7 +122,7 @@ public class AccountHandler extends BaseBridgeHandler implements AccessTokenRefr @Override public void dispose() { - if (!server.isEmpty()) { + if (server.isPresent()) { CallbackServer serv = server.get(); serv.stop(); serv.dispose(); diff --git a/bundles/org.openhab.binding.mercedesme/src/main/java/org/openhab/binding/mercedesme/internal/handler/VehicleHandler.java b/bundles/org.openhab.binding.mercedesme/src/main/java/org/openhab/binding/mercedesme/internal/handler/VehicleHandler.java index ac86182bf..03e0fa8c3 100644 --- a/bundles/org.openhab.binding.mercedesme/src/main/java/org/openhab/binding/mercedesme/internal/handler/VehicleHandler.java +++ b/bundles/org.openhab.binding.mercedesme/src/main/java/org/openhab/binding/mercedesme/internal/handler/VehicleHandler.java @@ -155,7 +155,7 @@ public class VehicleHandler extends BaseThingHandler { logger.debug("Image {} is empty", key); } } - } else if (channelUID.getIdWithoutGroup().equals("clear-cache") && command.equals(OnOffType.ON)) { + } else if ("clear-cache".equals(channelUID.getIdWithoutGroup()) && command.equals(OnOffType.ON)) { List removals = new ArrayList(); imageStorage.get().getKeys().forEach(entry -> { if (entry.contains("_" + config.get().vin)) { diff --git a/bundles/org.openhab.binding.mercedesme/src/main/java/org/openhab/binding/mercedesme/internal/server/CallbackServer.java b/bundles/org.openhab.binding.mercedesme/src/main/java/org/openhab/binding/mercedesme/internal/server/CallbackServer.java index cf9711acd..88c14ee46 100644 --- a/bundles/org.openhab.binding.mercedesme/src/main/java/org/openhab/binding/mercedesme/internal/server/CallbackServer.java +++ b/bundles/org.openhab.binding.mercedesme/src/main/java/org/openhab/binding/mercedesme/internal/server/CallbackServer.java @@ -92,7 +92,7 @@ public class CallbackServer { public boolean start() { LOGGER.debug("Start Callback Server for port {}", config.callbackPort); - if (!server.isEmpty()) { + if (server.isPresent()) { LOGGER.debug("Callback server for port {} already started", config.callbackPort); return true; } @@ -115,7 +115,7 @@ public class CallbackServer { public void stop() { LOGGER.debug("Stop Callback Server"); try { - if (!server.isEmpty()) { + if (server.isPresent()) { server.get().stop(); server = Optional.empty(); } diff --git a/bundles/org.openhab.binding.meteoalerte/src/main/java/org/openhab/binding/meteoalerte/internal/MeteoAlertIconProvider.java b/bundles/org.openhab.binding.meteoalerte/src/main/java/org/openhab/binding/meteoalerte/internal/MeteoAlertIconProvider.java index cff11eb84..d0c5ee4d0 100644 --- a/bundles/org.openhab.binding.meteoalerte/src/main/java/org/openhab/binding/meteoalerte/internal/MeteoAlertIconProvider.java +++ b/bundles/org.openhab.binding.meteoalerte/src/main/java/org/openhab/binding/meteoalerte/internal/MeteoAlertIconProvider.java @@ -103,7 +103,6 @@ public class MeteoAlertIconProvider implements IconProvider { AlertLevel alertLevel = ordinal < AlertLevel.values().length ? AlertLevel.values()[ordinal] : AlertLevel.UNKNOWN; icon = icon.replaceAll(AlertLevel.UNKNOWN.color, alertLevel.color); - } catch (NumberFormatException e) { logger.debug("{} is not a valid DecimalType", state); } diff --git a/bundles/org.openhab.binding.meteoalerte/src/main/java/org/openhab/binding/meteoalerte/internal/handler/MeteoAlerteHandler.java b/bundles/org.openhab.binding.meteoalerte/src/main/java/org/openhab/binding/meteoalerte/internal/handler/MeteoAlerteHandler.java index 0f6e5f005..2bb3d7290 100644 --- a/bundles/org.openhab.binding.meteoalerte/src/main/java/org/openhab/binding/meteoalerte/internal/handler/MeteoAlerteHandler.java +++ b/bundles/org.openhab.binding.meteoalerte/src/main/java/org/openhab/binding/meteoalerte/internal/handler/MeteoAlerteHandler.java @@ -56,9 +56,11 @@ import com.google.gson.Gson; @NonNullByDefault public class MeteoAlerteHandler extends BaseThingHandler { private static final int TIMEOUT_MS = 30000; - private static final String URL = "https://public.opendatasoft.com/api/records/1.0/search/?dataset=risques-meteorologiques-copy&" - + "facet=etat_vent&facet=etat_pluie_inondation&facet=etat_orage&facet=etat_inondation&facet=etat_neige&facet=etat_canicule&" - + "facet=etat_grand_froid&facet=etat_avalanches&refine.nom_dept=%s"; + private static final String URL = """ + https://public.opendatasoft.com/api/records/1.0/search/?dataset=risques-meteorologiques-copy&\ + facet=etat_vent&facet=etat_pluie_inondation&facet=etat_orage&facet=etat_inondation&facet=etat_neige&facet=etat_canicule&\ + facet=etat_grand_froid&facet=etat_avalanches&refine.nom_dept=%s\ + """; private final Logger logger = LoggerFactory.getLogger(MeteoAlerteHandler.class); private final MeteoAlertIconProvider iconProvider; diff --git a/bundles/org.openhab.binding.meteoblue/src/main/java/org/openhab/binding/meteoblue/internal/Forecast.java b/bundles/org.openhab.binding.meteoblue/src/main/java/org/openhab/binding/meteoblue/internal/Forecast.java index fc78d04bf..b627fee98 100644 --- a/bundles/org.openhab.binding.meteoblue/src/main/java/org/openhab/binding/meteoblue/internal/Forecast.java +++ b/bundles/org.openhab.binding.meteoblue/src/main/java/org/openhab/binding/meteoblue/internal/Forecast.java @@ -218,7 +218,7 @@ public class Forecast { // generic getter public Object getDatapoint(String datapointName) { - if (datapointName.equals("condition")) { + if ("condition".equals(datapointName)) { return String.valueOf(pictocode); } diff --git a/bundles/org.openhab.binding.meteoblue/src/main/java/org/openhab/binding/meteoblue/internal/MeteoBlueBindingConstants.java b/bundles/org.openhab.binding.meteoblue/src/main/java/org/openhab/binding/meteoblue/internal/MeteoBlueBindingConstants.java index 42c3bddf7..0714256e2 100644 --- a/bundles/org.openhab.binding.meteoblue/src/main/java/org/openhab/binding/meteoblue/internal/MeteoBlueBindingConstants.java +++ b/bundles/org.openhab.binding.meteoblue/src/main/java/org/openhab/binding/meteoblue/internal/MeteoBlueBindingConstants.java @@ -13,7 +13,6 @@ package org.openhab.binding.meteoblue.internal; import java.util.Arrays; -import java.util.Collections; import java.util.HashSet; import java.util.Set; @@ -32,7 +31,7 @@ public class MeteoBlueBindingConstants { public static final ThingTypeUID THING_TYPE_WEATHER = new ThingTypeUID(BINDING_ID, "weather"); public static final ThingTypeUID THING_TYPE_BRIDGE = new ThingTypeUID(BINDING_ID, "bridge"); - 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_WEATHER)); // Bridge configuration settings diff --git a/bundles/org.openhab.binding.meteoblue/src/main/java/org/openhab/binding/meteoblue/internal/handler/MeteoBlueBridgeHandler.java b/bundles/org.openhab.binding.meteoblue/src/main/java/org/openhab/binding/meteoblue/internal/handler/MeteoBlueBridgeHandler.java index c377be333..6cc35ed9e 100644 --- a/bundles/org.openhab.binding.meteoblue/src/main/java/org/openhab/binding/meteoblue/internal/handler/MeteoBlueBridgeHandler.java +++ b/bundles/org.openhab.binding.meteoblue/src/main/java/org/openhab/binding/meteoblue/internal/handler/MeteoBlueBridgeHandler.java @@ -14,7 +14,6 @@ package org.openhab.binding.meteoblue.internal.handler; import static org.openhab.binding.meteoblue.internal.MeteoBlueBindingConstants.THING_TYPE_BRIDGE; -import java.util.Collections; import java.util.Set; import org.openhab.binding.meteoblue.internal.MeteoBlueBridgeConfig; @@ -36,7 +35,7 @@ import org.slf4j.LoggerFactory; * @author Chris Carman - Initial contribution */ public class MeteoBlueBridgeHandler extends BaseBridgeHandler { - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_BRIDGE); + public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_BRIDGE); private final Logger logger = LoggerFactory.getLogger(MeteoBlueBridgeHandler.class); private String apiKey; diff --git a/bundles/org.openhab.binding.meteoblue/src/main/java/org/openhab/binding/meteoblue/internal/handler/MeteoBlueHandler.java b/bundles/org.openhab.binding.meteoblue/src/main/java/org/openhab/binding/meteoblue/internal/handler/MeteoBlueHandler.java index 3bc1c2484..66f2f82f8 100644 --- a/bundles/org.openhab.binding.meteoblue/src/main/java/org/openhab/binding/meteoblue/internal/handler/MeteoBlueHandler.java +++ b/bundles/org.openhab.binding.meteoblue/src/main/java/org/openhab/binding/meteoblue/internal/handler/MeteoBlueHandler.java @@ -230,9 +230,8 @@ public class MeteoBlueHandler extends BaseThingHandler { // Build a State from this value State state = null; - if (datapoint instanceof Calendar) { - state = new DateTimeType( - ZonedDateTime.ofInstant(((Calendar) datapoint).toInstant(), ZoneId.systemDefault())); + if (datapoint instanceof Calendar calendar) { + state = new DateTimeType(ZonedDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault())); } else if (datapoint instanceof Integer) { state = getStateForType(channel.getAcceptedItemType(), (Integer) datapoint); } else if (datapoint instanceof Number) { @@ -240,9 +239,9 @@ public class MeteoBlueHandler extends BaseThingHandler { state = getStateForType(channel.getAcceptedItemType(), decimalValue); } else if (datapoint instanceof String) { state = new StringType(datapoint.toString()); - } else if (datapoint instanceof BufferedImage) { + } else if (datapoint instanceof BufferedImage image) { ImageItem item = new ImageItem("rain area"); - state = new RawType(renderImage((BufferedImage) datapoint), "image/png"); + state = new RawType(renderImage(image), "image/png"); item.setState(state); } else { logger.debug("Unsupported value type {}", datapoint.getClass().getSimpleName()); @@ -263,13 +262,13 @@ public class MeteoBlueHandler extends BaseThingHandler { private State getStateForType(String type, BigDecimal value) { State state = new DecimalType(value); - if (type.equals("Number:Temperature")) { + if ("Number:Temperature".equals(type)) { state = new QuantityType<>(value, SIUnits.CELSIUS); - } else if (type.equals("Number:Length")) { + } else if ("Number:Length".equals(type)) { state = new QuantityType<>(value, MILLI(SIUnits.METRE)); - } else if (type.equals("Number:Pressure")) { + } else if ("Number:Pressure".equals(type)) { state = new QuantityType<>(value, HECTO(SIUnits.PASCAL)); - } else if (type.equals("Number:Speed")) { + } else if ("Number:Speed".equals(type)) { state = new QuantityType<>(value, Units.METRE_PER_SECOND); } @@ -335,9 +334,9 @@ public class MeteoBlueHandler extends BaseThingHandler { String errorMessage = jsonResult.getErrorMessage(); if (errorMessage != null) { - if (errorMessage.equals("MB_REQUEST::DISPATCH: Invalid api key")) { + if ("MB_REQUEST::DISPATCH: Invalid api key".equals(errorMessage)) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Invalid API Key"); - } else if (errorMessage.equals("MB_REQUEST::DISPATCH: This datafeed is not authorized for your api key")) { + } else if ("MB_REQUEST::DISPATCH: This datafeed is not authorized for your api key".equals(errorMessage)) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "API Key not authorized for this datafeed"); } else { diff --git a/bundles/org.openhab.binding.meteostick/src/main/java/org/openhab/binding/meteostick/internal/handler/MeteostickBridgeHandler.java b/bundles/org.openhab.binding.meteostick/src/main/java/org/openhab/binding/meteostick/internal/handler/MeteostickBridgeHandler.java index 8cf41ef07..afa1f9311 100644 --- a/bundles/org.openhab.binding.meteostick/src/main/java/org/openhab/binding/meteostick/internal/handler/MeteostickBridgeHandler.java +++ b/bundles/org.openhab.binding.meteostick/src/main/java/org/openhab/binding/meteostick/internal/handler/MeteostickBridgeHandler.java @@ -19,7 +19,6 @@ import static org.openhab.core.library.unit.SIUnits.*; import java.io.IOException; import java.math.BigDecimal; import java.math.RoundingMode; -import java.util.Collections; import java.util.Date; import java.util.Set; import java.util.TooManyListenersException; @@ -54,7 +53,7 @@ import org.slf4j.LoggerFactory; * @author Chris Jackson - Initial contribution */ public class MeteostickBridgeHandler extends BaseBridgeHandler { - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_BRIDGE); + public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_BRIDGE); private final Logger logger = LoggerFactory.getLogger(MeteostickBridgeHandler.class); @@ -256,7 +255,7 @@ public class MeteostickBridgeHandler extends BaseBridgeHandler { if (rxByte == 13 && rxCnt > 0) { String inputString = new String(rxPacket, 0, rxCnt); logger.debug("MeteoStick received: {}", inputString); - String p[] = inputString.split("\\s+"); + String[] p = inputString.split("\\s+"); switch (p[0]) { case "B": // Barometer diff --git a/bundles/org.openhab.binding.meteostick/src/main/java/org/openhab/binding/meteostick/internal/handler/MeteostickEventListener.java b/bundles/org.openhab.binding.meteostick/src/main/java/org/openhab/binding/meteostick/internal/handler/MeteostickEventListener.java index 3829d3e88..c73b12545 100644 --- a/bundles/org.openhab.binding.meteostick/src/main/java/org/openhab/binding/meteostick/internal/handler/MeteostickEventListener.java +++ b/bundles/org.openhab.binding.meteostick/src/main/java/org/openhab/binding/meteostick/internal/handler/MeteostickEventListener.java @@ -24,5 +24,5 @@ public interface MeteostickEventListener { * * @param data a line of data from the meteoStick */ - void onDataReceived(String data[]); + void onDataReceived(String[] data); } diff --git a/bundles/org.openhab.binding.meteostick/src/main/java/org/openhab/binding/meteostick/internal/handler/MeteostickSensorHandler.java b/bundles/org.openhab.binding.meteostick/src/main/java/org/openhab/binding/meteostick/internal/handler/MeteostickSensorHandler.java index d86fda0ec..bb62e1dd7 100644 --- a/bundles/org.openhab.binding.meteostick/src/main/java/org/openhab/binding/meteostick/internal/handler/MeteostickSensorHandler.java +++ b/bundles/org.openhab.binding.meteostick/src/main/java/org/openhab/binding/meteostick/internal/handler/MeteostickSensorHandler.java @@ -50,7 +50,7 @@ import org.slf4j.LoggerFactory; * @author John Cocula - Added variable spoon size, UoM, wind stats, bug fixes */ public class MeteostickSensorHandler extends BaseThingHandler implements MeteostickEventListener { - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_DAVIS); + public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_DAVIS); private final Logger logger = LoggerFactory.getLogger(MeteostickSensorHandler.class); diff --git a/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/discovery/MieleApplianceDiscoveryService.java b/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/discovery/MieleApplianceDiscoveryService.java index 748e7caf0..f79203cd1 100644 --- a/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/discovery/MieleApplianceDiscoveryService.java +++ b/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/discovery/MieleApplianceDiscoveryService.java @@ -152,8 +152,7 @@ public class MieleApplianceDiscoveryService extends AbstractDiscoveryService imp ThingTypeUID thingTypeUID = getThingTypeUidFromModelId(modelId); if (getSupportedThingTypes().contains(thingTypeUID)) { - ThingUID thingUID = new ThingUID(thingTypeUID, bridgeUID, appliance.getApplianceIdentifier().getId()); - return thingUID; + return new ThingUID(thingTypeUID, bridgeUID, appliance.getApplianceIdentifier().getId()); } else { return null; } diff --git a/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/CoffeeMachineChannelSelector.java b/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/CoffeeMachineChannelSelector.java index 20aaf8d6e..121e0b60b 100644 --- a/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/CoffeeMachineChannelSelector.java +++ b/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/CoffeeMachineChannelSelector.java @@ -150,6 +150,7 @@ public enum CoffeeMachineChannelSelector implements ApplianceChannelSelector { } } + @Override public State getState(String s) { try { Method valueOf = typeClass.getMethod("valueOf", String.class); diff --git a/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/DishwasherChannelSelector.java b/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/DishwasherChannelSelector.java index 82afac4d0..bbcaab2df 100644 --- a/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/DishwasherChannelSelector.java +++ b/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/DishwasherChannelSelector.java @@ -186,6 +186,7 @@ public enum DishwasherChannelSelector implements ApplianceChannelSelector { } } + @Override public State getState(String s) { try { Method valueOf = typeClass.getMethod("valueOf", String.class); diff --git a/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/DishwasherHandler.java b/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/DishwasherHandler.java index 5242b3cc8..b3addc870 100644 --- a/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/DishwasherHandler.java +++ b/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/DishwasherHandler.java @@ -122,6 +122,7 @@ public class DishwasherHandler extends MieleApplianceHandler & ApplianceChannel byte[] extendedStateBytes = DeviceUtil.stringToBytes(dp.Value); logger.trace("Extended device state for {}: {}", getThing().getUID(), DeviceUtil.bytesToHex(extendedStateBytes)); - if (this instanceof ExtendedDeviceStateListener) { - ((ExtendedDeviceStateListener) this).onApplianceExtendedStateChanged(extendedStateBytes); + if (this instanceof ExtendedDeviceStateListener listener) { + listener.onApplianceExtendedStateChanged(extendedStateBytes); } } return; @@ -441,8 +441,8 @@ public abstract class MieleApplianceHandler & ApplianceChannel return null; } ThingHandler handler = bridge.getHandler(); - if (handler instanceof MieleBridgeHandler) { - this.bridgeHandler = (MieleBridgeHandler) handler; + if (handler instanceof MieleBridgeHandler mieleBridgeHandler) { + this.bridgeHandler = mieleBridgeHandler; } } return this.bridgeHandler; diff --git a/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/OvenChannelSelector.java b/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/OvenChannelSelector.java index dcd983a03..12294effb 100644 --- a/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/OvenChannelSelector.java +++ b/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/OvenChannelSelector.java @@ -195,6 +195,7 @@ public enum OvenChannelSelector implements ApplianceChannelSelector { } } + @Override public State getState(String s) { try { Method valueOf = typeClass.getMethod("valueOf", String.class); diff --git a/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/TumbleDryerChannelSelector.java b/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/TumbleDryerChannelSelector.java index 8ccaecf4c..82eeabf08 100644 --- a/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/TumbleDryerChannelSelector.java +++ b/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/TumbleDryerChannelSelector.java @@ -195,6 +195,7 @@ public enum TumbleDryerChannelSelector implements ApplianceChannelSelector { } } + @Override public State getState(String s) { try { Method valueOf = typeClass.getMethod("valueOf", String.class); diff --git a/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/WashingMachineChannelSelector.java b/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/WashingMachineChannelSelector.java index 9dca96925..df9d1b129 100644 --- a/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/WashingMachineChannelSelector.java +++ b/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/WashingMachineChannelSelector.java @@ -210,6 +210,7 @@ public enum WashingMachineChannelSelector implements ApplianceChannelSelector { } } + @Override public State getState(String s) { try { Method valueOf = typeClass.getMethod("valueOf", String.class); diff --git a/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/WashingMachineHandler.java b/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/WashingMachineHandler.java index 57f872640..894225053 100644 --- a/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/WashingMachineHandler.java +++ b/bundles/org.openhab.binding.miele/src/main/java/org/openhab/binding/miele/internal/handler/WashingMachineHandler.java @@ -123,6 +123,7 @@ public class WashingMachineHandler extends MieleApplianceHandler\n" - + " Warning: We strongly advice to proceed only with SSL enabled for a secure data exchange.\n" - + " See Securing access to openHAB for details.\n" - + " "); + return skeleton.replace(NO_SSL_WARNING_PLACEHOLDER, + """ + \ + """); } else { return skeleton.replace(NO_SSL_WARNING_PLACEHOLDER, ""); } diff --git a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/discovery/ThingDiscoveryService.java b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/discovery/ThingDiscoveryService.java index 2bd48e504..074ab5c08 100644 --- a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/discovery/ThingDiscoveryService.java +++ b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/discovery/ThingDiscoveryService.java @@ -200,8 +200,7 @@ public class ThingDiscoveryService extends AbstractDiscoveryService implements D @Override public void setThingHandler(ThingHandler handler) { - if (handler instanceof MieleBridgeHandler) { - var bridgeHandler = (MieleBridgeHandler) handler; + if (handler instanceof MieleBridgeHandler bridgeHandler) { bridgeHandler.setDiscoveryService(this); this.bridgeHandler = bridgeHandler; } diff --git a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/discovery/ThingInformationExtractor.java b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/discovery/ThingInformationExtractor.java index dbecb0c4f..6db6675ce 100644 --- a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/discovery/ThingInformationExtractor.java +++ b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/discovery/ThingInformationExtractor.java @@ -82,10 +82,10 @@ public final class ThingInformationExtractor { if (deviceType.isPresent() && techType.isPresent()) { return Optional.of(deviceType.get() + " " + techType.get()); } - if (!deviceType.isPresent() && techType.isPresent()) { + if (deviceType.isEmpty() && techType.isPresent()) { return techType; } - if (deviceType.isPresent() && !techType.isPresent()) { + if (deviceType.isPresent() && techType.isEmpty()) { return deviceType; } return Optional.empty(); diff --git a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/handler/AbstractMieleThingHandler.java b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/handler/AbstractMieleThingHandler.java index a18af7171..b5b63b5bb 100644 --- a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/handler/AbstractMieleThingHandler.java +++ b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/handler/AbstractMieleThingHandler.java @@ -80,7 +80,7 @@ public abstract class AbstractMieleThingHandler extends BaseThingHandler { } BridgeHandler handler = bridge.getHandler(); - if (handler == null || !(handler instanceof MieleBridgeHandler)) { + if (!(handler instanceof MieleBridgeHandler)) { return Optional.empty(); } diff --git a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/handler/MieleBridgeHandler.java b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/handler/MieleBridgeHandler.java index bab514ffd..4a39cadfa 100644 --- a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/handler/MieleBridgeHandler.java +++ b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/handler/MieleBridgeHandler.java @@ -13,8 +13,8 @@ package org.openhab.binding.mielecloud.internal.handler; import java.util.Collection; -import java.util.Collections; import java.util.Optional; +import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledExecutorService; @@ -230,7 +230,7 @@ public class MieleBridgeHandler extends BaseBridgeHandler private void tryInitializeWebservice() { Optional accessToken = tokenRefresher.getAccessTokenFromStorage(getOAuthServiceHandle()); - if (!accessToken.isPresent()) { + if (accessToken.isEmpty()) { logger.debug("No OAuth2 access token available. Retrying later."); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING, I18NKeys.BRIDGE_STATUS_DESCRIPTION_ACCESS_TOKEN_NOT_CONFIGURED); @@ -301,8 +301,7 @@ public class MieleBridgeHandler extends BaseBridgeHandler @Override public Optional getLanguage() { Object languageObject = thing.getConfiguration().get(MieleCloudBindingConstants.CONFIG_PARAM_LOCALE); - if (languageObject instanceof String) { - String language = (String) languageObject; + if (languageObject instanceof String language) { if (language.isEmpty() || !LocaleValidator.isValidLanguage(language)) { return Optional.empty(); } else { @@ -348,6 +347,6 @@ public class MieleBridgeHandler extends BaseBridgeHandler @Override public Collection> getServices() { - return Collections.singleton(ThingDiscoveryService.class); + return Set.of(ThingDiscoveryService.class); } } diff --git a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/handler/channel/ChannelTypeUtil.java b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/handler/channel/ChannelTypeUtil.java index a1a50d28a..02404fb1d 100644 --- a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/handler/channel/ChannelTypeUtil.java +++ b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/handler/channel/ChannelTypeUtil.java @@ -46,7 +46,7 @@ public final class ChannelTypeUtil { * Converts an {@link Optional} of {@link String} to {@link State}. */ public static State stringToState(Optional value) { - return value.filter(v -> !v.isEmpty()).filter(v -> !v.equals("null")).map(v -> (State) new StringType(v)) + return value.filter(v -> !v.isEmpty()).filter(v -> !"null".equals(v)).map(v -> (State) new StringType(v)) .orElse(UnDefType.UNDEF); } diff --git a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/DefaultMieleWebservice.java b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/DefaultMieleWebservice.java index 44c6b1fec..2d4a6bde6 100644 --- a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/DefaultMieleWebservice.java +++ b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/DefaultMieleWebservice.java @@ -132,7 +132,7 @@ public final class DefaultMieleWebservice implements MieleWebservice, SseListene @Nullable private Request createSseRequest(String endpoint) { Optional accessToken = this.accessToken; - if (!accessToken.isPresent()) { + if (accessToken.isEmpty()) { logger.warn("No access token present."); return null; } @@ -243,7 +243,7 @@ public final class DefaultMieleWebservice implements MieleWebservice, SseListene @Override public void logout() { Optional accessToken = this.accessToken; - if (!accessToken.isPresent()) { + if (accessToken.isEmpty()) { logger.debug("No access token present."); return; } @@ -301,7 +301,7 @@ public final class DefaultMieleWebservice implements MieleWebservice, SseListene */ private Actions getActions(String deviceId) { Optional accessToken = this.accessToken; - if (!accessToken.isPresent()) { + if (accessToken.isEmpty()) { throw new MieleWebserviceException("Missing access token.", ConnectionError.AUTHORIZATION_FAILED); } @@ -337,7 +337,7 @@ public final class DefaultMieleWebservice implements MieleWebservice, SseListene private void putActions(String deviceId, String json) { retryStrategy.performRetryableOperation(() -> { Optional accessToken = this.accessToken; - if (!accessToken.isPresent()) { + if (accessToken.isEmpty()) { throw new MieleWebserviceException("Missing access token.", ConnectionError.AUTHORIZATION_FAILED); } diff --git a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/HttpUtil.java b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/HttpUtil.java index 6ffc29cc9..7e70b08e6 100644 --- a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/HttpUtil.java +++ b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/HttpUtil.java @@ -81,9 +81,9 @@ public final class HttpUtil { private static String getHttpErrorMessageFromCloudResponse(Response response) { String exceptionMessage = "HTTP error " + response.getStatus() + ": " + response.getReason(); - if (response instanceof ContentResponse) { + if (response instanceof ContentResponse contentResponse) { try { - ErrorMessage errorMessage = ErrorMessage.fromJson(((ContentResponse) response).getContentAsString()); + ErrorMessage errorMessage = ErrorMessage.fromJson(contentResponse.getContentAsString()); exceptionMessage += "\nCloud returned message: " + errorMessage.getMessage(); } catch (MieleSyntaxException e) { exceptionMessage += "\nCloud returned invalid message."; diff --git a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/api/DeviceState.java b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/api/DeviceState.java index 64477b6f9..e54ba0df4 100644 --- a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/api/DeviceState.java +++ b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/api/DeviceState.java @@ -181,7 +181,7 @@ public class DeviceState { Optional targetTemperature = getTargetTemperature(0); Optional currentTemperature = getTemperature(0); - if (!targetTemperature.isPresent() || !currentTemperature.isPresent()) { + if (targetTemperature.isEmpty() || currentTemperature.isEmpty()) { return Optional.empty(); } @@ -452,7 +452,7 @@ public class DeviceState { Optional doorState = getDoorState(); Optional failure = device.flatMap(Device::getState).flatMap(State::getSignalFailure); - if (!doorState.isPresent() || !failure.isPresent()) { + if (doorState.isEmpty() || failure.isEmpty()) { return Optional.empty(); } diff --git a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/api/TransitionState.java b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/api/TransitionState.java index 853905829..4a4cccda6 100644 --- a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/api/TransitionState.java +++ b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/api/TransitionState.java @@ -86,7 +86,7 @@ public class TransitionState { } private Optional hasFinishedFromPreviousState(DeviceState prevState) { - if (!prevState.getStateType().isPresent()) { + if (prevState.getStateType().isEmpty()) { return Optional.empty(); } diff --git a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/retry/AuthorizationFailedRetryStrategy.java b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/retry/AuthorizationFailedRetryStrategy.java index ca529487a..1540d832f 100644 --- a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/retry/AuthorizationFailedRetryStrategy.java +++ b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/retry/AuthorizationFailedRetryStrategy.java @@ -71,7 +71,7 @@ public class AuthorizationFailedRetryStrategy implements RetryStrategy { } catch (MieleWebserviceException e) { // Workaround for HTML response from cloud in case of a 401 HTTP error. var cause = e.getCause(); - if (cause == null || !(cause instanceof ExecutionException)) { + if (!(cause instanceof ExecutionException)) { throw e; } diff --git a/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/config/ThingsTemplateGeneratorTest.java b/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/config/ThingsTemplateGeneratorTest.java index 934a43bea..2efd61b8d 100644 --- a/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/config/ThingsTemplateGeneratorTest.java +++ b/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/config/ThingsTemplateGeneratorTest.java @@ -18,6 +18,7 @@ import static org.mockito.Mockito.*; import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.Map; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; @@ -138,7 +139,7 @@ public class ThingsTemplateGeneratorTest { when(discoveryResult.getThingTypeUID()).thenReturn(thingTypeUid); when(discoveryResult.getThingUID()).thenReturn(new ThingUID(thingTypeUid, id, bridgeId)); when(discoveryResult.getProperties()) - .thenReturn(Collections.singletonMap(MieleCloudBindingConstants.CONFIG_PARAM_DEVICE_IDENTIFIER, id)); + .thenReturn(Map.of(MieleCloudBindingConstants.CONFIG_PARAM_DEVICE_IDENTIFIER, id)); return discoveryResult; } @@ -177,9 +178,12 @@ public class ThingsTemplateGeneratorTest { Collections.emptyList()); // then: - assertEquals("Bridge mielecloud:account:mielebridge [ email=\"everyone@openhab.org\", locale=\"de\" ] {\n" - + " Thing oven 000137439123 \"Oven H7860XY\" [ deviceIdentifier=\"000137439123\" ]\n" - + " Thing hob 000160106123 [ deviceIdentifier=\"000160106123\" ]\n}", template); + assertEquals(""" + Bridge mielecloud:account:mielebridge [ email="everyone@openhab.org", locale="de" ] { + Thing oven 000137439123 "Oven H7860XY" [ deviceIdentifier="000137439123" ] + Thing hob 000160106123 [ deviceIdentifier="000160106123" ] + }\ + """, template); } @Test @@ -203,10 +207,12 @@ public class ThingsTemplateGeneratorTest { discoveredThings); // then: - assertEquals("Bridge mielecloud:account:mielebridge [ email=\"everyone@openhab.org\", locale=\"de\" ] {\n" - + " Thing fridge_freezer 000154106123 \"Fridge-Freezer Kitchen\" [ deviceIdentifier=\"000154106123\" ]\n" - + " Thing washing_machine 000189106123 \"Washing Machine\" [ deviceIdentifier=\"000189106123\" ]\n}", - template); + assertEquals(""" + Bridge mielecloud:account:mielebridge [ email="everyone@openhab.org", locale="de" ] { + Thing fridge_freezer 000154106123 "Fridge-Freezer Kitchen" [ deviceIdentifier="000154106123" ] + Thing washing_machine 000189106123 "Washing Machine" [ deviceIdentifier="000189106123" ] + }\ + """, template); } @Test @@ -237,12 +243,14 @@ public class ThingsTemplateGeneratorTest { discoveredThings); // then: - assertEquals("Bridge mielecloud:account:mielebridge [ email=\"openhab@openhab.org\", locale=\"de\" ] {\n" - + " Thing oven 000137439123 \"Oven H7860XY\" [ deviceIdentifier=\"000137439123\" ]\n" - + " Thing hob 000160106123 [ deviceIdentifier=\"000160106123\" ]\n" - + " Thing fridge_freezer 000154106123 \"Fridge-Freezer Kitchen\" [ deviceIdentifier=\"000154106123\" ]\n" - + " Thing washing_machine 000189106123 \"Washing Machine\" [ deviceIdentifier=\"000189106123\" ]\n}", - template); + assertEquals(""" + Bridge mielecloud:account:mielebridge [ email="openhab@openhab.org", locale="de" ] { + Thing oven 000137439123 "Oven H7860XY" [ deviceIdentifier="000137439123" ] + Thing hob 000160106123 [ deviceIdentifier="000160106123" ] + Thing fridge_freezer 000154106123 "Fridge-Freezer Kitchen" [ deviceIdentifier="000154106123" ] + Thing washing_machine 000189106123 "Washing Machine" [ deviceIdentifier="000189106123" ] + }\ + """, template); } @Test diff --git a/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/webservice/DefaultMieleWebserviceTest.java b/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/webservice/DefaultMieleWebserviceTest.java index da10dd4f9..4a249353f 100644 --- a/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/webservice/DefaultMieleWebserviceTest.java +++ b/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/webservice/DefaultMieleWebserviceTest.java @@ -398,7 +398,6 @@ public class DefaultMieleWebserviceTest { try (DefaultMieleWebservice webservice = new DefaultMieleWebservice(requestFactory, retryStrategy, new DeviceStateDispatcher(), scheduler)) { - // when: assertThrows(IllegalArgumentException.class, () -> { webservice.putProcessAction(DEVICE_IDENTIFIER, ProcessAction.UNKNOWN); diff --git a/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/webservice/api/ActionsStateTest.java b/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/webservice/api/ActionsStateTest.java index 0a69c71f9..24cd24b43 100644 --- a/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/webservice/api/ActionsStateTest.java +++ b/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/webservice/api/ActionsStateTest.java @@ -125,7 +125,7 @@ public class ActionsStateTest { // given: Actions actions = mock(Actions.class); ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions); - when(actions.getProcessAction()).thenReturn(Collections.singletonList(ProcessAction.START)); + when(actions.getProcessAction()).thenReturn(List.of(ProcessAction.START)); // when: boolean canBeStarted = actionState.canBeStarted(); @@ -141,7 +141,7 @@ public class ActionsStateTest { // given: Actions actions = mock(Actions.class); ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions); - when(actions.getProcessAction()).thenReturn(Collections.singletonList(ProcessAction.STOP)); + when(actions.getProcessAction()).thenReturn(List.of(ProcessAction.STOP)); // when: boolean canBeStarted = actionState.canBeStarted(); @@ -173,7 +173,7 @@ public class ActionsStateTest { // given: Actions actions = mock(Actions.class); ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions); - when(actions.getProcessAction()).thenReturn(Collections.singletonList(ProcessAction.START_SUPERCOOLING)); + when(actions.getProcessAction()).thenReturn(List.of(ProcessAction.START_SUPERCOOLING)); // when: boolean canStartSupercooling = actionState.canStartSupercooling(); @@ -189,7 +189,7 @@ public class ActionsStateTest { // given: Actions actions = mock(Actions.class); ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions); - when(actions.getProcessAction()).thenReturn(Collections.singletonList(ProcessAction.START_SUPERFREEZING)); + when(actions.getProcessAction()).thenReturn(List.of(ProcessAction.START_SUPERFREEZING)); // when: boolean canStartSuperfreezing = actionState.canStartSuperfreezing(); @@ -205,7 +205,7 @@ public class ActionsStateTest { // given: Actions actions = mock(Actions.class); ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions); - when(actions.getLight()).thenReturn(Collections.singletonList(Light.ENABLE)); + when(actions.getLight()).thenReturn(List.of(Light.ENABLE)); // when: boolean canEnableLight = actionState.canEnableLight(); @@ -219,7 +219,7 @@ public class ActionsStateTest { // given: Actions actions = mock(Actions.class); ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions); - when(actions.getLight()).thenReturn(Collections.singletonList(Light.DISABLE)); + when(actions.getLight()).thenReturn(List.of(Light.DISABLE)); // when: boolean canDisableLight = actionState.canDisableLight(); @@ -232,7 +232,7 @@ public class ActionsStateTest { public void testCanControlLightReturnsTrueWhenLightCanBeEnabled() { // given: Actions actions = mock(Actions.class); - when(actions.getLight()).thenReturn(Collections.singletonList(Light.ENABLE)); + when(actions.getLight()).thenReturn(List.of(Light.ENABLE)); ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions); @@ -247,7 +247,7 @@ public class ActionsStateTest { public void testCanControlLightReturnsTrueWhenLightCanBeDisabled() { // given: Actions actions = mock(Actions.class); - when(actions.getLight()).thenReturn(Collections.singletonList(Light.DISABLE)); + when(actions.getLight()).thenReturn(List.of(Light.DISABLE)); ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions); @@ -307,7 +307,7 @@ public class ActionsStateTest { public void testProgramIdCanBeSetWhenProgramIdIsPresent() { // given: Actions actions = mock(Actions.class); - when(actions.getProgramId()).thenReturn(Collections.singletonList(1)); + when(actions.getProgramId()).thenReturn(List.of(1)); ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions); diff --git a/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/webservice/api/DeviceStateTest.java b/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/webservice/api/DeviceStateTest.java index 616c9fbdd..e2a4592e0 100644 --- a/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/webservice/api/DeviceStateTest.java +++ b/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/webservice/api/DeviceStateTest.java @@ -18,6 +18,7 @@ import static org.mockito.Mockito.*; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; +import java.util.List; import java.util.Optional; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -851,7 +852,7 @@ public class DeviceStateTest { when(plateStepMock.getValueLocalized()).thenReturn(Optional.empty()); State state = mock(State.class); - when(state.getPlateStep()).thenReturn(Collections.singletonList(plateStepMock)); + when(state.getPlateStep()).thenReturn(List.of(plateStepMock)); when(state.getStatus()).thenReturn(Optional.of(status)); Device device = mock(Device.class); @@ -1111,7 +1112,7 @@ public class DeviceStateTest { State state = mock(State.class); when(state.getStatus()).thenReturn(Optional.of(status)); - when(state.getElapsedTime()).thenReturn(Optional.of(Collections.singletonList(2))); + when(state.getElapsedTime()).thenReturn(Optional.of(List.of(2))); Device device = mock(Device.class); when(device.getState()).thenReturn(Optional.of(state)); @@ -1866,7 +1867,7 @@ public class DeviceStateTest { // Test TargetTemperature: Temperature targetTemperatureMock = mock(Temperature.class); - when(state.getTargetTemperature()).thenReturn(Collections.singletonList(targetTemperatureMock)); + when(state.getTargetTemperature()).thenReturn(List.of(targetTemperatureMock)); when(targetTemperatureMock.getValueLocalized()).thenReturn(Optional.of(200)); // when: Optional targetTemperature = deviceState.getTargetTemperature(0); @@ -1875,7 +1876,7 @@ public class DeviceStateTest { // Test Temperature: Temperature temperature = mock(Temperature.class); - when(state.getTemperature()).thenReturn(Collections.singletonList(temperature)); + when(state.getTemperature()).thenReturn(List.of(temperature)); when(temperature.getValueLocalized()).thenReturn(Optional.of(200)); // when: Optional t = deviceState.getTemperature(0); diff --git a/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/webservice/api/json/ActionsCollectionTest.java b/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/webservice/api/json/ActionsCollectionTest.java index afbaeff3a..30c7fecd6 100644 --- a/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/webservice/api/json/ActionsCollectionTest.java +++ b/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/webservice/api/json/ActionsCollectionTest.java @@ -16,9 +16,9 @@ import static org.junit.jupiter.api.Assertions.*; import static org.openhab.binding.mielecloud.internal.util.ResourceUtil.getResourceAsString; import java.io.IOException; -import java.util.Collections; import java.util.List; import java.util.Optional; +import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; import org.junit.jupiter.api.Test; @@ -38,13 +38,13 @@ public class ActionsCollectionTest { ActionsCollection collection = ActionsCollection.fromJson(json); // then: - assertEquals(Collections.singleton("000123456789"), collection.getDeviceIdentifiers()); + assertEquals(Set.of("000123456789"), collection.getDeviceIdentifiers()); Actions actions = collection.getActions("000123456789"); assertEquals(List.of(ProcessAction.START, ProcessAction.STOP), actions.getProcessAction()); - assertEquals(Collections.singletonList(Light.DISABLE), actions.getLight()); + assertEquals(List.of(Light.DISABLE), actions.getLight()); assertEquals(Optional.empty(), actions.getStartTime()); - assertEquals(Collections.singletonList(123), actions.getProgramId()); + assertEquals(List.of(123), actions.getProgramId()); assertEquals(Optional.of(true), actions.getPowerOn()); assertEquals(Optional.of(false), actions.getPowerOff()); } @@ -69,6 +69,6 @@ public class ActionsCollectionTest { DeviceCollection collection = DeviceCollection.fromJson(json); // then: - assertEquals(Collections.singleton("mac-00124B000AE539D6"), collection.getDeviceIdentifiers()); + assertEquals(Set.of("mac-00124B000AE539D6"), collection.getDeviceIdentifiers()); } } diff --git a/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/webservice/api/json/ActionsTest.java b/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/webservice/api/json/ActionsTest.java index dd4ea2571..959662f98 100644 --- a/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/webservice/api/json/ActionsTest.java +++ b/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/webservice/api/json/ActionsTest.java @@ -16,7 +16,6 @@ import static org.junit.jupiter.api.Assertions.*; import java.io.IOException; import java.util.Arrays; -import java.util.Collections; import java.util.List; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -112,7 +111,7 @@ public class ActionsTest { Actions actions = new Gson().fromJson(json, Actions.class); // then: - assertEquals(Collections.singletonList(ProcessAction.START), actions.getProcessAction()); + assertEquals(List.of(ProcessAction.START), actions.getProcessAction()); } @Test diff --git a/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/discovery/XiaomiBridgeDiscoveryService.java b/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/discovery/XiaomiBridgeDiscoveryService.java index 96e2d8018..cf52e3b01 100644 --- a/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/discovery/XiaomiBridgeDiscoveryService.java +++ b/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/discovery/XiaomiBridgeDiscoveryService.java @@ -14,7 +14,6 @@ package org.openhab.binding.mihome.internal.discovery; import static org.openhab.binding.mihome.internal.XiaomiGatewayBindingConstants.*; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -43,7 +42,7 @@ import com.google.gson.JsonObject; @Component(service = DiscoveryService.class, configurationPid = "discovery.mihome") public class XiaomiBridgeDiscoveryService extends AbstractDiscoveryService implements XiaomiSocketListener { - 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 DISCOVERY_TIMEOUT_SEC = 30; private final Logger logger = LoggerFactory.getLogger(XiaomiBridgeDiscoveryService.class); @@ -78,7 +77,7 @@ public class XiaomiBridgeDiscoveryService extends AbstractDiscoveryService imple @Override public void onDataReceived(JsonObject data) { logger.debug("Received message {}", data); - if (data.get("cmd").getAsString().equals("iam")) { + if ("iam".equals(data.get("cmd").getAsString())) { getGatewayInfo(data); } } diff --git a/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/discovery/XiaomiItemDiscoveryService.java b/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/discovery/XiaomiItemDiscoveryService.java index c2733c5de..28a2ed31f 100644 --- a/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/discovery/XiaomiItemDiscoveryService.java +++ b/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/discovery/XiaomiItemDiscoveryService.java @@ -91,7 +91,7 @@ public class XiaomiItemDiscoveryService extends AbstractDiscoveryService impleme @Override public void onItemUpdate(String sid, String command, JsonObject data) { - if (command.equals("read_ack") || command.equals("report") || command.equals("heartbeat")) { + if ("read_ack".equals(command) || "report".equals(command) || "heartbeat".equals(command)) { String model = data.get("model").getAsString(); ThingTypeUID thingType = getThingTypeForModel(model); diff --git a/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/handler/XiaomiActorGatewayHandler.java b/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/handler/XiaomiActorGatewayHandler.java index 5a6511153..9cda485b1 100644 --- a/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/handler/XiaomiActorGatewayHandler.java +++ b/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/handler/XiaomiActorGatewayHandler.java @@ -62,8 +62,8 @@ public class XiaomiActorGatewayHandler extends XiaomiActorBaseHandler { void execute(ChannelUID channelUID, Command command) { switch (channelUID.getId()) { case CHANNEL_BRIGHTNESS: - if (command instanceof PercentType) { - int newBright = ((PercentType) command).intValue(); + if (command instanceof PercentType percentCommand) { + int newBright = percentCommand.intValue(); if (lastBrigthness != newBright) { lastBrigthness = newBright; logger.debug("Set brigthness to {}", lastBrigthness); @@ -78,16 +78,15 @@ public class XiaomiActorGatewayHandler extends XiaomiActorBaseHandler { } break; case CHANNEL_COLOR: - if (command instanceof HSBType) { - lastColor = ((HSBType) command).getRGB() & 0xffffff; + if (command instanceof HSBType hsbCommand) { + lastColor = hsbCommand.getRGB() & 0xffffff; writeBridgeLightColor(lastColor, lastBrigthness); return; } break; case CHANNEL_COLOR_TEMPERATURE: - if (command instanceof PercentType) { - PercentType colorTemperature = (PercentType) command; - int kelvin = (COLOR_TEMPERATURE_MAX - COLOR_TEMPERATURE_MIN) / 100 * colorTemperature.intValue() + if (command instanceof PercentType percentCommand) { + int kelvin = (COLOR_TEMPERATURE_MAX - COLOR_TEMPERATURE_MIN) / 100 * percentCommand.intValue() + COLOR_TEMPERATURE_MIN; int color = ColorUtil.getRGBFromK(kelvin); writeBridgeLightColor(color, lastBrigthness); @@ -97,23 +96,23 @@ public class XiaomiActorGatewayHandler extends XiaomiActorBaseHandler { } break; case CHANNEL_GATEWAY_SOUND: - if (command instanceof DecimalType) { - writeBridgeRingtone(((DecimalType) command).intValue(), lastVolume); + if (command instanceof DecimalType decimalCommand) { + writeBridgeRingtone(decimalCommand.intValue(), lastVolume); updateState(CHANNEL_GATEWAY_SOUND_SWITCH, OnOffType.ON); return; } break; case CHANNEL_GATEWAY_SOUND_SWITCH: - if (command instanceof OnOffType) { - if (((OnOffType) command) == OnOffType.OFF) { + if (command instanceof OnOffType onOffCommand) { + if (onOffCommand == OnOffType.OFF) { stopRingtone(); } return; } break; case CHANNEL_GATEWAY_VOLUME: - if (command instanceof DecimalType) { - updateLastVolume((DecimalType) command); + if (command instanceof DecimalType decimalCommand) { + updateLastVolume(decimalCommand); } return; } diff --git a/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/handler/XiaomiBridgeHandler.java b/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/handler/XiaomiBridgeHandler.java index d1c53b42b..edd5d7076 100644 --- a/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/handler/XiaomiBridgeHandler.java +++ b/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/handler/XiaomiBridgeHandler.java @@ -66,7 +66,7 @@ public class XiaomiBridgeHandler extends ConfigStatusBridgeHandler implements Xi private static final String YES = "yes"; private static final String NO = "no"; - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_BRIDGE); + public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_BRIDGE); private static final EncryptionHelper CRYPTER = new EncryptionHelper(); private static Map retentionInbox = new ConcurrentHashMap<>(); @@ -370,15 +370,15 @@ public class XiaomiBridgeHandler extends ConfigStatusBridgeHandler implements Xi } private String escapeQuotes(String string) { - return string.replaceAll("\"", "\\\\\""); + return string.replace("\"", "\\\\\""); } private int getConfigInteger(Configuration config, String key) { Object value = config.get(key); - if (value instanceof BigDecimal) { - return ((BigDecimal) value).intValue(); - } else if (value instanceof String) { - return Integer.parseInt((String) value); + if (value instanceof BigDecimal decimal) { + return decimal.intValue(); + } else if (value instanceof String str) { + return Integer.parseInt(str); } else { return (Integer) value; } diff --git a/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/handler/XiaomiDeviceBaseHandler.java b/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/handler/XiaomiDeviceBaseHandler.java index f6fd19771..28263556f 100644 --- a/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/handler/XiaomiDeviceBaseHandler.java +++ b/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/handler/XiaomiDeviceBaseHandler.java @@ -203,8 +203,8 @@ public class XiaomiDeviceBaseHandler extends BaseThingHandler implements XiaomiI void execute(ChannelUID channelUID, Command command) { if (CHANNEL_WRITE_MSG.equals(channelUID.getId())) { - if (command instanceof StringType) { - getXiaomiBridgeHandler().writeToDevice(itemId, ((StringType) command).toFullString()); + if (command instanceof StringType str) { + getXiaomiBridgeHandler().writeToDevice(itemId, str.toFullString()); } else { logger.debug("Command \"{}\" has to be of StringType", command); } @@ -246,8 +246,8 @@ public class XiaomiDeviceBaseHandler extends BaseThingHandler implements XiaomiI return null; } ThingHandler handler = bridge.getHandler(); - if (handler instanceof XiaomiBridgeHandler) { - this.bridgeHandler = (XiaomiBridgeHandler) handler; + if (handler instanceof XiaomiBridgeHandler xiaomiBridgeHandler) { + this.bridgeHandler = xiaomiBridgeHandler; this.bridgeHandler.registerItemListener(this); } else { return null; diff --git a/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/handler/XiaomiSensorMagnetHandler.java b/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/handler/XiaomiSensorMagnetHandler.java index c35b1a29a..d62289319 100644 --- a/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/handler/XiaomiSensorMagnetHandler.java +++ b/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/handler/XiaomiSensorMagnetHandler.java @@ -81,8 +81,8 @@ public class XiaomiSensorMagnetHandler extends XiaomiSensorBaseHandlerWithTimer @Override void execute(ChannelUID channelUID, Command command) { if (CHANNEL_OPEN_ALARM_TIMER.equals(channelUID.getId())) { - if (command != null && command instanceof DecimalType) { - setTimerFromDecimalType((DecimalType) command); + if (command instanceof DecimalType decimalCommand) { + setTimerFromDecimalType(decimalCommand); return; } // Only gets here, if no condition was met diff --git a/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/handler/XiaomiSensorMotionHandler.java b/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/handler/XiaomiSensorMotionHandler.java index 3641b17bb..23a3e9414 100644 --- a/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/handler/XiaomiSensorMotionHandler.java +++ b/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/handler/XiaomiSensorMotionHandler.java @@ -66,8 +66,8 @@ public class XiaomiSensorMotionHandler extends XiaomiSensorBaseHandlerWithTimer @Override void execute(ChannelUID channelUID, Command command) { if (CHANNEL_MOTION_OFF_TIMER.equals(channelUID.getId())) { - if (command != null && command instanceof DecimalType) { - setTimerFromDecimalType((DecimalType) command); + if (command instanceof DecimalType decimalCommand) { + setTimerFromDecimalType(decimalCommand); return; } // Only gets here, if no condition was met diff --git a/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/socket/XiaomiSocket.java b/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/socket/XiaomiSocket.java index 771af6ba8..c0c9483bf 100644 --- a/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/socket/XiaomiSocket.java +++ b/bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/socket/XiaomiSocket.java @@ -219,8 +219,8 @@ public abstract class XiaomiSocket { */ private void notifyListeners(JsonObject message, InetAddress address) { for (XiaomiSocketListener listener : listeners) { - if (listener instanceof XiaomiBridgeHandler) { - if (((XiaomiBridgeHandler) listener).getHost().equals(address)) { + if (listener instanceof XiaomiBridgeHandler handler) { + if (handler.getHost().equals(address)) { listener.onDataReceived(message); } } else if (listener instanceof XiaomiBridgeDiscoveryService) { diff --git a/bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/basic/ActionConditions.java b/bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/basic/ActionConditions.java index 70d9ba278..acc31076d 100644 --- a/bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/basic/ActionConditions.java +++ b/bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/basic/ActionConditions.java @@ -77,7 +77,7 @@ public class ActionConditions { * @return RGB value + brightness as first byte */ private static @Nullable JsonElement hsvToBRGB(@Nullable Command command, @Nullable JsonElement value) { - if (command != null && command instanceof HSBType) { + if (command instanceof HSBType) { HSBType hsb = (HSBType) command; Color color = Color.getHSBColor(hsb.getHue().floatValue() / 360, hsb.getSaturation().floatValue() / 100, hsb.getBrightness().floatValue() / 100); @@ -119,7 +119,7 @@ public class ActionConditions { * @return */ private static @Nullable JsonElement hsbOnly(@Nullable Command command, @Nullable JsonElement value) { - if (command != null && command instanceof HSBType) { + if (command instanceof HSBType) { return value; } return null; diff --git a/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/config/InterfaceThingConfig.java b/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/config/InterfaceThingConfig.java index da8d31058..bb346bbe9 100644 --- a/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/config/InterfaceThingConfig.java +++ b/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/config/InterfaceThingConfig.java @@ -24,6 +24,7 @@ import org.eclipse.jdt.annotation.NonNullByDefault; public class InterfaceThingConfig implements ConfigValidation { public String name = ""; + @Override public boolean isValid() { return !name.isBlank(); } diff --git a/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/config/RouterosThingConfig.java b/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/config/RouterosThingConfig.java index edb03c553..0bb67bd76 100644 --- a/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/config/RouterosThingConfig.java +++ b/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/config/RouterosThingConfig.java @@ -28,6 +28,7 @@ public class RouterosThingConfig implements ConfigValidation { public String password = ""; public int refresh = 10; + @Override public boolean isValid() { return !host.isBlank() && !login.isBlank() && !password.isBlank() && refresh > 0 && port > 0; } diff --git a/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/config/WirelessClientThingConfig.java b/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/config/WirelessClientThingConfig.java index 537f63f19..671b71073 100644 --- a/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/config/WirelessClientThingConfig.java +++ b/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/config/WirelessClientThingConfig.java @@ -26,6 +26,7 @@ public class WirelessClientThingConfig implements ConfigValidation { public String ssid = ""; public int considerContinuous = 180; + @Override public boolean isValid() { return !mac.isBlank() && considerContinuous > 0; } diff --git a/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/handler/MikrotikRouterosBridgeHandler.java b/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/handler/MikrotikRouterosBridgeHandler.java index 882b10efd..2e1f09bde 100644 --- a/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/handler/MikrotikRouterosBridgeHandler.java +++ b/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/handler/MikrotikRouterosBridgeHandler.java @@ -211,8 +211,8 @@ public class MikrotikRouterosBridgeHandler extends BaseBridgeHandler { // refresh all the client things below getThing().getThings().forEach(thing -> { ThingHandler handler = thing.getHandler(); - if (handler instanceof MikrotikBaseThingHandler) { - ((MikrotikBaseThingHandler) handler).refresh(); + if (handler instanceof MikrotikBaseThingHandler thingHandler) { + thingHandler.refresh(); } }); } catch (ChannelUpdateException e) { diff --git a/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/model/RouterosCapInterface.java b/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/model/RouterosCapInterface.java index 666c528b4..325d23275 100644 --- a/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/model/RouterosCapInterface.java +++ b/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/model/RouterosCapInterface.java @@ -45,19 +45,19 @@ public class RouterosCapInterface extends RouterosInterfaceBase { } public boolean isMaster() { - return getProp("slave", "").equals("false"); + return "false".equals(getProp("slave", "")); } public boolean isDynamic() { - return getProp("dynamic", "").equals("true"); + return "true".equals(getProp("dynamic", "")); } public boolean isBound() { - return getProp("bound", "").equals("true"); + return "true".equals(getProp("bound", "")); } public boolean isActive() { - return getProp("inactive", "").equals("false"); + return "false".equals(getProp("inactive", "")); } public @Nullable String getCurrentState() { diff --git a/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/model/RouterosInterfaceBase.java b/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/model/RouterosInterfaceBase.java index c74b9fed5..c97a4ded7 100644 --- a/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/model/RouterosInterfaceBase.java +++ b/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/model/RouterosInterfaceBase.java @@ -76,11 +76,11 @@ public abstract class RouterosInterfaceBase extends RouterosBaseData { } public boolean isEnabled() { - return getProp("disabled", "").equals("false"); + return "false".equals(getProp("disabled", "")); } public boolean isConnected() { - return getProp("running", "").equals("true"); + return "true".equals(getProp("running", "")); } public @Nullable Integer getLinkDowns() { diff --git a/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/model/RouterosInterfaceType.java b/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/model/RouterosInterfaceType.java index ca530f541..e31ed858a 100644 --- a/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/model/RouterosInterfaceType.java +++ b/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/model/RouterosInterfaceType.java @@ -44,6 +44,7 @@ public enum RouterosInterfaceType { return typeName.equals(otherType); } + @Override public String toString() { return this.typeName; } diff --git a/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/model/RouterosPPPCliInterface.java b/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/model/RouterosPPPCliInterface.java index bfb4ac10d..244a0950b 100644 --- a/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/model/RouterosPPPCliInterface.java +++ b/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/model/RouterosPPPCliInterface.java @@ -51,6 +51,7 @@ public class RouterosPPPCliInterface extends RouterosInterfaceBase { return true; } + @Override public @Nullable String getMacAddress() { return null; } diff --git a/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/model/RouterosPPPoECliInterface.java b/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/model/RouterosPPPoECliInterface.java index b61479fb8..424ff28ce 100644 --- a/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/model/RouterosPPPoECliInterface.java +++ b/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/model/RouterosPPPoECliInterface.java @@ -51,6 +51,7 @@ public class RouterosPPPoECliInterface extends RouterosInterfaceBase { return true; } + @Override public @Nullable String getMacAddress() { return getProp("ac-mac"); } diff --git a/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/model/RouterosRouterboardInfo.java b/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/model/RouterosRouterboardInfo.java index 0a71302c7..21eca3a2a 100644 --- a/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/model/RouterosRouterboardInfo.java +++ b/bundles/org.openhab.binding.mikrotik/src/main/java/org/openhab/binding/mikrotik/internal/model/RouterosRouterboardInfo.java @@ -33,7 +33,7 @@ public class RouterosRouterboardInfo extends RouterosBaseData { } public boolean isRouterboard() { - return getProp("routerboard", "").equals("true"); + return "true".equals(getProp("routerboard", "")); } public String getModel() { diff --git a/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/discovery/MilightBridgeDiscovery.java b/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/discovery/MilightBridgeDiscovery.java index 9eb8ddc25..490764688 100644 --- a/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/discovery/MilightBridgeDiscovery.java +++ b/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/discovery/MilightBridgeDiscovery.java @@ -324,8 +324,7 @@ public class MilightBridgeDiscovery extends AbstractDiscoveryService implements try (MilightV6SessionManager session = new MilightV6SessionManager(bridgeID, sessionState, addressOfBridge, MilightBindingConstants.PORT_VER6, MilightV6SessionManager.TIMEOUT_MS, new byte[] { 0, 0 })) { session.start(); - boolean success = s.tryAcquire(1, 1300, TimeUnit.MILLISECONDS); - return success; + return s.tryAcquire(1, 1300, TimeUnit.MILLISECONDS); } catch (IOException e) { logger.debug("checkForV6Bridge failed", e); } diff --git a/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/handler/AbstractLedHandler.java b/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/handler/AbstractLedHandler.java index b44946b2e..98a9e4b8e 100644 --- a/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/handler/AbstractLedHandler.java +++ b/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/handler/AbstractLedHandler.java @@ -105,20 +105,16 @@ public abstract class AbstractLedHandler extends BaseThingHandler implements Led switch (channelUID.getId()) { case MilightBindingConstants.CHANNEL_COLOR: { - if (command instanceof HSBType) { - HSBType hsb = (HSBType) command; + if (command instanceof HSBType hsb) { this.setHSB(hsb.getHue().intValue(), hsb.getSaturation().intValue(), hsb.getBrightness().intValue(), state); updateState(MilightBindingConstants.CHANNEL_SATURATION, new PercentType(state.saturation)); - } else if (command instanceof OnOffType) { - OnOffType hsb = (OnOffType) command; + } else if (command instanceof OnOffType hsb) { this.setPower(hsb == OnOffType.ON, state); - } else if (command instanceof PercentType) { - PercentType p = (PercentType) command; + } else if (command instanceof PercentType p) { this.setBrightness(p.intValue(), state); - } else if (command instanceof IncreaseDecreaseType) { - this.changeBrightness((IncreaseDecreaseType) command == IncreaseDecreaseType.INCREASE ? 1 : -1, - state); + } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) { + this.changeBrightness(increaseDecreaseCommand == IncreaseDecreaseType.INCREASE ? 1 : -1, state); } else { logger.error( "CHANNEL_COLOR channel only supports OnOffType/IncreaseDecreaseType/HSBType/PercentType"); @@ -137,15 +133,12 @@ public abstract class AbstractLedHandler extends BaseThingHandler implements Led break; } case MilightBindingConstants.CHANNEL_BRIGHTNESS: { - if (command instanceof OnOffType) { - OnOffType hsb = (OnOffType) command; - this.setPower(hsb == OnOffType.ON, state); - } else if (command instanceof DecimalType) { - DecimalType d = (DecimalType) command; - this.setBrightness(d.intValue(), state); - } else if (command instanceof IncreaseDecreaseType) { - this.changeBrightness((IncreaseDecreaseType) command == IncreaseDecreaseType.INCREASE ? 1 : -1, - state); + if (command instanceof OnOffType onOffCommand) { + this.setPower(onOffCommand == OnOffType.ON, state); + } else if (command instanceof DecimalType decimalCommand) { + this.setBrightness(decimalCommand.intValue(), state); + } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) { + this.changeBrightness(increaseDecreaseCommand == IncreaseDecreaseType.INCREASE ? 1 : -1, state); } else { logger.error("CHANNEL_BRIGHTNESS channel only supports OnOffType/IncreaseDecreaseType/DecimalType"); } @@ -155,15 +148,12 @@ public abstract class AbstractLedHandler extends BaseThingHandler implements Led break; } case MilightBindingConstants.CHANNEL_SATURATION: { - if (command instanceof OnOffType) { - OnOffType s = (OnOffType) command; - this.setSaturation((s == OnOffType.ON) ? 100 : 0, state); - } else if (command instanceof DecimalType) { - DecimalType d = (DecimalType) command; - this.setSaturation(d.intValue(), state); - } else if (command instanceof IncreaseDecreaseType) { - this.changeSaturation((IncreaseDecreaseType) command == IncreaseDecreaseType.INCREASE ? 1 : -1, - state); + if (command instanceof OnOffType onOffCommand) { + this.setSaturation((onOffCommand == OnOffType.ON) ? 100 : 0, state); + } else if (command instanceof DecimalType decimalCommand) { + this.setSaturation(decimalCommand.intValue(), state); + } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) { + this.changeSaturation(increaseDecreaseCommand == IncreaseDecreaseType.INCREASE ? 1 : -1, state); } else { logger.error("CHANNEL_SATURATION channel only supports OnOffType/IncreaseDecreaseType/DecimalType"); } @@ -173,14 +163,12 @@ public abstract class AbstractLedHandler extends BaseThingHandler implements Led break; } case MilightBindingConstants.CHANNEL_TEMP: { - if (command instanceof OnOffType) { - OnOffType s = (OnOffType) command; - this.setColorTemperature((s == OnOffType.ON) ? 100 : 0, state); - } else if (command instanceof IncreaseDecreaseType) { - this.changeColorTemperature( - (IncreaseDecreaseType) command == IncreaseDecreaseType.INCREASE ? 1 : -1, state); - } else if (command instanceof DecimalType) { - DecimalType d = (DecimalType) command; + if (command instanceof OnOffType onOffCommand) { + this.setColorTemperature((onOffCommand == OnOffType.ON) ? 100 : 0, state); + } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) { + this.changeColorTemperature(increaseDecreaseCommand == IncreaseDecreaseType.INCREASE ? 1 : -1, + state); + } else if (command instanceof DecimalType d) { this.setColorTemperature(d.intValue(), state); } else { logger.error("CHANNEL_TEMP channel only supports OnOffType/IncreaseDecreaseType/DecimalType"); @@ -188,11 +176,10 @@ public abstract class AbstractLedHandler extends BaseThingHandler implements Led break; } case MilightBindingConstants.CHANNEL_SPEED_REL: { - if (command instanceof IncreaseDecreaseType) { - IncreaseDecreaseType id = (IncreaseDecreaseType) command; - if (id == IncreaseDecreaseType.INCREASE) { + if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) { + if (increaseDecreaseCommand == IncreaseDecreaseType.INCREASE) { this.changeSpeed(1, state); - } else if (id == IncreaseDecreaseType.DECREASE) { + } else if (increaseDecreaseCommand == IncreaseDecreaseType.DECREASE) { this.changeSpeed(-1, state); } } else { @@ -201,20 +188,18 @@ public abstract class AbstractLedHandler extends BaseThingHandler implements Led break; } case MilightBindingConstants.CHANNEL_ANIMATION_MODE: { - if (command instanceof DecimalType) { - DecimalType d = (DecimalType) command; - this.setLedMode(d.intValue(), state); + if (command instanceof DecimalType decimalCommand) { + this.setLedMode(decimalCommand.intValue(), state); } else { logger.error("Animation mode channel only supports DecimalType"); } break; } case MilightBindingConstants.CHANNEL_ANIMATION_MODE_REL: { - if (command instanceof IncreaseDecreaseType) { - IncreaseDecreaseType id = (IncreaseDecreaseType) command; - if (id == IncreaseDecreaseType.INCREASE) { + if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) { + if (increaseDecreaseCommand == IncreaseDecreaseType.INCREASE) { this.nextAnimationMode(state); - } else if (id == IncreaseDecreaseType.DECREASE) { + } else if (increaseDecreaseCommand == IncreaseDecreaseType.DECREASE) { this.previousAnimationMode(state); } } else { diff --git a/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/handler/MilightV2RGBHandler.java b/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/handler/MilightV2RGBHandler.java index 5bd799c9e..6651c52db 100644 --- a/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/handler/MilightV2RGBHandler.java +++ b/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/handler/MilightV2RGBHandler.java @@ -71,13 +71,13 @@ public class MilightV2RGBHandler extends AbstractLedHandler { public void setPower(boolean on, MilightThingState state) { if (on) { logger.debug("milight: sendOn"); - byte messageBytes[] = null; + byte[] messageBytes = null; // message rgb bulbs ON messageBytes = new byte[] { 0x22, 0x00, 0x55 }; sendQueue.queue(createRepeatable(uidc(ProtocolConstants.CAT_POWER_MODE), messageBytes)); } else { logger.debug("milight: sendOff"); - byte messageBytes[] = null; + byte[] messageBytes = null; // message rgb bulbs OFF messageBytes = new byte[] { 0x21, 0x00, 0x55 }; diff --git a/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/handler/MilightV3RGBWHandler.java b/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/handler/MilightV3RGBWHandler.java index a884120fd..b62c347ba 100644 --- a/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/handler/MilightV3RGBWHandler.java +++ b/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/handler/MilightV3RGBWHandler.java @@ -26,12 +26,12 @@ import org.openhab.core.thing.Thing; public class MilightV3RGBWHandler extends AbstractLedV3Handler { protected static final int BRIGHTNESS_LEVELS = 26; - private static final byte COMMAND_ON[] = { (byte) 0x42, (byte) 0x45, (byte) 0x47, (byte) 0x49, (byte) 0x4B }; - private static final byte COMMAND_OFF[] = { (byte) 0x41, (byte) 0x46, (byte) 0x48, (byte) 0x4A, (byte) 0x4C }; - private static final byte COMMAND_WHITEMODE[] = { (byte) 0xC2, (byte) 0xC5, (byte) 0xC7, (byte) 0xC9, (byte) 0xCB }; - private static final byte NIGHTMODE_FIRST[] = { 0x41, 0x46, 0x48, 0x4A, 0x4C }; - private static final byte NIGHTMODE_SECOND[] = { (byte) 0xC1, (byte) 0xC6, (byte) 0xC8, (byte) 0xCA, (byte) 0xCC }; - private static final byte NEXT_ANIMATION_MODE[] = { 0x4D, 0x00, 0x55 }; + private static final byte[] COMMAND_ON = { (byte) 0x42, (byte) 0x45, (byte) 0x47, (byte) 0x49, (byte) 0x4B }; + private static final byte[] COMMAND_OFF = { (byte) 0x41, (byte) 0x46, (byte) 0x48, (byte) 0x4A, (byte) 0x4C }; + private static final byte[] COMMAND_WHITEMODE = { (byte) 0xC2, (byte) 0xC5, (byte) 0xC7, (byte) 0xC9, (byte) 0xCB }; + private static final byte[] NIGHTMODE_FIRST = { 0x41, 0x46, 0x48, 0x4A, 0x4C }; + private static final byte[] NIGHTMODE_SECOND = { (byte) 0xC1, (byte) 0xC6, (byte) 0xC8, (byte) 0xCA, (byte) 0xCC }; + private static final byte[] NEXT_ANIMATION_MODE = { 0x4D, 0x00, 0x55 }; public MilightV3RGBWHandler(Thing thing, QueuedSend sendQueue) { super(thing, sendQueue, 10); @@ -45,8 +45,8 @@ public class MilightV3RGBWHandler extends AbstractLedV3Handler { whiteMode(state); } else { state.hue360 = hue; - final byte messageBytes[] = new byte[] { 0x40, makeColor(hue), 0x55 }; - final byte cOn[] = { COMMAND_ON[config.zone], 0x00, 0x55 }; + final byte[] messageBytes = new byte[] { 0x40, makeColor(hue), 0x55 }; + final byte[] cOn = { COMMAND_ON[config.zone], 0x00, 0x55 }; sendQueue.queue(createRepeatable(uidc(ProtocolConstants.CAT_COLOR_SET), cOn).addRepeatable(messageBytes)); } @@ -68,15 +68,15 @@ public class MilightV3RGBWHandler extends AbstractLedV3Handler { @Override public void whiteMode(MilightThingState state) { - final byte cOn[] = { COMMAND_ON[config.zone], 0x00, 0x55 }; - final byte cWhite[] = { COMMAND_WHITEMODE[config.zone], 0x00, 0x55 }; + final byte[] cOn = { COMMAND_ON[config.zone], 0x00, 0x55 }; + final byte[] cWhite = { COMMAND_WHITEMODE[config.zone], 0x00, 0x55 }; sendQueue.queue(createRepeatable(uidc(ProtocolConstants.CAT_WHITEMODE), cOn).addRepeatable(cWhite)); } @Override public void nightMode(MilightThingState state) { - final byte cN1[] = { NIGHTMODE_FIRST[config.zone], 0x00, 0x55 }; - final byte cN2[] = { NIGHTMODE_SECOND[config.zone], 0x00, 0x55 }; + final byte[] cN1 = { NIGHTMODE_FIRST[config.zone], 0x00, 0x55 }; + final byte[] cN2 = { NIGHTMODE_SECOND[config.zone], 0x00, 0x55 }; sendQueue.queue(createRepeatable(uidc(ProtocolConstants.CAT_POWER_MODE), cN1).addRepeatable(cN2)); } @@ -101,7 +101,7 @@ public class MilightV3RGBWHandler extends AbstractLedV3Handler { int br = (int) Math.ceil((value * BRIGHTNESS_LEVELS) / 100.0) + 1; - final byte cOn[] = { COMMAND_ON[config.zone], 0x00, 0x55 }; + final byte[] cOn = { COMMAND_ON[config.zone], 0x00, 0x55 }; sendQueue.queue(createRepeatable(uidc(ProtocolConstants.CAT_BRIGHTNESS_SET), cOn) .addRepeatable(new byte[] { 0x4E, (byte) br, 0x55 })); @@ -119,8 +119,8 @@ public class MilightV3RGBWHandler extends AbstractLedV3Handler { return; } - final byte cOn[] = { COMMAND_ON[config.zone], 0x00, 0x55 }; - final byte cSpeed[] = { (byte) (relativeSpeed > 0 ? 0x44 : 0x43), 0x00, 0x55 }; + final byte[] cOn = { COMMAND_ON[config.zone], 0x00, 0x55 }; + final byte[] cSpeed = { (byte) (relativeSpeed > 0 ? 0x44 : 0x43), 0x00, 0x55 }; sendQueue.queue(createRepeatable(cOn).addNonRepeatable(cSpeed)); } @@ -128,14 +128,14 @@ public class MilightV3RGBWHandler extends AbstractLedV3Handler { // instead. @Override public void previousAnimationMode(MilightThingState state) { - final byte cOn[] = { COMMAND_ON[config.zone], 0x00, 0x55 }; + final byte[] cOn = { COMMAND_ON[config.zone], 0x00, 0x55 }; sendQueue.queue(createRepeatable(cOn).addNonRepeatable(NEXT_ANIMATION_MODE)); state.animationMode = (state.animationMode + 1) % (MAX_ANIM_MODES + 1); } @Override public void nextAnimationMode(MilightThingState state) { - final byte cOn[] = { COMMAND_ON[config.zone], 0x00, 0x55 }; + final byte[] cOn = { COMMAND_ON[config.zone], 0x00, 0x55 }; sendQueue.queue(createRepeatable(cOn).addNonRepeatable(NEXT_ANIMATION_MODE)); state.animationMode = (state.animationMode + 1) % (MAX_ANIM_MODES + 1); } diff --git a/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/handler/MilightV3WhiteHandler.java b/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/handler/MilightV3WhiteHandler.java index 4af9b3dbc..a79f704eb 100644 --- a/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/handler/MilightV3WhiteHandler.java +++ b/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/handler/MilightV3WhiteHandler.java @@ -33,12 +33,12 @@ public class MilightV3WhiteHandler extends AbstractLedV3Handler { super(thing, sendQueue, 0); } - private static final byte COMMAND_FULL[] = { (byte) 0xB5, (byte) 0xB8, (byte) 0xBD, (byte) 0xB7, (byte) 0xB2 }; - private static final byte COMMAND_ON[] = { (byte) 0x35, (byte) 0x38, (byte) 0x3D, (byte) 0x37, (byte) 0x32 }; - private static final byte COMMAND_OFF[] = { (byte) 0x39, (byte) 0x3B, (byte) 0x33, (byte) 0x3A, (byte) 0x36 }; - private static final byte COMMAND_NIGHTMODE[] = { (byte) 0xB9, (byte) 0xBB, (byte) 0xB3, (byte) 0xBA, (byte) 0xB6 }; - private static final byte PREV_ANIMATION_MODE[] = { 0x27, 0x00, 0x55 }; - private static final byte NEXT_ANIMATION_MODE[] = { 0x27, 0x00, 0x55 }; + private static final byte[] COMMAND_FULL = { (byte) 0xB5, (byte) 0xB8, (byte) 0xBD, (byte) 0xB7, (byte) 0xB2 }; + private static final byte[] COMMAND_ON = { (byte) 0x35, (byte) 0x38, (byte) 0x3D, (byte) 0x37, (byte) 0x32 }; + private static final byte[] COMMAND_OFF = { (byte) 0x39, (byte) 0x3B, (byte) 0x33, (byte) 0x3A, (byte) 0x36 }; + private static final byte[] COMMAND_NIGHTMODE = { (byte) 0xB9, (byte) 0xBB, (byte) 0xB3, (byte) 0xBA, (byte) 0xB6 }; + private static final byte[] PREV_ANIMATION_MODE = { 0x27, 0x00, 0x55 }; + private static final byte[] NEXT_ANIMATION_MODE = { 0x27, 0x00, 0x55 }; protected void setFull(int zone, MilightThingState state) { sendQueue.queue(createRepeatable(uidc(ProtocolConstants.CAT_BRIGHTNESS_SET), @@ -72,8 +72,8 @@ public class MilightV3WhiteHandler extends AbstractLedV3Handler { @Override public void nightMode(MilightThingState state) { - final byte cOn[] = { COMMAND_ON[config.zone], 0x00, 0x55 }; - final byte cNight[] = { COMMAND_NIGHTMODE[config.zone], 0x00, 0x55 }; + final byte[] cOn = { COMMAND_ON[config.zone], 0x00, 0x55 }; + final byte[] cNight = { COMMAND_NIGHTMODE[config.zone], 0x00, 0x55 }; sendQueue.queue(createRepeatable(uidc(ProtocolConstants.CAT_POWER_MODE), cOn).addRepeatable(cNight)); } @@ -113,8 +113,8 @@ public class MilightV3WhiteHandler extends AbstractLedV3Handler { @Override public void changeColorTemperature(int colorTempRelative, MilightThingState state) { state.colorTemperature = Math.min(100, Math.max(state.colorTemperature + colorTempRelative, 0)); - final byte cOn[] = { COMMAND_ON[config.zone], 0x00, 0x55 }; - final byte cTemp[] = { (byte) (colorTempRelative > 0 ? 0x3E : 0x3F), 0x00, 0x55 }; + final byte[] cOn = { COMMAND_ON[config.zone], 0x00, 0x55 }; + final byte[] cTemp = { (byte) (colorTempRelative > 0 ? 0x3E : 0x3F), 0x00, 0x55 }; sendQueue.queue(createRepeatable(cOn).addNonRepeatable(cTemp)); } @@ -134,7 +134,7 @@ public class MilightV3WhiteHandler extends AbstractLedV3Handler { // When turning on start from full brightness int oldLevel; - final byte cFull[] = { COMMAND_FULL[config.zone], 0x00, 0x55 }; + final byte[] cFull = { COMMAND_FULL[config.zone], 0x00, 0x55 }; QueueItem item = createRepeatable(cFull); boolean skipFirst = false; @@ -155,7 +155,7 @@ public class MilightV3WhiteHandler extends AbstractLedV3Handler { String.valueOf(value), repeatCount); int op = newLevel > oldLevel ? +1 : -1; - final byte cOn[] = { COMMAND_ON[config.zone], 0x00, 0x55 }; + final byte[] cOn = { COMMAND_ON[config.zone], 0x00, 0x55 }; for (int i = 0; i < repeatCount; i++) { final byte[] cBr = { (byte) (op < 0 ? 0x34 : 0x3C), 0x00, 0x55 }; item = item.addRepeatable(cOn).addNonRepeatable(cBr); @@ -182,8 +182,8 @@ public class MilightV3WhiteHandler extends AbstractLedV3Handler { sendQueue.queue(createRepeatable(uidc(ProtocolConstants.CAT_POWER_MODE), new byte[] { COMMAND_OFF[config.zone], 0x00, 0x55 })); } else { - final byte cOn[] = { COMMAND_ON[config.zone], 0x00, 0x55 }; - final byte cBr[] = { (byte) (relativeBrightness < 0 ? 0x34 : 0x3C), 0x00, 0x55 }; + final byte[] cOn = { COMMAND_ON[config.zone], 0x00, 0x55 }; + final byte[] cBr = { (byte) (relativeBrightness < 0 ? 0x34 : 0x3C), 0x00, 0x55 }; sendQueue.queue(createRepeatable(cOn).addNonRepeatable(cBr)); } } @@ -194,14 +194,14 @@ public class MilightV3WhiteHandler extends AbstractLedV3Handler { @Override public void previousAnimationMode(MilightThingState state) { - final byte cOn[] = { COMMAND_ON[config.zone], 0x00, 0x55 }; + final byte[] cOn = { COMMAND_ON[config.zone], 0x00, 0x55 }; sendQueue.queue(createRepeatable(cOn).addNonRepeatable(PREV_ANIMATION_MODE)); state.animationMode = Math.max(state.animationMode - 1, 0); } @Override public void nextAnimationMode(MilightThingState state) { - final byte cOn[] = { COMMAND_ON[config.zone], 0x00, 0x55 }; + final byte[] cOn = { COMMAND_ON[config.zone], 0x00, 0x55 }; sendQueue.queue(createRepeatable(cOn).addNonRepeatable(NEXT_ANIMATION_MODE)); state.animationMode = Math.min(state.animationMode + 1, MAX_ANIM_MODES); } diff --git a/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/protocol/MilightV6SessionManager.java b/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/protocol/MilightV6SessionManager.java index 5be1a48d8..0eb776376 100644 --- a/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/protocol/MilightV6SessionManager.java +++ b/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/protocol/MilightV6SessionManager.java @@ -64,10 +64,10 @@ public class MilightV6SessionManager implements Runnable, Closeable { private int sequenceNo = 0; // Password bytes 1 and 2 - public byte pw[] = { 0, 0 }; + public byte[] pw = { 0, 0 }; // Session bytes 1 and 2 - public byte sid[] = { 0, 0 }; + public byte[] sid = { 0, 0 }; // Client session bytes 1 and 2. Those are fixed for now. public final byte clientSID1 = (byte) 0xab; diff --git a/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/test/EmulatedV6Bridge.java b/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/test/EmulatedV6Bridge.java index a15ffd914..5fa35e406 100644 --- a/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/test/EmulatedV6Bridge.java +++ b/bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/test/EmulatedV6Bridge.java @@ -47,29 +47,29 @@ public class EmulatedV6Bridge { (byte) 0xD4 }; // Send to the network by clients to find V6 bridges - private byte searchBroadcast[] = new byte[] { 0x10, 0, 0, 0, 0x24, 0x02, cls1, cls2, 0x02, 0x39, 0x38, 0x35, 0x62, + private byte[] searchBroadcast = new byte[] { 0x10, 0, 0, 0, 0x24, 0x02, cls1, cls2, 0x02, 0x39, 0x38, 0x35, 0x62, 0x31, 0x35, 0x37, 0x62, 0x66, 0x36, 0x66, 0x63, 0x34, 0x33, 0x33, 0x36, 0x38, 0x61, 0x36, 0x33, 0x34, 0x36, 0x37, 0x65, 0x61, 0x33, 0x62, 0x31, 0x39, 0x64, 0x30, 0x64 }; // Send to broadcast address by the client usually and used to test if the client with the contained bridge id // is present on the network. If the IP of the bridge is known already, then SESSION_REQUEST is used usually. - private byte sessionRequestFindBroadcast[] = new byte[] { 0x10, 0, 0, 0, 0x0A, 2, cls1, cls2, 1, FAKE_MAC[0], + private byte[] sessionRequestFindBroadcast = new byte[] { 0x10, 0, 0, 0, 0x0A, 2, cls1, cls2, 1, FAKE_MAC[0], FAKE_MAC[1], FAKE_MAC[2], FAKE_MAC[3], FAKE_MAC[4], FAKE_MAC[5] }; // Some clients send this as first command to get a session id, especially if the bridge IP is already known. - private byte sessionRequest[] = new byte[] { (byte) 0x20, 0, 0, 0, (byte) 0x16, 2, (byte) 0x62, (byte) 0x3A, + private byte[] sessionRequest = new byte[] { (byte) 0x20, 0, 0, 0, (byte) 0x16, 2, (byte) 0x62, (byte) 0x3A, (byte) 0xD5, (byte) 0xED, (byte) 0xA3, 1, (byte) 0xAE, (byte) 0x08, (byte) 0x2D, (byte) 0x46, (byte) 0x61, (byte) 0x41, (byte) 0xA7, (byte) 0xF6, (byte) 0xDC, (byte) 0xAF, cls1, cls2, 0, 0, (byte) 0x1E }; - private byte sessionResponse[] = { (byte) 0x28, 0, 0, 0, (byte) 0x11, 0, 2, (byte) 0xAC, (byte) 0xCF, (byte) 0x23, + private byte[] sessionResponse = { (byte) 0x28, 0, 0, 0, (byte) 0x11, 0, 2, (byte) 0xAC, (byte) 0xCF, (byte) 0x23, (byte) 0xF5, (byte) 0x7A, (byte) 0xD4, (byte) 0x69, (byte) 0xF0, (byte) 0x3C, (byte) 0x23, 0, 1, SID1, SID2, 0 }; // Some clients call this as second command to establish a session. - private static final byte ESTABLISH_SESSION_REQUEST[] = new byte[] { (byte) 0x30, 0, 0, 0, 3, SID1, SID2, 0 }; + private static final byte[] ESTABLISH_SESSION_REQUEST = new byte[] { (byte) 0x30, 0, 0, 0, 3, SID1, SID2, 0 }; // In response to SEARCH, ESTABLISH_SESSION_REQUEST but also to SESSION_REQUEST_FIND_BROADCAST - private static final byte REESTABLISH_SESSION_RESPONSE[] = new byte[] { (byte) 0x18, 0, 0, 0, (byte) 0x40, 2, + private static final byte[] REESTABLISH_SESSION_RESPONSE = new byte[] { (byte) 0x18, 0, 0, 0, (byte) 0x40, 2, FAKE_MAC[0], FAKE_MAC[1], FAKE_MAC[2], FAKE_MAC[3], FAKE_MAC[4], FAKE_MAC[5], 0, (byte) 0x20, (byte) 0x39, (byte) 0x38, (byte) 0x35, (byte) 0x62, (byte) 0x31, (byte) 0x35, (byte) 0x37, (byte) 0x62, (byte) 0x66, (byte) 0x36, (byte) 0x66, (byte) 0x63, (byte) 0x34, (byte) 0x33, (byte) 0x33, (byte) 0x36, (byte) 0x38, @@ -79,11 +79,11 @@ public class EmulatedV6Bridge { (byte) 0x6E, (byte) 0x6B, (byte) 0x5F, (byte) 0x64, (byte) 0x65, (byte) 0x76, (byte) 0x07, (byte) 0x5B, (byte) 0xCD, (byte) 0x15 }; - private static final byte REGISTRATION_REQUEST[] = { (byte) 0x80, 0, 0, 0, 0x11, SID1, SID2, SEQ1, SEQ2, 0, 0x33, + private static final byte[] REGISTRATION_REQUEST = { (byte) 0x80, 0, 0, 0, 0x11, SID1, SID2, SEQ1, SEQ2, 0, 0x33, PW1, PW2, 0, 0, 0, 0, 0, 0, 0, 0, 0x33 }; // 80:00:00:00:15:(f0:fe:6b:16:b0:8a):05:02:00:34:00:00:00:00:00:00:00:00:00:00:34 - private static final byte REGISTRATION_REQUEST_RESPONSE[] = { (byte) 0x80, 0, 0, 0, 0x15, FAKE_MAC[0], FAKE_MAC[1], + private static final byte[] REGISTRATION_REQUEST_RESPONSE = { (byte) 0x80, 0, 0, 0, 0x15, FAKE_MAC[0], FAKE_MAC[1], FAKE_MAC[2], FAKE_MAC[3], FAKE_MAC[4], FAKE_MAC[5], 5, 2, 0, 0x34, PW1, PW2, 0, 0, 0, 0, 0, 0, 0, 0, 0x34 }; private static final byte[] KEEP_ALIVE_REQUEST = { (byte) 0xD0, 0, 0, 0, 2, SID1, SID2 }; @@ -96,7 +96,7 @@ public class EmulatedV6Bridge { new Thread(this::runBrigde).start(); } - private void replaceWithMac(byte data[], int offset) { + private void replaceWithMac(byte[] data, int offset) { data[offset + 0] = FAKE_MAC[0]; data[offset + 1] = FAKE_MAC[1]; data[offset + 2] = FAKE_MAC[2]; @@ -106,7 +106,7 @@ public class EmulatedV6Bridge { } public void runDiscovery() { - final byte discover[] = "HF-A11ASSISTHREAD".getBytes(); + final byte[] discover = "HF-A11ASSISTHREAD".getBytes(); try { byte[] a = new byte[0]; @@ -286,7 +286,7 @@ public class EmulatedV6Bridge { debugStr.append("iBox "); } - debugStr.append("Zone " + String.valueOf(buffer[19]) + " "); + debugStr.append("Zone " + buffer[19] + " "); for (int i = 13; i < 19; ++i) { debugStr.append(String.format("%02X ", buffer[i])); @@ -295,7 +295,7 @@ public class EmulatedV6Bridge { } } - byte response[] = { (byte) 0x88, 0, 0, 0, (byte) 0x03, 0, seq, 0 }; + byte[] response = { (byte) 0x88, 0, 0, 0, (byte) 0x03, 0, seq, 0 }; sendMessage(sPacket, datagramSocket, response); continue; } @@ -320,7 +320,7 @@ public class EmulatedV6Bridge { logger.error("{}: {}", reason, s); } - protected void sendMessage(DatagramPacket packet, DatagramSocket datagramSocket, byte buffer[]) { + protected void sendMessage(DatagramPacket packet, DatagramSocket datagramSocket, byte[] buffer) { packet.setData(buffer); try { datagramSocket.send(packet); @@ -330,7 +330,7 @@ public class EmulatedV6Bridge { } } - private void debugSessionSend(byte buffer[], InetAddress address) { + private void debugSessionSend(byte[] buffer, InetAddress address) { StringBuilder s = new StringBuilder(); for (int i = 0; i < buffer.length; ++i) { s.append(String.format("%02X ", buffer[i])); diff --git a/bundles/org.openhab.binding.millheat/src/main/java/org/openhab/binding/millheat/internal/dto/GetIndependentDevicesByHomeResponse.java b/bundles/org.openhab.binding.millheat/src/main/java/org/openhab/binding/millheat/internal/dto/GetIndependentDevicesByHomeResponse.java index 3a12c7690..21aec1b58 100644 --- a/bundles/org.openhab.binding.millheat/src/main/java/org/openhab/binding/millheat/internal/dto/GetIndependentDevicesByHomeResponse.java +++ b/bundles/org.openhab.binding.millheat/src/main/java/org/openhab/binding/millheat/internal/dto/GetIndependentDevicesByHomeResponse.java @@ -21,5 +21,5 @@ import com.google.gson.annotations.SerializedName; */ public class GetIndependentDevicesByHomeResponse extends AbstractResponse { @SerializedName("deviceInfo") - public DeviceDTO devices[] = new DeviceDTO[0]; + public DeviceDTO[] devices = new DeviceDTO[0]; } diff --git a/bundles/org.openhab.binding.millheat/src/main/java/org/openhab/binding/millheat/internal/handler/MillheatAccountHandler.java b/bundles/org.openhab.binding.millheat/src/main/java/org/openhab/binding/millheat/internal/handler/MillheatAccountHandler.java index 176608f01..9ce18af1f 100644 --- a/bundles/org.openhab.binding.millheat/src/main/java/org/openhab/binding/millheat/internal/handler/MillheatAccountHandler.java +++ b/bundles/org.openhab.binding.millheat/src/main/java/org/openhab/binding/millheat/internal/handler/MillheatAccountHandler.java @@ -372,8 +372,8 @@ public class MillheatAccountHandler extends BaseBridgeHandler { final Optional optionalRoom = model.findRoomById(roomId); if (optionalHome.isPresent() && optionalRoom.isPresent()) { final SetRoomTempRequest req = new SetRoomTempRequest(optionalHome.get(), optionalRoom.get()); - if (command instanceof QuantityType) { - final int newTemp = (int) ((QuantityType) command).longValue(); + if (command instanceof QuantityType quantityCommand) { + final int newTemp = (int) quantityCommand.longValue(); switch (mode) { case SLEEP: req.sleepTemp = newTemp; @@ -404,8 +404,8 @@ public class MillheatAccountHandler extends BaseBridgeHandler { @Nullable final Command fanCommand) { model.findHeaterByMacOrId(macAddress, heaterId).ifPresent(heater -> { int setTemp = heater.getTargetTemp(); - if (temperatureCommand instanceof QuantityType) { - setTemp = (int) ((QuantityType) temperatureCommand).longValue(); + if (temperatureCommand instanceof QuantityType temperature) { + setTemp = (int) temperature.longValue(); } boolean masterOnOff = heater.powerStatus(); if (masterOnOffCommand != null) { diff --git a/bundles/org.openhab.binding.millheat/src/main/java/org/openhab/binding/millheat/internal/handler/MillheatHomeHandler.java b/bundles/org.openhab.binding.millheat/src/main/java/org/openhab/binding/millheat/internal/handler/MillheatHomeHandler.java index 5a084b22a..a9b97bc3f 100644 --- a/bundles/org.openhab.binding.millheat/src/main/java/org/openhab/binding/millheat/internal/handler/MillheatHomeHandler.java +++ b/bundles/org.openhab.binding.millheat/src/main/java/org/openhab/binding/millheat/internal/handler/MillheatHomeHandler.java @@ -68,9 +68,9 @@ public class MillheatHomeHandler extends MillheatBaseThingHandler { updateState(channelUID, new QuantityType<>(home.getHolidayTemp(), SIUnits.CELSIUS)); } else if (command instanceof QuantityType) { updateVacationModeProperty(home, SetHolidayParameterRequest.PROP_TEMP, command); - } else if (command instanceof DecimalType) { + } else if (command instanceof DecimalType decimalCommand) { updateVacationModeProperty(home, SetHolidayParameterRequest.PROP_TEMP, - new QuantityType<>((DecimalType) command, SIUnits.CELSIUS)); + new QuantityType<>(decimalCommand, SIUnits.CELSIUS)); } } else if (CHANNEL_HOME_VACATION_MODE.equals(channelUID.getId())) { if (command instanceof RefreshType) { diff --git a/bundles/org.openhab.binding.millheat/src/main/java/org/openhab/binding/millheat/internal/model/MillheatModel.java b/bundles/org.openhab.binding.millheat/src/main/java/org/openhab/binding/millheat/internal/model/MillheatModel.java index a2766be76..8dc27f03f 100644 --- a/bundles/org.openhab.binding.millheat/src/main/java/org/openhab/binding/millheat/internal/model/MillheatModel.java +++ b/bundles/org.openhab.binding.millheat/src/main/java/org/openhab/binding/millheat/internal/model/MillheatModel.java @@ -60,7 +60,7 @@ public class MillheatModel { if (macAddress != null) { heater = findHeaterByMac(macAddress); } - if (!heater.isPresent() && id != null) { + if (heater.isEmpty() && id != null) { heater = findHeaterById(id); } return heater; diff --git a/bundles/org.openhab.binding.minecraft/src/main/java/org/openhab/binding/minecraft/internal/MinecraftHandlerFactory.java b/bundles/org.openhab.binding.minecraft/src/main/java/org/openhab/binding/minecraft/internal/MinecraftHandlerFactory.java index eef426f8b..4ef3f0824 100644 --- a/bundles/org.openhab.binding.minecraft/src/main/java/org/openhab/binding/minecraft/internal/MinecraftHandlerFactory.java +++ b/bundles/org.openhab.binding.minecraft/src/main/java/org/openhab/binding/minecraft/internal/MinecraftHandlerFactory.java @@ -65,11 +65,9 @@ public class MinecraftHandlerFactory extends BaseThingHandlerFactory { minecraftServers.add(serverHandler); return serverHandler; } else if (thingTypeUID.equals(MinecraftBindingConstants.THING_TYPE_PLAYER)) { - MinecraftPlayerHandler playerHandler = new MinecraftPlayerHandler(thing); - return playerHandler; + return new MinecraftPlayerHandler(thing); } else if (thingTypeUID.equals(MinecraftBindingConstants.THING_TYPE_SIGN)) { - MinecraftSignHandler signHandler = new MinecraftSignHandler(thing); - return signHandler; + return new MinecraftSignHandler(thing); } return null; diff --git a/bundles/org.openhab.binding.minecraft/src/main/java/org/openhab/binding/minecraft/internal/discovery/MinecraftDiscoveryService.java b/bundles/org.openhab.binding.minecraft/src/main/java/org/openhab/binding/minecraft/internal/discovery/MinecraftDiscoveryService.java index 650034ec0..738da9c62 100644 --- a/bundles/org.openhab.binding.minecraft/src/main/java/org/openhab/binding/minecraft/internal/discovery/MinecraftDiscoveryService.java +++ b/bundles/org.openhab.binding.minecraft/src/main/java/org/openhab/binding/minecraft/internal/discovery/MinecraftDiscoveryService.java @@ -12,9 +12,9 @@ */ package org.openhab.binding.minecraft.internal.discovery; -import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.Set; import org.openhab.binding.minecraft.internal.MinecraftBindingConstants; import org.openhab.binding.minecraft.internal.MinecraftHandlerFactory; @@ -53,7 +53,7 @@ public class MinecraftDiscoveryService extends AbstractDiscoveryService { private CompositeSubscription subscription; public MinecraftDiscoveryService() { - super(Collections.singleton(MinecraftBindingConstants.THING_TYPE_SERVER), DISCOVER_TIMEOUT_SECONDS, false); + super(Set.of(MinecraftBindingConstants.THING_TYPE_SERVER), DISCOVER_TIMEOUT_SECONDS, false); } @Override @@ -91,10 +91,8 @@ public class MinecraftDiscoveryService extends AbstractDiscoveryService { * @return subscription for listening to sign events. */ private Subscription subscribeSignsRx(Observable serverRx) { - return serverRx - .flatMap(connection -> connection.getSocketHandler().getSignsRx().distinct(), (connection, signs) -> { - return new Pair<>(connection, signs); - }).subscribe(conectionSignPair -> { + return serverRx.flatMap(connection -> connection.getSocketHandler().getSignsRx().distinct(), + (connection, signs) -> new Pair<>(connection, signs)).subscribe(conectionSignPair -> { for (SignData sign : conectionSignPair.second) { submitSignDiscoveryResults(conectionSignPair.first.getThingUID(), sign); } diff --git a/bundles/org.openhab.binding.minecraft/src/main/java/org/openhab/binding/minecraft/internal/discovery/MinecraftMDNSDiscoveryParticipant.java b/bundles/org.openhab.binding.minecraft/src/main/java/org/openhab/binding/minecraft/internal/discovery/MinecraftMDNSDiscoveryParticipant.java index ad8411871..f85a4d46b 100644 --- a/bundles/org.openhab.binding.minecraft/src/main/java/org/openhab/binding/minecraft/internal/discovery/MinecraftMDNSDiscoveryParticipant.java +++ b/bundles/org.openhab.binding.minecraft/src/main/java/org/openhab/binding/minecraft/internal/discovery/MinecraftMDNSDiscoveryParticipant.java @@ -12,7 +12,6 @@ */ package org.openhab.binding.minecraft.internal.discovery; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -38,7 +37,7 @@ public class MinecraftMDNSDiscoveryParticipant implements MDNSDiscoveryParticipa @Override public Set getSupportedThingTypeUIDs() { - return Collections.singleton(MinecraftBindingConstants.THING_TYPE_SERVER); + return Set.of(MinecraftBindingConstants.THING_TYPE_SERVER); } @Override @@ -48,7 +47,7 @@ public class MinecraftMDNSDiscoveryParticipant implements MDNSDiscoveryParticipa @Override public DiscoveryResult createResult(ServiceInfo service) { - if (service.getName().equals("wc-minecraft")) { + if ("wc-minecraft".equals(service.getName())) { ThingUID uid = getThingUID(service); if (uid != null) { diff --git a/bundles/org.openhab.binding.minecraft/src/main/java/org/openhab/binding/minecraft/internal/handler/MinecraftPlayerHandler.java b/bundles/org.openhab.binding.minecraft/src/main/java/org/openhab/binding/minecraft/internal/handler/MinecraftPlayerHandler.java index ed8e46cc6..784d64013 100644 --- a/bundles/org.openhab.binding.minecraft/src/main/java/org/openhab/binding/minecraft/internal/handler/MinecraftPlayerHandler.java +++ b/bundles/org.openhab.binding.minecraft/src/main/java/org/openhab/binding/minecraft/internal/handler/MinecraftPlayerHandler.java @@ -141,8 +141,8 @@ public class MinecraftPlayerHandler extends BaseThingHandler { MinecraftServerHandler bridgeHandler = null; ThingHandler handler = bridge.getHandler(); - if (handler instanceof MinecraftServerHandler) { - bridgeHandler = (MinecraftServerHandler) handler; + if (handler instanceof MinecraftServerHandler serverHandler) { + bridgeHandler = serverHandler; } else { logger.debug("No available bridge handler found yet. Bridge: {} .", bridge.getUID()); bridgeHandler = null; diff --git a/bundles/org.openhab.binding.minecraft/src/main/java/org/openhab/binding/minecraft/internal/handler/MinecraftSignHandler.java b/bundles/org.openhab.binding.minecraft/src/main/java/org/openhab/binding/minecraft/internal/handler/MinecraftSignHandler.java index 80858941b..6316dffad 100644 --- a/bundles/org.openhab.binding.minecraft/src/main/java/org/openhab/binding/minecraft/internal/handler/MinecraftSignHandler.java +++ b/bundles/org.openhab.binding.minecraft/src/main/java/org/openhab/binding/minecraft/internal/handler/MinecraftSignHandler.java @@ -113,8 +113,8 @@ public class MinecraftSignHandler extends BaseThingHandler { MinecraftServerHandler bridgeHandler = null; ThingHandler handler = bridge.getHandler(); - if (handler instanceof MinecraftServerHandler) { - bridgeHandler = (MinecraftServerHandler) handler; + if (handler instanceof MinecraftServerHandler serverHandler) { + bridgeHandler = serverHandler; } else { logger.debug("No available bridge handler found yet. Bridge: {} .", bridge.getUID()); bridgeHandler = null; diff --git a/bundles/org.openhab.binding.modbus.e3dc/src/main/java/org/openhab/binding/modbus/e3dc/internal/handler/E3DCThingHandler.java b/bundles/org.openhab.binding.modbus.e3dc/src/main/java/org/openhab/binding/modbus/e3dc/internal/handler/E3DCThingHandler.java index f5104dd5a..eef3382f6 100644 --- a/bundles/org.openhab.binding.modbus.e3dc/src/main/java/org/openhab/binding/modbus/e3dc/internal/handler/E3DCThingHandler.java +++ b/bundles/org.openhab.binding.modbus.e3dc/src/main/java/org/openhab/binding/modbus/e3dc/internal/handler/E3DCThingHandler.java @@ -276,9 +276,8 @@ public class E3DCThingHandler extends BaseBridgeHandler { return null; } - if (handler instanceof ModbusEndpointThingHandler) { - ModbusEndpointThingHandler slaveEndpoint = (ModbusEndpointThingHandler) handler; - return slaveEndpoint; + if (handler instanceof ModbusEndpointThingHandler thingHandler) { + return thingHandler; } else { logger.debug("Unexpected bridge handler: {}", handler); return null; diff --git a/bundles/org.openhab.binding.modbus.helioseasycontrols/src/main/java/org/openhab/binding/modbus/helioseasycontrols/internal/HeliosEasyControlsActions.java b/bundles/org.openhab.binding.modbus.helioseasycontrols/src/main/java/org/openhab/binding/modbus/helioseasycontrols/internal/HeliosEasyControlsActions.java index 327b2b314..49ed4ff59 100644 --- a/bundles/org.openhab.binding.modbus.helioseasycontrols/src/main/java/org/openhab/binding/modbus/helioseasycontrols/internal/HeliosEasyControlsActions.java +++ b/bundles/org.openhab.binding.modbus.helioseasycontrols/src/main/java/org/openhab/binding/modbus/helioseasycontrols/internal/HeliosEasyControlsActions.java @@ -54,7 +54,6 @@ public class HeliosEasyControlsActions implements ThingActions { private void triggerSwitch(String variableName) { try { if (handler != null) { - handler.writeValue(variableName, "1"); } } catch (HeliosException e) { diff --git a/bundles/org.openhab.binding.modbus.helioseasycontrols/src/main/java/org/openhab/binding/modbus/helioseasycontrols/internal/HeliosEasyControlsHandler.java b/bundles/org.openhab.binding.modbus.helioseasycontrols/src/main/java/org/openhab/binding/modbus/helioseasycontrols/internal/HeliosEasyControlsHandler.java index 30603d92d..d0a8f366b 100644 --- a/bundles/org.openhab.binding.modbus.helioseasycontrols/src/main/java/org/openhab/binding/modbus/helioseasycontrols/internal/HeliosEasyControlsHandler.java +++ b/bundles/org.openhab.binding.modbus.helioseasycontrols/src/main/java/org/openhab/binding/modbus/helioseasycontrols/internal/HeliosEasyControlsHandler.java @@ -21,10 +21,10 @@ import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.Semaphore; @@ -207,8 +207,8 @@ public class HeliosEasyControlsHandler extends BaseThingHandler { return null; } - if (handler instanceof ModbusEndpointThingHandler) { - return (ModbusEndpointThingHandler) handler; + if (handler instanceof ModbusEndpointThingHandler thingHandler) { + return thingHandler; } else { logger.debug("Unexpected bridge handler: {}", handler); return null; @@ -319,9 +319,9 @@ public class HeliosEasyControlsHandler extends BaseThingHandler { String value = null; if (command instanceof OnOffType) { value = command == OnOffType.ON ? "1" : "0"; - } else if (command instanceof DateTimeType) { + } else if (command instanceof DateTimeType dateTimeCommand) { try { - ZonedDateTime d = ((DateTimeType) command).getZonedDateTime(); + ZonedDateTime d = dateTimeCommand.getZonedDateTime(); if (channelId.equals(HeliosEasyControlsBindingConstants.SYS_DATE)) { setSysDateTime(d); } else if (channelId.equals(HeliosEasyControlsBindingConstants.BYPASS_FROM)) { @@ -329,7 +329,7 @@ public class HeliosEasyControlsHandler extends BaseThingHandler { } else if (channelId.equals(HeliosEasyControlsBindingConstants.BYPASS_TO)) { this.setBypass(false, d.getDayOfMonth(), d.getMonthValue()); } else { - value = formatDate(channelId, ((DateTimeType) command).getZonedDateTime()); + value = formatDate(channelId, dateTimeCommand.getZonedDateTime()); } } catch (InterruptedException e) { logger.debug( @@ -338,14 +338,13 @@ public class HeliosEasyControlsHandler extends BaseThingHandler { } } else if ((command instanceof DecimalType) || (command instanceof StringType)) { value = command.toString(); - } else if (command instanceof QuantityType) { + } else if (command instanceof QuantityType val) { // convert item's unit to the Helios device's unit Map variableMap = this.variableMap; if (variableMap != null) { HeliosVariable v = variableMap.get(channelId); if (v != null) { String unit = v.getUnit(); - QuantityType val = (QuantityType) command; if (unit != null) { switch (unit) { case HeliosVariable.UNIT_DAY: @@ -406,7 +405,7 @@ public class HeliosEasyControlsHandler extends BaseThingHandler { @Override public Collection> getServices() { - return Collections.singleton(HeliosEasyControlsActions.class); + return Set.of(HeliosEasyControlsActions.class); } /** @@ -855,7 +854,7 @@ public class HeliosEasyControlsHandler extends BaseThingHandler { switch (itemType) { case "Number": if (((HeliosVariable.TYPE_INTEGER.equals(variableType)) - || (HeliosVariable.TYPE_FLOAT.equals(variableType))) && (!value.equals("-"))) { + || (HeliosVariable.TYPE_FLOAT.equals(variableType))) && (!"-".equals(value))) { State state = null; if (v.getUnit() == null) { state = DecimalType.valueOf(value); @@ -880,7 +879,7 @@ public class HeliosEasyControlsHandler extends BaseThingHandler { break; case "Switch": if (variableType.equals(HeliosVariable.TYPE_INTEGER)) { - updateState(v.getGroupAndName(), value.equals("1") ? OnOffType.ON : OnOffType.OFF); + updateState(v.getGroupAndName(), "1".equals(value) ? OnOffType.ON : OnOffType.OFF); } break; case "String": diff --git a/bundles/org.openhab.binding.modbus.helioseasycontrols/src/main/java/org/openhab/binding/modbus/helioseasycontrols/internal/HeliosEasyControlsHandlerFactory.java b/bundles/org.openhab.binding.modbus.helioseasycontrols/src/main/java/org/openhab/binding/modbus/helioseasycontrols/internal/HeliosEasyControlsHandlerFactory.java index 3db53f6b0..6c61b108e 100644 --- a/bundles/org.openhab.binding.modbus.helioseasycontrols/src/main/java/org/openhab/binding/modbus/helioseasycontrols/internal/HeliosEasyControlsHandlerFactory.java +++ b/bundles/org.openhab.binding.modbus.helioseasycontrols/src/main/java/org/openhab/binding/modbus/helioseasycontrols/internal/HeliosEasyControlsHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.modbus.helioseasycontrols.internal; import static org.openhab.binding.modbus.helioseasycontrols.internal.HeliosEasyControlsBindingConstants.THING_TYPE_HELIOS_VENTILATION_EASY_CONTROLS; -import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -39,8 +38,8 @@ import org.osgi.service.component.annotations.Reference; @Component(configurationPid = "binding.helioseasycontrols", service = ThingHandlerFactory.class) public class HeliosEasyControlsHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections - .singleton(THING_TYPE_HELIOS_VENTILATION_EASY_CONTROLS); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set + .of(THING_TYPE_HELIOS_VENTILATION_EASY_CONTROLS); private final HeliosEasyControlsTranslationProvider translationProvider; @Activate diff --git a/bundles/org.openhab.binding.modbus.stiebeleltron/src/main/java/org/openhab/binding/modbus/stiebeleltron/internal/StiebelEltronHandlerFactory.java b/bundles/org.openhab.binding.modbus.stiebeleltron/src/main/java/org/openhab/binding/modbus/stiebeleltron/internal/StiebelEltronHandlerFactory.java index d9aa3feba..69d83ee84 100644 --- a/bundles/org.openhab.binding.modbus.stiebeleltron/src/main/java/org/openhab/binding/modbus/stiebeleltron/internal/StiebelEltronHandlerFactory.java +++ b/bundles/org.openhab.binding.modbus.stiebeleltron/src/main/java/org/openhab/binding/modbus/stiebeleltron/internal/StiebelEltronHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.modbus.stiebeleltron.internal; import static org.openhab.binding.modbus.stiebeleltron.internal.StiebelEltronBindingConstants.THING_TYPE_HEATPUMP; -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.stiebeleltron", service = ThingHandlerFactory.class) public class StiebelEltronHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_HEATPUMP); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_HEATPUMP); @Override public boolean supportsThingType(ThingTypeUID thingTypeUID) { diff --git a/bundles/org.openhab.binding.modbus.stiebeleltron/src/main/java/org/openhab/binding/modbus/stiebeleltron/internal/handler/StiebelEltronHandler.java b/bundles/org.openhab.binding.modbus.stiebeleltron/src/main/java/org/openhab/binding/modbus/stiebeleltron/internal/handler/StiebelEltronHandler.java index 67cd7982c..20f280447 100644 --- a/bundles/org.openhab.binding.modbus.stiebeleltron/src/main/java/org/openhab/binding/modbus/stiebeleltron/internal/handler/StiebelEltronHandler.java +++ b/bundles/org.openhab.binding.modbus.stiebeleltron/src/main/java/org/openhab/binding/modbus/stiebeleltron/internal/handler/StiebelEltronHandler.java @@ -90,7 +90,6 @@ public class StiebelEltronHandler extends BaseThingHandler { * Register poll task This is where we set up our regular poller */ public synchronized void registerPollTask(int address, int length, ModbusReadFunctionCode readFunctionCode) { - logger.debug("Setting up regular polling"); ModbusCommunicationInterface mycomms = StiebelEltronHandler.this.comms; @@ -220,16 +219,15 @@ public class StiebelEltronHandler extends BaseThingHandler { * the stiebel eltron modbus documentation) */ private short getScaledInt16Value(Command command) throws StiebelEltronException { - if (command instanceof QuantityType) { - QuantityType c = ((QuantityType) command).toUnit(CELSIUS); + if (command instanceof QuantityType quantityCommand) { + QuantityType c = quantityCommand.toUnit(CELSIUS); if (c != null) { return (short) (c.doubleValue() * 10); } else { throw new StiebelEltronException("Unsupported unit"); } } - if (command instanceof DecimalType) { - DecimalType c = (DecimalType) command; + if (command instanceof DecimalType c) { return (short) (c.doubleValue() * 10); } throw new StiebelEltronException("Unsupported command type"); @@ -240,8 +238,7 @@ public class StiebelEltronHandler extends BaseThingHandler { * @return short the value of the command as short */ private short getInt16Value(Command command) throws StiebelEltronException { - if (command instanceof DecimalType) { - DecimalType c = (DecimalType) command; + if (command instanceof DecimalType c) { return c.shortValue(); } throw new StiebelEltronException("Unsupported command type"); @@ -327,7 +324,6 @@ public class StiebelEltronHandler extends BaseThingHandler { * Start the periodic polling1 */ private void startUp() { - if (comms != null) { return; } @@ -479,9 +475,8 @@ public class StiebelEltronHandler extends BaseThingHandler { return null; } - if (handler instanceof ModbusEndpointThingHandler) { - ModbusEndpointThingHandler slaveEndpoint = (ModbusEndpointThingHandler) handler; - return slaveEndpoint; + if (handler instanceof ModbusEndpointThingHandler thingHandler) { + return thingHandler; } else { throw new IllegalStateException("Unexpected bridge handler: " + handler.toString()); } diff --git a/bundles/org.openhab.binding.modbus.studer/src/main/java/org/openhab/binding/modbus/studer/internal/StuderHandler.java b/bundles/org.openhab.binding.modbus.studer/src/main/java/org/openhab/binding/modbus/studer/internal/StuderHandler.java index 7df703382..d6a9aeb9c 100644 --- a/bundles/org.openhab.binding.modbus.studer/src/main/java/org/openhab/binding/modbus/studer/internal/StuderHandler.java +++ b/bundles/org.openhab.binding.modbus.studer/src/main/java/org/openhab/binding/modbus/studer/internal/StuderHandler.java @@ -106,7 +106,6 @@ public class StuderHandler extends BaseThingHandler { @Override public void handleCommand(ChannelUID channelUID, Command command) { - // Currently we do not support any commands } @@ -132,7 +131,6 @@ public class StuderHandler extends BaseThingHandler { * Start the periodic polling */ private void startUp() { - connectEndpoint(); if (comms == null || config == null) { @@ -203,9 +201,8 @@ public class StuderHandler extends BaseThingHandler { return null; } - if (handler instanceof ModbusEndpointThingHandler) { - ModbusEndpointThingHandler slaveEndpoint = (ModbusEndpointThingHandler) handler; - return slaveEndpoint; + if (handler instanceof ModbusEndpointThingHandler thingHandler) { + return thingHandler; } else { logger.debug("Unexpected bridge handler: {}", handler); return null; diff --git a/bundles/org.openhab.binding.modbus.studer/src/main/java/org/openhab/binding/modbus/studer/internal/StuderParser.java b/bundles/org.openhab.binding.modbus.studer/src/main/java/org/openhab/binding/modbus/studer/internal/StuderParser.java index 257fd2033..fa0299dbd 100644 --- a/bundles/org.openhab.binding.modbus.studer/src/main/java/org/openhab/binding/modbus/studer/internal/StuderParser.java +++ b/bundles/org.openhab.binding.modbus.studer/src/main/java/org/openhab/binding/modbus/studer/internal/StuderParser.java @@ -207,7 +207,7 @@ public class StuderParser { * @return the converted float */ public @Nullable Float hexToFloat(String hex) { - String t = hex.replaceAll(" ", ""); + String t = hex.replace(" ", ""); float f = Float.intBitsToFloat((int) Long.parseLong(t, 16)); if (Float.isNaN(f)) { return null; diff --git a/bundles/org.openhab.binding.modbus.sunspec/src/main/java/org/openhab/binding/modbus/sunspec/internal/discovery/SunspecDiscoveryProcess.java b/bundles/org.openhab.binding.modbus.sunspec/src/main/java/org/openhab/binding/modbus/sunspec/internal/discovery/SunspecDiscoveryProcess.java index 00dd6316b..8f6500ebf 100644 --- a/bundles/org.openhab.binding.modbus.sunspec/src/main/java/org/openhab/binding/modbus/sunspec/internal/discovery/SunspecDiscoveryProcess.java +++ b/bundles/org.openhab.binding.modbus.sunspec/src/main/java/org/openhab/binding/modbus/sunspec/internal/discovery/SunspecDiscoveryProcess.java @@ -171,7 +171,7 @@ public class SunspecDiscoveryProcess { Optional id = ModbusBitUtilities.extractStateFromRegisters(registers, 0, ValueType.UINT32); - if (!id.isPresent() || id.get().longValue() != SUNSPEC_ID) { + if (id.isEmpty() || id.get().longValue() != SUNSPEC_ID) { logger.debug("Could not find SunSpec DID at address {}, received: {}, expected: {}", baseAddress, id, SUNSPEC_ID); detectModel(); @@ -207,7 +207,7 @@ public class SunspecDiscoveryProcess { Optional blockLength = ModbusBitUtilities.extractStateFromRegisters(registers, 1, ValueType.UINT16); - if (!moduleID.isPresent() || !blockLength.isPresent()) { + if (moduleID.isEmpty() || blockLength.isEmpty()) { logger.info("Could not find valid module id or block length field."); parsingFinished(); return; diff --git a/bundles/org.openhab.binding.modbus.sunspec/src/main/java/org/openhab/binding/modbus/sunspec/internal/handler/AbstractSunSpecHandler.java b/bundles/org.openhab.binding.modbus.sunspec/src/main/java/org/openhab/binding/modbus/sunspec/internal/handler/AbstractSunSpecHandler.java index e509a77a1..3a23c0df2 100644 --- a/bundles/org.openhab.binding.modbus.sunspec/src/main/java/org/openhab/binding/modbus/sunspec/internal/handler/AbstractSunSpecHandler.java +++ b/bundles/org.openhab.binding.modbus.sunspec/src/main/java/org/openhab/binding/modbus/sunspec/internal/handler/AbstractSunSpecHandler.java @@ -257,9 +257,8 @@ public abstract class AbstractSunSpecHandler extends BaseThingHandler { return null; } - if (handler instanceof ModbusEndpointThingHandler) { - ModbusEndpointThingHandler slaveEndpoint = (ModbusEndpointThingHandler) handler; - return slaveEndpoint; + if (handler instanceof ModbusEndpointThingHandler thingHandler) { + return thingHandler; } else { logger.debug("Unexpected bridge handler: {}", handler); return null; @@ -433,7 +432,7 @@ public abstract class AbstractSunSpecHandler extends BaseThingHandler { * @return the scaled value as a DecimalType */ protected State getScaled(Optional value, Optional scaleFactor, Unit unit) { - if (!value.isPresent() || !scaleFactor.isPresent()) { + if (value.isEmpty() || scaleFactor.isEmpty()) { return UnDefType.UNDEF; } return getScaled(value.get().longValue(), scaleFactor.get(), unit); diff --git a/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/discovery/internal/ModbusEndpointDiscoveryService.java b/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/discovery/internal/ModbusEndpointDiscoveryService.java index 23721dfa4..91e3d3b0d 100644 --- a/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/discovery/internal/ModbusEndpointDiscoveryService.java +++ b/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/discovery/internal/ModbusEndpointDiscoveryService.java @@ -52,8 +52,8 @@ public class ModbusEndpointDiscoveryService implements ModbusThingHandlerDiscove @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof ModbusEndpointThingHandler) { - this.handler = (ModbusEndpointThingHandler) handler; + if (handler instanceof ModbusEndpointThingHandler thingHandler) { + this.handler = thingHandler; } } diff --git a/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/handler/BaseModbusThingHandler.java b/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/handler/BaseModbusThingHandler.java index 8de22c625..6ae9652b0 100644 --- a/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/handler/BaseModbusThingHandler.java +++ b/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/handler/BaseModbusThingHandler.java @@ -185,8 +185,8 @@ public abstract class BaseModbusThingHandler extends BaseThingHandler { BridgeHandler handler = bridge.getHandler(); - if (handler instanceof ModbusEndpointThingHandler) { - return (ModbusEndpointThingHandler) handler; + if (handler instanceof ModbusEndpointThingHandler thingHandler) { + return thingHandler; } else { throw new IllegalStateException("Not a Modbus Bridge: " + handler); } diff --git a/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/handler/ModbusPollerThingHandler.java b/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/handler/ModbusPollerThingHandler.java index 82ca09579..10491b01a 100644 --- a/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/handler/ModbusPollerThingHandler.java +++ b/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/handler/ModbusPollerThingHandler.java @@ -225,9 +225,8 @@ public class ModbusPollerThingHandler extends BaseBridgeHandler { return null; } - if (handler instanceof ModbusEndpointThingHandler) { - ModbusEndpointThingHandler slaveEndpoint = (ModbusEndpointThingHandler) handler; - return slaveEndpoint; + if (handler instanceof ModbusEndpointThingHandler thingHandler) { + return thingHandler; } else { logger.debug("Unexpected bridge handler: {}", handler); return null; @@ -385,8 +384,8 @@ public class ModbusPollerThingHandler extends BaseBridgeHandler { @Override public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) { - if (childHandler instanceof ModbusDataThingHandler) { - this.childCallbacks.add((ModbusDataThingHandler) childHandler); + if (childHandler instanceof ModbusDataThingHandler modbusDataThingHandler) { + this.childCallbacks.add(modbusDataThingHandler); } } diff --git a/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/internal/CascadedValueTransformationImpl.java b/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/internal/CascadedValueTransformationImpl.java index c04bfd11e..8c02d7fbc 100644 --- a/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/internal/CascadedValueTransformationImpl.java +++ b/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/internal/CascadedValueTransformationImpl.java @@ -13,7 +13,6 @@ package org.openhab.binding.modbus.internal; import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @@ -38,7 +37,7 @@ public class CascadedValueTransformationImpl implements ValueTransformation { .filter(s -> !s.isEmpty()).map(transformation -> new SingleValueTransformation(transformation)) .collect(Collectors.toList()); if (localTransformations.isEmpty()) { - localTransformations = Collections.singletonList(new SingleValueTransformation(transformationString)); + localTransformations = List.of(new SingleValueTransformation(transformationString)); } transformations = localTransformations; } diff --git a/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/internal/SingleValueTransformation.java b/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/internal/SingleValueTransformation.java index fc20b7d19..bcfdfb308 100644 --- a/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/internal/SingleValueTransformation.java +++ b/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/internal/SingleValueTransformation.java @@ -168,8 +168,7 @@ public class SingleValueTransformation implements ValueTransformation { } public static Optional tryConvertToCommand(String transformed) { - Optional transformedCommand = Optional.ofNullable(TypeParser.parseCommand(DEFAULT_TYPES, transformed)); - return transformedCommand; + return Optional.ofNullable(TypeParser.parseCommand(DEFAULT_TYPES, transformed)); } @Override diff --git a/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/internal/handler/ModbusDataThingHandler.java b/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/internal/handler/ModbusDataThingHandler.java index 1e3ca0863..8eb720b40 100644 --- a/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/internal/handler/ModbusDataThingHandler.java +++ b/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/internal/handler/ModbusDataThingHandler.java @@ -211,7 +211,7 @@ public class ModbusDataThingHandler extends BaseThingHandler { return; } - if (!transformedCommand.isPresent()) { + if (transformedCommand.isEmpty()) { // transformation failed, return logger.warn("Cannot process command {} (of type {}) with channel {} since transformation was unsuccessful", command, command.getClass().getSimpleName(), channelUID); @@ -277,7 +277,7 @@ public class ModbusDataThingHandler extends BaseThingHandler { } if (writeType.equals(WRITE_TYPE_COIL)) { Optional commandAsBoolean = ModbusBitUtilities.translateCommand2Boolean(transformedCommand); - if (!commandAsBoolean.isPresent()) { + if (commandAsBoolean.isEmpty()) { logger.warn( "Cannot process command {} with channel {} since command is not OnOffType, OpenClosedType or Decimal trying to write to coil. Do not know how to convert to 0/1. Transformed command was '{}'", origCommand, channelUID, transformedCommand); @@ -417,9 +417,7 @@ public class ModbusDataThingHandler extends BaseThingHandler { bridge.getLabel()); throw new ModbusConfigurationException(errmsg); } - if (bridgeHandler instanceof ModbusEndpointThingHandler) { - // Write-only thing, parent is endpoint - ModbusEndpointThingHandler endpointHandler = (ModbusEndpointThingHandler) bridgeHandler; + if (bridgeHandler instanceof ModbusEndpointThingHandler endpointHandler) { slaveId = endpointHandler.getSlaveId(); comms = endpointHandler.getCommunicationInterface(); childOfEndpoint = true; @@ -691,7 +689,7 @@ public class ModbusDataThingHandler extends BaseThingHandler { @Nullable ModbusReadRequestBlueprint readRequest = this.readRequest; ValueType readValueType = this.readValueType; - if (!readIndex.isPresent() || readRequest == null) { + if (readIndex.isEmpty() || readRequest == null) { return; } assert readValueType != null; @@ -721,7 +719,7 @@ public class ModbusDataThingHandler extends BaseThingHandler { String errmsg = String.format( "readStart=X.Y notation is not allowed to be used with value types larger than 16bit! Use readStart=X instead."); throw new ModbusConfigurationException(errmsg); - } else if (!bitQuery && valueTypeBitCount < 16 && !readSubIndex.isPresent()) { + } else if (!bitQuery && valueTypeBitCount < 16 && readSubIndex.isEmpty()) { // User has specified value type which is less than register width (16 bits). // readStart=X.Y notation must be used to define which data to extract from the 16 bit register. String errmsg = String @@ -753,7 +751,7 @@ public class ModbusDataThingHandler extends BaseThingHandler { private void validateWriteIndex() throws ModbusConfigurationException { @Nullable ModbusReadRequestBlueprint readRequest = this.readRequest; - if (!writeStart.isPresent() || !writeSubIndex.isPresent()) { + if (writeStart.isEmpty() || writeSubIndex.isEmpty()) { // // this validation is really about writeStart=X.Y validation // @@ -786,15 +784,11 @@ public class ModbusDataThingHandler extends BaseThingHandler { } private boolean containsOnOff(List> channelAcceptedDataTypes) { - return channelAcceptedDataTypes.stream().anyMatch(clz -> { - return clz.equals(OnOffType.class); - }); + return channelAcceptedDataTypes.stream().anyMatch(clz -> clz.equals(OnOffType.class)); } private boolean containsOpenClosed(List> acceptedDataTypes) { - return acceptedDataTypes.stream().anyMatch(clz -> { - return clz.equals(OpenClosedType.class); - }); + return acceptedDataTypes.stream().anyMatch(clz -> clz.equals(OpenClosedType.class)); } public synchronized void onReadResult(AsyncModbusReadResult result) { diff --git a/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/internal/handler/ModbusSerialThingHandler.java b/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/internal/handler/ModbusSerialThingHandler.java index d60ec5fd4..67c951983 100644 --- a/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/internal/handler/ModbusSerialThingHandler.java +++ b/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/internal/handler/ModbusSerialThingHandler.java @@ -13,8 +13,8 @@ package org.openhab.binding.modbus.internal.handler; import java.util.Collection; -import java.util.Collections; import java.util.Optional; +import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; import org.openhab.binding.modbus.discovery.internal.ModbusEndpointDiscoveryService; @@ -111,6 +111,6 @@ public class ModbusSerialThingHandler @Override public Collection> getServices() { - return Collections.singleton(ModbusEndpointDiscoveryService.class); + return Set.of(ModbusEndpointDiscoveryService.class); } } diff --git a/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/internal/handler/ModbusTcpThingHandler.java b/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/internal/handler/ModbusTcpThingHandler.java index 13359dc66..8bf45d4e4 100644 --- a/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/internal/handler/ModbusTcpThingHandler.java +++ b/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/internal/handler/ModbusTcpThingHandler.java @@ -13,8 +13,8 @@ package org.openhab.binding.modbus.internal.handler; import java.util.Collection; -import java.util.Collections; import java.util.Optional; +import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; import org.openhab.binding.modbus.discovery.internal.ModbusEndpointDiscoveryService; @@ -101,6 +101,6 @@ public class ModbusTcpThingHandler @Override public Collection> getServices() { - return Collections.singleton(ModbusEndpointDiscoveryService.class); + return Set.of(ModbusEndpointDiscoveryService.class); } } diff --git a/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/internal/profiles/ModbusGainOffsetProfile.java b/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/internal/profiles/ModbusGainOffsetProfile.java index cabddd0ae..34620910d 100644 --- a/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/internal/profiles/ModbusGainOffsetProfile.java +++ b/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/internal/profiles/ModbusGainOffsetProfile.java @@ -104,18 +104,18 @@ public class ModbusGainOffsetProfile> implements StateProf @Override public void onCommandFromItem(Command command) { Type result = applyGainOffset(command, false); - if (result instanceof Command) { + if (result instanceof Command cmd) { logger.trace("Command '{}' from item, sending converted '{}' state towards handler.", command, result); - callback.handleCommand((Command) result); + callback.handleCommand(cmd); } } @Override public void onCommandFromHandler(Command command) { Type result = applyGainOffset(command, true); - if (result instanceof Command) { + if (result instanceof Command cmd) { logger.trace("Command '{}' from handler, sending converted '{}' command towards item.", command, result); - callback.sendCommand((Command) result); + callback.sendCommand(cmd); } } @@ -141,23 +141,22 @@ public class ModbusGainOffsetProfile> implements StateProf QuantityType pregainOffsetQt = localPregainOffset.get(); String formula = towardsItem ? String.format("( '%s' + '%s') * '%s'", state, pregainOffsetQt, gain) : String.format("'%s'/'%s' - '%s'", state, gain, pregainOffsetQt); - if (state instanceof QuantityType) { + if (state instanceof QuantityType quantityState) { try { if (towardsItem) { @SuppressWarnings("unchecked") // xx.toUnit(ONE) returns null or QuantityType @Nullable - QuantityType qtState = (QuantityType) (((QuantityType) state) + QuantityType qtState = (QuantityType) (quantityState .toUnit(Units.ONE)); if (qtState == null) { logger.warn("Profile can only process plain numbers from handler. Got unit {}. Returning UNDEF", - ((QuantityType) state).getUnit()); + quantityState.getUnit()); return UnDefType.UNDEF; } QuantityType offsetted = qtState.add(pregainOffsetQt); result = applyGainTowardsItem(offsetted, gain); } else { - final QuantityType qtState = (QuantityType) state; - result = applyGainTowardsHandler(qtState, gain).subtract(pregainOffsetQt); + result = applyGainTowardsHandler(quantityState, gain).subtract(pregainOffsetQt); } } catch (UnconvertibleException | UnsupportedOperationException e) { @@ -166,8 +165,7 @@ public class ModbusGainOffsetProfile> implements StateProf gain, pregainOffsetQt, state, formula, towardsItem, e.getMessage()); return UnDefType.UNDEF; } - } else if (state instanceof DecimalType) { - DecimalType decState = (DecimalType) state; + } else if (state instanceof DecimalType decState) { return applyGainOffset(new QuantityType<>(decState, Units.ONE), towardsItem); } else if (state instanceof RefreshType) { result = state; @@ -188,17 +186,16 @@ public class ModbusGainOffsetProfile> implements StateProf Object parameterValue, @Nullable Unit assertUnit) { Optional> result = Optional.empty(); Unit sourceUnit = null; - if (parameterValue instanceof String) { + if (parameterValue instanceof String str) { try { - QuantityType qt = new QuantityType<>((String) parameterValue); + QuantityType qt = new QuantityType<>(str); result = Optional.of(qt); sourceUnit = qt.getUnit(); } catch (IllegalArgumentException e) { logger.error("Cannot convert value '{}' of parameter '{}' into a QuantityType.", parameterValue, parameterName); } - } else if (parameterValue instanceof BigDecimal) { - BigDecimal parameterBigDecimal = (BigDecimal) parameterValue; + } else if (parameterValue instanceof BigDecimal parameterBigDecimal) { result = Optional.of(new QuantityType(parameterBigDecimal.toString())); } else { logger.error("Parameter '{}' is not of type String or BigDecimal", parameterName); @@ -248,7 +245,7 @@ public class ModbusGainOffsetProfile> implements StateProf private static Object orDefault(Object defaultValue, @Nullable Object value) { if (value == null) { return defaultValue; - } else if (value instanceof String && ((String) value).isBlank()) { + } else if (value instanceof String str && str.isBlank()) { return defaultValue; } else { return value; diff --git a/bundles/org.openhab.binding.modbus/src/test/java/org/openhab/binding/modbus/internal/profiles/ModbusGainOffsetProfileTest.java b/bundles/org.openhab.binding.modbus/src/test/java/org/openhab/binding/modbus/internal/profiles/ModbusGainOffsetProfileTest.java index c57e663ef..5f0faddb8 100644 --- a/bundles/org.openhab.binding.modbus/src/test/java/org/openhab/binding/modbus/internal/profiles/ModbusGainOffsetProfileTest.java +++ b/bundles/org.openhab.binding.modbus/src/test/java/org/openhab/binding/modbus/internal/profiles/ModbusGainOffsetProfileTest.java @@ -137,8 +137,8 @@ public class ModbusGainOffsetProfileTest { final Type actualStateUpdateTowardsItem; if (stateUpdateFromHandler) { final State updateFromHandler; - if (updateFromHandlerObj instanceof String) { - updateFromHandler = new QuantityType((String) updateFromHandlerObj); + if (updateFromHandlerObj instanceof String str) { + updateFromHandler = new QuantityType(str); } else { assertTrue(updateFromHandlerObj instanceof State); updateFromHandler = (State) updateFromHandlerObj; @@ -151,8 +151,8 @@ public class ModbusGainOffsetProfileTest { actualStateUpdateTowardsItem = capture.getValue(); } else { final Command updateFromHandler; - if (updateFromHandlerObj instanceof String) { - updateFromHandler = new QuantityType((String) updateFromHandlerObj); + if (updateFromHandlerObj instanceof String str) { + updateFromHandler = new QuantityType(str); } else { assertTrue(updateFromHandlerObj instanceof State); updateFromHandler = (Command) updateFromHandlerObj; @@ -165,8 +165,7 @@ public class ModbusGainOffsetProfileTest { actualStateUpdateTowardsItem = capture.getValue(); } - Type expectedStateUpdateTowardsItem = (expectedUpdateTowardsItemObj instanceof String) - ? new QuantityType((String) expectedUpdateTowardsItemObj) + Type expectedStateUpdateTowardsItem = (expectedUpdateTowardsItemObj instanceof String s) ? new QuantityType(s) : (Type) expectedUpdateTowardsItemObj; assertEquals(expectedStateUpdateTowardsItem, actualStateUpdateTowardsItem); verifyNoMoreInteractions(callback); @@ -218,7 +217,7 @@ public class ModbusGainOffsetProfileTest { ProfileCallback callback = mock(ProfileCallback.class); ModbusGainOffsetProfile profile = createProfile(callback, gain, preGainOffset); - Command commandFromItem = (commandFromItemObj instanceof String) ? new QuantityType((String) commandFromItemObj) + Command commandFromItem = (commandFromItemObj instanceof String str) ? new QuantityType(str) : (Command) commandFromItemObj; profile.onCommandFromItem(commandFromItem); @@ -227,8 +226,8 @@ public class ModbusGainOffsetProfileTest { ArgumentCaptor capture = ArgumentCaptor.forClass(Command.class); verify(callback, times(1)).handleCommand(capture.capture()); Command actualCommandTowardsHandler = capture.getValue(); - Command expectedCommandTowardsHandler = (expectedCommandTowardsHandlerObj instanceof String) - ? new QuantityType((String) expectedCommandTowardsHandlerObj) + Command expectedCommandTowardsHandler = (expectedCommandTowardsHandlerObj instanceof String str) + ? new QuantityType(str) : (Command) expectedCommandTowardsHandlerObj; assertEquals(expectedCommandTowardsHandler, actualCommandTowardsHandler); verifyNoMoreInteractions(callback); diff --git a/bundles/org.openhab.binding.monopriceaudio/src/main/java/org/openhab/binding/monopriceaudio/internal/handler/MonopriceAudioHandler.java b/bundles/org.openhab.binding.monopriceaudio/src/main/java/org/openhab/binding/monopriceaudio/internal/handler/MonopriceAudioHandler.java index d54c25908..ab270297d 100644 --- a/bundles/org.openhab.binding.monopriceaudio/src/main/java/org/openhab/binding/monopriceaudio/internal/handler/MonopriceAudioHandler.java +++ b/bundles/org.openhab.binding.monopriceaudio/src/main/java/org/openhab/binding/monopriceaudio/internal/handler/MonopriceAudioHandler.java @@ -248,8 +248,8 @@ public class MonopriceAudioHandler extends BaseThingHandler implements Monoprice } break; case CHANNEL_TYPE_SOURCE: - if (command instanceof DecimalType) { - final int value = ((DecimalType) command).intValue(); + if (command instanceof DecimalType decimalCommand) { + final int value = decimalCommand.intValue(); if (value >= ONE && value <= amp.getNumSources()) { logger.debug("Got source command {} zone {}", value, zoneId); connector.sendCommand(zoneId, amp.getSourceCmd(), value); @@ -258,9 +258,9 @@ public class MonopriceAudioHandler extends BaseThingHandler implements Monoprice } break; case CHANNEL_TYPE_VOLUME: - if (command instanceof PercentType) { - final int value = (int) Math.round( - ((PercentType) command).doubleValue() / 100.0 * (amp.getMaxVol() - MIN_VOLUME)) + if (command instanceof PercentType percentCommand) { + final int value = (int) Math + .round(percentCommand.doubleValue() / 100.0 * (amp.getMaxVol() - MIN_VOLUME)) + MIN_VOLUME; logger.debug("Got volume command {} zone {}", value, zoneId); connector.sendCommand(zoneId, amp.getVolumeCmd(), value); @@ -274,8 +274,8 @@ public class MonopriceAudioHandler extends BaseThingHandler implements Monoprice } break; case CHANNEL_TYPE_TREBLE: - if (command instanceof DecimalType) { - final int value = ((DecimalType) command).intValue(); + if (command instanceof DecimalType decimalCommand) { + final int value = decimalCommand.intValue(); if (value >= amp.getMinTone() && value <= amp.getMaxTone()) { logger.debug("Got treble command {} zone {}", value, zoneId); connector.sendCommand(zoneId, amp.getTrebleCmd(), value + amp.getToneOffset()); @@ -284,8 +284,8 @@ public class MonopriceAudioHandler extends BaseThingHandler implements Monoprice } break; case CHANNEL_TYPE_BASS: - if (command instanceof DecimalType) { - final int value = ((DecimalType) command).intValue(); + if (command instanceof DecimalType decimalCommand) { + final int value = decimalCommand.intValue(); if (value >= amp.getMinTone() && value <= amp.getMaxTone()) { logger.debug("Got bass command {} zone {}", value, zoneId); connector.sendCommand(zoneId, amp.getBassCmd(), value + amp.getToneOffset()); @@ -294,8 +294,8 @@ public class MonopriceAudioHandler extends BaseThingHandler implements Monoprice } break; case CHANNEL_TYPE_BALANCE: - if (command instanceof DecimalType) { - final int value = ((DecimalType) command).intValue(); + if (command instanceof DecimalType decimalCommand) { + final int value = decimalCommand.intValue(); if (value >= amp.getMinBal() && value <= amp.getMaxBal()) { logger.debug("Got balance command {} zone {}", value, zoneId); connector.sendCommand(zoneId, amp.getBalanceCmd(), value + amp.getBalOffset()); @@ -334,8 +334,8 @@ public class MonopriceAudioHandler extends BaseThingHandler implements Monoprice } break; case CHANNEL_TYPE_ALLSOURCE: - if (command instanceof DecimalType) { - final int value = ((DecimalType) command).intValue(); + if (command instanceof DecimalType decimalCommand) { + final int value = decimalCommand.intValue(); if (value >= ONE && value <= amp.getNumSources()) { zoneStream.forEach((streamZoneId) -> { if (!ignoreZones.contains(amp.getZoneName(streamZoneId))) { @@ -355,9 +355,9 @@ public class MonopriceAudioHandler extends BaseThingHandler implements Monoprice } break; case CHANNEL_TYPE_ALLVOLUME: - if (command instanceof PercentType) { - allVolume = (int) Math.round( - ((PercentType) command).doubleValue() / 100.0 * (amp.getMaxVol() - MIN_VOLUME)) + if (command instanceof PercentType percentCommand) { + allVolume = (int) Math + .round(percentCommand.doubleValue() / 100.0 * (amp.getMaxVol() - MIN_VOLUME)) + MIN_VOLUME; zoneStream.forEach((streamZoneId) -> { if (!ignoreZones.contains(amp.getZoneName(streamZoneId))) { diff --git a/bundles/org.openhab.binding.mpd/src/main/java/org/openhab/binding/mpd/internal/MPDHandlerFactory.java b/bundles/org.openhab.binding.mpd/src/main/java/org/openhab/binding/mpd/internal/MPDHandlerFactory.java index f4cce9a08..dbd4f29d8 100644 --- a/bundles/org.openhab.binding.mpd/src/main/java/org/openhab/binding/mpd/internal/MPDHandlerFactory.java +++ b/bundles/org.openhab.binding.mpd/src/main/java/org/openhab/binding/mpd/internal/MPDHandlerFactory.java @@ -14,7 +14,6 @@ package org.openhab.binding.mpd.internal; import static org.openhab.binding.mpd.internal.MPDBindingConstants.THING_TYPE_MPD; -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.mpd", service = ThingHandlerFactory.class) public class MPDHandlerFactory extends BaseThingHandlerFactory { - private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_MPD); + private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_MPD); @Override public boolean supportsThingType(ThingTypeUID thingTypeUID) { diff --git a/bundles/org.openhab.binding.mpd/src/main/java/org/openhab/binding/mpd/internal/action/MPDActions.java b/bundles/org.openhab.binding.mpd/src/main/java/org/openhab/binding/mpd/internal/action/MPDActions.java index 00e08dcc3..14c74131c 100644 --- a/bundles/org.openhab.binding.mpd/src/main/java/org/openhab/binding/mpd/internal/action/MPDActions.java +++ b/bundles/org.openhab.binding.mpd/src/main/java/org/openhab/binding/mpd/internal/action/MPDActions.java @@ -38,8 +38,8 @@ public class MPDActions implements ThingActions { @Override public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof MPDHandler) { - this.handler = (MPDHandler) handler; + if (handler instanceof MPDHandler mpdHandler) { + this.handler = mpdHandler; } } diff --git a/bundles/org.openhab.binding.mpd/src/main/java/org/openhab/binding/mpd/internal/discovery/MPDDiscoveryParticipant.java b/bundles/org.openhab.binding.mpd/src/main/java/org/openhab/binding/mpd/internal/discovery/MPDDiscoveryParticipant.java index 34fd36c5f..42988e404 100644 --- a/bundles/org.openhab.binding.mpd/src/main/java/org/openhab/binding/mpd/internal/discovery/MPDDiscoveryParticipant.java +++ b/bundles/org.openhab.binding.mpd/src/main/java/org/openhab/binding/mpd/internal/discovery/MPDDiscoveryParticipant.java @@ -13,7 +13,6 @@ package org.openhab.binding.mpd.internal.discovery; import java.net.Inet4Address; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -46,7 +45,7 @@ public class MPDDiscoveryParticipant implements MDNSDiscoveryParticipant { @Override public Set getSupportedThingTypeUIDs() { - return Collections.singleton(MPDBindingConstants.THING_TYPE_MPD); + return Set.of(MPDBindingConstants.THING_TYPE_MPD); } @Override @@ -76,9 +75,8 @@ public class MPDDiscoveryParticipant implements MDNSDiscoveryParticipant { String name = service.getName(); - final DiscoveryResult result = DiscoveryResultBuilder.create(uid).withLabel(name).withProperties(properties) + return DiscoveryResultBuilder.create(uid).withLabel(name).withProperties(properties) .withRepresentationProperty(MPDBindingConstants.UNIQUE_ID).build(); - return result; } @Nullable diff --git a/bundles/org.openhab.binding.mpd/src/main/java/org/openhab/binding/mpd/internal/handler/MPDHandler.java b/bundles/org.openhab.binding.mpd/src/main/java/org/openhab/binding/mpd/internal/handler/MPDHandler.java index bc10b5bc6..61589f829 100644 --- a/bundles/org.openhab.binding.mpd/src/main/java/org/openhab/binding/mpd/internal/handler/MPDHandler.java +++ b/bundles/org.openhab.binding.mpd/src/main/java/org/openhab/binding/mpd/internal/handler/MPDHandler.java @@ -18,6 +18,7 @@ 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; @@ -111,7 +112,7 @@ public class MPDHandler extends BaseThingHandler implements MPDEventListener { @Override public Collection> getServices() { - return Collections.singleton(MPDActions.class); + return Set.of(MPDActions.class); } /** @@ -232,10 +233,10 @@ public class MPDHandler extends BaseThingHandler implements MPDEventListener { } else if (command == OnOffType.OFF) { newValue = 0; } - } else if (command instanceof DecimalType) { - newValue = ((DecimalType) command).intValue(); - } else if (command instanceof PercentType) { - newValue = ((PercentType) command).intValue(); + } else if (command instanceof DecimalType decimalCommand) { + newValue = decimalCommand.intValue(); + } else if (command instanceof PercentType percentCommand) { + newValue = percentCommand.intValue(); } else { logger.debug("Command {} is not supported to change volume", command); return; diff --git a/bundles/org.openhab.binding.mpd/src/main/java/org/openhab/binding/mpd/internal/protocol/MPDCommand.java b/bundles/org.openhab.binding.mpd/src/main/java/org/openhab/binding/mpd/internal/protocol/MPDCommand.java index afc4c3e33..19c4346d0 100644 --- a/bundles/org.openhab.binding.mpd/src/main/java/org/openhab/binding/mpd/internal/protocol/MPDCommand.java +++ b/bundles/org.openhab.binding.mpd/src/main/java/org/openhab/binding/mpd/internal/protocol/MPDCommand.java @@ -82,7 +82,7 @@ public class MPDCommand { for (String param : parameters) { builder.append(" "); builder.append("\""); - builder.append(param.replaceAll("\"", "\\\\\"").replaceAll("'", "\\\\'")); + builder.append(param.replace("\"", "\\\\\"").replace("'", "\\\\'")); builder.append("\""); } @@ -100,7 +100,7 @@ public class MPDCommand { if ("password".equals(command)) { builder.append(param.replaceAll(".", ".")); } else { - builder.append(param.replaceAll("\"", "\\\\\"").replaceAll("'", "\\\\'")); + builder.append(param.replace("\"", "\\\\\"").replace("'", "\\\\'")); } builder.append("\""); } diff --git a/bundles/org.openhab.binding.mqtt.espmilighthub/src/main/java/org/openhab/binding/mqtt/espmilighthub/internal/handler/EspMilightHubHandler.java b/bundles/org.openhab.binding.mqtt.espmilighthub/src/main/java/org/openhab/binding/mqtt/espmilighthub/internal/handler/EspMilightHubHandler.java index 48fef50fd..72d46aa90 100644 --- a/bundles/org.openhab.binding.mqtt.espmilighthub/src/main/java/org/openhab/binding/mqtt/espmilighthub/internal/handler/EspMilightHubHandler.java +++ b/bundles/org.openhab.binding.mqtt.espmilighthub/src/main/java/org/openhab/binding/mqtt/espmilighthub/internal/handler/EspMilightHubHandler.java @@ -190,7 +190,7 @@ public class EspMilightHubHandler extends BaseThingHandler implements MqttMessag bulbSaturation = "100"; } // 360 isn't allowed by OpenHAB - if (bulbHue.equals("360")) { + if ("360".equals(bulbHue)) { bulbHue = "0"; } var hsb = new HSBType(new DecimalType(Integer.valueOf(bulbHue)), @@ -368,8 +368,7 @@ public class EspMilightHubHandler extends BaseThingHandler implements MqttMessag } sendMQTT("{\"state\":\"ON\",\"level\":" + savedLevel.intValue() + "}"); return; - } else if (command instanceof HSBType) { - HSBType hsb = (HSBType) command; + } else if (command instanceof HSBType hsb) { // This feature allows google home or Echo to trigger white mode when asked to turn color to white. if (hsb.getHue().intValue() == config.whiteHue && hsb.getSaturation().intValue() == config.whiteSat) { if (hasCCT()) { @@ -394,8 +393,7 @@ public class EspMilightHubHandler extends BaseThingHandler implements MqttMessag } savedLevel = hsb.getBrightness().toBigDecimal(); return; - } else if (command instanceof PercentType) { - PercentType percentType = (PercentType) command; + } else if (command instanceof PercentType percentType) { if (percentType.intValue() == 0) { turnOff(); return; @@ -526,8 +524,7 @@ public class EspMilightHubHandler extends BaseThingHandler implements MqttMessag return; } ThingHandler handler = localBridge.getHandler(); - if (handler instanceof AbstractBrokerHandler) { - AbstractBrokerHandler abh = (AbstractBrokerHandler) handler; + if (handler instanceof AbstractBrokerHandler abh) { final MqttBrokerConnection connection; try { connection = abh.getConnectionAsync().get(500, TimeUnit.MILLISECONDS); diff --git a/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/mapping/SubscribeFieldToMQTTtopic.java b/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/mapping/SubscribeFieldToMQTTtopic.java index cfe3f7316..41866f077 100644 --- a/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/mapping/SubscribeFieldToMQTTtopic.java +++ b/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/mapping/SubscribeFieldToMQTTtopic.java @@ -79,8 +79,7 @@ public class SubscribeFieldToMQTTtopic implements MqttMessageSubscriber { // Handle the conversion case of BigDecimal to Float,Double,Long,Integer and the respective // primitive types String typeName = type.getSimpleName(); - if (value instanceof BigDecimal && !type.equals(BigDecimal.class)) { - BigDecimal bdValue = (BigDecimal) value; + if (value instanceof BigDecimal bdValue && !type.equals(BigDecimal.class)) { if (type.equals(Float.class) || "float".equals(typeName)) { result = bdValue.floatValue(); } else if (type.equals(Double.class) || "double".equals(typeName)) { @@ -93,8 +92,7 @@ public class SubscribeFieldToMQTTtopic implements MqttMessageSubscriber { } else // Handle the conversion case of String to Float,Double,Long,Integer,BigDecimal and the respective // primitive types - if (value instanceof String && !type.equals(String.class)) { - String bdValue = (String) value; + if (value instanceof String bdValue && !type.equals(String.class)) { if (type.equals(Float.class) || "float".equals(typeName)) { result = Float.valueOf(bdValue); } else if (type.equals(Double.class) || "double".equals(typeName)) { diff --git a/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/ColorValue.java b/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/ColorValue.java index 541c0e16f..b6ad6fbdb 100644 --- a/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/ColorValue.java +++ b/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/ColorValue.java @@ -83,15 +83,14 @@ public class ColorValue extends Value { @Override public HSBType parseCommand(Command command) throws IllegalArgumentException { HSBType oldvalue = (state == UnDefType.UNDEF) ? new HSBType() : (HSBType) state; - if (command instanceof HSBType) { - return (HSBType) command; - } else if (command instanceof OnOffType) { - OnOffType boolValue = ((OnOffType) command); + if (command instanceof HSBType hsbCommand) { + return hsbCommand; + } else if (command instanceof OnOffType onOffCommand) { PercentType minOn = new PercentType(Math.max(oldvalue.getBrightness().intValue(), onBrightness)); return new HSBType(oldvalue.getHue(), oldvalue.getSaturation(), - boolValue == OnOffType.ON ? minOn : new PercentType(0)); - } else if (command instanceof PercentType) { - return new HSBType(oldvalue.getHue(), oldvalue.getSaturation(), (PercentType) command); + onOffCommand == OnOffType.ON ? minOn : new PercentType(0)); + } else if (command instanceof PercentType percentCommand) { + return new HSBType(oldvalue.getHue(), oldvalue.getSaturation(), percentCommand); } else { final String updatedValue = command.toString(); if (onValue.equals(updatedValue)) { diff --git a/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/DateTimeValue.java b/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/DateTimeValue.java index fa2c4a052..209d1c4bf 100644 --- a/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/DateTimeValue.java +++ b/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/DateTimeValue.java @@ -35,8 +35,8 @@ public class DateTimeValue extends Value { @Override public DateTimeType parseCommand(Command command) throws IllegalArgumentException { - if (command instanceof DateTimeType) { - return ((DateTimeType) command); + if (command instanceof DateTimeType dateTimeCommand) { + return dateTimeCommand; } else { return DateTimeType.valueOf(command.toString()); } diff --git a/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/LocationValue.java b/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/LocationValue.java index 5e2daa917..aa23020b9 100644 --- a/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/LocationValue.java +++ b/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/LocationValue.java @@ -52,8 +52,8 @@ public class LocationValue extends Value { @Override public PointType parseCommand(Command command) throws IllegalArgumentException { - if (command instanceof PointType) { - return ((PointType) command); + if (command instanceof PointType point) { + return point; } else { return PointType.valueOf(command.toString()); } diff --git a/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/NumberValue.java b/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/NumberValue.java index 16b9e53ec..f65dd125e 100644 --- a/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/NumberValue.java +++ b/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/NumberValue.java @@ -86,8 +86,8 @@ public class NumberValue extends Value { @Override public Command parseCommand(Command command) throws IllegalArgumentException { BigDecimal newValue = null; - if (command instanceof DecimalType) { - newValue = ((DecimalType) command).toBigDecimal(); + if (command instanceof DecimalType decimalCommand) { + newValue = decimalCommand.toBigDecimal(); } else if (command instanceof IncreaseDecreaseType || command instanceof UpDownType) { BigDecimal oldValue = getOldValue(); if (command == IncreaseDecreaseType.INCREASE || command == UpDownType.UP) { @@ -95,8 +95,8 @@ public class NumberValue extends Value { } else { newValue = oldValue.subtract(step); } - } else if (command instanceof QuantityType) { - newValue = getQuantityTypeAsDecimal((QuantityType) command); + } else if (command instanceof QuantityType quantityCommand) { + newValue = getQuantityTypeAsDecimal(quantityCommand); } else { newValue = new BigDecimal(command.toString()); } @@ -114,10 +114,10 @@ public class NumberValue extends Value { private BigDecimal getOldValue() { BigDecimal val = BigDecimal.ZERO; - if (state instanceof DecimalType) { - val = ((DecimalType) state).toBigDecimal(); - } else if (state instanceof QuantityType) { - val = ((QuantityType) state).toBigDecimal(); + if (state instanceof DecimalType decimalCommand) { + val = decimalCommand.toBigDecimal(); + } else if (state instanceof QuantityType quantityCommand) { + val = quantityCommand.toBigDecimal(); } return val; } diff --git a/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/OnOffValue.java b/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/OnOffValue.java index 839502d9f..116c8de61 100644 --- a/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/OnOffValue.java +++ b/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/OnOffValue.java @@ -73,8 +73,8 @@ public class OnOffValue extends Value { @Override public OnOffType parseCommand(Command command) throws IllegalArgumentException { - if (command instanceof OnOffType) { - return (OnOffType) command; + if (command instanceof OnOffType onOffCommand) { + return onOffCommand; } else { final String updatedValue = command.toString(); if (onState.equals(updatedValue)) { diff --git a/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/OpenCloseValue.java b/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/OpenCloseValue.java index d9cf7f9ad..d9064dbae 100644 --- a/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/OpenCloseValue.java +++ b/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/OpenCloseValue.java @@ -54,8 +54,8 @@ public class OpenCloseValue extends Value { @Override public OpenClosedType parseCommand(Command command) throws IllegalArgumentException { - if (command instanceof OpenClosedType) { - return (OpenClosedType) command; + if (command instanceof OpenClosedType openClosed) { + return openClosed; } else { final String updatedValue = command.toString(); if (openString.equals(updatedValue)) { diff --git a/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/PercentageValue.java b/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/PercentageValue.java index 12a01e3f0..217d16dc1 100644 --- a/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/PercentageValue.java +++ b/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/PercentageValue.java @@ -75,18 +75,18 @@ public class PercentageValue extends Value { public PercentType parseCommand(Command command) throws IllegalArgumentException { PercentType oldvalue = (state == UnDefType.UNDEF) ? new PercentType() : (PercentType) state; // Nothing do to -> We have received a percentage - if (command instanceof PercentType) { - return (PercentType) command; + if (command instanceof PercentType percent) { + return percent; } else // // A decimal type need to be converted according to the current min/max values - if (command instanceof DecimalType) { - BigDecimal v = ((DecimalType) command).toBigDecimal(); + if (command instanceof DecimalType decimal) { + BigDecimal v = decimal.toBigDecimal(); v = v.subtract(min).multiply(HUNDRED).divide(max.subtract(min), MathContext.DECIMAL128); return new PercentType(v); } else // // A quantity type need to be converted according to the current min/max values - if (command instanceof QuantityType) { - QuantityType qty = ((QuantityType) command).toUnit(Units.PERCENT); + if (command instanceof QuantityType quantity) { + QuantityType qty = quantity.toUnit(Units.PERCENT); if (qty != null) { BigDecimal v = qty.toBigDecimal(); v = v.subtract(min).multiply(HUNDRED).divide(max.subtract(min), MathContext.DECIMAL128); @@ -95,8 +95,8 @@ public class PercentageValue extends Value { return oldvalue; } else // // Increase or decrease by "step" - if (command instanceof IncreaseDecreaseType) { - if (((IncreaseDecreaseType) command) == IncreaseDecreaseType.INCREASE) { + if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) { + if (increaseDecreaseCommand == IncreaseDecreaseType.INCREASE) { final BigDecimal v = oldvalue.toBigDecimal().add(stepPercent); return v.compareTo(HUNDRED) <= 0 ? new PercentType(v) : PercentType.HUNDRED; } else { @@ -105,12 +105,12 @@ public class PercentageValue extends Value { } } else // // On/Off equals 100 or 0 percent - if (command instanceof OnOffType) { - return ((OnOffType) command) == OnOffType.ON ? PercentType.HUNDRED : PercentType.ZERO; + if (command instanceof OnOffType increaseDecreaseCommand) { + return increaseDecreaseCommand == OnOffType.ON ? PercentType.HUNDRED : PercentType.ZERO; } else// // Increase or decrease by "step" - if (command instanceof UpDownType) { - if (((UpDownType) command) == UpDownType.UP) { + if (command instanceof UpDownType upDownCommand) { + if (upDownCommand == UpDownType.UP) { final BigDecimal v = oldvalue.toBigDecimal().add(stepPercent); return v.compareTo(HUNDRED) <= 0 ? new PercentType(v) : PercentType.HUNDRED; } else { diff --git a/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/RollershutterValue.java b/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/RollershutterValue.java index 8626f8df3..c0a977ac4 100644 --- a/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/RollershutterValue.java +++ b/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/RollershutterValue.java @@ -77,8 +77,8 @@ public class RollershutterValue extends Value { return PercentType.HUNDRED; } } - } else if (command instanceof PercentType) { - return (PercentType) command; + } else if (command instanceof PercentType percentage) { + return percentage; } else if (command instanceof StringType) { final String updatedValue = command.toString(); if (updatedValue.equals(upString)) { @@ -115,13 +115,13 @@ public class RollershutterValue extends Value { } else { return ((StopMoveType) command).name(); } - } else if (command instanceof PercentType) { + } else if (command instanceof PercentType percentage) { if (command.equals(PercentType.HUNDRED) && downString != null) { return downString; } else if (command.equals(PercentType.ZERO) && upString != null) { return upString; } else { - return String.valueOf(((PercentType) command).intValue()); + return String.valueOf(percentage.intValue()); } } else { throw new IllegalArgumentException("Invalid command type for Rollershutter item"); diff --git a/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/Value.java b/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/Value.java index 9604eb968..e5f672da2 100644 --- a/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/Value.java +++ b/bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/Value.java @@ -155,7 +155,7 @@ public abstract class Value { * @param data The binary payload to update the internal value. * @exception IllegalArgumentException Thrown if for example a text is assigned to a number type. */ - public void update(byte data[]) throws IllegalArgumentException { + public void update(byte[] data) throws IllegalArgumentException { String mimeType = null; // URLConnection.guessContentTypeFromStream(input) is not sufficient to detect all JPEG files diff --git a/bundles/org.openhab.binding.mqtt.generic/src/test/java/org/openhab/binding/mqtt/generic/ChannelStateTransformationTests.java b/bundles/org.openhab.binding.mqtt.generic/src/test/java/org/openhab/binding/mqtt/generic/ChannelStateTransformationTests.java index 8a6fc89ef..e56bca227 100644 --- a/bundles/org.openhab.binding.mqtt.generic/src/test/java/org/openhab/binding/mqtt/generic/ChannelStateTransformationTests.java +++ b/bundles/org.openhab.binding.mqtt.generic/src/test/java/org/openhab/binding/mqtt/generic/ChannelStateTransformationTests.java @@ -112,7 +112,7 @@ public class ChannelStateTransformationTests { ChannelStateTransformation transformation = channelConfig.transformationsIn.get(0); - byte payload[] = JSON_PATH_JSON.getBytes(); + byte[] payload = JSON_PATH_JSON.getBytes(); assertThat(transformation.pattern, is(JSON_PATH_PATTERN)); // Test process message channelConfig.processMessage(channelConfig.getStateTopic(), payload); diff --git a/bundles/org.openhab.binding.mqtt.generic/src/test/java/org/openhab/binding/mqtt/generic/internal/handler/GenericThingHandlerTests.java b/bundles/org.openhab.binding.mqtt.generic/src/test/java/org/openhab/binding/mqtt/generic/internal/handler/GenericThingHandlerTests.java index 4204a21a5..ccfa9d778 100644 --- a/bundles/org.openhab.binding.mqtt.generic/src/test/java/org/openhab/binding/mqtt/generic/internal/handler/GenericThingHandlerTests.java +++ b/bundles/org.openhab.binding.mqtt.generic/src/test/java/org/openhab/binding/mqtt/generic/internal/handler/GenericThingHandlerTests.java @@ -185,7 +185,7 @@ public class GenericThingHandlerTests { textValue, thingHandler)); doReturn(channelConfig).when(thingHandler).createChannelState(any(), any(), any()); thingHandler.initialize(); - byte payload[] = "UPDATE".getBytes(); + byte[] payload = "UPDATE".getBytes(); // Test process message channelConfig.processMessage("test/state", payload); diff --git a/bundles/org.openhab.binding.mqtt.homeassistant/src/main/java/org/openhab/binding/mqtt/homeassistant/internal/component/AbstractRawSchemaLight.java b/bundles/org.openhab.binding.mqtt.homeassistant/src/main/java/org/openhab/binding/mqtt/homeassistant/internal/component/AbstractRawSchemaLight.java index 728c25ecd..c2e354dab 100644 --- a/bundles/org.openhab.binding.mqtt.homeassistant/src/main/java/org/openhab/binding/mqtt/homeassistant/internal/component/AbstractRawSchemaLight.java +++ b/bundles/org.openhab.binding.mqtt.homeassistant/src/main/java/org/openhab/binding/mqtt/homeassistant/internal/component/AbstractRawSchemaLight.java @@ -53,10 +53,10 @@ abstract class AbstractRawSchemaLight extends Light { if (newState.getBrightness().equals(PercentType.ZERO)) { newState = new HSBType(newState.getHue(), newState.getSaturation(), PercentType.HUNDRED); } - } else if (command instanceof HSBType) { - newState = (HSBType) command; - } else if (command instanceof PercentType) { - newState = new HSBType(newState.getHue(), newState.getSaturation(), (PercentType) command); + } else if (command instanceof HSBType hsb) { + newState = hsb; + } else if (command instanceof PercentType brightness) { + newState = new HSBType(newState.getHue(), newState.getSaturation(), brightness); } else { return false; } diff --git a/bundles/org.openhab.binding.mqtt.homeassistant/src/main/java/org/openhab/binding/mqtt/homeassistant/internal/component/Climate.java b/bundles/org.openhab.binding.mqtt.homeassistant/src/main/java/org/openhab/binding/mqtt/homeassistant/internal/component/Climate.java index e082782e6..a2ad15e81 100644 --- a/bundles/org.openhab.binding.mqtt.homeassistant/src/main/java/org/openhab/binding/mqtt/homeassistant/internal/component/Climate.java +++ b/bundles/org.openhab.binding.mqtt.homeassistant/src/main/java/org/openhab/binding/mqtt/homeassistant/internal/component/Climate.java @@ -58,7 +58,7 @@ public class Climate extends AbstractComponent { public static final String TEMPERATURE_LOW_CH_ID = "temperatureLow"; public static final String POWER_CH_ID = "power"; - public static enum TemperatureUnit { + public enum TemperatureUnit { @SerializedName("C") CELSIUS(SIUnits.CELSIUS, new BigDecimal("0.1")), @SerializedName("F") diff --git a/bundles/org.openhab.binding.mqtt.homeassistant/src/main/java/org/openhab/binding/mqtt/homeassistant/internal/component/DefaultSchemaLight.java b/bundles/org.openhab.binding.mqtt.homeassistant/src/main/java/org/openhab/binding/mqtt/homeassistant/internal/component/DefaultSchemaLight.java index 55d0b310e..092b898a6 100644 --- a/bundles/org.openhab.binding.mqtt.homeassistant/src/main/java/org/openhab/binding/mqtt/homeassistant/internal/component/DefaultSchemaLight.java +++ b/bundles/org.openhab.binding.mqtt.homeassistant/src/main/java/org/openhab/binding/mqtt/homeassistant/internal/component/DefaultSchemaLight.java @@ -224,8 +224,7 @@ public class DefaultSchemaLight extends Light { private boolean handleColorCommand(Command command) { if (!handleOnOffCommand(command)) { return false; - } else if (command instanceof HSBType) { - HSBType color = (HSBType) command; + } else if (command instanceof HSBType color) { if (channelConfiguration.hsCommandTopic != null) { // If we don't have a brightness channel, something is probably busted // but don't choke @@ -250,7 +249,7 @@ public class DefaultSchemaLight extends Light { String xyString = String.format("%f,%f", xy[0].doubleValue(), xy[1].doubleValue()); xyChannel.getState().publishValue(new StringType(xyString)); } - } else if (command instanceof PercentType) { + } else if (command instanceof PercentType brightness) { if (channelConfiguration.brightnessCommandTopic != null) { brightnessChannel.getState().publishValue(command); } else { @@ -261,8 +260,7 @@ public class DefaultSchemaLight extends Light { color = HSBType.WHITE; } HSBType existingColor = (HSBType) color; - HSBType newCommand = new HSBType(existingColor.getHue(), existingColor.getSaturation(), - (PercentType) command); + HSBType newCommand = new HSBType(existingColor.getHue(), existingColor.getSaturation(), brightness); // re-process handleColorCommand(newCommand); } diff --git a/bundles/org.openhab.binding.mqtt.homeassistant/src/main/java/org/openhab/binding/mqtt/homeassistant/internal/component/DeviceTrigger.java b/bundles/org.openhab.binding.mqtt.homeassistant/src/main/java/org/openhab/binding/mqtt/homeassistant/internal/component/DeviceTrigger.java index a0da35871..657483fc5 100644 --- a/bundles/org.openhab.binding.mqtt.homeassistant/src/main/java/org/openhab/binding/mqtt/homeassistant/internal/component/DeviceTrigger.java +++ b/bundles/org.openhab.binding.mqtt.homeassistant/src/main/java/org/openhab/binding/mqtt/homeassistant/internal/component/DeviceTrigger.java @@ -47,7 +47,7 @@ public class DeviceTrigger extends AbstractComponent { try { list = json.getAsJsonArray(); } catch (IllegalStateException e) { - throw new JsonParseException("Cannot parse JSON array. Each connection must be defined as array with two " - + "elements: connection_type, connection identifier. For example: \"connections\": [[\"mac\", " - + "\"02:5b:26:a8:dc:12\"]]", e); + throw new JsonParseException(""" + Cannot parse JSON array. Each connection must be defined as array with two \ + elements: connection_type, connection identifier. For example: "connections": [["mac", \ + "02:5b:26:a8:dc:12"]]\ + """, e); } if (list.size() != 2) { throw new JsonParseException("Connection information must be a tuple, but has " + list.size() diff --git a/bundles/org.openhab.binding.mqtt.homeassistant/src/main/java/org/openhab/binding/mqtt/homeassistant/internal/config/ListOrStringDeserializer.java b/bundles/org.openhab.binding.mqtt.homeassistant/src/main/java/org/openhab/binding/mqtt/homeassistant/internal/config/ListOrStringDeserializer.java index 503dd12ff..01c78712d 100644 --- a/bundles/org.openhab.binding.mqtt.homeassistant/src/main/java/org/openhab/binding/mqtt/homeassistant/internal/config/ListOrStringDeserializer.java +++ b/bundles/org.openhab.binding.mqtt.homeassistant/src/main/java/org/openhab/binding/mqtt/homeassistant/internal/config/ListOrStringDeserializer.java @@ -14,7 +14,6 @@ package org.openhab.binding.mqtt.homeassistant.internal.config; import java.io.IOException; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.Objects; @@ -63,7 +62,7 @@ public class ListOrStringDeserializer extends TypeAdapter> { in.nextNull(); return null; case STRING: - return Collections.singletonList(in.nextString()); + return List.of(in.nextString()); case BEGIN_ARRAY: return readList(in); default: diff --git a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/HaIDTests.java b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/HaIDTests.java index 776c2ed6a..0b9570a62 100644 --- a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/HaIDTests.java +++ b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/HaIDTests.java @@ -17,7 +17,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsIterableContaining.hasItem; import java.util.Collection; -import java.util.Collections; +import java.util.List; import org.eclipse.jdt.annotation.NonNullByDefault; import org.junit.jupiter.api.Test; @@ -45,8 +45,7 @@ public class HaIDTests { assertThat(restore, is(subject)); - HandlerConfiguration haConfig = new HandlerConfiguration(subject.baseTopic, - Collections.singletonList(subject.toShortTopic())); + HandlerConfiguration haConfig = new HandlerConfiguration(subject.baseTopic, List.of(subject.toShortTopic())); Collection restoreList = HaID.fromConfig(haConfig); assertThat(restoreList, hasItem(new HaID("homeassistant/switch/name/config"))); @@ -68,8 +67,7 @@ public class HaIDTests { assertThat(restore, is(subject)); - HandlerConfiguration haConfig = new HandlerConfiguration(subject.baseTopic, - Collections.singletonList(subject.toShortTopic())); + HandlerConfiguration haConfig = new HandlerConfiguration(subject.baseTopic, List.of(subject.toShortTopic())); Collection restoreList = HaID.fromConfig(haConfig); assertThat(restoreList, hasItem(new HaID("homeassistant/switch/node/name/config"))); diff --git a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/AlarmControlPanelTests.java b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/AlarmControlPanelTests.java index 5f07e6fff..3a3654247 100644 --- a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/AlarmControlPanelTests.java +++ b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/AlarmControlPanelTests.java @@ -36,31 +36,33 @@ public class AlarmControlPanelTests extends AbstractComponentTests { public void testAlarmControlPanel() { // @formatter:off var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), - "{ " + - " \"availability\": [ " + - " { " + - " \"topic\": \"zigbee2mqtt/bridge/state\" " + - " } " + - " ], " + - " \"code\": \"12345\", " + - " \"command_topic\": \"zigbee2mqtt/alarm/set/state\", " + - " \"device\": { " + - " \"identifiers\": [ " + - " \"zigbee2mqtt_0x0000000000000000\" " + - " ], " + - " \"manufacturer\": \"BestAlarmEver\", " + - " \"model\": \"Heavy duty super duper alarm\", " + - " \"name\": \"Alarm\", " + - " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " + - " }, " + - " \"name\": \"alarm\", " + - " \"payload_arm_away\": \"ARM_AWAY_\", " + - " \"payload_arm_home\": \"ARM_HOME_\", " + - " \"payload_arm_night\": \"ARM_NIGHT_\", " + - " \"payload_arm_custom_bypass\": \"ARM_CUSTOM_BYPASS_\", " + - " \"payload_disarm\": \"DISARM_\", " + - " \"state_topic\": \"zigbee2mqtt/alarm/state\" " + - "} "); + """ + { \ + "availability": [ \ + { \ + "topic": "zigbee2mqtt/bridge/state" \ + } \ + ], \ + "code": "12345", \ + "command_topic": "zigbee2mqtt/alarm/set/state", \ + "device": { \ + "identifiers": [ \ + "zigbee2mqtt_0x0000000000000000" \ + ], \ + "manufacturer": "BestAlarmEver", \ + "model": "Heavy duty super duper alarm", \ + "name": "Alarm", \ + "sw_version": "Zigbee2MQTT 1.18.2" \ + }, \ + "name": "alarm", \ + "payload_arm_away": "ARM_AWAY_", \ + "payload_arm_home": "ARM_HOME_", \ + "payload_arm_night": "ARM_NIGHT_", \ + "payload_arm_custom_bypass": "ARM_CUSTOM_BYPASS_", \ + "payload_disarm": "DISARM_", \ + "state_topic": "zigbee2mqtt/alarm/state" \ + } \ + """); // @formatter:on assertThat(component.channels.size(), is(4)); diff --git a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/BinarySensorTests.java b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/BinarySensorTests.java index f2ef928fc..0bc38915a 100644 --- a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/BinarySensorTests.java +++ b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/BinarySensorTests.java @@ -36,29 +36,31 @@ public class BinarySensorTests extends AbstractComponentTests { public void test() throws InterruptedException { // @formatter:off var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), - "{ " + - " \"availability\": [ " + - " { " + - " \"topic\": \"zigbee2mqtt/bridge/state\" " + - " } " + - " ], " + - " \"device\": { " + - " \"identifiers\": [ " + - " \"zigbee2mqtt_0x0000000000000000\" " + - " ], " + - " \"manufacturer\": \"Sensors inc\", " + - " \"model\": \"On Off Sensor\", " + - " \"name\": \"OnOffSensor\", " + - " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " + - " }, " + - " \"name\": \"onoffsensor\", " + - " \"force_update\": \"true\", " + - " \"payload_off\": \"OFF_\", " + - " \"payload_on\": \"ON_\", " + - " \"state_topic\": \"zigbee2mqtt/sensor/state\", " + - " \"unique_id\": \"sn1\", " + - " \"value_template\": \"{{ value_json.state }}\" " + - "}"); + """ + { \ + "availability": [ \ + { \ + "topic": "zigbee2mqtt/bridge/state" \ + } \ + ], \ + "device": { \ + "identifiers": [ \ + "zigbee2mqtt_0x0000000000000000" \ + ], \ + "manufacturer": "Sensors inc", \ + "model": "On Off Sensor", \ + "name": "OnOffSensor", \ + "sw_version": "Zigbee2MQTT 1.18.2" \ + }, \ + "name": "onoffsensor", \ + "force_update": "true", \ + "payload_off": "OFF_", \ + "payload_on": "ON_", \ + "state_topic": "zigbee2mqtt/sensor/state", \ + "unique_id": "sn1", \ + "value_template": "{{ value_json.state }}" \ + }\ + """); // @formatter:on assertThat(component.channels.size(), is(1)); @@ -82,30 +84,32 @@ public class BinarySensorTests extends AbstractComponentTests { public void offDelayTest() { // @formatter:off var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), - "{ " + - " \"availability\": [ " + - " { " + - " \"topic\": \"zigbee2mqtt/bridge/state\" " + - " } " + - " ], " + - " \"device\": { " + - " \"identifiers\": [ " + - " \"zigbee2mqtt_0x0000000000000000\" " + - " ], " + - " \"manufacturer\": \"Sensors inc\", " + - " \"model\": \"On Off Sensor\", " + - " \"name\": \"OnOffSensor\", " + - " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " + - " }, " + - " \"name\": \"onoffsensor\", " + - " \"force_update\": \"true\", " + - " \"off_delay\": \"1\", " + - " \"payload_off\": \"OFF_\", " + - " \"payload_on\": \"ON_\", " + - " \"state_topic\": \"zigbee2mqtt/sensor/state\", " + - " \"unique_id\": \"sn1\", " + - " \"value_template\": \"{{ value_json.state }}\" " + - "}"); + """ + { \ + "availability": [ \ + { \ + "topic": "zigbee2mqtt/bridge/state" \ + } \ + ], \ + "device": { \ + "identifiers": [ \ + "zigbee2mqtt_0x0000000000000000" \ + ], \ + "manufacturer": "Sensors inc", \ + "model": "On Off Sensor", \ + "name": "OnOffSensor", \ + "sw_version": "Zigbee2MQTT 1.18.2" \ + }, \ + "name": "onoffsensor", \ + "force_update": "true", \ + "off_delay": "1", \ + "payload_off": "OFF_", \ + "payload_on": "ON_", \ + "state_topic": "zigbee2mqtt/sensor/state", \ + "unique_id": "sn1", \ + "value_template": "{{ value_json.state }}" \ + }\ + """); // @formatter:on publishMessage("zigbee2mqtt/sensor/state", "{ \"state\": \"ON_\" }"); @@ -118,30 +122,32 @@ public class BinarySensorTests extends AbstractComponentTests { public void expireAfterTest() { // @formatter:off var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), - "{ " + - " \"availability\": [ " + - " { " + - " \"topic\": \"zigbee2mqtt/bridge/state\" " + - " } " + - " ], " + - " \"device\": { " + - " \"identifiers\": [ " + - " \"zigbee2mqtt_0x0000000000000000\" " + - " ], " + - " \"manufacturer\": \"Sensors inc\", " + - " \"model\": \"On Off Sensor\", " + - " \"name\": \"OnOffSensor\", " + - " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " + - " }, " + - " \"name\": \"onoffsensor\", " + - " \"expire_after\": \"1\", " + - " \"force_update\": \"true\", " + - " \"payload_off\": \"OFF_\", " + - " \"payload_on\": \"ON_\", " + - " \"state_topic\": \"zigbee2mqtt/sensor/state\", " + - " \"unique_id\": \"sn1\", " + - " \"value_template\": \"{{ value_json.state }}\" " + - "}"); + """ + { \ + "availability": [ \ + { \ + "topic": "zigbee2mqtt/bridge/state" \ + } \ + ], \ + "device": { \ + "identifiers": [ \ + "zigbee2mqtt_0x0000000000000000" \ + ], \ + "manufacturer": "Sensors inc", \ + "model": "On Off Sensor", \ + "name": "OnOffSensor", \ + "sw_version": "Zigbee2MQTT 1.18.2" \ + }, \ + "name": "onoffsensor", \ + "expire_after": "1", \ + "force_update": "true", \ + "payload_off": "OFF_", \ + "payload_on": "ON_", \ + "state_topic": "zigbee2mqtt/sensor/state", \ + "unique_id": "sn1", \ + "value_template": "{{ value_json.state }}" \ + }\ + """); // @formatter:on publishMessage("zigbee2mqtt/sensor/state", "{ \"state\": \"OFF_\" }"); diff --git a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/CameraTests.java b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/CameraTests.java index b1b8b77cf..8b32c33a3 100644 --- a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/CameraTests.java +++ b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/CameraTests.java @@ -35,24 +35,26 @@ public class CameraTests extends AbstractComponentTests { public void test() throws InterruptedException { // @formatter:off var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), - "{ " + - " \"availability\": [ " + - " { " + - " \"topic\": \"zigbee2mqtt/bridge/state\" " + - " } " + - " ], " + - " \"device\": { " + - " \"identifiers\": [ " + - " \"zigbee2mqtt_0x0000000000000000\" " + - " ], " + - " \"manufacturer\": \"Cameras inc\", " + - " \"model\": \"Camera\", " + - " \"name\": \"camera\", " + - " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " + - " }, " + - " \"name\": \"cam1\", " + - " \"topic\": \"zigbee2mqtt/cam1/state\"" + - "}"); + """ + { \ + "availability": [ \ + { \ + "topic": "zigbee2mqtt/bridge/state" \ + } \ + ], \ + "device": { \ + "identifiers": [ \ + "zigbee2mqtt_0x0000000000000000" \ + ], \ + "manufacturer": "Cameras inc", \ + "model": "Camera", \ + "name": "camera", \ + "sw_version": "Zigbee2MQTT 1.18.2" \ + }, \ + "name": "cam1", \ + "topic": "zigbee2mqtt/cam1/state"\ + }\ + """); // @formatter:on assertThat(component.channels.size(), is(1)); diff --git a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/ClimateTests.java b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/ClimateTests.java index 96afff6de..1093bce45 100644 --- a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/ClimateTests.java +++ b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/ClimateTests.java @@ -41,31 +41,34 @@ public class ClimateTests extends AbstractComponentTests { @SuppressWarnings("null") @Test public void testTS0601Climate() { - var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), "{" - + " \"action_template\": \"{% set values = {'idle':'off','heat':'heating','cool':'cooling','fan only':'fan'} %}{{ values[value_json.running_state] }}\"," - + " \"action_topic\": \"zigbee2mqtt/th1\", \"availability\": [ {" - + " \"topic\": \"zigbee2mqtt/bridge/state\" } ]," - + " \"away_mode_command_topic\": \"zigbee2mqtt/th1/set/away_mode\"," - + " \"away_mode_state_template\": \"{{ value_json.away_mode }}\"," - + " \"away_mode_state_topic\": \"zigbee2mqtt/th1\"," - + " \"current_temperature_template\": \"{{ value_json.local_temperature }}\"," - + " \"current_temperature_topic\": \"zigbee2mqtt/th1\", \"device\": {" - + " \"identifiers\": [ \"zigbee2mqtt_0x847127fffe11dd6a\" ], \"manufacturer\": \"TuYa\"," - + " \"model\": \"Radiator valve with thermostat (TS0601_thermostat)\"," - + " \"name\": \"th1\", \"sw_version\": \"Zigbee2MQTT 1.18.2\" }," - + " \"hold_command_topic\": \"zigbee2mqtt/th1/set/preset\", \"hold_modes\": [" - + " \"schedule\", \"manual\", \"boost\", \"complex\", \"comfort\", \"eco\" ]," - + " \"hold_state_template\": \"{{ value_json.preset }}\"," - + " \"hold_state_topic\": \"zigbee2mqtt/th1\"," - + " \"json_attributes_topic\": \"zigbee2mqtt/th1\", \"max_temp\": \"35\"," - + " \"min_temp\": \"5\", \"mode_command_topic\": \"zigbee2mqtt/th1/set/system_mode\"," - + " \"mode_state_template\": \"{{ value_json.system_mode }}\"," - + " \"mode_state_topic\": \"zigbee2mqtt/th1\", \"modes\": [ \"heat\"," - + " \"auto\", \"off\" ], \"name\": \"th1\", \"temp_step\": 0.5," - + " \"temperature_command_topic\": \"zigbee2mqtt/th1/set/current_heating_setpoint\"," - + " \"temperature_state_template\": \"{{ value_json.current_heating_setpoint }}\"," - + " \"temperature_state_topic\": \"zigbee2mqtt/th1\", \"temperature_unit\": \"C\"," - + " \"unique_id\": \"0x847127fffe11dd6a_climate_zigbee2mqtt\"}"); + var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), + """ + {\ + "action_template": "{% set values = {'idle':'off','heat':'heating','cool':'cooling','fan only':'fan'} %}{{ values[value_json.running_state] }}",\ + "action_topic": "zigbee2mqtt/th1", "availability": [ {\ + "topic": "zigbee2mqtt/bridge/state" } ],\ + "away_mode_command_topic": "zigbee2mqtt/th1/set/away_mode",\ + "away_mode_state_template": "{{ value_json.away_mode }}",\ + "away_mode_state_topic": "zigbee2mqtt/th1",\ + "current_temperature_template": "{{ value_json.local_temperature }}",\ + "current_temperature_topic": "zigbee2mqtt/th1", "device": {\ + "identifiers": [ "zigbee2mqtt_0x847127fffe11dd6a" ], "manufacturer": "TuYa",\ + "model": "Radiator valve with thermostat (TS0601_thermostat)",\ + "name": "th1", "sw_version": "Zigbee2MQTT 1.18.2" },\ + "hold_command_topic": "zigbee2mqtt/th1/set/preset", "hold_modes": [\ + "schedule", "manual", "boost", "complex", "comfort", "eco" ],\ + "hold_state_template": "{{ value_json.preset }}",\ + "hold_state_topic": "zigbee2mqtt/th1",\ + "json_attributes_topic": "zigbee2mqtt/th1", "max_temp": "35",\ + "min_temp": "5", "mode_command_topic": "zigbee2mqtt/th1/set/system_mode",\ + "mode_state_template": "{{ value_json.system_mode }}",\ + "mode_state_topic": "zigbee2mqtt/th1", "modes": [ "heat",\ + "auto", "off" ], "name": "th1", "temp_step": 0.5,\ + "temperature_command_topic": "zigbee2mqtt/th1/set/current_heating_setpoint",\ + "temperature_state_template": "{{ value_json.current_heating_setpoint }}",\ + "temperature_state_topic": "zigbee2mqtt/th1", "temperature_unit": "C",\ + "unique_id": "0x847127fffe11dd6a_climate_zigbee2mqtt"}\ + """); assertThat(component.channels.size(), is(6)); assertThat(component.getName(), is("th1")); @@ -81,10 +84,11 @@ public class ClimateTests extends AbstractComponentTests { assertChannel(component, Climate.TEMPERATURE_CH_ID, "zigbee2mqtt/th1", "zigbee2mqtt/th1/set/current_heating_setpoint", "th1", NumberValue.class); - publishMessage("zigbee2mqtt/th1", - "{\"running_state\": \"idle\", \"away_mode\": \"ON\", " - + "\"local_temperature\": \"22.2\", \"preset\": \"schedule\", \"system_mode\": \"heat\", " - + "\"current_heating_setpoint\": \"24\"}"); + publishMessage("zigbee2mqtt/th1", """ + {"running_state": "idle", "away_mode": "ON", \ + "local_temperature": "22.2", "preset": "schedule", "system_mode": "heat", \ + "current_heating_setpoint": "24"}\ + """); assertState(component, Climate.ACTION_CH_ID, new StringType("off")); assertState(component, Climate.AWAY_MODE_CH_ID, OnOffType.ON); assertState(component, Climate.CURRENT_TEMPERATURE_CH_ID, new QuantityType<>(22.2, SIUnits.CELSIUS)); @@ -105,32 +109,35 @@ public class ClimateTests extends AbstractComponentTests { @SuppressWarnings("null") @Test public void testTS0601ClimateNotSendIfOff() { - var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), "{" - + " \"action_template\": \"{% set values = {'idle':'off','heat':'heating','cool':'cooling','fan only':'fan'} %}{{ values[value_json.running_state] }}\"," - + " \"action_topic\": \"zigbee2mqtt/th1\", \"availability\": [ {" - + " \"topic\": \"zigbee2mqtt/bridge/state\" } ]," - + " \"away_mode_command_topic\": \"zigbee2mqtt/th1/set/away_mode\"," - + " \"away_mode_state_template\": \"{{ value_json.away_mode }}\"," - + " \"away_mode_state_topic\": \"zigbee2mqtt/th1\"," - + " \"current_temperature_template\": \"{{ value_json.local_temperature }}\"," - + " \"current_temperature_topic\": \"zigbee2mqtt/th1\", \"device\": {" - + " \"identifiers\": [ \"zigbee2mqtt_0x847127fffe11dd6a\" ], \"manufacturer\": \"TuYa\"," - + " \"model\": \"Radiator valve with thermostat (TS0601_thermostat)\"," - + " \"name\": \"th1\", \"sw_version\": \"Zigbee2MQTT 1.18.2\" }," - + " \"hold_command_topic\": \"zigbee2mqtt/th1/set/preset\", \"hold_modes\": [" - + " \"schedule\", \"manual\", \"boost\", \"complex\", \"comfort\", \"eco\" ]," - + " \"hold_state_template\": \"{{ value_json.preset }}\"," - + " \"hold_state_topic\": \"zigbee2mqtt/th1\"," - + " \"json_attributes_topic\": \"zigbee2mqtt/th1\", \"max_temp\": \"35\"," - + " \"min_temp\": \"5\", \"mode_command_topic\": \"zigbee2mqtt/th1/set/system_mode\"," - + " \"mode_state_template\": \"{{ value_json.system_mode }}\"," - + " \"mode_state_topic\": \"zigbee2mqtt/th1\", \"modes\": [ \"heat\"," - + " \"auto\", \"off\" ], \"name\": \"th1\", \"temp_step\": 0.5," - + " \"temperature_command_topic\": \"zigbee2mqtt/th1/set/current_heating_setpoint\"," - + " \"temperature_state_template\": \"{{ value_json.current_heating_setpoint }}\"," - + " \"temperature_state_topic\": \"zigbee2mqtt/th1\", \"temperature_unit\": \"C\"," - + " \"power_command_topic\": \"zigbee2mqtt/th1/power\"," - + " \"unique_id\": \"0x847127fffe11dd6a_climate_zigbee2mqtt\", \"send_if_off\": \"false\"}"); + var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), + """ + {\ + "action_template": "{% set values = {'idle':'off','heat':'heating','cool':'cooling','fan only':'fan'} %}{{ values[value_json.running_state] }}",\ + "action_topic": "zigbee2mqtt/th1", "availability": [ {\ + "topic": "zigbee2mqtt/bridge/state" } ],\ + "away_mode_command_topic": "zigbee2mqtt/th1/set/away_mode",\ + "away_mode_state_template": "{{ value_json.away_mode }}",\ + "away_mode_state_topic": "zigbee2mqtt/th1",\ + "current_temperature_template": "{{ value_json.local_temperature }}",\ + "current_temperature_topic": "zigbee2mqtt/th1", "device": {\ + "identifiers": [ "zigbee2mqtt_0x847127fffe11dd6a" ], "manufacturer": "TuYa",\ + "model": "Radiator valve with thermostat (TS0601_thermostat)",\ + "name": "th1", "sw_version": "Zigbee2MQTT 1.18.2" },\ + "hold_command_topic": "zigbee2mqtt/th1/set/preset", "hold_modes": [\ + "schedule", "manual", "boost", "complex", "comfort", "eco" ],\ + "hold_state_template": "{{ value_json.preset }}",\ + "hold_state_topic": "zigbee2mqtt/th1",\ + "json_attributes_topic": "zigbee2mqtt/th1", "max_temp": "35",\ + "min_temp": "5", "mode_command_topic": "zigbee2mqtt/th1/set/system_mode",\ + "mode_state_template": "{{ value_json.system_mode }}",\ + "mode_state_topic": "zigbee2mqtt/th1", "modes": [ "heat",\ + "auto", "off" ], "name": "th1", "temp_step": 0.5,\ + "temperature_command_topic": "zigbee2mqtt/th1/set/current_heating_setpoint",\ + "temperature_state_template": "{{ value_json.current_heating_setpoint }}",\ + "temperature_state_topic": "zigbee2mqtt/th1", "temperature_unit": "C",\ + "power_command_topic": "zigbee2mqtt/th1/power",\ + "unique_id": "0x847127fffe11dd6a_climate_zigbee2mqtt", "send_if_off": "false"}\ + """); assertThat(component.channels.size(), is(7)); assertThat(component.getName(), is("th1")); @@ -146,10 +153,11 @@ public class ClimateTests extends AbstractComponentTests { assertChannel(component, Climate.TEMPERATURE_CH_ID, "zigbee2mqtt/th1", "zigbee2mqtt/th1/set/current_heating_setpoint", "th1", NumberValue.class); - publishMessage("zigbee2mqtt/th1", - "{\"running_state\": \"idle\", \"away_mode\": \"ON\", " - + "\"local_temperature\": \"22.2\", \"preset\": \"schedule\", \"system_mode\": \"heat\", " - + "\"current_heating_setpoint\": \"24\"}"); + publishMessage("zigbee2mqtt/th1", """ + {"running_state": "idle", "away_mode": "ON", \ + "local_temperature": "22.2", "preset": "schedule", "system_mode": "heat", \ + "current_heating_setpoint": "24"}\ + """); assertState(component, Climate.ACTION_CH_ID, new StringType("off")); assertState(component, Climate.AWAY_MODE_CH_ID, OnOffType.ON); assertState(component, Climate.CURRENT_TEMPERATURE_CH_ID, new QuantityType<>(22.2, SIUnits.CELSIUS)); @@ -170,10 +178,11 @@ public class ClimateTests extends AbstractComponentTests { assertPublished("zigbee2mqtt/th1/power", "ON"); // Enabled - publishMessage("zigbee2mqtt/th1", - "{\"running_state\": \"heat\", \"away_mode\": \"ON\", " - + "\"local_temperature\": \"22.2\", \"preset\": \"schedule\", \"system_mode\": \"heat\", " - + "\"current_heating_setpoint\": \"24\"}"); + publishMessage("zigbee2mqtt/th1", """ + {"running_state": "heat", "away_mode": "ON", \ + "local_temperature": "22.2", "preset": "schedule", "system_mode": "heat", \ + "current_heating_setpoint": "24"}\ + """); // Climate is in ON state component.getChannel(Climate.AWAY_MODE_CH_ID).getState().publishValue(OnOffType.OFF); @@ -189,48 +198,49 @@ public class ClimateTests extends AbstractComponentTests { @SuppressWarnings("null") @Test public void testClimate() { - var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), - "{\"action_template\": \"{{ value_json.action }}\", \"action_topic\": \"zigbee2mqtt/th1\"," - + " \"aux_command_topic\": \"zigbee2mqtt/th1/aux\"," - + " \"aux_state_template\": \"{{ value_json.aux }}\", \"aux_state_topic\": \"zigbee2mqtt/th1\"," - + " \"away_mode_command_topic\": \"zigbee2mqtt/th1/away_mode\"," - + " \"away_mode_state_template\": \"{{ value_json.away_mode }}\"," - + " \"away_mode_state_topic\": \"zigbee2mqtt/th1\"," - + " \"current_temperature_template\": \"{{ value_json.current_temperature }}\"," - + " \"current_temperature_topic\": \"zigbee2mqtt/th1\"," - + " \"fan_mode_command_template\": \"fan_mode={{ value }}\"," - + " \"fan_mode_command_topic\": \"zigbee2mqtt/th1/fan_mode\"," - + " \"fan_mode_state_template\": \"{{ value_json.fan_mode }}\"," - + " \"fan_mode_state_topic\": \"zigbee2mqtt/th1\", \"fan_modes\": [ \"p1\"," - + " \"p2\" ], \"hold_command_template\": \"hold={{ value }}\"," - + " \"hold_command_topic\": \"zigbee2mqtt/th1/hold\"," - + " \"hold_state_template\": \"{{ value_json.hold }}\"," - + " \"hold_state_topic\": \"zigbee2mqtt/th1\", \"hold_modes\": [ \"u1\", \"u2\"," - + " \"u3\" ], \"json_attributes_template\": \"{{ value_json.attrs }}\"," - + " \"json_attributes_topic\": \"zigbee2mqtt/th1\"," - + " \"mode_command_template\": \"mode={{ value }}\"," - + " \"mode_command_topic\": \"zigbee2mqtt/th1/mode\"," - + " \"mode_state_template\": \"{{ value_json.mode }}\"," - + " \"mode_state_topic\": \"zigbee2mqtt/th1\", \"modes\": [ \"B1\", \"B2\"" - + " ], \"swing_command_template\": \"swing={{ value }}\"," - + " \"swing_command_topic\": \"zigbee2mqtt/th1/swing\"," - + " \"swing_state_template\": \"{{ value_json.swing }}\"," - + " \"swing_state_topic\": \"zigbee2mqtt/th1\", \"swing_modes\": [ \"G1\"," - + " \"G2\" ], \"temperature_command_template\": \"temperature={{ value }}\"," - + " \"temperature_command_topic\": \"zigbee2mqtt/th1/temperature\"," - + " \"temperature_state_template\": \"{{ value_json.temperature }}\"," - + " \"temperature_state_topic\": \"zigbee2mqtt/th1\"," - + " \"temperature_high_command_template\": \"temperature_high={{ value }}\"," - + " \"temperature_high_command_topic\": \"zigbee2mqtt/th1/temperature_high\"," - + " \"temperature_high_state_template\": \"{{ value_json.temperature_high }}\"," - + " \"temperature_high_state_topic\": \"zigbee2mqtt/th1\"," - + " \"temperature_low_command_template\": \"temperature_low={{ value }}\"," - + " \"temperature_low_command_topic\": \"zigbee2mqtt/th1/temperature_low\"," - + " \"temperature_low_state_template\": \"{{ value_json.temperature_low }}\"," - + " \"temperature_low_state_topic\": \"zigbee2mqtt/th1\"," - + " \"power_command_topic\": \"zigbee2mqtt/th1/power\", \"initial\": \"10\"," - + " \"max_temp\": \"40\", \"min_temp\": \"0\", \"temperature_unit\": \"F\"," - + " \"temp_step\": \"1\", \"precision\": \"0.5\", \"send_if_off\": \"false\" }"); + var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), """ + {"action_template": "{{ value_json.action }}", "action_topic": "zigbee2mqtt/th1",\ + "aux_command_topic": "zigbee2mqtt/th1/aux",\ + "aux_state_template": "{{ value_json.aux }}", "aux_state_topic": "zigbee2mqtt/th1",\ + "away_mode_command_topic": "zigbee2mqtt/th1/away_mode",\ + "away_mode_state_template": "{{ value_json.away_mode }}",\ + "away_mode_state_topic": "zigbee2mqtt/th1",\ + "current_temperature_template": "{{ value_json.current_temperature }}",\ + "current_temperature_topic": "zigbee2mqtt/th1",\ + "fan_mode_command_template": "fan_mode={{ value }}",\ + "fan_mode_command_topic": "zigbee2mqtt/th1/fan_mode",\ + "fan_mode_state_template": "{{ value_json.fan_mode }}",\ + "fan_mode_state_topic": "zigbee2mqtt/th1", "fan_modes": [ "p1",\ + "p2" ], "hold_command_template": "hold={{ value }}",\ + "hold_command_topic": "zigbee2mqtt/th1/hold",\ + "hold_state_template": "{{ value_json.hold }}",\ + "hold_state_topic": "zigbee2mqtt/th1", "hold_modes": [ "u1", "u2",\ + "u3" ], "json_attributes_template": "{{ value_json.attrs }}",\ + "json_attributes_topic": "zigbee2mqtt/th1",\ + "mode_command_template": "mode={{ value }}",\ + "mode_command_topic": "zigbee2mqtt/th1/mode",\ + "mode_state_template": "{{ value_json.mode }}",\ + "mode_state_topic": "zigbee2mqtt/th1", "modes": [ "B1", "B2"\ + ], "swing_command_template": "swing={{ value }}",\ + "swing_command_topic": "zigbee2mqtt/th1/swing",\ + "swing_state_template": "{{ value_json.swing }}",\ + "swing_state_topic": "zigbee2mqtt/th1", "swing_modes": [ "G1",\ + "G2" ], "temperature_command_template": "temperature={{ value }}",\ + "temperature_command_topic": "zigbee2mqtt/th1/temperature",\ + "temperature_state_template": "{{ value_json.temperature }}",\ + "temperature_state_topic": "zigbee2mqtt/th1",\ + "temperature_high_command_template": "temperature_high={{ value }}",\ + "temperature_high_command_topic": "zigbee2mqtt/th1/temperature_high",\ + "temperature_high_state_template": "{{ value_json.temperature_high }}",\ + "temperature_high_state_topic": "zigbee2mqtt/th1",\ + "temperature_low_command_template": "temperature_low={{ value }}",\ + "temperature_low_command_topic": "zigbee2mqtt/th1/temperature_low",\ + "temperature_low_state_template": "{{ value_json.temperature_low }}",\ + "temperature_low_state_topic": "zigbee2mqtt/th1",\ + "power_command_topic": "zigbee2mqtt/th1/power", "initial": "10",\ + "max_temp": "40", "min_temp": "0", "temperature_unit": "F",\ + "temp_step": "1", "precision": "0.5", "send_if_off": "false" }\ + """); assertThat(component.channels.size(), is(12)); assertThat(component.getName(), is("MQTT HVAC")); @@ -258,11 +268,12 @@ public class ClimateTests extends AbstractComponentTests { "MQTT HVAC", NumberValue.class); assertChannel(component, Climate.POWER_CH_ID, "", "zigbee2mqtt/th1/power", "MQTT HVAC", OnOffValue.class); - publishMessage("zigbee2mqtt/th1", - "{ \"action\": \"fan\", \"aux\": \"ON\", \"away_mode\": \"OFF\", " - + "\"current_temperature\": \"35.5\", \"fan_mode\": \"p2\", \"hold\": \"u2\", " - + "\"mode\": \"B1\", \"swing\": \"G1\", \"temperature\": \"30\", " - + "\"temperature_high\": \"37\", \"temperature_low\": \"20\" }"); + publishMessage("zigbee2mqtt/th1", """ + { "action": "fan", "aux": "ON", "away_mode": "OFF", \ + "current_temperature": "35.5", "fan_mode": "p2", "hold": "u2", \ + "mode": "B1", "swing": "G1", "temperature": "30", \ + "temperature_high": "37", "temperature_low": "20" }\ + """); assertState(component, Climate.ACTION_CH_ID, new StringType("fan")); assertState(component, Climate.AUX_CH_ID, OnOffType.ON); diff --git a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/CoverTests.java b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/CoverTests.java index a63a758a0..502d77dcf 100644 --- a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/CoverTests.java +++ b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/CoverTests.java @@ -37,28 +37,30 @@ public class CoverTests extends AbstractComponentTests { public void test() throws InterruptedException { // @formatter:off var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), - "{ " + - " \"availability\": [ " + - " { " + - " \"topic\": \"zigbee2mqtt/bridge/state\" " + - " } " + - " ], " + - " \"device\": { " + - " \"identifiers\": [ " + - " \"zigbee2mqtt_0x0000000000000000\" " + - " ], " + - " \"manufacturer\": \"Covers inc\", " + - " \"model\": \"cover v1\", " + - " \"name\": \"Cover\", " + - " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " + - " }, " + - " \"name\": \"cover\", " + - " \"payload_open\": \"OPEN_\", " + - " \"payload_close\": \"CLOSE_\", " + - " \"payload_stop\": \"STOP_\", " + - " \"state_topic\": \"zigbee2mqtt/cover/state\", " + - " \"command_topic\": \"zigbee2mqtt/cover/set/state\" " + - "}"); + """ + { \ + "availability": [ \ + { \ + "topic": "zigbee2mqtt/bridge/state" \ + } \ + ], \ + "device": { \ + "identifiers": [ \ + "zigbee2mqtt_0x0000000000000000" \ + ], \ + "manufacturer": "Covers inc", \ + "model": "cover v1", \ + "name": "Cover", \ + "sw_version": "Zigbee2MQTT 1.18.2" \ + }, \ + "name": "cover", \ + "payload_open": "OPEN_", \ + "payload_close": "CLOSE_", \ + "payload_stop": "STOP_", \ + "state_topic": "zigbee2mqtt/cover/state", \ + "command_topic": "zigbee2mqtt/cover/set/state" \ + }\ + """); // @formatter:on assertThat(component.channels.size(), is(1)); diff --git a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/DefaultSchemaLightTests.java b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/DefaultSchemaLightTests.java index 7d1217fa4..a5b092b01 100644 --- a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/DefaultSchemaLightTests.java +++ b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/DefaultSchemaLightTests.java @@ -46,34 +46,36 @@ public class DefaultSchemaLightTests extends AbstractComponentTests { public void testRgb() throws InterruptedException { // @formatter:off var component = (Light) discoverComponent(configTopicToMqtt(CONFIG_TOPIC), - "{ " + - " \"availability\": [ " + - " { " + - " \"topic\": \"zigbee2mqtt/bridge/state\" " + - " } " + - " ], " + - " \"device\": { " + - " \"identifiers\": [ " + - " \"zigbee2mqtt_0x0000000000000000\" " + - " ], " + - " \"manufacturer\": \"Lights inc\", " + - " \"model\": \"light v1\", " + - " \"name\": \"Light\", " + - " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " + - " }, " + - " \"name\": \"light\", " + - " \"state_topic\": \"zigbee2mqtt/light/state\", " + - " \"command_topic\": \"zigbee2mqtt/light/set/state\", " + - " \"state_value_template\": \"{{ value_json.power }}\", " + - " \"payload_on\": \"ON_\", " + - " \"payload_off\": \"OFF_\", " + - " \"rgb_state_topic\": \"zigbee2mqtt/light/rgb\", " + - " \"rgb_command_topic\": \"zigbee2mqtt/light/set/rgb\", " + - " \"rgb_value_template\": \"{{ value_json.rgb }}\", " + - " \"brightness_state_topic\": \"zigbee2mqtt/light/brightness\", " + - " \"brightness_command_topic\": \"zigbee2mqtt/light/set/brightness\", " + - " \"brightness_value_template\": \"{{ value_json.br }}\" " + - "}"); + """ + { \ + "availability": [ \ + { \ + "topic": "zigbee2mqtt/bridge/state" \ + } \ + ], \ + "device": { \ + "identifiers": [ \ + "zigbee2mqtt_0x0000000000000000" \ + ], \ + "manufacturer": "Lights inc", \ + "model": "light v1", \ + "name": "Light", \ + "sw_version": "Zigbee2MQTT 1.18.2" \ + }, \ + "name": "light", \ + "state_topic": "zigbee2mqtt/light/state", \ + "command_topic": "zigbee2mqtt/light/set/state", \ + "state_value_template": "{{ value_json.power }}", \ + "payload_on": "ON_", \ + "payload_off": "OFF_", \ + "rgb_state_topic": "zigbee2mqtt/light/rgb", \ + "rgb_command_topic": "zigbee2mqtt/light/set/rgb", \ + "rgb_value_template": "{{ value_json.rgb }}", \ + "brightness_state_topic": "zigbee2mqtt/light/brightness", \ + "brightness_command_topic": "zigbee2mqtt/light/set/brightness", \ + "brightness_value_template": "{{ value_json.br }}" \ + }\ + """); // @formatter:on assertThat(component.channels.size(), is(1)); @@ -119,17 +121,19 @@ public class DefaultSchemaLightTests extends AbstractComponentTests { public void testRgbWithoutBrightness() throws InterruptedException { // @formatter:off var component = (Light) discoverComponent(configTopicToMqtt(CONFIG_TOPIC), - "{ " + - " \"name\": \"light\", " + - " \"state_topic\": \"zigbee2mqtt/light/state\", " + - " \"command_topic\": \"zigbee2mqtt/light/set/state\", " + - " \"state_value_template\": \"{{ value_json.power }}\", " + - " \"payload_on\": \"ON_\", " + - " \"payload_off\": \"OFF_\", " + - " \"rgb_state_topic\": \"zigbee2mqtt/light/rgb\", " + - " \"rgb_command_topic\": \"zigbee2mqtt/light/set/rgb\", " + - " \"rgb_value_template\": \"{{ value_json.rgb }}\"" + - "}"); + """ + { \ + "name": "light", \ + "state_topic": "zigbee2mqtt/light/state", \ + "command_topic": "zigbee2mqtt/light/set/state", \ + "state_value_template": "{{ value_json.power }}", \ + "payload_on": "ON_", \ + "payload_off": "OFF_", \ + "rgb_state_topic": "zigbee2mqtt/light/rgb", \ + "rgb_command_topic": "zigbee2mqtt/light/set/rgb", \ + "rgb_value_template": "{{ value_json.rgb }}"\ + }\ + """); // @formatter:on publishMessage("zigbee2mqtt/light/rgb", "{\"rgb\": \"255,255,255\"}"); @@ -148,20 +152,22 @@ public class DefaultSchemaLightTests extends AbstractComponentTests { public void testHsb() throws InterruptedException { // @formatter:off var component = (Light) discoverComponent(configTopicToMqtt(CONFIG_TOPIC), - "{ " + - " \"name\": \"light\", " + - " \"state_topic\": \"zigbee2mqtt/light/state\", " + - " \"command_topic\": \"zigbee2mqtt/light/set/state\", " + - " \"state_value_template\": \"{{ value_json.power }}\", " + - " \"payload_on\": \"ON_\", " + - " \"payload_off\": \"OFF_\", " + - " \"hs_state_topic\": \"zigbee2mqtt/light/hs\", " + - " \"hs_command_topic\": \"zigbee2mqtt/light/set/hs\", " + - " \"hs_value_template\": \"{{ value_json.hs }}\", " + - " \"brightness_state_topic\": \"zigbee2mqtt/light/brightness\", " + - " \"brightness_command_topic\": \"zigbee2mqtt/light/set/brightness\", " + - " \"brightness_value_template\": \"{{ value_json.br }}\" " + - "}"); + """ + { \ + "name": "light", \ + "state_topic": "zigbee2mqtt/light/state", \ + "command_topic": "zigbee2mqtt/light/set/state", \ + "state_value_template": "{{ value_json.power }}", \ + "payload_on": "ON_", \ + "payload_off": "OFF_", \ + "hs_state_topic": "zigbee2mqtt/light/hs", \ + "hs_command_topic": "zigbee2mqtt/light/set/hs", \ + "hs_value_template": "{{ value_json.hs }}", \ + "brightness_state_topic": "zigbee2mqtt/light/brightness", \ + "brightness_command_topic": "zigbee2mqtt/light/set/brightness", \ + "brightness_value_template": "{{ value_json.br }}" \ + }\ + """); // @formatter:on assertThat(component.channels.size(), is(1)); @@ -206,16 +212,18 @@ public class DefaultSchemaLightTests extends AbstractComponentTests { public void testBrightnessAndOnOff() throws InterruptedException { // @formatter:off var component = (Light) discoverComponent(configTopicToMqtt(CONFIG_TOPIC), - "{ " + - " \"name\": \"light\", " + - " \"state_topic\": \"zigbee2mqtt/light/state\", " + - " \"command_topic\": \"zigbee2mqtt/light/set/state\", " + - " \"state_value_template\": \"{{ value_json.power }}\", " + - " \"brightness_state_topic\": \"zigbee2mqtt/light/brightness\", " + - " \"brightness_command_topic\": \"zigbee2mqtt/light/set/brightness\", " + - " \"payload_on\": \"ON_\", " + - " \"payload_off\": \"OFF_\" " + - "}"); + """ + { \ + "name": "light", \ + "state_topic": "zigbee2mqtt/light/state", \ + "command_topic": "zigbee2mqtt/light/set/state", \ + "state_value_template": "{{ value_json.power }}", \ + "brightness_state_topic": "zigbee2mqtt/light/brightness", \ + "brightness_command_topic": "zigbee2mqtt/light/set/brightness", \ + "payload_on": "ON_", \ + "payload_off": "OFF_" \ + }\ + """); // @formatter:on assertThat(component.channels.size(), is(1)); @@ -249,14 +257,16 @@ public class DefaultSchemaLightTests extends AbstractComponentTests { public void testOnOffOnly() throws InterruptedException { // @formatter:off var component = (Light) discoverComponent(configTopicToMqtt(CONFIG_TOPIC), - "{ " + - " \"name\": \"light\", " + - " \"state_topic\": \"zigbee2mqtt/light/state\", " + - " \"command_topic\": \"zigbee2mqtt/light/set/state\", " + - " \"state_value_template\": \"{{ value_json.power }}\", " + - " \"payload_on\": \"ON_\", " + - " \"payload_off\": \"OFF_\" " + - "}"); + """ + { \ + "name": "light", \ + "state_topic": "zigbee2mqtt/light/state", \ + "command_topic": "zigbee2mqtt/light/set/state", \ + "state_value_template": "{{ value_json.power }}", \ + "payload_on": "ON_", \ + "payload_off": "OFF_" \ + }\ + """); // @formatter:on assertThat(component.channels.size(), is(1)); diff --git a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/FanTests.java b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/FanTests.java index fde17cfc1..a5e6328aa 100644 --- a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/FanTests.java +++ b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/FanTests.java @@ -36,27 +36,29 @@ public class FanTests extends AbstractComponentTests { public void test() throws InterruptedException { // @formatter:off var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), - "{ " + - " \"availability\": [ " + - " { " + - " \"topic\": \"zigbee2mqtt/bridge/state\" " + - " } " + - " ], " + - " \"device\": { " + - " \"identifiers\": [ " + - " \"zigbee2mqtt_0x0000000000000000\" " + - " ], " + - " \"manufacturer\": \"Fans inc\", " + - " \"model\": \"Fan\", " + - " \"name\": \"FanBlower\", " + - " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " + - " }, " + - " \"name\": \"fan\", " + - " \"payload_off\": \"OFF_\", " + - " \"payload_on\": \"ON_\", " + - " \"state_topic\": \"zigbee2mqtt/fan/state\", " + - " \"command_topic\": \"zigbee2mqtt/fan/set/state\" " + - "}"); + """ + { \ + "availability": [ \ + { \ + "topic": "zigbee2mqtt/bridge/state" \ + } \ + ], \ + "device": { \ + "identifiers": [ \ + "zigbee2mqtt_0x0000000000000000" \ + ], \ + "manufacturer": "Fans inc", \ + "model": "Fan", \ + "name": "FanBlower", \ + "sw_version": "Zigbee2MQTT 1.18.2" \ + }, \ + "name": "fan", \ + "payload_off": "OFF_", \ + "payload_on": "ON_", \ + "state_topic": "zigbee2mqtt/fan/state", \ + "command_topic": "zigbee2mqtt/fan/set/state" \ + }\ + """); // @formatter:on assertThat(component.channels.size(), is(1)); diff --git a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/JSONSchemaLightTests.java b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/JSONSchemaLightTests.java index fdd18ee34..e1c50de28 100644 --- a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/JSONSchemaLightTests.java +++ b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/JSONSchemaLightTests.java @@ -41,29 +41,31 @@ public class JSONSchemaLightTests extends AbstractComponentTests { public void testRgb() throws InterruptedException { // @formatter:off var component = (Light) discoverComponent(configTopicToMqtt(CONFIG_TOPIC), - "{ " + - " \"availability\": [ " + - " { " + - " \"topic\": \"zigbee2mqtt/bridge/state\" " + - " } " + - " ], " + - " \"device\": { " + - " \"identifiers\": [ " + - " \"zigbee2mqtt_0x0000000000000000\" " + - " ], " + - " \"manufacturer\": \"Lights inc\", " + - " \"model\": \"light v1\", " + - " \"name\": \"Light\", " + - " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " + - " }, " + - " \"name\": \"light\", " + - " \"schema\": \"json\", " + - " \"state_topic\": \"zigbee2mqtt/light/state\", " + - " \"command_topic\": \"zigbee2mqtt/light/set/state\", " + - " \"brightness\": true, " + - " \"color_mode\": true, " + - " \"supported_color_modes\": [\"onoff\", \"brightness\", \"rgb\"]" + - "}"); + """ + { \ + "availability": [ \ + { \ + "topic": "zigbee2mqtt/bridge/state" \ + } \ + ], \ + "device": { \ + "identifiers": [ \ + "zigbee2mqtt_0x0000000000000000" \ + ], \ + "manufacturer": "Lights inc", \ + "model": "light v1", \ + "name": "Light", \ + "sw_version": "Zigbee2MQTT 1.18.2" \ + }, \ + "name": "light", \ + "schema": "json", \ + "state_topic": "zigbee2mqtt/light/state", \ + "command_topic": "zigbee2mqtt/light/set/state", \ + "brightness": true, \ + "color_mode": true, \ + "supported_color_modes": ["onoff", "brightness", "rgb"]\ + }\ + """); // @formatter:on assertThat(component.channels.size(), is(1)); @@ -97,13 +99,15 @@ public class JSONSchemaLightTests extends AbstractComponentTests { public void testBrightnessAndOnOff() throws InterruptedException { // @formatter:off var component = (Light) discoverComponent(configTopicToMqtt(CONFIG_TOPIC), - "{ " + - " \"name\": \"light\", " + - " \"schema\": \"json\", " + - " \"state_topic\": \"zigbee2mqtt/light/state\", " + - " \"command_topic\": \"zigbee2mqtt/light/set/state\", " + - " \"brightness\": true" + - "}"); + """ + { \ + "name": "light", \ + "schema": "json", \ + "state_topic": "zigbee2mqtt/light/state", \ + "command_topic": "zigbee2mqtt/light/set/state", \ + "brightness": true\ + }\ + """); // @formatter:on assertThat(component.channels.size(), is(1)); @@ -126,12 +130,14 @@ public class JSONSchemaLightTests extends AbstractComponentTests { public void testOnOffOnly() throws InterruptedException { // @formatter:off var component = (Light) discoverComponent(configTopicToMqtt(CONFIG_TOPIC), - "{ " + - " \"name\": \"light\", " + - " \"schema\": \"json\", " + - " \"state_topic\": \"zigbee2mqtt/light/state\", " + - " \"command_topic\": \"zigbee2mqtt/light/set/state\"" + - "}"); + """ + { \ + "name": "light", \ + "schema": "json", \ + "state_topic": "zigbee2mqtt/light/state", \ + "command_topic": "zigbee2mqtt/light/set/state"\ + }\ + """); // @formatter:on assertThat(component.channels.size(), is(1)); diff --git a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/LockTests.java b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/LockTests.java index 83fb02c3e..c988806ef 100644 --- a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/LockTests.java +++ b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/LockTests.java @@ -36,27 +36,29 @@ public class LockTests extends AbstractComponentTests { public void test() throws InterruptedException { // @formatter:off var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), - "{ " + - " \"availability\": [ " + - " { " + - " \"topic\": \"zigbee2mqtt/bridge/state\" " + - " } " + - " ], " + - " \"device\": { " + - " \"identifiers\": [ " + - " \"zigbee2mqtt_0x0000000000000000\" " + - " ], " + - " \"manufacturer\": \"Locks inc\", " + - " \"model\": \"Lock\", " + - " \"name\": \"LockBlower\", " + - " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " + - " }, " + - " \"name\": \"lock\", " + - " \"payload_unlock\": \"UNLOCK_\", " + - " \"payload_lock\": \"LOCK_\", " + - " \"state_topic\": \"zigbee2mqtt/lock/state\", " + - " \"command_topic\": \"zigbee2mqtt/lock/set/state\" " + - "}"); + """ + { \ + "availability": [ \ + { \ + "topic": "zigbee2mqtt/bridge/state" \ + } \ + ], \ + "device": { \ + "identifiers": [ \ + "zigbee2mqtt_0x0000000000000000" \ + ], \ + "manufacturer": "Locks inc", \ + "model": "Lock", \ + "name": "LockBlower", \ + "sw_version": "Zigbee2MQTT 1.18.2" \ + }, \ + "name": "lock", \ + "payload_unlock": "UNLOCK_", \ + "payload_lock": "LOCK_", \ + "state_topic": "zigbee2mqtt/lock/state", \ + "command_topic": "zigbee2mqtt/lock/set/state" \ + }\ + """); // @formatter:on assertThat(component.channels.size(), is(1)); @@ -84,28 +86,30 @@ public class LockTests extends AbstractComponentTests { public void forceOptimisticIsNotSupported() { // @formatter:off publishMessage(configTopicToMqtt(CONFIG_TOPIC), - "{ " + - " \"availability\": [ " + - " { " + - " \"topic\": \"zigbee2mqtt/bridge/state\" " + - " } " + - " ], " + - " \"device\": { " + - " \"identifiers\": [ " + - " \"zigbee2mqtt_0x0000000000000000\" " + - " ], " + - " \"manufacturer\": \"Locks inc\", " + - " \"model\": \"Lock\", " + - " \"name\": \"LockBlower\", " + - " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " + - " }, " + - " \"name\": \"lock\", " + - " \"payload_unlock\": \"UNLOCK_\", " + - " \"payload_lock\": \"LOCK_\", " + - " \"optimistic\": \"true\", " + - " \"state_topic\": \"zigbee2mqtt/lock/state\", " + - " \"command_topic\": \"zigbee2mqtt/lock/set/state\" " + - "}"); + """ + { \ + "availability": [ \ + { \ + "topic": "zigbee2mqtt/bridge/state" \ + } \ + ], \ + "device": { \ + "identifiers": [ \ + "zigbee2mqtt_0x0000000000000000" \ + ], \ + "manufacturer": "Locks inc", \ + "model": "Lock", \ + "name": "LockBlower", \ + "sw_version": "Zigbee2MQTT 1.18.2" \ + }, \ + "name": "lock", \ + "payload_unlock": "UNLOCK_", \ + "payload_lock": "LOCK_", \ + "optimistic": "true", \ + "state_topic": "zigbee2mqtt/lock/state", \ + "command_topic": "zigbee2mqtt/lock/set/state" \ + }\ + """); // @formatter:on } diff --git a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/SensorTests.java b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/SensorTests.java index 4ea7b25f1..b42b912af 100644 --- a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/SensorTests.java +++ b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/SensorTests.java @@ -40,25 +40,27 @@ public class SensorTests extends AbstractComponentTests { public void test() throws InterruptedException { // @formatter:off var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), - "{ " + - " \"availability_topic\": \"zigbee2mqtt/bridge/state\", " + - " \"availability_template\": \"{{value_json.state}}\", " + - " \"device\": { " + - " \"identifiers\": [ " + - " \"zigbee2mqtt_0x0000000000000000\" " + - " ], " + - " \"manufacturer\": \"Sensors inc\", " + - " \"model\": \"Sensor\", " + - " \"name\": \"Sensor\", " + - " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " + - " }, " + - " \"name\": \"sensor1\", " + - " \"expire_after\": \"1\", " + - " \"force_update\": \"true\", " + - " \"unit_of_measurement\": \"W\", " + - " \"state_topic\": \"zigbee2mqtt/sensor/state\", " + - " \"unique_id\": \"sn1\" " + - "}"); + """ + { \ + "availability_topic": "zigbee2mqtt/bridge/state", \ + "availability_template": "{{value_json.state}}", \ + "device": { \ + "identifiers": [ \ + "zigbee2mqtt_0x0000000000000000" \ + ], \ + "manufacturer": "Sensors inc", \ + "model": "Sensor", \ + "name": "Sensor", \ + "sw_version": "Zigbee2MQTT 1.18.2" \ + }, \ + "name": "sensor1", \ + "expire_after": "1", \ + "force_update": "true", \ + "unit_of_measurement": "W", \ + "state_topic": "zigbee2mqtt/sensor/state", \ + "unique_id": "sn1" \ + }\ + """); // @formatter:on assertThat(component.channels.size(), is(1)); @@ -87,23 +89,25 @@ public class SensorTests extends AbstractComponentTests { public void testMeasurementStateClass() throws InterruptedException { // @formatter:off var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), - "{ " + - " \"device\": { " + - " \"identifiers\": [ " + - " \"zigbee2mqtt_0x0000000000000000\" " + - " ], " + - " \"manufacturer\": \"Sensors inc\", " + - " \"model\": \"Sensor\", " + - " \"name\": \"Sensor\", " + - " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " + - " }, " + - " \"name\": \"sensor1\", " + - " \"expire_after\": \"1\", " + - " \"force_update\": \"true\", " + - " \"state_class\": \"measurement\", " + - " \"state_topic\": \"zigbee2mqtt/sensor/state\", " + - " \"unique_id\": \"sn1\" " + - "}"); + """ + { \ + "device": { \ + "identifiers": [ \ + "zigbee2mqtt_0x0000000000000000" \ + ], \ + "manufacturer": "Sensors inc", \ + "model": "Sensor", \ + "name": "Sensor", \ + "sw_version": "Zigbee2MQTT 1.18.2" \ + }, \ + "name": "sensor1", \ + "expire_after": "1", \ + "force_update": "true", \ + "state_class": "measurement", \ + "state_topic": "zigbee2mqtt/sensor/state", \ + "unique_id": "sn1" \ + }\ + """); // @formatter:on assertChannel(component, Sensor.SENSOR_CHANNEL_ID, "zigbee2mqtt/sensor/state", "", "sensor1", @@ -114,22 +118,24 @@ public class SensorTests extends AbstractComponentTests { public void testNonNumericSensor() throws InterruptedException { // @formatter:off var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), - "{ " + - " \"device\": { " + - " \"identifiers\": [ " + - " \"zigbee2mqtt_0x0000000000000000\" " + - " ], " + - " \"manufacturer\": \"Sensors inc\", " + - " \"model\": \"Sensor\", " + - " \"name\": \"Sensor\", " + - " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " + - " }, " + - " \"name\": \"sensor1\", " + - " \"expire_after\": \"1\", " + - " \"force_update\": \"true\", " + - " \"state_topic\": \"zigbee2mqtt/sensor/state\", " + - " \"unique_id\": \"sn1\" " + - "}"); + """ + { \ + "device": { \ + "identifiers": [ \ + "zigbee2mqtt_0x0000000000000000" \ + ], \ + "manufacturer": "Sensors inc", \ + "model": "Sensor", \ + "name": "Sensor", \ + "sw_version": "Zigbee2MQTT 1.18.2" \ + }, \ + "name": "sensor1", \ + "expire_after": "1", \ + "force_update": "true", \ + "state_topic": "zigbee2mqtt/sensor/state", \ + "unique_id": "sn1" \ + }\ + """); // @formatter:on assertChannel(component, Sensor.SENSOR_CHANNEL_ID, "zigbee2mqtt/sensor/state", "", "sensor1", TextValue.class); diff --git a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/SwitchTests.java b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/SwitchTests.java index fdb250539..032a094ca 100644 --- a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/SwitchTests.java +++ b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/SwitchTests.java @@ -34,20 +34,34 @@ public class SwitchTests extends AbstractComponentTests { @SuppressWarnings("null") @Test public void testSwitchWithStateAndCommand() { - var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), - "" + "{\n" + " \"availability\": [\n" + " {\n" + " \"topic\": \"zigbee2mqtt/bridge/state\"\n" - + " }\n" + " ],\n" + " \"command_topic\": \"zigbee2mqtt/th1/set/auto_lock\",\n" - + " \"device\": {\n" + " \"identifiers\": [\n" - + " \"zigbee2mqtt_0x847127fffe11dd6a\"\n" + " ],\n" - + " \"manufacturer\": \"TuYa\",\n" - + " \"model\": \"Radiator valve with thermostat (TS0601_thermostat)\",\n" - + " \"name\": \"th1\",\n" + " \"sw_version\": \"Zigbee2MQTT 1.18.2\"\n" + " },\n" - + " \"json_attributes_topic\": \"zigbee2mqtt/th1\",\n" + " \"name\": \"th1 auto lock\",\n" - + " \"payload_off\": \"MANUAL\",\n" + " \"payload_on\": \"AUTO\",\n" - + " \"state_off\": \"MANUAL\",\n" + " \"state_on\": \"AUTO\",\n" - + " \"state_topic\": \"zigbee2mqtt/th1\",\n" - + " \"unique_id\": \"0x847127fffe11dd6a_auto_lock_zigbee2mqtt\",\n" - + " \"value_template\": \"{{ value_json.auto_lock }}\"\n" + "}"); + var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), """ + { + "availability": [ + { + "topic": "zigbee2mqtt/bridge/state" + } + ], + "command_topic": "zigbee2mqtt/th1/set/auto_lock", + "device": { + "identifiers": [ + "zigbee2mqtt_0x847127fffe11dd6a" + ], + "manufacturer": "TuYa", + "model": "Radiator valve with thermostat (TS0601_thermostat)", + "name": "th1", + "sw_version": "Zigbee2MQTT 1.18.2" + }, + "json_attributes_topic": "zigbee2mqtt/th1", + "name": "th1 auto lock", + "payload_off": "MANUAL", + "payload_on": "AUTO", + "state_off": "MANUAL", + "state_on": "AUTO", + "state_topic": "zigbee2mqtt/th1", + "unique_id": "0x847127fffe11dd6a_auto_lock_zigbee2mqtt", + "value_template": "{{ value_json.auto_lock }}" + }\ + """); assertThat(component.channels.size(), is(1)); assertThat(component.getName(), is("th1 auto lock")); @@ -68,18 +82,31 @@ public class SwitchTests extends AbstractComponentTests { @Test public void testSwitchWithState() { - var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), - "" + "{\n" + " \"availability\": [\n" + " {\n" + " \"topic\": \"zigbee2mqtt/bridge/state\"\n" - + " }\n" + " ],\n" + " \"device\": {\n" + " \"identifiers\": [\n" - + " \"zigbee2mqtt_0x847127fffe11dd6a\"\n" + " ],\n" - + " \"manufacturer\": \"TuYa\",\n" - + " \"model\": \"Radiator valve with thermostat (TS0601_thermostat)\",\n" - + " \"name\": \"th1\",\n" + " \"sw_version\": \"Zigbee2MQTT 1.18.2\"\n" + " },\n" - + " \"json_attributes_topic\": \"zigbee2mqtt/th1\",\n" + " \"name\": \"th1 auto lock\",\n" - + " \"state_off\": \"MANUAL\",\n" + " \"state_on\": \"AUTO\",\n" - + " \"state_topic\": \"zigbee2mqtt/th1\",\n" - + " \"unique_id\": \"0x847127fffe11dd6a_auto_lock_zigbee2mqtt\",\n" - + " \"value_template\": \"{{ value_json.auto_lock }}\"\n" + "}"); + var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), """ + { + "availability": [ + { + "topic": "zigbee2mqtt/bridge/state" + } + ], + "device": { + "identifiers": [ + "zigbee2mqtt_0x847127fffe11dd6a" + ], + "manufacturer": "TuYa", + "model": "Radiator valve with thermostat (TS0601_thermostat)", + "name": "th1", + "sw_version": "Zigbee2MQTT 1.18.2" + }, + "json_attributes_topic": "zigbee2mqtt/th1", + "name": "th1 auto lock", + "state_off": "MANUAL", + "state_on": "AUTO", + "state_topic": "zigbee2mqtt/th1", + "unique_id": "0x847127fffe11dd6a_auto_lock_zigbee2mqtt", + "value_template": "{{ value_json.auto_lock }}" + }\ + """); assertThat(component.channels.size(), is(1)); assertThat(component.getName(), is("th1 auto lock")); @@ -95,18 +122,31 @@ public class SwitchTests extends AbstractComponentTests { @SuppressWarnings("null") @Test public void testSwitchWithCommand() { - var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), - "" + "{\n" + " \"availability\": [\n" + " {\n" + " \"topic\": \"zigbee2mqtt/bridge/state\"\n" - + " }\n" + " ],\n" + " \"command_topic\": \"zigbee2mqtt/th1/set/auto_lock\",\n" - + " \"device\": {\n" + " \"identifiers\": [\n" - + " \"zigbee2mqtt_0x847127fffe11dd6a\"\n" + " ],\n" - + " \"manufacturer\": \"TuYa\",\n" - + " \"model\": \"Radiator valve with thermostat (TS0601_thermostat)\",\n" - + " \"name\": \"th1\",\n" + " \"sw_version\": \"Zigbee2MQTT 1.18.2\"\n" + " },\n" - + " \"json_attributes_topic\": \"zigbee2mqtt/th1\",\n" + " \"name\": \"th1 auto lock\",\n" - + " \"payload_off\": \"MANUAL\",\n" + " \"payload_on\": \"AUTO\",\n" - + " \"unique_id\": \"0x847127fffe11dd6a_auto_lock_zigbee2mqtt\",\n" - + " \"value_template\": \"{{ value_json.auto_lock }}\"\n" + "}"); + var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), """ + { + "availability": [ + { + "topic": "zigbee2mqtt/bridge/state" + } + ], + "command_topic": "zigbee2mqtt/th1/set/auto_lock", + "device": { + "identifiers": [ + "zigbee2mqtt_0x847127fffe11dd6a" + ], + "manufacturer": "TuYa", + "model": "Radiator valve with thermostat (TS0601_thermostat)", + "name": "th1", + "sw_version": "Zigbee2MQTT 1.18.2" + }, + "json_attributes_topic": "zigbee2mqtt/th1", + "name": "th1 auto lock", + "payload_off": "MANUAL", + "payload_on": "AUTO", + "unique_id": "0x847127fffe11dd6a_auto_lock_zigbee2mqtt", + "value_template": "{{ value_json.auto_lock }}" + }\ + """); assertThat(component.channels.size(), is(1)); assertThat(component.getName(), is("th1 auto lock")); diff --git a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/VacuumTests.java b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/VacuumTests.java index fdb75650f..9713c1675 100644 --- a/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/VacuumTests.java +++ b/bundles/org.openhab.binding.mqtt.homeassistant/src/test/java/org/openhab/binding/mqtt/homeassistant/internal/component/VacuumTests.java @@ -40,26 +40,28 @@ public class VacuumTests extends AbstractComponentTests { @Test public void testRoborockValetudo() { // @formatter:off - var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), "{" + - "\"name\":\"Rockrobo\"," + - "\"unique_id\":\"rockrobo_vacuum\"," + - "\"schema\":\"state\"," + - "\"device\":{" + - " \"manufacturer\":\"Roborock\"," + - " \"model\":\"v1\"," + - " \"name\":\"rockrobo\"," + - " \"identifiers\":[\"rockrobo\"]," + - " \"sw_version\":\"0.9.9\"" + - "}," + - "\"supported_features\":[\"start\",\"pause\",\"stop\",\"return_home\",\"battery\",\"status\"," + - " \"locate\",\"clean_spot\",\"fan_speed\",\"send_command\"]," + - "\"command_topic\":\"valetudo/rockrobo/command\"," + - "\"state_topic\":\"valetudo/rockrobo/state\"," + - "\"set_fan_speed_topic\":\"valetudo/rockrobo/set_fan_speed\"," + - "\"fan_speed_list\":[\"min\",\"medium\",\"high\",\"max\",\"mop\"]," + - "\"send_command_topic\":\"valetudo/rockrobo/custom_command\"," + - "\"json_attributes_topic\":\"valetudo/rockrobo/attributes\"" + - "}"); + var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), """ + {\ + "name":"Rockrobo",\ + "unique_id":"rockrobo_vacuum",\ + "schema":"state",\ + "device":{\ + "manufacturer":"Roborock",\ + "model":"v1",\ + "name":"rockrobo",\ + "identifiers":["rockrobo"],\ + "sw_version":"0.9.9"\ + },\ + "supported_features":["start","pause","stop","return_home","battery","status",\ + "locate","clean_spot","fan_speed","send_command"],\ + "command_topic":"valetudo/rockrobo/command",\ + "state_topic":"valetudo/rockrobo/state",\ + "set_fan_speed_topic":"valetudo/rockrobo/set_fan_speed",\ + "fan_speed_list":["min","medium","high","max","mop"],\ + "send_command_topic":"valetudo/rockrobo/custom_command",\ + "json_attributes_topic":"valetudo/rockrobo/attributes"\ + }\ + """); // @formatter:on assertThat(component.channels.size(), is(6)); // command, state, fan speed, send command, battery, json attrs @@ -82,41 +84,45 @@ public class VacuumTests extends AbstractComponentTests { // @formatter:off String jsonValue; - publishMessage("valetudo/rockrobo/attributes", jsonValue = "{" + - "\"mainBrush\":\"245.1\"," + - "\"sideBrush\":\"145.1\"," + - "\"filter\":\"95.1\"," + - "\"sensor\":\"0.0\"," + - "\"currentCleanTime\":\"52.0\"," + - "\"currentCleanArea\":\"46.7\"," + - "\"cleanTime\":\"54.9\"," + - "\"cleanArea\":\"3280.9\"," + - "\"cleanCount\":84," + - "\"last_run_stats\":{" + - " \"startTime\":1633257319000," + - " \"endTime\":1633260439000," + - " \"duration\":3120," + - " \"area\":\"46.7\"," + - " \"errorCode\":0," + - " \"errorDescription\":\"No error\"," + - " \"finishedFlag\":true" + - "}," + - "\"last_bin_out\":2147483647000," + - "\"state\":\"docked\"," + - "\"valetudo_state\":{" + - " \"id\":8," + - " \"name\":\"Charging\"" + - "}," + - "\"last_bin_full\":0" + - "}"); + publishMessage("valetudo/rockrobo/attributes", jsonValue = """ + {\ + "mainBrush":"245.1",\ + "sideBrush":"145.1",\ + "filter":"95.1",\ + "sensor":"0.0",\ + "currentCleanTime":"52.0",\ + "currentCleanArea":"46.7",\ + "cleanTime":"54.9",\ + "cleanArea":"3280.9",\ + "cleanCount":84,\ + "last_run_stats":{\ + "startTime":1633257319000,\ + "endTime":1633260439000,\ + "duration":3120,\ + "area":"46.7",\ + "errorCode":0,\ + "errorDescription":"No error",\ + "finishedFlag":true\ + },\ + "last_bin_out":2147483647000,\ + "state":"docked",\ + "valetudo_state":{\ + "id":8,\ + "name":"Charging"\ + },\ + "last_bin_full":0\ + }\ + """); // @formatter:on // @formatter:off - publishMessage("valetudo/rockrobo/state", "{" + - "\"state\":\"docked\"," + - "\"battery_level\":100," + - "\"fan_speed\":\"max\"" + - "}"); + publishMessage("valetudo/rockrobo/state", """ + {\ + "state":"docked",\ + "battery_level":100,\ + "fan_speed":"max"\ + }\ + """); // @formatter:on assertState(component, Vacuum.STATE_CH_ID, new StringType(Vacuum.STATE_DOCKED)); @@ -128,11 +134,13 @@ public class VacuumTests extends AbstractComponentTests { assertPublished("valetudo/rockrobo/command", "start"); // @formatter:off - publishMessage("valetudo/rockrobo/state", "{" + - "\"state\":\"cleaning\"," + - "\"battery_level\":99," + - "\"fan_speed\":\"max\"" + - "}"); + publishMessage("valetudo/rockrobo/state", """ + {\ + "state":"cleaning",\ + "battery_level":99,\ + "fan_speed":"max"\ + }\ + """); // @formatter:on assertState(component, Vacuum.STATE_CH_ID, new StringType(Vacuum.STATE_CLEANING)); @@ -144,11 +152,13 @@ public class VacuumTests extends AbstractComponentTests { assertPublished("valetudo/rockrobo/set_fan_speed", "medium"); // @formatter:off - publishMessage("valetudo/rockrobo/state", "{" + - "\"state\":\"returning\"," + - "\"battery_level\":80," + - "\"fan_speed\":\"medium\"" + - "}"); + publishMessage("valetudo/rockrobo/state", """ + {\ + "state":"returning",\ + "battery_level":80,\ + "fan_speed":"medium"\ + }\ + """); // @formatter:on assertState(component, Vacuum.STATE_CH_ID, new StringType(Vacuum.STATE_RETURNING)); @@ -161,35 +171,37 @@ public class VacuumTests extends AbstractComponentTests { @Test public void testLegacySchema() { // @formatter:off - var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), "{" + - "\"name\":\"Rockrobo\"," + - "\"unique_id\":\"rockrobo_vacuum\"," + - "\"device\":{" + - " \"manufacturer\":\"Roborock\"," + - " \"model\":\"v1\"," + - " \"name\":\"rockrobo\"," + - " \"identifiers\":[\"rockrobo\"]," + - " \"sw_version\":\"0.9.9\"" + - "}," + - "\"supported_features\":[\"turn_on\", \"turn_off\",\"pause\",\"stop\",\"return_home\",\"battery\",\"status\"," + - " \"locate\",\"clean_spot\",\"fan_speed\",\"send_command\"]," + - "\"command_topic\":\"vacuum/command\"," + - "\"battery_level_topic\":\"vacuum/state\"," + - "\"battery_level_template\":\"{{ value_json.battery_level }}\"," + - "\"charging_topic\":\"vacuum/state\"," + - "\"charging_template\":\"{{ value_json.charging }}\"," + - "\"cleaning_topic\":\"vacuum/state\"," + - "\"cleaning_template\":\"{{ value_json.cleaning }}\"," + - "\"docked_topic\":\"vacuum/state\"," + - "\"docked_template\":\"{{ value_json.docked }}\"," + - "\"error_topic\":\"vacuum/state\"," + - "\"error_template\":\"{{ value_json.error }}\"," + - "\"fan_speed_topic\":\"vacuum/state\"," + - "\"set_fan_speed_topic\":\"vacuum/set_fan_speed\"," + - "\"fan_speed_template\":\"{{ value_json.fan_speed }}\"," + - "\"fan_speed_list\":[\"min\",\"medium\",\"high\",\"max\"]," + - "\"send_command_topic\":\"vacuum/send_command\"" + - "}"); + var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), """ + {\ + "name":"Rockrobo",\ + "unique_id":"rockrobo_vacuum",\ + "device":{\ + "manufacturer":"Roborock",\ + "model":"v1",\ + "name":"rockrobo",\ + "identifiers":["rockrobo"],\ + "sw_version":"0.9.9"\ + },\ + "supported_features":["turn_on", "turn_off","pause","stop","return_home","battery","status",\ + "locate","clean_spot","fan_speed","send_command"],\ + "command_topic":"vacuum/command",\ + "battery_level_topic":"vacuum/state",\ + "battery_level_template":"{{ value_json.battery_level }}",\ + "charging_topic":"vacuum/state",\ + "charging_template":"{{ value_json.charging }}",\ + "cleaning_topic":"vacuum/state",\ + "cleaning_template":"{{ value_json.cleaning }}",\ + "docked_topic":"vacuum/state",\ + "docked_template":"{{ value_json.docked }}",\ + "error_topic":"vacuum/state",\ + "error_template":"{{ value_json.error }}",\ + "fan_speed_topic":"vacuum/state",\ + "set_fan_speed_topic":"vacuum/set_fan_speed",\ + "fan_speed_template":"{{ value_json.fan_speed }}",\ + "fan_speed_list":["min","medium","high","max"],\ + "send_command_topic":"vacuum/send_command"\ + }\ + """); // @formatter:on assertThat(component.channels.size(), is(8)); // command, battery, charging, cleaning, docked, error, @@ -206,14 +218,16 @@ public class VacuumTests extends AbstractComponentTests { assertChannel(component, Vacuum.CUSTOM_COMMAND_CH_ID, "", "vacuum/send_command", "Rockrobo", TextValue.class); // @formatter:off - publishMessage("vacuum/state", "{" + - "\"battery_level\": 61," + - "\"docked\": true," + - "\"cleaning\": false," + - "\"charging\": true," + - "\"fan_speed\": \"off\"," + - "\"error\": \"Error message\"" + - "}"); + publishMessage("vacuum/state", """ + {\ + "battery_level": 61,\ + "docked": true,\ + "cleaning": false,\ + "charging": true,\ + "fan_speed": "off",\ + "error": "Error message"\ + }\ + """); // @formatter:on assertState(component, Vacuum.BATTERY_LEVEL_CH_ID, new PercentType(61)); @@ -227,14 +241,16 @@ public class VacuumTests extends AbstractComponentTests { assertPublished("vacuum/command", "turn_on"); // @formatter:off - publishMessage("vacuum/state", "{" + - "\"battery_level\": 55," + - "\"docked\": false," + - "\"cleaning\": true," + - "\"charging\": false," + - "\"fan_speed\": \"medium\"," + - "\"error\": \"\"" + - "}"); + publishMessage("vacuum/state", """ + {\ + "battery_level": 55,\ + "docked": false,\ + "cleaning": true,\ + "charging": false,\ + "fan_speed": "medium",\ + "error": ""\ + }\ + """); // @formatter:on assertState(component, Vacuum.BATTERY_LEVEL_CH_ID, new PercentType(55)); diff --git a/bundles/org.openhab.binding.mqtt.homie/src/main/java/org/openhab/binding/mqtt/homie/internal/discovery/Homie300Discovery.java b/bundles/org.openhab.binding.mqtt.homie/src/main/java/org/openhab/binding/mqtt/homie/internal/discovery/Homie300Discovery.java index 397432047..f18920f0c 100644 --- a/bundles/org.openhab.binding.mqtt.homie/src/main/java/org/openhab/binding/mqtt/homie/internal/discovery/Homie300Discovery.java +++ b/bundles/org.openhab.binding.mqtt.homie/src/main/java/org/openhab/binding/mqtt/homie/internal/discovery/Homie300Discovery.java @@ -13,9 +13,9 @@ package org.openhab.binding.mqtt.homie.internal.discovery; import java.nio.charset.StandardCharsets; -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; @@ -47,7 +47,7 @@ public class Homie300Discovery extends AbstractMQTTDiscovery { @Activate public Homie300Discovery(@Reference MQTTTopicDiscoveryService discoveryService) { - super(Collections.singleton(MqttBindingConstants.HOMIE300_MQTT_THING), 3, true, "+/+/$homie"); + super(Set.of(MqttBindingConstants.HOMIE300_MQTT_THING), 3, true, "+/+/$homie"); this.discoveryService = discoveryService; } diff --git a/bundles/org.openhab.binding.mqtt.homie/src/main/java/org/openhab/binding/mqtt/homie/internal/handler/HomieThingHandler.java b/bundles/org.openhab.binding.mqtt.homie/src/main/java/org/openhab/binding/mqtt/homie/internal/handler/HomieThingHandler.java index 56d43475e..96a5a2d59 100644 --- a/bundles/org.openhab.binding.mqtt.homie/src/main/java/org/openhab/binding/mqtt/homie/internal/handler/HomieThingHandler.java +++ b/bundles/org.openhab.binding.mqtt.homie/src/main/java/org/openhab/binding/mqtt/homie/internal/handler/HomieThingHandler.java @@ -126,11 +126,11 @@ public class HomieThingHandler extends AbstractMQTTThingHandler implements Devic "Homie devices require QoS 1 but Qos 0/2 is configured. Using override. Please check the configuration"); connection.setQos(1); } - return device.subscribe(connection, scheduler, attributeReceiveTimeout).thenCompose((Void v) -> { - return device.startChannels(connection, scheduler, attributeReceiveTimeout, this); - }).thenRun(() -> { - logger.debug("Homie device {} fully attached (start)", config.deviceid); - }); + return device.subscribe(connection, scheduler, attributeReceiveTimeout) + .thenCompose((Void v) -> device.startChannels(connection, scheduler, attributeReceiveTimeout, this)) + .thenRun(() -> { + logger.debug("Homie device {} fully attached (start)", config.deviceid); + }); } @Override @@ -241,9 +241,8 @@ public class HomieThingHandler extends AbstractMQTTThingHandler implements Devic logger.warn("couldn't remove retained topics for {} because connection is null", thing.getUID()); return; } - device.getRetainedTopics().stream().map(d -> { - return String.format("%s/%s", config.basetopic, d); - }).collect(Collectors.toList()).forEach(t -> connection.publish(t, new byte[0], 1, true)); + device.getRetainedTopics().stream().map(d -> String.format("%s/%s", config.basetopic, d)) + .collect(Collectors.toList()).forEach(t -> connection.publish(t, new byte[0], 1, true)); } @Override diff --git a/bundles/org.openhab.binding.mqtt.homie/src/main/java/org/openhab/binding/mqtt/homie/internal/homie300/Property.java b/bundles/org.openhab.binding.mqtt.homie/src/main/java/org/openhab/binding/mqtt/homie/internal/homie300/Property.java index 86e251a89..5a3d16d7b 100644 --- a/bundles/org.openhab.binding.mqtt.homie/src/main/java/org/openhab/binding/mqtt/homie/internal/homie300/Property.java +++ b/bundles/org.openhab.binding.mqtt.homie/src/main/java/org/openhab/binding/mqtt/homie/internal/homie300/Property.java @@ -188,9 +188,9 @@ public class Property implements AttributeChanged { value = new OnOffValue("true", "false"); break; case color_: - if (attributes.format.equals("hsv")) { + if ("hsv".equals(attributes.format)) { value = new ColorValue(ColorMode.HSB, null, null, 100); - } else if (attributes.format.equals("rgb")) { + } else if ("rgb".equals(attributes.format)) { value = new ColorValue(ColorMode.RGB, null, null, 100); } else { logger.warn("Non supported color format: '{}'. Only 'hsv' and 'rgb' are supported", @@ -199,13 +199,13 @@ public class Property implements AttributeChanged { } break; case enum_: - String enumValues[] = attributes.format.split(","); + String[] enumValues = attributes.format.split(","); value = new TextValue(enumValues); break; case float_: case integer_: isDecimal = attributes.datatype == DataTypeEnum.float_; - String s[] = attributes.format.split("\\:"); + String[] s = attributes.format.split("\\:"); BigDecimal min = s.length == 2 ? convertFromString(s[0]) : null; BigDecimal max = s.length == 2 ? convertFromString(s[1]) : null; BigDecimal step = (min != null && max != null) @@ -338,9 +338,8 @@ public class Property implements AttributeChanged { public List getRetainedTopics() { List topics = new ArrayList<>(); - topics.addAll(Stream.of(this.attributes.getClass().getDeclaredFields()).map(f -> { - return String.format("%s/$%s", this.propertyID, f.getName()); - }).collect(Collectors.toList())); + topics.addAll(Stream.of(this.attributes.getClass().getDeclaredFields()) + .map(f -> String.format("%s/$%s", this.propertyID, f.getName())).collect(Collectors.toList())); // All exceptions can be ignored because the 'retained' attribute of the PropertyAttributes class // is public, is a boolean variable and has a default value (true) diff --git a/bundles/org.openhab.binding.mqtt.ruuvigateway/src/main/java/org/openhab/binding/mqtt/ruuvigateway/internal/parser/GatewayPayloadParser.java b/bundles/org.openhab.binding.mqtt.ruuvigateway/src/main/java/org/openhab/binding/mqtt/ruuvigateway/internal/parser/GatewayPayloadParser.java index d19f1c37d..35c51a304 100644 --- a/bundles/org.openhab.binding.mqtt.ruuvigateway/src/main/java/org/openhab/binding/mqtt/ruuvigateway/internal/parser/GatewayPayloadParser.java +++ b/bundles/org.openhab.binding.mqtt.ruuvigateway/src/main/java/org/openhab/binding/mqtt/ruuvigateway/internal/parser/GatewayPayloadParser.java @@ -170,7 +170,6 @@ public class GatewayPayloadParser { if (payloadIntermediate == null) { throw new JsonSyntaxException("JSON parsing failed"); } - GatewayPayload payload = new GatewayPayload(payloadIntermediate); - return payload; + return new GatewayPayload(payloadIntermediate); } } diff --git a/bundles/org.openhab.binding.mqtt.ruuvigateway/src/test/java/org/openhab/binding/mqtt/ruuvigateway/internal/discovery/RuuviGatewayDiscoveryTests.java b/bundles/org.openhab.binding.mqtt.ruuvigateway/src/test/java/org/openhab/binding/mqtt/ruuvigateway/internal/discovery/RuuviGatewayDiscoveryTests.java index fdc5d8cfe..fa99b56e1 100644 --- a/bundles/org.openhab.binding.mqtt.ruuvigateway/src/test/java/org/openhab/binding/mqtt/ruuvigateway/internal/discovery/RuuviGatewayDiscoveryTests.java +++ b/bundles/org.openhab.binding.mqtt.ruuvigateway/src/test/java/org/openhab/binding/mqtt/ruuvigateway/internal/discovery/RuuviGatewayDiscoveryTests.java @@ -113,18 +113,16 @@ public class RuuviGatewayDiscoveryTests { })); assertTrue(// - discoveryResults.stream().anyMatch(result -> { - return "DE:EA:DB:BE:FF:00" - .equals(result.getProperties().get(RuuviGatewayBindingConstants.PROPERTY_TAG_ID)) - && "ruuvi/foo/bar/de:ea:DB:be:ff:00".equals(result.getProperties() - .get(RuuviGatewayBindingConstants.CONFIGURATION_PROPERTY_TOPIC)); - }) && // - discoveryResults.stream().anyMatch(result -> { - return "DE:EA:DB:BE:FF:01" - .equals(result.getProperties().get(RuuviGatewayBindingConstants.PROPERTY_TAG_ID)) - && "ruuvi/foo/bar/de:ea:DB:be:ff:01".equals(result.getProperties() - .get(RuuviGatewayBindingConstants.CONFIGURATION_PROPERTY_TOPIC)); - }) + discoveryResults.stream().anyMatch(result -> "DE:EA:DB:BE:FF:00" + .equals(result.getProperties().get(RuuviGatewayBindingConstants.PROPERTY_TAG_ID)) + && "ruuvi/foo/bar/de:ea:DB:be:ff:00".equals( + result.getProperties().get(RuuviGatewayBindingConstants.CONFIGURATION_PROPERTY_TOPIC))) + && // + discoveryResults.stream() + .anyMatch(result -> "DE:EA:DB:BE:FF:01".equals( + result.getProperties().get(RuuviGatewayBindingConstants.PROPERTY_TAG_ID)) + && "ruuvi/foo/bar/de:ea:DB:be:ff:01".equals(result.getProperties() + .get(RuuviGatewayBindingConstants.CONFIGURATION_PROPERTY_TOPIC))) , "Failed to match: " + discoveryResults.toString()); } diff --git a/bundles/org.openhab.binding.mqtt.ruuvigateway/src/test/java/org/openhab/binding/mqtt/ruuvigateway/internal/parser/GatewayPayloadParserTests.java b/bundles/org.openhab.binding.mqtt.ruuvigateway/src/test/java/org/openhab/binding/mqtt/ruuvigateway/internal/parser/GatewayPayloadParserTests.java index dca4c824a..db0b20fa1 100644 --- a/bundles/org.openhab.binding.mqtt.ruuvigateway/src/test/java/org/openhab/binding/mqtt/ruuvigateway/internal/parser/GatewayPayloadParserTests.java +++ b/bundles/org.openhab.binding.mqtt.ruuvigateway/src/test/java/org/openhab/binding/mqtt/ruuvigateway/internal/parser/GatewayPayloadParserTests.java @@ -114,13 +114,16 @@ public class GatewayPayloadParserTests { public void testUnexpectedTypes3() { assertThrows(JsonSyntaxException.class, () -> { GatewayPayloadParser.parse(bytes(// - "{\"gw_mac\": \"DE:AD:BE:EF:00:00\","// - + " \"rssi\": \"foobar\","// should be number - + " \"aoa\": [],"// - + " \"gwts\": \"1659365438\","// - + " \"ts\": \"1659365438\","// - + " \"data\": \"0201061BFF99040512FC5394C37C0004FFFC040CAC364200CDCBB8334C884F\"," - + " \"coords\": \"\"" + "}")); + """ + {"gw_mac": "DE:AD:BE:EF:00:00",\ + "rssi": "foobar",\ + "aoa": [],\ + "gwts": "1659365438",\ + "ts": "1659365438",\ + "data": "0201061BFF99040512FC5394C37C0004FFFC040CAC364200CDCBB8334C884F",\ + "coords": ""\ + }\ + """)); }); } @@ -141,14 +144,16 @@ public class GatewayPayloadParserTests { public void testUnexpectedManufacturer() { assertThrows(IllegalArgumentException.class, () -> { GatewayPayloadParser.parse(bytes(// - "{\"gw_mac\": \"DE:AD:BE:EF:00:00\","// - + " \"rssi\": -83,"// - + " \"aoa\": [],"// - + " \"gwts\": \"1659365438\","// - + " \"ts\": \"1659365438\","// - // manufacturer is not 99 04 (Ruuvi) but 99 99 - + " \"data\": \"0201061BFF99990512FC5394C37C0004FFFC040CAC364200CDCBB8334C884F\"," - + " \"coords\": \"\"" + "}")); + """ + {"gw_mac": "DE:AD:BE:EF:00:00",\ + "rssi": -83,\ + "aoa": [],\ + "gwts": "1659365438",\ + "ts": "1659365438",\ + "data": "0201061BFF99990512FC5394C37C0004FFFC040CAC364200CDCBB8334C884F",\ + "coords": ""\ + }\ + """)); }); } @@ -156,14 +161,16 @@ public class GatewayPayloadParserTests { public void testDataNotBluetoothAdvertisement() { assertThrows(IllegalArgumentException.class, () -> { GatewayPayloadParser.parse(bytes(// - "{\"gw_mac\": \"DE:AD:BE:EF:00:00\","// - + " \"rssi\": -83,"// - + " \"aoa\": [],"// - + " \"gwts\": \"1659365438\","// - + " \"ts\": \"1659365438\","// - // not advertisement (FF) but AA - + " \"data\": \"0201061BAA99040512FC5394C37C0004FFFC040CAC364200CDCBB8334C884F\"," - + " \"coords\": \"\"" + "}")); + """ + {"gw_mac": "DE:AD:BE:EF:00:00",\ + "rssi": -83,\ + "aoa": [],\ + "gwts": "1659365438",\ + "ts": "1659365438",\ + "data": "0201061BAA99040512FC5394C37C0004FFFC040CAC364200CDCBB8334C884F",\ + "coords": ""\ + }\ + """)); }); } } diff --git a/bundles/org.openhab.binding.mqtt/src/main/java/org/openhab/binding/mqtt/handler/AbstractBrokerHandler.java b/bundles/org.openhab.binding.mqtt/src/main/java/org/openhab/binding/mqtt/handler/AbstractBrokerHandler.java index f859ea2ad..68906bf89 100644 --- a/bundles/org.openhab.binding.mqtt/src/main/java/org/openhab/binding/mqtt/handler/AbstractBrokerHandler.java +++ b/bundles/org.openhab.binding.mqtt/src/main/java/org/openhab/binding/mqtt/handler/AbstractBrokerHandler.java @@ -13,9 +13,9 @@ package org.openhab.binding.mqtt.handler; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeoutException; @@ -61,7 +61,7 @@ public abstract class AbstractBrokerHandler extends BaseBridgeHandler implements @Override public Collection> getServices() { - return Collections.singleton(MQTTActions.class); + return Set.of(MQTTActions.class); } /** diff --git a/bundles/org.openhab.binding.mqtt/src/main/java/org/openhab/binding/mqtt/internal/MqttThingID.java b/bundles/org.openhab.binding.mqtt/src/main/java/org/openhab/binding/mqtt/internal/MqttThingID.java index 53a8ddf01..3613ba6f5 100644 --- a/bundles/org.openhab.binding.mqtt/src/main/java/org/openhab/binding/mqtt/internal/MqttThingID.java +++ b/bundles/org.openhab.binding.mqtt/src/main/java/org/openhab/binding/mqtt/internal/MqttThingID.java @@ -28,7 +28,7 @@ public class MqttThingID { * for creating a ThingUID with that string (tcp_122_123_111_123_1883). */ public static String getThingID(String host, int port) { - return host.replace('.', '_').replace("://", "_") + "_" + String.valueOf(port); + return host.replace('.', '_').replace("://", "_") + "_" + port; } /** diff --git a/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/MyBMWHandlerFactory.java b/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/MyBMWHandlerFactory.java index 6ee4c4f66..881d6b5a8 100644 --- a/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/MyBMWHandlerFactory.java +++ b/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/MyBMWHandlerFactory.java @@ -66,9 +66,7 @@ public class MyBMWHandlerFactory extends BaseThingHandlerFactory { if (THING_TYPE_CONNECTED_DRIVE_ACCOUNT.equals(thingTypeUID)) { return new MyBMWBridgeHandler((Bridge) thing, httpClientFactory, localeLanguage); } else if (SUPPORTED_THING_SET.contains(thingTypeUID)) { - VehicleHandler vh = new VehicleHandler(thing, commandOptionProvider, locationProvider, - thingTypeUID.getId()); - return vh; + return new VehicleHandler(thing, commandOptionProvider, locationProvider, thingTypeUID.getId()); } return null; } diff --git a/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/discovery/VehicleDiscovery.java b/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/discovery/VehicleDiscovery.java index c5fa7c36e..9612ec20d 100644 --- a/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/discovery/VehicleDiscovery.java +++ b/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/discovery/VehicleDiscovery.java @@ -161,8 +161,8 @@ public class VehicleDiscovery extends AbstractDiscoveryService implements Discov @Override public void setThingHandler(ThingHandler handler) { - if (handler instanceof MyBMWBridgeHandler) { - bridgeHandler = Optional.of((MyBMWBridgeHandler) handler); + if (handler instanceof MyBMWBridgeHandler bmwBridgeHandler) { + bridgeHandler = Optional.of(bmwBridgeHandler); bridgeHandler.get().setDiscoveryService(this); } } diff --git a/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/handler/MyBMWBridgeHandler.java b/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/handler/MyBMWBridgeHandler.java index 91c3b5b06..837afe857 100644 --- a/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/handler/MyBMWBridgeHandler.java +++ b/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/handler/MyBMWBridgeHandler.java @@ -13,9 +13,9 @@ package org.openhab.binding.mybmw.internal.handler; import java.util.Collection; -import java.util.Collections; import java.util.List; import java.util.Optional; +import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -128,7 +128,7 @@ public class MyBMWBridgeHandler extends BaseBridgeHandler implements StringRespo @Override public Collection> getServices() { - return Collections.singleton(VehicleDiscovery.class); + return Set.of(VehicleDiscovery.class); } public Optional getProxy() { diff --git a/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/handler/MyBMWProxy.java b/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/handler/MyBMWProxy.java index e29021e0e..6dd9a8531 100644 --- a/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/handler/MyBMWProxy.java +++ b/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/handler/MyBMWProxy.java @@ -163,10 +163,10 @@ public class MyBMWProxy { logger.debug("HTTP Error {}", error.toString()); callback.onError(error); } else { - if (callback instanceof StringResponseCallback) { - ((StringResponseCallback) callback).onResponse(getContentAsString()); - } else if (callback instanceof ByteResponseCallback) { - ((ByteResponseCallback) callback).onResponse(getContent()); + if (callback instanceof StringResponseCallback responseCallback) { + responseCallback.onResponse(getContentAsString()); + } else if (callback instanceof ByteResponseCallback responseCallback) { + responseCallback.onResponse(getContent()); } else { logger.error("unexpected reponse type {}", callback.getClass().getName()); } @@ -425,10 +425,10 @@ public class MyBMWProxy { UrlEncoded.decodeTo(encodedUrl, tokenMap, StandardCharsets.US_ASCII); final StringBuilder codeFound = new StringBuilder(); tokenMap.forEach((key, value) -> { - if (value.size() > 0) { + if (!value.isEmpty()) { String val = value.get(0); if (key.endsWith(CODE)) { - codeFound.append(val.toString()); + codeFound.append(val); } } }); diff --git a/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/handler/VehicleHandler.java b/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/handler/VehicleHandler.java index 81c0b67ad..cc38f261d 100644 --- a/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/handler/VehicleHandler.java +++ b/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/handler/VehicleHandler.java @@ -83,8 +83,8 @@ public class VehicleHandler extends VehicleChannelHandler { // Check for Channel Group and corresponding Actions } else if (CHANNEL_GROUP_REMOTE.equals(group)) { // Executing Remote Services - if (command instanceof StringType) { - String serviceCommand = ((StringType) command).toFullString(); + if (command instanceof StringType str) { + String serviceCommand = str.toFullString(); remote.ifPresent(remot -> { switch (serviceCommand) { case REMOTE_SERVICE_LIGHT_FLASH: @@ -213,7 +213,7 @@ public class VehicleHandler extends VehicleChannelHandler { prox.requestChargeStatistics(config, chargeStatisticsCallback); prox.requestChargeSessions(config, chargeSessionCallback); } - if (!imageCache.isPresent() && !imageProperties.failLimitReached()) { + if (imageCache.isEmpty() && !imageProperties.failLimitReached()) { prox.requestImage(config, imageProperties, imageCallback); } }, () -> { diff --git a/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/utils/Converter.java b/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/utils/Converter.java index d94e6a872..5b1047c91 100644 --- a/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/utils/Converter.java +++ b/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/utils/Converter.java @@ -254,10 +254,8 @@ public class Converter { int rightLimit = 122; // letter 'z' Random random = new SecureRandom(); - String generatedString = random.ints(leftLimit, rightLimit + 1).limit(size) + return random.ints(leftLimit, rightLimit + 1).limit(size) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString(); - - return generatedString; } public static State getLockState(boolean lock) { diff --git a/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/utils/VehicleStatusUtils.java b/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/utils/VehicleStatusUtils.java index 0b2d862ea..05b82e7f6 100644 --- a/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/utils/VehicleStatusUtils.java +++ b/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/utils/VehicleStatusUtils.java @@ -55,8 +55,7 @@ public class VehicleStatusUtils { if (serviceDate.equals(farFuture)) { return UnDefType.UNDEF; } else { - DateTimeType dt = DateTimeType.valueOf(serviceDate.format(Converter.DATE_INPUT_PATTERN)); - return dt; + return DateTimeType.valueOf(serviceDate.format(Converter.DATE_INPUT_PATTERN)); } } diff --git a/bundles/org.openhab.binding.mybmw/src/test/java/org/openhab/binding/mybmw/internal/dto/StatusWrapper.java b/bundles/org.openhab.binding.mybmw/src/test/java/org/openhab/binding/mybmw/internal/dto/StatusWrapper.java index c7f0f5f10..9f51a3186 100644 --- a/bundles/org.openhab.binding.mybmw/src/test/java/org/openhab/binding/mybmw/internal/dto/StatusWrapper.java +++ b/bundles/org.openhab.binding.mybmw/src/test/java/org/openhab/binding/mybmw/internal/dto/StatusWrapper.java @@ -248,8 +248,8 @@ public class StatusWrapper { assertEquals(expected.toString(), dtt.toString(), "Last Update"); break; case GPS: - if (state instanceof PointType) { - pt = (PointType) state; + if (state instanceof PointType point) { + pt = point; assertNotNull(vehicle.properties.vehicleLocation); assertEquals( PointType.valueOf(Double.toString(vehicle.properties.vehicleLocation.coordinates.latitude) @@ -258,8 +258,8 @@ public class StatusWrapper { } // else no check needed break; case HEADING: - if (state instanceof QuantityType) { - qt = ((QuantityType) state); + if (state instanceof QuantityType quantityCommand) { + qt = quantityCommand; assertEquals(Units.DEGREE_ANGLE, qt.getUnit(), "Angle Unit"); assertNotNull(vehicle.properties.vehicleLocation); assertEquals(vehicle.properties.vehicleLocation.heading, qt.intValue(), 0.01, "Heading"); @@ -572,15 +572,15 @@ public class StatusWrapper { } break; case ADDRESS: - if (state instanceof StringType) { - st = (StringType) state; + if (state instanceof StringType str) { + st = str; assertEquals(st.toFullString(), vehicle.properties.vehicleLocation.address.formatted, "Location Address"); } // else no check needed break; case HOME_DISTANCE: - if (state instanceof QuantityType) { - qt = (QuantityType) state; + if (state instanceof QuantityType quantity) { + qt = quantity; PointType vehicleLocation = PointType .valueOf(Double.toString(vehicle.properties.vehicleLocation.coordinates.latitude) + "," + Double.toString(vehicle.properties.vehicleLocation.coordinates.longitude)); diff --git a/bundles/org.openhab.binding.mybmw/src/test/java/org/openhab/binding/mybmw/internal/handler/AuthTest.java b/bundles/org.openhab.binding.mybmw/src/test/java/org/openhab/binding/mybmw/internal/handler/AuthTest.java index 081982168..52f05bd57 100644 --- a/bundles/org.openhab.binding.mybmw/src/test/java/org/openhab/binding/mybmw/internal/handler/AuthTest.java +++ b/bundles/org.openhab.binding.mybmw/src/test/java/org/openhab/binding/mybmw/internal/handler/AuthTest.java @@ -313,10 +313,10 @@ class AuthTest { UrlEncoded.decodeTo(encodedUrl, tokenMap, StandardCharsets.US_ASCII); final StringBuilder codeFound = new StringBuilder(); tokenMap.forEach((key, value) -> { - if (value.size() > 0) { + if (!value.isEmpty()) { String val = value.get(0); if (key.endsWith(CODE)) { - codeFound.append(val.toString()); + codeFound.append(val); } } }); diff --git a/bundles/org.openhab.binding.mybmw/src/test/java/org/openhab/binding/mybmw/internal/util/FileReader.java b/bundles/org.openhab.binding.mybmw/src/test/java/org/openhab/binding/mybmw/internal/util/FileReader.java index 559d7daf5..61b509254 100644 --- a/bundles/org.openhab.binding.mybmw/src/test/java/org/openhab/binding/mybmw/internal/util/FileReader.java +++ b/bundles/org.openhab.binding.mybmw/src/test/java/org/openhab/binding/mybmw/internal/util/FileReader.java @@ -31,7 +31,7 @@ import org.openhab.binding.mybmw.internal.utils.Constants; public class FileReader { public static String readFileInString(String filename) { - try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "UTF-8"));) { + try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "UTF-8"))) { StringBuilder buf = new StringBuilder(); String sCurrentLine; diff --git a/bundles/org.openhab.binding.mycroft/src/main/java/org/openhab/binding/mycroft/internal/api/MycroftConnection.java b/bundles/org.openhab.binding.mycroft/src/main/java/org/openhab/binding/mycroft/internal/api/MycroftConnection.java index 1ce4763f2..47014f04c 100644 --- a/bundles/org.openhab.binding.mycroft/src/main/java/org/openhab/binding/mycroft/internal/api/MycroftConnection.java +++ b/bundles/org.openhab.binding.mycroft/src/main/java/org/openhab/binding/mycroft/internal/api/MycroftConnection.java @@ -190,7 +190,6 @@ public class MycroftConnection { listeners.getOrDefault(mycroftMessage.type, new HashSet<>()).stream()).forEach(listener -> { listener.baseMessageReceived(finalMessage); }); - } catch (RuntimeException e) { // we need to catch all processing exceptions, otherwise they could affect the connection logger.debug("{} encountered an error while processing the message {}: {}", socketName, message, @@ -200,7 +199,6 @@ public class MycroftConnection { @OnWebSocketError public void onError(@Nullable Session session, Throwable cause) { - if (session == null || !session.equals(this.session)) { handleWrongSession(session, "Connection error: " + cause.getMessage()); return; diff --git a/bundles/org.openhab.binding.mycroft/src/main/java/org/openhab/binding/mycroft/internal/channels/AudioPlayerChannel.java b/bundles/org.openhab.binding.mycroft/src/main/java/org/openhab/binding/mycroft/internal/channels/AudioPlayerChannel.java index eb3d4bdf6..be3a8e62b 100644 --- a/bundles/org.openhab.binding.mycroft/src/main/java/org/openhab/binding/mycroft/internal/channels/AudioPlayerChannel.java +++ b/bundles/org.openhab.binding.mycroft/src/main/java/org/openhab/binding/mycroft/internal/channels/AudioPlayerChannel.java @@ -69,26 +69,26 @@ public class AudioPlayerChannel extends MycroftChannel { @Override public void handleCommand(Command command) { - if (command instanceof PlayPauseType) { - if (((PlayPauseType) command) == PlayPauseType.PAUSE) { + if (command instanceof PlayPauseType playPauseCommand) { + if (playPauseCommand == PlayPauseType.PAUSE) { if (handler.sendMessage(new MessageAudioPause())) { updateMyState(PlayPauseType.PAUSE); } } - if (((PlayPauseType) command) == PlayPauseType.PLAY) { + if (playPauseCommand == PlayPauseType.PLAY) { handler.sendMessage(new MessageAudioPlay()); if (handler.sendMessage(new MessageAudioResume())) { updateMyState(PlayPauseType.PLAY); } } } - if (command instanceof NextPreviousType) { - if (((NextPreviousType) command) == NextPreviousType.NEXT) { + if (command instanceof NextPreviousType nextPreviousCommand) { + if (nextPreviousCommand == NextPreviousType.NEXT) { if (handler.sendMessage(new MessageAudioNext())) { updateMyState(PlayPauseType.PLAY); } } - if (((NextPreviousType) command) == NextPreviousType.PREVIOUS) { + if (nextPreviousCommand == NextPreviousType.PREVIOUS) { if (handler.sendMessage(new MessageAudioPrev())) { updateMyState(PlayPauseType.PLAY); } diff --git a/bundles/org.openhab.binding.mycroft/src/main/java/org/openhab/binding/mycroft/internal/channels/MuteChannel.java b/bundles/org.openhab.binding.mycroft/src/main/java/org/openhab/binding/mycroft/internal/channels/MuteChannel.java index 5e81d6dae..bf038715e 100644 --- a/bundles/org.openhab.binding.mycroft/src/main/java/org/openhab/binding/mycroft/internal/channels/MuteChannel.java +++ b/bundles/org.openhab.binding.mycroft/src/main/java/org/openhab/binding/mycroft/internal/channels/MuteChannel.java @@ -72,8 +72,7 @@ public class MuteChannel extends MycroftChannel { } private boolean sendVolumeSetMessage(float volume) { - String messageToSend = VolumeChannel.VOLUME_SETTER_MESSAGE.replaceAll("\\$\\$VOLUME", - Float.valueOf(volume).toString()); + String messageToSend = VolumeChannel.VOLUME_SETTER_MESSAGE.replaceAll("\\$\\$VOLUME", Float.toString(volume)); return handler.sendMessage(messageToSend); } diff --git a/bundles/org.openhab.binding.mycroft/src/main/java/org/openhab/binding/mycroft/internal/channels/VolumeChannel.java b/bundles/org.openhab.binding.mycroft/src/main/java/org/openhab/binding/mycroft/internal/channels/VolumeChannel.java index 4764854ad..a5064098f 100644 --- a/bundles/org.openhab.binding.mycroft/src/main/java/org/openhab/binding/mycroft/internal/channels/VolumeChannel.java +++ b/bundles/org.openhab.binding.mycroft/src/main/java/org/openhab/binding/mycroft/internal/channels/VolumeChannel.java @@ -68,7 +68,6 @@ public class VolumeChannel extends MycroftChannel { @Override public void messageReceived(BaseMessage message) { - if (message.type == MessageType.mycroft_volume_get_response) { float volumeGet = ((MessageVolumeGetResponse) message).data.percent; updateAndSaveMyState(normalizeVolume(volumeGet)); @@ -87,10 +86,10 @@ public class VolumeChannel extends MycroftChannel { } protected final void updateAndSaveMyState(State state) { - if (state instanceof PercentType) { - this.lastVolume = ((PercentType) state); - if (((PercentType) state).intValue() > 0) { - this.lastNonZeroVolume = ((PercentType) state); + if (state instanceof PercentType volume) { + this.lastVolume = volume; + if (volume.intValue() > 0) { + this.lastNonZeroVolume = volume; } } super.updateMyState(state); @@ -140,7 +139,7 @@ public class VolumeChannel extends MycroftChannel { } private boolean sendSetMessage(float volume) { - String messageToSend = VOLUME_SETTER_MESSAGE.replaceAll("\\$\\$VOLUME", Float.valueOf(volume).toString()); + String messageToSend = VOLUME_SETTER_MESSAGE.replaceAll("\\$\\$VOLUME", Float.toString(volume)); return handler.sendMessage(messageToSend); } @@ -167,9 +166,9 @@ public class VolumeChannel extends MycroftChannel { handler.sendMessage(new MessageVolumeDecrease()); updateAndSaveMyState(computeNewVolume(-10)); } - } else if (command instanceof PercentType) { - sendSetMessage(toMycroftVolume((PercentType) command)); - updateAndSaveMyState((PercentType) command); + } else if (command instanceof PercentType volume) { + sendSetMessage(toMycroftVolume(volume)); + updateAndSaveMyState(volume); } else if (command instanceof RefreshType) { handler.sendMessage(new MessageVolumeGet()); } diff --git a/bundles/org.openhab.binding.mycroft/src/test/java/org/openhab/binding/mycroft/internal/api/MycroftConnectionTest.java b/bundles/org.openhab.binding.mycroft/src/test/java/org/openhab/binding/mycroft/internal/api/MycroftConnectionTest.java index c7148b0fa..85d74a6b3 100644 --- a/bundles/org.openhab.binding.mycroft/src/test/java/org/openhab/binding/mycroft/internal/api/MycroftConnectionTest.java +++ b/bundles/org.openhab.binding.mycroft/src/test/java/org/openhab/binding/mycroft/internal/api/MycroftConnectionTest.java @@ -48,7 +48,6 @@ public class MycroftConnectionTest { @Test public void testConnectionOK() throws IOException { - MycroftConnection mycroftConnection = new MycroftConnection(mycroftConnectionListener, new WebSocketClient()); Mockito.when(sessionMock.getRemoteAddress()).thenReturn(new InetSocketAddress(1234)); mycroftConnection.onConnect(sessionMock); @@ -85,7 +84,6 @@ public class MycroftConnectionTest { @Test public void testSpeakListener() throws IOException { - MycroftConnection mycroftConnection = new MycroftConnection(mycroftConnectionListener, new WebSocketClient()); Mockito.when(sessionMock.getRemoteAddress()).thenReturn(new InetSocketAddress(1234)); diff --git a/bundles/org.openhab.binding.mynice/src/main/java/org/openhab/binding/mynice/internal/xml/dto/Authentication.java b/bundles/org.openhab.binding.mynice/src/main/java/org/openhab/binding/mynice/internal/xml/dto/Authentication.java index 0c5be7dc5..d6d820432 100644 --- a/bundles/org.openhab.binding.mynice/src/main/java/org/openhab/binding/mynice/internal/xml/dto/Authentication.java +++ b/bundles/org.openhab.binding.mynice/src/main/java/org/openhab/binding/mynice/internal/xml/dto/Authentication.java @@ -22,7 +22,7 @@ public class Authentication { public enum UserPerm { wait, user, - admin; + admin } @XStreamAsAttribute diff --git a/bundles/org.openhab.binding.mynice/src/main/java/org/openhab/binding/mynice/internal/xml/dto/Device.java b/bundles/org.openhab.binding.mynice/src/main/java/org/openhab/binding/mynice/internal/xml/dto/Device.java index e4a0b3b04..9094f67f5 100644 --- a/bundles/org.openhab.binding.mynice/src/main/java/org/openhab/binding/mynice/internal/xml/dto/Device.java +++ b/bundles/org.openhab.binding.mynice/src/main/java/org/openhab/binding/mynice/internal/xml/dto/Device.java @@ -25,7 +25,7 @@ public class Device { UP_AND_OVER, SLIDING, BARRIER, - SWING; + SWING } @XStreamAsAttribute diff --git a/bundles/org.openhab.binding.mynice/src/main/java/org/openhab/binding/mynice/internal/xml/dto/Properties.java b/bundles/org.openhab.binding.mynice/src/main/java/org/openhab/binding/mynice/internal/xml/dto/Properties.java index 92026c025..a0a524644 100644 --- a/bundles/org.openhab.binding.mynice/src/main/java/org/openhab/binding/mynice/internal/xml/dto/Properties.java +++ b/bundles/org.openhab.binding.mynice/src/main/java/org/openhab/binding/mynice/internal/xml/dto/Properties.java @@ -20,7 +20,7 @@ import com.thoughtworks.xstream.annotations.XStreamAlias; */ @XStreamAlias("Properties") public class Properties { - public static enum DoorStatus { + public enum DoorStatus { OPEN(false), CLOSED(false), OPENING(true), diff --git a/bundles/org.openhab.binding.myq/src/main/java/org/openhab/binding/myq/internal/MyQDiscoveryService.java b/bundles/org.openhab.binding.myq/src/main/java/org/openhab/binding/myq/internal/MyQDiscoveryService.java index 26c95e76d..48863f228 100644 --- a/bundles/org.openhab.binding.myq/src/main/java/org/openhab/binding/myq/internal/MyQDiscoveryService.java +++ b/bundles/org.openhab.binding.myq/src/main/java/org/openhab/binding/myq/internal/MyQDiscoveryService.java @@ -81,8 +81,8 @@ public class MyQDiscoveryService extends AbstractDiscoveryService implements Dis @Override public void setThingHandler(ThingHandler handler) { - if (handler instanceof MyQAccountHandler) { - accountHandler = (MyQAccountHandler) handler; + if (handler instanceof MyQAccountHandler myqAccountHandler) { + accountHandler = myqAccountHandler; } } diff --git a/bundles/org.openhab.binding.myq/src/main/java/org/openhab/binding/myq/internal/handler/MyQAccountHandler.java b/bundles/org.openhab.binding.myq/src/main/java/org/openhab/binding/myq/internal/handler/MyQAccountHandler.java index 70902167f..c850d15fa 100644 --- a/bundles/org.openhab.binding.myq/src/main/java/org/openhab/binding/myq/internal/handler/MyQAccountHandler.java +++ b/bundles/org.openhab.binding.myq/src/main/java/org/openhab/binding/myq/internal/handler/MyQAccountHandler.java @@ -27,10 +27,10 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.Collection; -import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Random; +import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; @@ -176,17 +176,15 @@ public class MyQAccountHandler extends BaseBridgeHandler implements AccessTokenR @Override public Collection> getServices() { - return Collections.singleton(MyQDiscoveryService.class); + return Set.of(MyQDiscoveryService.class); } @Override public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) { List localDeviceCaches = devicesCache; - if (childHandler instanceof MyQDeviceHandler) { - MyQDeviceHandler handler = (MyQDeviceHandler) childHandler; - localDeviceCaches.stream() - .filter(d -> ((MyQDeviceHandler) childHandler).getSerialNumber().equalsIgnoreCase(d.serialNumber)) - .findFirst().ifPresent(handler::handleDeviceUpdate); + if (childHandler instanceof MyQDeviceHandler deviceHandler) { + localDeviceCaches.stream().filter(d -> deviceHandler.getSerialNumber().equalsIgnoreCase(d.serialNumber)) + .findFirst().ifPresent(deviceHandler::handleDeviceUpdate); } } diff --git a/bundles/org.openhab.binding.myq/src/main/java/org/openhab/binding/myq/internal/handler/MyQGarageDoorHandler.java b/bundles/org.openhab.binding.myq/src/main/java/org/openhab/binding/myq/internal/handler/MyQGarageDoorHandler.java index 8cb59267b..7f7591600 100644 --- a/bundles/org.openhab.binding.myq/src/main/java/org/openhab/binding/myq/internal/handler/MyQGarageDoorHandler.java +++ b/bundles/org.openhab.binding.myq/src/main/java/org/openhab/binding/myq/internal/handler/MyQGarageDoorHandler.java @@ -71,8 +71,8 @@ public class MyQGarageDoorHandler extends BaseThingHandler implements MyQDeviceH if (command instanceof UpDownType) { cmd = command == UpDownType.UP ? "open" : "close"; } - if (command instanceof PercentType) { - cmd = ((PercentType) command).as(UpDownType.class) == UpDownType.UP ? "open" : "close"; + if (command instanceof PercentType percentage) { + cmd = percentage.as(UpDownType.class) == UpDownType.UP ? "open" : "close"; } if (command instanceof StringType) { cmd = command.toString(); diff --git a/bundles/org.openhab.binding.mystrom/src/main/java/org/openhab/binding/mystrom/internal/MyStromBulbHandler.java b/bundles/org.openhab.binding.mystrom/src/main/java/org/openhab/binding/mystrom/internal/MyStromBulbHandler.java index aad1dad8e..9187ca06f 100644 --- a/bundles/org.openhab.binding.mystrom/src/main/java/org/openhab/binding/mystrom/internal/MyStromBulbHandler.java +++ b/bundles/org.openhab.binding.mystrom/src/main/java/org/openhab/binding/mystrom/internal/MyStromBulbHandler.java @@ -95,18 +95,18 @@ public class MyStromBulbHandler extends AbstractMyStromHandler { } break; case CHANNEL_COLOR: - if (command instanceof HSBType) { - if (Objects.equals(((HSBType) command).as(OnOffType.class), OnOffType.OFF)) { + if (command instanceof HSBType hsb) { + if (Objects.equals(hsb.as(OnOffType.class), OnOffType.OFF)) { sResp = sendToBulb("off", null, null, null); } else { - String hsv = command.toString().replaceAll(",", ";"); + String hsv = command.toString().replace(",", ";"); sResp = sendToBulb("on", hsv, null, HSV); } } break; case CHANNEL_BRIGHTNESS: - if (command instanceof PercentType) { - if (Objects.equals(((PercentType) command).as(OnOffType.class), OnOffType.OFF)) { + if (command instanceof PercentType brightness) { + if (Objects.equals(brightness.as(OnOffType.class), OnOffType.OFF)) { sResp = sendToBulb("off", null, null, null); } else { if (lastMode.equals(MONO)) { @@ -122,9 +122,8 @@ public class MyStromBulbHandler extends AbstractMyStromHandler { } break; case CHANNEL_COLOR_TEMPERATURE: - if (command instanceof PercentType) { - String mono = convertPercentageToMyStromCT((PercentType) command) + ";" - + lastBrightness.toString(); + if (command instanceof PercentType temperature) { + String mono = convertPercentageToMyStromCT(temperature) + ";" + lastBrightness.toString(); sResp = sendToBulb("on", mono, null, MONO); } break; @@ -186,8 +185,8 @@ public class MyStromBulbHandler extends AbstractMyStromHandler { if (deviceInfo != null) { updateState(CHANNEL_SWITCH, deviceInfo.on ? OnOffType.ON : OnOffType.OFF); updateState(CHANNEL_RAMP, QuantityType.valueOf(deviceInfo.ramp, MetricPrefix.MILLI(SECOND))); - if (deviceInfo instanceof MyStromDeviceSpecificInfo) { - updateState(CHANNEL_POWER, QuantityType.valueOf(((MyStromDeviceSpecificInfo) deviceInfo).power, WATT)); + if (deviceInfo instanceof MyStromDeviceSpecificInfo info) { + updateState(CHANNEL_POWER, QuantityType.valueOf(info.power, WATT)); } if (deviceInfo.on) { try { @@ -200,9 +199,9 @@ public class MyStromBulbHandler extends AbstractMyStromHandler { lastColor = new HSBType(lastColor.getHue() + ",0," + lastBrightness); updateState(CHANNEL_COLOR_TEMPERATURE, lastColorTemperature); } else if (numSemicolon == 2 && deviceInfo.mode.equals(HSV)) { - lastColor = HSBType.valueOf(deviceInfo.color.replaceAll(";", ",")); + lastColor = HSBType.valueOf(deviceInfo.color.replace(";", ",")); lastBrightness = lastColor.getBrightness(); - } else if (!deviceInfo.color.equals("") && deviceInfo.mode.equals(RGB)) { + } else if (!"".equals(deviceInfo.color) && deviceInfo.mode.equals(RGB)) { int r = Integer.parseInt(deviceInfo.color.substring(2, 4), 16); int g = Integer.parseInt(deviceInfo.color.substring(4, 6), 16); int b = Integer.parseInt(deviceInfo.color.substring(6, 8), 16);