]> git.basschouten.com Git - openhab-addons.git/commitdiff
[infrastructure] add external null-annotations (#8848)
authorJ-N-K <J-N-K@users.noreply.github.com>
Fri, 30 Oct 2020 23:29:03 +0000 (00:29 +0100)
committerGitHub <noreply@github.com>
Fri, 30 Oct 2020 23:29:03 +0000 (00:29 +0100)
Signed-off-by: Jan N. Klug <jan.n.klug@rub.de>
162 files changed:
bundles/org.openhab.binding.airquality/src/main/java/org/openhab/binding/airquality/internal/json/AirQualityJsonCity.java
bundles/org.openhab.binding.airquality/src/main/java/org/openhab/binding/airquality/internal/json/AirQualityJsonData.java
bundles/org.openhab.binding.alarmdecoder/src/main/java/org/openhab/binding/alarmdecoder/internal/handler/ADBridgeHandler.java
bundles/org.openhab.binding.amazonechocontrol/src/main/java/org/openhab/binding/amazonechocontrol/internal/AccountServlet.java
bundles/org.openhab.binding.amazonechocontrol/src/main/java/org/openhab/binding/amazonechocontrol/internal/discovery/SmartHomeDevicesDiscovery.java
bundles/org.openhab.binding.amazonechocontrol/src/main/java/org/openhab/binding/amazonechocontrol/internal/handler/SmartHomeDeviceHandler.java
bundles/org.openhab.binding.ambientweather/src/main/java/org/openhab/binding/ambientweather/internal/handler/AmbientWeatherBridgeHandler.java
bundles/org.openhab.binding.ambientweather/src/main/java/org/openhab/binding/ambientweather/internal/processor/RemoteSensor.java
bundles/org.openhab.binding.automower/src/main/java/org/openhab/binding/automower/internal/rest/exceptions/AutomowerCommunicationException.java
bundles/org.openhab.binding.bluetooth.bluegiga/src/main/java/org/openhab/binding/bluetooth/bluegiga/internal/eir/EirDataType.java
bundles/org.openhab.binding.bluetooth.bluegiga/src/main/java/org/openhab/binding/bluetooth/bluegiga/internal/eir/EirFlags.java
bundles/org.openhab.binding.bluetooth.roaming/src/main/java/org/openhab/binding/bluetooth/roaming/internal/RoamingBluetoothDevice.java
bundles/org.openhab.binding.bticinosmarther/src/main/java/org/openhab/binding/bticinosmarther/internal/api/SmartherApiConnector.java
bundles/org.openhab.binding.bticinosmarther/src/main/java/org/openhab/binding/bticinosmarther/internal/api/dto/Enums.java
bundles/org.openhab.binding.bticinosmarther/src/main/java/org/openhab/binding/bticinosmarther/internal/api/exception/SmartherAuthorizationException.java
bundles/org.openhab.binding.bticinosmarther/src/main/java/org/openhab/binding/bticinosmarther/internal/api/exception/SmartherGatewayException.java
bundles/org.openhab.binding.bticinosmarther/src/main/java/org/openhab/binding/bticinosmarther/internal/api/exception/SmartherInvalidResponseException.java
bundles/org.openhab.binding.bticinosmarther/src/main/java/org/openhab/binding/bticinosmarther/internal/util/DateUtil.java
bundles/org.openhab.binding.buienradar/src/main/java/org/openhab/binding/buienradar/internal/buienradarapi/BuienradarParseException.java
bundles/org.openhab.binding.buienradar/src/main/java/org/openhab/binding/buienradar/internal/buienradarapi/BuienradarPredictionAPI.java
bundles/org.openhab.binding.caddx/src/main/java/org/openhab/binding/caddx/internal/CaddxMessage.java
bundles/org.openhab.binding.darksky/src/main/java/org/openhab/binding/darksky/internal/connection/DarkSkyCommunicationException.java
bundles/org.openhab.binding.darksky/src/main/java/org/openhab/binding/darksky/internal/connection/DarkSkyConfigurationException.java
bundles/org.openhab.binding.darksky/src/main/java/org/openhab/binding/darksky/internal/connection/DarkSkyConnection.java
bundles/org.openhab.binding.deconz/src/main/java/org/openhab/binding/deconz/internal/handler/LightThingHandler.java
bundles/org.openhab.binding.digitalstrom/src/main/java/org/openhab/binding/digitalstrom/internal/lib/manager/impl/DeviceStatusManagerImpl.java
bundles/org.openhab.binding.digitalstrom/src/main/java/org/openhab/binding/digitalstrom/internal/lib/manager/impl/TemperatureControlManager.java
bundles/org.openhab.binding.digitalstrom/src/main/java/org/openhab/binding/digitalstrom/internal/lib/structure/devices/deviceparameters/impl/DeviceSensorValue.java
bundles/org.openhab.binding.draytonwiser/src/main/java/org/openhab/binding/draytonwiser/internal/api/DraytonWiserApiException.java
bundles/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/device/cosem/CosemObjectFactory.java
bundles/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/discovery/DSMRMeterDiscoveryService.java
bundles/org.openhab.binding.enturno/src/main/java/org/openhab/binding/enturno/internal/connection/EnturCommunicationException.java
bundles/org.openhab.binding.exec/src/main/java/org/openhab/binding/exec/internal/handler/ExecHandler.java
bundles/org.openhab.binding.fmiweather/src/main/java/org/openhab/binding/fmiweather/internal/client/Client.java
bundles/org.openhab.binding.foobot/src/main/java/org/openhab/binding/foobot/internal/FoobotApiException.java
bundles/org.openhab.binding.foobot/src/main/java/org/openhab/binding/foobot/internal/handler/FoobotAccountHandler.java
bundles/org.openhab.binding.gree/src/main/java/org/openhab/binding/gree/internal/GreeException.java
bundles/org.openhab.binding.gree/src/main/java/org/openhab/binding/gree/internal/discovery/GreeDeviceFinder.java
bundles/org.openhab.binding.hdpowerview/src/main/java/org/openhab/binding/hdpowerview/internal/handler/HDPowerViewShadeHandler.java
bundles/org.openhab.binding.heliosventilation/src/main/java/org/openhab/binding/heliosventilation/internal/HeliosPropertiesFormatException.java
bundles/org.openhab.binding.hpprinter/src/main/java/org/openhab/binding/hpprinter/internal/api/HPServerResult.java
bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/HueBridge.java
bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/Scene.java
bundles/org.openhab.binding.innogysmarthome/src/main/java/org/openhab/binding/innogysmarthome/internal/manager/DeviceStructureManager.java
bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/CommandHandler.java
bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/device/MessageHandler.java
bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/driver/hub/ReadByteBuffer.java
bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/message/Msg.java
bundles/org.openhab.binding.km200/src/main/java/org/openhab/binding/km200/internal/KM200Utils.java
bundles/org.openhab.binding.km200/src/main/java/org/openhab/binding/km200/internal/handler/KM200GatewayHandler.java
bundles/org.openhab.binding.km200/src/main/java/org/openhab/binding/km200/internal/handler/KM200ThingHandler.java
bundles/org.openhab.binding.knx/src/main/java/org/openhab/binding/knx/internal/client/AbstractKNXClient.java
bundles/org.openhab.binding.kostalinverter/src/main/java/org/openhab/binding/internal/kostal/inverter/KostalInverterFactory.java
bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/connection/ConnectionStateMachine.java
bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/handler/LGWebOSTVMouseSocket.java
bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/handler/LGWebOSTVSocket.java
bundles/org.openhab.binding.linky/src/main/java/org/openhab/binding/linky/internal/api/EnedisHttpApi.java
bundles/org.openhab.binding.logreader/src/main/java/org/openhab/binding/logreader/internal/handler/LogHandler.java
bundles/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/LxServerHandler.java
bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/xml/DbXmlInfoReader.java
bundles/org.openhab.binding.meteoalerte/src/main/java/org/openhab/binding/meteoalerte/internal/handler/MeteoAlerteHandler.java
bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/MiIoCryptoException.java
bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/cloud/MiCloudException.java
bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/handler/MiIoAbstractHandler.java
bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/robot/RRMapFileParser.java
bundles/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/internal/protocol/MilightV6SessionManager.java
bundles/org.openhab.binding.modbus.helioseasycontrols/src/main/java/org/openhab/binding/modbus/helioseasycontrols/internal/HeliosEasyControlsHandler.java
bundles/org.openhab.binding.modbus.studer/src/main/java/org/openhab/binding/modbus/studer/internal/StuderHandler.java
bundles/org.openhab.binding.modbus.sunspec/src/main/java/org/openhab/binding/modbus/sunspec/internal/discovery/SunspecDiscoveryProcess.java
bundles/org.openhab.binding.modbus.sunspec/src/main/java/org/openhab/binding/modbus/sunspec/internal/handler/AbstractSunSpecHandler.java
bundles/org.openhab.binding.monopriceaudio/src/main/java/org/openhab/binding/monopriceaudio/internal/handler/MonopriceAudioHandler.java
bundles/org.openhab.binding.mqtt.generic/src/main/java/org/openhab/binding/mqtt/generic/values/NumberValue.java
bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/OpenAPIUtils.java
bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/handler/NanoleafControllerHandler.java
bundles/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/net/HttpResponse.java
bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/AbstractNetatmoThingHandler.java
bundles/org.openhab.binding.nibeuplink/src/main/java/org/openhab/binding/nibeuplink/internal/connector/CommunicationStatus.java
bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/protocol/nhc1/NikoHomeControlCommunication1.java
bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/protocol/nhc2/NikoHomeControlCommunication2.java
bundles/org.openhab.binding.ojelectronics/src/main/java/org/openhab/binding/ojelectronics/internal/ThermostatHandler.java
bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/SensorId.java
bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/discovery/OwDiscoveryItem.java
bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/AdvancedMultisensorThingHandler.java
bundles/org.openhab.binding.openweathermap/src/main/java/org/openhab/binding/openweathermap/internal/connection/OpenWeatherMapCommunicationException.java
bundles/org.openhab.binding.openweathermap/src/main/java/org/openhab/binding/openweathermap/internal/connection/OpenWeatherMapConfigurationException.java
bundles/org.openhab.binding.openweathermap/src/main/java/org/openhab/binding/openweathermap/internal/connection/OpenWeatherMapConnection.java
bundles/org.openhab.binding.pjlinkdevice/src/main/java/org/openhab/binding/pjlinkdevice/internal/device/PJLinkDevice.java
bundles/org.openhab.binding.plclogo/src/main/java/org/openhab/binding/plclogo/internal/handler/PLCCommonHandler.java
bundles/org.openhab.binding.plugwise/src/main/java/org/openhab/binding/plugwise/internal/handler/AbstractPlugwiseThingHandler.java
bundles/org.openhab.binding.pulseaudio/src/main/java/org/openhab/binding/pulseaudio/internal/cli/Parser.java
bundles/org.openhab.binding.radiothermostat/src/main/java/org/openhab/binding/radiothermostat/internal/communication/RadioThermostatConnector.java
bundles/org.openhab.binding.remoteopenhab/src/main/java/org/openhab/binding/remoteopenhab/internal/exceptions/RemoteopenhabException.java
bundles/org.openhab.binding.sagercaster/src/main/java/org/openhab/binding/sagercaster/internal/handler/ExpiringMap.java
bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/service/MediaRendererService.java
bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/service/ServiceFactory.java
bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/action/SatelEventLogActions.java
bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelThingHandler.java
bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/protocol/SatelModule.java
bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/api/ShellyApiException.java
bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/coap/ShellyCoIoTProtocol.java
bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/discovery/ShellyThingCreator.java
bundles/org.openhab.binding.shelly/src/main/java/org/openhab/binding/shelly/internal/util/ShellyChannelCache.java
bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/points/BasePoint.java
bundles/org.openhab.binding.siemensrds/src/main/java/org/openhab/binding/siemensrds/points/StringPoint.java
bundles/org.openhab.binding.smartmeter/src/main/java/org/openhab/binding/smartmeter/internal/conformity/Conformity.java
bundles/org.openhab.binding.smartthings/src/main/java/org/openhab/binding/smartthings/internal/converter/SmartthingsHue100Converter.java
bundles/org.openhab.binding.snmp/src/test/java/org/openhab/binding/snmp/internal/AbstractSnmpTargetHandlerTest.java
bundles/org.openhab.binding.solaredge/src/main/java/org/openhab/binding/solaredge/internal/connector/CommunicationStatus.java
bundles/org.openhab.binding.sonos/src/main/java/org/openhab/binding/sonos/internal/SonosXMLParser.java
bundles/org.openhab.binding.sonos/src/main/java/org/openhab/binding/sonos/internal/handler/ZonePlayerHandler.java
bundles/org.openhab.binding.sonyprojector/src/main/java/org/openhab/binding/sonyprojector/internal/SonyProjectorException.java
bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/api/SpotifyConnector.java
bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/handler/SpotifyBridgeHandler.java
bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/handler/SqueezeBoxPlayerHandler.java
bundles/org.openhab.binding.tacmi/src/main/java/org/openhab/binding/tacmi/internal/TACmiChannelTypeProvider.java
bundles/org.openhab.binding.tacmi/src/main/java/org/openhab/binding/tacmi/internal/schema/ApiPageParser.java
bundles/org.openhab.binding.tacmi/src/main/java/org/openhab/binding/tacmi/internal/schema/ChangerX2Parser.java
bundles/org.openhab.binding.telegram/src/main/java/org/openhab/binding/telegram/internal/TelegramHandler.java
bundles/org.openhab.binding.telegram/src/main/java/org/openhab/binding/telegram/internal/action/TelegramActions.java
bundles/org.openhab.binding.tibber/src/main/java/org/openhab/binding/tibber/internal/handler/TibberHandler.java
bundles/org.openhab.binding.touchwand/src/main/java/org/openhab/binding/touchwand/internal/TouchWandBaseUnitHandler.java
bundles/org.openhab.binding.upnpcontrol/src/main/java/org/openhab/binding/upnpcontrol/internal/UpnpXMLParser.java
bundles/org.openhab.binding.upnpcontrol/src/main/java/org/openhab/binding/upnpcontrol/internal/handler/UpnpHandler.java
bundles/org.openhab.binding.upnpcontrol/src/main/java/org/openhab/binding/upnpcontrol/internal/handler/UpnpRendererHandler.java
bundles/org.openhab.binding.upnpcontrol/src/main/java/org/openhab/binding/upnpcontrol/internal/handler/UpnpServerHandler.java
bundles/org.openhab.binding.velux/src/main/java/org/openhab/binding/velux/internal/VeluxRSBindingConfig.java
bundles/org.openhab.binding.velux/src/main/java/org/openhab/binding/velux/internal/things/VeluxExistingProducts.java
bundles/org.openhab.binding.velux/src/main/java/org/openhab/binding/velux/internal/things/VeluxExistingScenes.java
bundles/org.openhab.binding.velux/src/main/java/org/openhab/binding/velux/internal/things/VeluxGwState.java
bundles/org.openhab.binding.velux/src/main/java/org/openhab/binding/velux/internal/things/VeluxKLFAPI.java
bundles/org.openhab.binding.venstarthermostat/src/main/java/org/openhab/binding/venstarthermostat/internal/handler/VenstarThermostatHandler.java
bundles/org.openhab.binding.verisure/src/main/java/org/openhab/binding/verisure/internal/handler/VerisureEventLogThingHandler.java
bundles/org.openhab.binding.verisure/src/main/java/org/openhab/binding/verisure/internal/handler/VerisureGatewayThingHandler.java
bundles/org.openhab.binding.volvooncall/src/main/java/org/openhab/binding/volvooncall/internal/dto/TripDetail.java
bundles/org.openhab.binding.volvooncall/src/main/java/org/openhab/binding/volvooncall/internal/handler/VehicleHandler.java
bundles/org.openhab.binding.yamahareceiver/src/main/java/org/openhab/binding/yamahareceiver/internal/handler/YamahaBridgeHandler.java
bundles/org.openhab.binding.yamahareceiver/src/main/java/org/openhab/binding/yamahareceiver/internal/handler/YamahaZoneThingHandler.java
bundles/org.openhab.binding.yeelight/src/main/java/org/openhab/binding/yeelight/internal/lib/services/DeviceManager.java
bundles/org.openhab.binding.zway/src/main/java/org/openhab/binding/zway/internal/handler/ZWayDeviceHandler.java
bundles/org.openhab.io.homekit/src/main/java/org/openhab/io/homekit/internal/HomekitChangeListener.java
bundles/org.openhab.io.homekit/src/main/java/org/openhab/io/homekit/internal/accessories/HomekitAccessoryFactory.java
bundles/org.openhab.io.hueemulation/src/main/java/org/openhab/io/hueemulation/internal/NetworkUtils.java
bundles/org.openhab.io.hueemulation/src/main/java/org/openhab/io/hueemulation/internal/rest/Scenes.java
bundles/org.openhab.io.hueemulation/src/test/java/org/openhab/io/hueemulation/internal/rest/mocks/DummyItemRegistry.java
bundles/org.openhab.io.neeo/src/main/java/org/openhab/io/neeo/internal/OpenHabToDeviceConverter.java
bundles/org.openhab.io.neeo/src/main/java/org/openhab/io/neeo/internal/net/HttpRequest.java
bundles/org.openhab.io.neeo/src/main/java/org/openhab/io/neeo/internal/net/HttpResponse.java
bundles/org.openhab.io.transport.modbus/src/main/java/org/openhab/io/transport/modbus/exception/ModbusConnectionException.java
bundles/org.openhab.io.transport.modbus/src/main/java/org/openhab/io/transport/modbus/exception/ModbusUnexpectedResponseFunctionCodeException.java
bundles/org.openhab.io.transport.modbus/src/main/java/org/openhab/io/transport/modbus/exception/ModbusUnexpectedResponseSizeException.java
bundles/org.openhab.io.transport.modbus/src/main/java/org/openhab/io/transport/modbus/exception/ModbusUnexpectedTransactionIdException.java
bundles/org.openhab.io.transport.modbus/src/main/java/org/openhab/io/transport/modbus/internal/ModbusSlaveErrorResponseExceptionImpl.java
bundles/org.openhab.io.transport.modbus/src/main/java/org/openhab/io/transport/modbus/internal/ModbusSlaveIOExceptionImpl.java
bundles/org.openhab.persistence.dynamodb/src/main/java/org/openhab/persistence/dynamodb/internal/DynamoDBPersistenceService.java
bundles/org.openhab.persistence.dynamodb/src/test/java/org/openhab/persistence/dynamodb/internal/AbstractTwoItemIntegrationTest.java
bundles/org.openhab.persistence.dynamodb/src/test/java/org/openhab/persistence/dynamodb/internal/BaseIntegrationTest.java
bundles/org.openhab.transform.javascript/src/main/java/org/openhab/transform/javascript/internal/JavaScriptEngineManager.java
bundles/org.openhab.transform.map/src/test/java/org/openhab/transform/map/internal/MapTransformationServiceTest.java
bundles/pom.xml
itests/org.openhab.binding.modbus.tests/src/main/java/org/openhab/binding/modbus/tests/AbstractModbusOSGiTest.java
itests/pom.xml
pom.xml

index 6fc021eb077b0c587d8b5ef8f40ea3b81d8ef1ea..b601eadae6774f28c039cf162790adb5a67d17ba 100644 (file)
@@ -14,6 +14,7 @@ package org.openhab.binding.airquality.internal.json;
 
 import java.util.ArrayList;
 import java.util.List;
+import java.util.stream.Collectors;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
 import org.eclipse.jdt.annotation.Nullable;
@@ -40,8 +41,6 @@ public class AirQualityJsonCity {
     }
 
     public String getGeo() {
-        List<String> list = new ArrayList<>();
-        geo.forEach(item -> list.add(item.toString()));
-        return String.join(",", list);
+        return geo.stream().map(Object::toString).collect(Collectors.joining(", "));
     }
 }
index d1acd66e131c815775c1c0a90140c79167c90001..76ec79d67dc813e0175d3e331c48b003f723367d 100644 (file)
@@ -16,6 +16,7 @@ import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.stream.Collectors;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
 import org.eclipse.jdt.annotation.Nullable;
@@ -82,9 +83,8 @@ public class AirQualityJsonData {
      * @return {String}
      */
     public String getAttributions() {
-        List<String> list = new ArrayList<>();
-        attributions.forEach(item -> list.add(item.getName()));
-        return "Attributions : " + String.join(", ", list);
+        String attributionsString = attributions.stream().map(Attribute::getName).collect(Collectors.joining(", "));
+        return "Attributions : " + attributionsString;
     }
 
     public String getDominentPol() {
index dada4767737b259c973e613d74da28c8a5e945e6..e3eddab79ffdb45b3e2dad9e8a96e80d3029c294 100644 (file)
@@ -368,7 +368,7 @@ public abstract class ADBridgeHandler extends BaseBridgeHandler {
     private static class MessageParseException extends Exception {
         private static final long serialVersionUID = 1L;
 
-        public MessageParseException(String msg) {
+        public MessageParseException(@Nullable String msg) {
             super(msg);
         }
     }
index f92e34d4895e2a8101e715e3b7711d1c00790458..83c5e1e0e3c3492078785617616aae7af51166f9 100644 (file)
@@ -697,9 +697,10 @@ public class AccountServlet extends HttpServlet {
         }
     }
 
-    void returnError(HttpServletResponse resp, String errorMessage) {
+    void returnError(HttpServletResponse resp, @Nullable String errorMessage) {
         try {
-            resp.getWriter().write("<html>" + StringEscapeUtils.escapeHtml(errorMessage) + "<br><a href='" + servletUrl
+            String message = errorMessage != null ? errorMessage : "null";
+            resp.getWriter().write("<html>" + StringEscapeUtils.escapeHtml(message) + "<br><a href='" + servletUrl
                     + "'>Try again</a></html>");
         } catch (IOException e) {
             logger.info("Returning error message failed", e);
index 9316a46c53d5e7338ac630aab877175ebb7150ea..c3b32271008b45b0edcb676dafc0ad83423d6697 100644 (file)
@@ -32,6 +32,7 @@ import org.eclipse.jdt.annotation.Nullable;
 import org.openhab.binding.amazonechocontrol.internal.Connection;
 import org.openhab.binding.amazonechocontrol.internal.handler.AccountHandler;
 import org.openhab.binding.amazonechocontrol.internal.handler.SmartHomeDeviceHandler;
+import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities;
 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.DriverIdentity;
 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice;
 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeGroups.SmartHomeGroup;
@@ -171,7 +172,8 @@ public class SmartHomeDevicesDiscovery extends AbstractDiscoveryService {
                     continue;
                 }
 
-                if (Stream.of(shd.capabilities).noneMatch(capability -> capability != null
+                JsonSmartHomeCapabilities.SmartHomeCapability[] capabilities = shd.capabilities;
+                if (capabilities == null || Stream.of(capabilities).noneMatch(capability -> capability != null
                         && Constants.SUPPORTED_INTERFACES.contains(capability.interfaceName))) {
                     // No supported interface found
                     continue;
index c9b7900ab303b556c026c659f5e971f7a30f35a5..b6a7001ce61e3266c245c52c1624b21c0f029bbb 100644 (file)
@@ -109,7 +109,8 @@ public class SmartHomeDeviceHandler extends BaseThingHandler {
                 }
             }
             if (handler != null) {
-                Collection<ChannelInfo> required = handler.initialize(this, capabilities.get(interfaceName));
+                Collection<ChannelInfo> required = handler.initialize(this,
+                        capabilities.getOrDefault(interfaceName, Collections.emptyList()));
                 for (ChannelInfo channelInfo : required) {
                     unusedChannels.remove(channelInfo.channelId);
                     if (addChannelToDevice(thingBuilder, channelInfo.channelId, channelInfo.itemType,
index d373a9c2e64e97e3cc5913f3fc272bdc6bcef000..ed7e10bd2fec9090dfe3385398506c9a36ce9cb3 100644 (file)
@@ -62,12 +62,10 @@ public class AmbientWeatherBridgeHandler extends BaseBridgeHandler {
     private ScheduledFuture<?> validateKeysJob;
 
     // Application key is granted only by request from developer
-    @Nullable
-    private String applicationKey;
+    private String applicationKey = "";
 
     // API key assigned to user in ambientweather.net dashboard
-    @Nullable
-    private String apiKey;
+    private String apiKey = "";
 
     // Used Ambient Weather real-time API to retrieve weather data
     // for weather stations assigned to an API key
@@ -151,8 +149,9 @@ public class AmbientWeatherBridgeHandler extends BaseBridgeHandler {
         return true;
     }
 
-    public void setThingOfflineWithCommError(String errorDetail, String statusDescription) {
-        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, statusDescription);
+    public void setThingOfflineWithCommError(@Nullable String errorDetail, @Nullable String statusDescription) {
+        String status = statusDescription != null ? statusDescription : "null";
+        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, status);
     }
 
     @Override
@@ -213,11 +212,11 @@ public class AmbientWeatherBridgeHandler extends BaseBridgeHandler {
         updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
     }
 
-    public @Nullable String getApplicationKey() {
+    public String getApplicationKey() {
         return applicationKey;
     }
 
-    public @Nullable String getApiKey() {
+    public String getApiKey() {
         return apiKey;
     }
 
index 22f68a7a078509c345dfbee7aa264bfc55b30873..f2e2dccd3b4350f03706b0b05bda9687cf74621a 100644 (file)
@@ -132,6 +132,6 @@ public class RemoteSensor {
      */
     private String convertSoilMoistureToString(double soilMoisture) {
         Double key = soilMoistureMap.ceilingKey(soilMoisture);
-        return key == null ? "UNKNOWN" : soilMoistureMap.get(key);
+        return key == null ? "UNKNOWN" : soilMoistureMap.getOrDefault(key, "UNKNOWN");
     }
 }
index 4b0cef23f89d7432fb4edcdd2a291a8d7a20103f..2094fbb10d0be708a3b57a805c854892578e3f3d 100644 (file)
@@ -15,6 +15,7 @@ package org.openhab.binding.automower.internal.rest.exceptions;
 import java.io.IOException;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 
 /**
  * An exception that occurred while communicating with an automower or an automower bridge
@@ -57,8 +58,9 @@ public class AutomowerCommunicationException extends IOException {
     }
 
     @Override
-    public String getMessage() {
-        return "Rest call failed: statusCode=" + statusCode + ", message=" + super.getMessage();
+    public @Nullable String getMessage() {
+        String message = super.getMessage();
+        return message == null ? null : "Rest call failed: statusCode=" + statusCode + ", message=" + message;
     }
 
     @Override
index 82a62b94ca0a8d56a7804e34e1b82c083377c4f2..d5b9b955e0b816831cc9d822157ff13b9fe05406 100644 (file)
@@ -100,11 +100,7 @@ public enum EirDataType {
             initMapping();
         }
 
-        if (codeMapping.get(eirDataType) == null) {
-            return UNKNOWN;
-        }
-
-        return codeMapping.get(eirDataType);
+        return codeMapping.getOrDefault(eirDataType, UNKNOWN);
     }
 
     /**
index ff5b4343d869be530deaa388edf4acc59be5c8aa..2c152f0e6a98c515829ab69c8bc6fcc8dea381d9 100644 (file)
@@ -75,11 +75,7 @@ public enum EirFlags {
             initMapping();
         }
 
-        if (codeMapping.get(eirFlag) == null) {
-            return UNKNOWN;
-        }
-
-        return codeMapping.get(eirFlag);
+        return codeMapping.getOrDefault(eirFlag, UNKNOWN);
     }
 
     /**
index 0c73a7b6554786241e29395ca46d4668127d4c05..e992d4a43ba6a321bf789916bb84a5c48e484a88 100644 (file)
@@ -56,7 +56,10 @@ public class RoamingBluetoothDevice extends DelegateBluetoothDevice {
     }
 
     public void removeBluetoothDevice(BluetoothDevice device) {
-        device.removeListener(devices.remove(device));
+        BluetoothDeviceListener listener = devices.remove(device);
+        if (listener != null) {
+            device.removeListener(listener);
+        }
     }
 
     @Override
index 11aa8d604d9693a945b0a7a3e6d850636d300525..34e6c0215c7a47eaaf0fe2205b174120cca069a7 100644 (file)
@@ -197,7 +197,8 @@ public class SmartherApiConnector {
                     }
                 }
             } catch (ExecutionException e) {
-                future.completeExceptionally(e.getCause());
+                Throwable cause = e.getCause();
+                future.completeExceptionally(cause != null ? cause : e);
             } catch (SmartherGatewayException e) {
                 future.completeExceptionally(e);
             } catch (RuntimeException | TimeoutException e) {
index 05646a03c99e03b0abfc7995529f5eac8464d8fa..0485966b465b25d9574ff47768f06936e8f8f325 100644 (file)
@@ -243,9 +243,12 @@ public class Enums {
 
     public static <E extends Enum<E> & TypeWithIntProperty> E lookup(Class<E> en, int value)
             throws SmartherIllegalPropertyValueException {
-        for (E constant : en.getEnumConstants()) {
-            if (constant.getValue() == value) {
-                return constant;
+        E[] constants = en.getEnumConstants();
+        if (constants != null) {
+            for (E constant : constants) {
+                if (constant.getValue() == value) {
+                    return constant;
+                }
             }
         }
         throw new SmartherIllegalPropertyValueException(en.getSimpleName(), String.valueOf(value));
@@ -257,9 +260,12 @@ public class Enums {
 
     public static <E extends Enum<E> & TypeWithStringProperty> E lookup(Class<E> en, String value)
             throws SmartherIllegalPropertyValueException {
-        for (E constant : en.getEnumConstants()) {
-            if (constant.getValue().equals(value)) {
-                return constant;
+        E[] constants = en.getEnumConstants();
+        if (constants != null) {
+            for (E constant : constants) {
+                if (constant.getValue().equals(value)) {
+                    return constant;
+                }
             }
         }
         throw new SmartherIllegalPropertyValueException(en.getSimpleName(), value);
index f24e0f4ef05e09ed9b21921565f6778968d5bc57..69c0874738ae1ca283ddbcf2134e702aee9b00dd 100644 (file)
@@ -13,6 +13,7 @@
 package org.openhab.binding.bticinosmarther.internal.api.exception;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 
 /**
  * Signals that a generic OAuth2 authorization issue with API gateway has occurred.
@@ -30,7 +31,7 @@ public class SmartherAuthorizationException extends SmartherGatewayException {
      * @param message
      *            the error message returned from the API gateway
      */
-    public SmartherAuthorizationException(String message) {
+    public SmartherAuthorizationException(@Nullable String message) {
         super(message);
     }
 
@@ -42,7 +43,7 @@ public class SmartherAuthorizationException extends SmartherGatewayException {
      * @param cause
      *            the cause (a null value is permitted, and indicates that the cause is nonexistent or unknown)
      */
-    public SmartherAuthorizationException(String message, Throwable cause) {
+    public SmartherAuthorizationException(@Nullable String message, @Nullable Throwable cause) {
         super(message, cause);
     }
 }
index ca7233f3c5fd4e82e0494add7e0b936940dda062..f235116e50e8b9342447901ad9ebb4516da390cc 100644 (file)
@@ -15,6 +15,7 @@ package org.openhab.binding.bticinosmarther.internal.api.exception;
 import java.io.IOException;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 
 /**
  * Signals that a generic communication issue with API gateway has occurred.
@@ -32,7 +33,7 @@ public class SmartherGatewayException extends IOException {
      * @param message
      *            the error message returned from the API gateway
      */
-    public SmartherGatewayException(String message) {
+    public SmartherGatewayException(@Nullable String message) {
         super(message);
     }
 
@@ -44,7 +45,7 @@ public class SmartherGatewayException extends IOException {
      * @param cause
      *            the cause (a null value is permitted, and indicates that the cause is nonexistent or unknown)
      */
-    public SmartherGatewayException(String message, Throwable cause) {
+    public SmartherGatewayException(@Nullable String message, @Nullable Throwable cause) {
         super(message, cause);
     }
 
@@ -57,7 +58,7 @@ public class SmartherGatewayException extends IOException {
      * @param cause
      *            the cause (a null value is permitted, and indicates that the cause is nonexistent or unknown)
      */
-    public SmartherGatewayException(Throwable cause) {
+    public SmartherGatewayException(@Nullable Throwable cause) {
         super(cause);
     }
 }
index 857a78de62856fdf1252e7c372bd0c7f4c66413c..5ee0f25c601cdfdcb7782b7d1e6543a927a53e60 100644 (file)
@@ -13,6 +13,7 @@
 package org.openhab.binding.bticinosmarther.internal.api.exception;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 
 /**
  * Signals that an "invalid response" messaging issue with API gateway has occurred.
@@ -30,7 +31,7 @@ public class SmartherInvalidResponseException extends SmartherGatewayException {
      * @param message
      *            the error message returned from the API gateway
      */
-    public SmartherInvalidResponseException(String message) {
+    public SmartherInvalidResponseException(@Nullable String message) {
         super(message);
     }
 }
index 4993edc693b350a9d1b0e68a2fe3e2a94f095f03..a1f5cb29c39810bcd9961d502e6db93a6376fcc8 100644 (file)
@@ -17,6 +17,7 @@ import java.time.LocalDateTime;
 import java.time.ZoneId;
 import java.time.ZonedDateTime;
 import java.time.format.DateTimeFormatter;
+import java.time.format.DateTimeParseException;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
 import org.eclipse.jdt.annotation.Nullable;
@@ -45,6 +46,9 @@ public final class DateUtil {
      *             if the string cannot be parsed to a local date
      */
     public static LocalDate parseDate(@Nullable String str, String pattern) {
+        if (str == null) {
+            throw new DateTimeParseException("date string is null", "<null>", 0);
+        }
         DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
         return LocalDate.parse(str, dtf);
     }
@@ -63,6 +67,9 @@ public final class DateUtil {
      *             if the string cannot be parsed to a local date and time
      */
     public static LocalDateTime parseLocalTime(@Nullable String str, String pattern) {
+        if (str == null) {
+            throw new DateTimeParseException("time string is null", "<null>", 0);
+        }
         DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
         return LocalDateTime.parse(str, dtf);
     }
@@ -81,6 +88,9 @@ public final class DateUtil {
      *             if the string cannot be parsed to a date and time with timezone
      */
     public static ZonedDateTime parseZonedTime(@Nullable String str, String pattern) {
+        if (str == null) {
+            throw new DateTimeParseException("zoned string is null", "<null>", 0);
+        }
         DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
         return ZonedDateTime.parse(str, dtf);
     }
index 9a1ca663168745959e731b3397edef2bd096ca66..7dbf6026b2d1f939c1abda0fcf1574b705390a0b 100644 (file)
@@ -13,6 +13,7 @@
 package org.openhab.binding.buienradar.internal.buienradarapi;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 
 /**
  * An exception thrown when a result from Buienradar could not be correctly parsed.
@@ -28,19 +29,19 @@ public class BuienradarParseException extends Exception {
         super();
     }
 
-    public BuienradarParseException(String message) {
+    public BuienradarParseException(@Nullable String message) {
         super(message);
     }
 
-    public BuienradarParseException(Throwable cause) {
+    public BuienradarParseException(@Nullable Throwable cause) {
         super(cause);
     }
 
-    public BuienradarParseException(String message, Throwable cause) {
+    public BuienradarParseException(@Nullable String message, @Nullable Throwable cause) {
         super(message, cause);
     }
 
-    public BuienradarParseException(String message, Throwable cause, boolean enableSuppression,
+    public BuienradarParseException(@Nullable String message, @Nullable Throwable cause, boolean enableSuppression,
             boolean writableStackTrace) {
         super(message, cause, enableSuppression, writableStackTrace);
     }
index 137a0c9570d9967506a140c9c589a921603c9a44..05aa1ab3b37b7b4b7b596ddb297e8eca779d9c38 100644 (file)
@@ -162,7 +162,8 @@ public class BuienradarPredictionAPI implements PredictionAPI {
                 actual = Optional.of(prediction.getActualDateTime());
                 predictions.add(prediction);
             } catch (BuienradarParseException e) {
-                errors.add(e.getMessage());
+                String error = e.getMessage();
+                errors.add(error != null ? error : "null");
             }
         }
         if (!errors.isEmpty()) {
index 86b88123ca0953831faf6395ad402fbe2f8bff3c..a9998d403330620cbd83d979cb31fc92a36de403 100644 (file)
@@ -196,7 +196,7 @@ public class CaddxMessage {
             logger.debug("Message does not contain property [{}]", property);
             return "";
         }
-        return propertyMap.get(property);
+        return propertyMap.getOrDefault(property, "");
     }
 
     public String getPropertyById(String id) {
@@ -204,7 +204,7 @@ public class CaddxMessage {
             logger.debug("Message does not contain id [{}]", id);
             return "";
         }
-        return idMap.get(id);
+        return idMap.getOrDefault(id, "");
     }
 
     public int @Nullable [] getReplyMessageNumbers() {
index 206d23a5583106079f3f0ce02f03446f9c8fa0a6..fecec898c01cc7ffb3c9924c5c3e5003c3285d7e 100644 (file)
@@ -13,6 +13,7 @@
 package org.openhab.binding.darksky.internal.connection;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 
 /**
  * The {@link DarkSkyCommunicationException} is a communication exception for the connections to Dark Sky API.
@@ -36,7 +37,7 @@ public class DarkSkyCommunicationException extends RuntimeException {
      *
      * @param message Detail message
      */
-    public DarkSkyCommunicationException(String message) {
+    public DarkSkyCommunicationException(@Nullable String message) {
         super(message);
     }
 
@@ -45,7 +46,7 @@ public class DarkSkyCommunicationException extends RuntimeException {
      *
      * @param cause The cause
      */
-    public DarkSkyCommunicationException(Throwable cause) {
+    public DarkSkyCommunicationException(@Nullable Throwable cause) {
         super(cause);
     }
 
@@ -55,7 +56,7 @@ public class DarkSkyCommunicationException extends RuntimeException {
      * @param message Detail message
      * @param cause The cause
      */
-    public DarkSkyCommunicationException(String message, Throwable cause) {
+    public DarkSkyCommunicationException(@Nullable String message, @Nullable Throwable cause) {
         super(message, cause);
     }
 }
index 3ffb847051a7822c9cbe3da9b295417dd40752f6..a9370ecf75bc22da459362605f0702f70c374874 100644 (file)
@@ -13,6 +13,7 @@
 package org.openhab.binding.darksky.internal.connection;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 
 /**
  * The {@link DarkSkyConfigurationException} is a configuration exception for the connections to Dark Sky API.
@@ -36,7 +37,7 @@ public class DarkSkyConfigurationException extends IllegalArgumentException {
      *
      * @param message Detail message
      */
-    public DarkSkyConfigurationException(String message) {
+    public DarkSkyConfigurationException(@Nullable String message) {
         super(message);
     }
 
@@ -45,7 +46,7 @@ public class DarkSkyConfigurationException extends IllegalArgumentException {
      *
      * @param cause The cause
      */
-    public DarkSkyConfigurationException(Throwable cause) {
+    public DarkSkyConfigurationException(@Nullable Throwable cause) {
         super(cause);
     }
 
@@ -55,7 +56,7 @@ public class DarkSkyConfigurationException extends IllegalArgumentException {
      * @param message Detail message
      * @param cause The cause
      */
-    public DarkSkyConfigurationException(String message, Throwable cause) {
+    public DarkSkyConfigurationException(@Nullable String message, @Nullable Throwable cause) {
         super(message, cause);
     }
 }
index 5adbe8ce3b9eb828a8f2d0135a992e1f0dcb3cde..5beb05eeef53cb99bb737d58e36eaf5e7c8a5486 100644 (file)
@@ -163,7 +163,7 @@ public class DarkSkyConnection {
     }
 
     private String buildURL(String url, Map<String, String> requestParams) {
-        return requestParams.keySet().stream().map(key -> key + "=" + encodeParam(requestParams.get(key)))
+        return requestParams.entrySet().stream().map(e -> e.getKey() + "=" + encodeParam(e.getValue()))
                 .collect(joining("&", url + "?", ""));
     }
 
index 24983d838759fe1d2971d2048c63b182143d7774..6b966fb246de3ad3dbc659be8ae4340c982e72dc 100644 (file)
@@ -105,8 +105,10 @@ public class LightThingHandler extends DeconzBaseThingHandler<LightMessage> {
                 || thing.getThingTypeUID().equals(THING_TYPE_EXTENDED_COLOR_LIGHT)) {
             try {
                 Map<String, String> properties = thing.getProperties();
-                ctMax = Integer.parseInt(properties.get(PROPERTY_CT_MAX));
-                ctMin = Integer.parseInt(properties.get(PROPERTY_CT_MIN));
+                String ctMaxString = properties.get(PROPERTY_CT_MAX);
+                ctMax = ctMaxString == null ? ZCL_CT_MAX : Integer.parseInt(ctMaxString);
+                String ctMinString = properties.get(PROPERTY_CT_MIN);
+                ctMin = ctMinString == null ? ZCL_CT_MIN : Integer.parseInt(ctMinString);
 
                 // minimum and maximum are inverted due to mired/kelvin conversion!
                 StateDescription stateDescription = StateDescriptionFragmentBuilder.create()
index 6ec5d801072a70b5b83fcb59ce3d3a66c57029e8..ccaa75c3dd83c695a9e1428f4fe40d936708c716 100644 (file)
@@ -1280,22 +1280,27 @@ public class DeviceStatusManagerImpl implements DeviceStatusManager {
 
     @Override
     public void handleEvent(EventItem eventItem) {
-        if (EventNames.DEVICE_SENSOR_VALUE.equals(eventItem.getName())
-                || EventNames.DEVICE_BINARY_INPUT_EVENT.equals(eventItem.getName())) {
-            logger.debug("Detect {} eventItem = {}", eventItem.getName(), eventItem.toString());
-            Device dev = getDeviceOfEvent(eventItem);
-            if (dev != null) {
-                if (EventNames.DEVICE_SENSOR_VALUE.equals(eventItem.getName())) {
-                    dev.setDeviceSensorByEvent(eventItem);
-                } else {
-                    DeviceBinarayInputEnum binaryInputType = DeviceBinarayInputEnum.getdeviceBinarayInput(
-                            Short.parseShort(eventItem.getProperties().get(EventResponseEnum.INPUT_TYPE)));
-                    Short newState = Short.parseShort(eventItem.getProperties().get(EventResponseEnum.INPUT_STATE));
-                    if (binaryInputType != null) {
-                        dev.setBinaryInputState(binaryInputType, newState);
+        try {
+            if (EventNames.DEVICE_SENSOR_VALUE.equals(eventItem.getName())
+                    || EventNames.DEVICE_BINARY_INPUT_EVENT.equals(eventItem.getName())) {
+                logger.debug("Detect {} eventItem = {}", eventItem.getName(), eventItem.toString());
+                Device dev = getDeviceOfEvent(eventItem);
+                if (dev != null) {
+                    if (EventNames.DEVICE_SENSOR_VALUE.equals(eventItem.getName())) {
+                        dev.setDeviceSensorByEvent(eventItem);
+                    } else {
+                        DeviceBinarayInputEnum binaryInputType = DeviceBinarayInputEnum.getdeviceBinarayInput(Short
+                                .parseShort(eventItem.getProperties().getOrDefault(EventResponseEnum.INPUT_TYPE, "")));
+                        Short newState = Short
+                                .parseShort(eventItem.getProperties().getOrDefault(EventResponseEnum.INPUT_STATE, ""));
+                        if (binaryInputType != null) {
+                            dev.setBinaryInputState(binaryInputType, newState);
+                        }
                     }
                 }
             }
+        } catch (NumberFormatException e) {
+            logger.debug("Unexpected missing or invalid number while handling event", e);
         }
     }
 
index 023f98043f0c27f4a884e6105a4ac2727420cb92..9755114890ea7ba0eb44907dba0bd72a90e91e97 100644 (file)
@@ -284,54 +284,64 @@ public class TemperatureControlManager implements EventHandler, TemperatureContr
 
     @Override
     public void handleEvent(EventItem eventItem) {
-        logger.debug("detect event: {}", eventItem.toString());
-        if (eventItem.getName().equals(EventNames.ZONE_SENSOR_VALUE)) {
-            if (zoneTemperationControlListenerMap != null) {
-                if (SensorEnum.ROOM_TEMPERATURE_SET_POINT.getSensorType().toString()
-                        .equals(eventItem.getProperties().get(EventResponseEnum.SENSOR_TYPE))) {
-                    Integer zoneID = Integer.parseInt(eventItem.getSource().get(EventResponseEnum.ZONEID));
-                    if (zoneTemperationControlListenerMap.get(zoneID) != null) {
-                        Float newValue = Float
-                                .parseFloat(eventItem.getProperties().get(EventResponseEnum.SENSOR_VALUE_FLOAT));
-                        if (!isEcho(zoneID, SensorEnum.ROOM_TEMPERATURE_CONTROL_VARIABLE, newValue)) {
-                            zoneTemperationControlListenerMap.get(zoneID).onTargetTemperatureChanged(newValue);
+        try {
+            logger.debug("detect event: {}", eventItem.toString());
+            if (eventItem.getName().equals(EventNames.ZONE_SENSOR_VALUE)) {
+                if (zoneTemperationControlListenerMap != null) {
+                    if (SensorEnum.ROOM_TEMPERATURE_SET_POINT.getSensorType().toString()
+                            .equals(eventItem.getProperties().get(EventResponseEnum.SENSOR_TYPE))) {
+                        Integer zoneID = Integer
+                                .parseInt(eventItem.getSource().getOrDefault(EventResponseEnum.ZONEID, ""));
+                        if (zoneTemperationControlListenerMap.get(zoneID) != null) {
+
+                            Float newValue = Float.parseFloat(
+                                    eventItem.getProperties().getOrDefault(EventResponseEnum.SENSOR_VALUE_FLOAT, ""));
+                            if (!isEcho(zoneID, SensorEnum.ROOM_TEMPERATURE_CONTROL_VARIABLE, newValue)) {
+                                zoneTemperationControlListenerMap.get(zoneID).onTargetTemperatureChanged(newValue);
+                            }
                         }
                     }
-                }
-                if (SensorEnum.ROOM_TEMPERATURE_CONTROL_VARIABLE.getSensorType().toString()
-                        .equals(eventItem.getProperties().get(EventResponseEnum.SENSOR_TYPE))) {
-                    Integer zoneID = Integer.parseInt(eventItem.getSource().get(EventResponseEnum.ZONEID));
-                    if (zoneTemperationControlListenerMap.get(zoneID) != null) {
-                        Float newValue = Float
-                                .parseFloat(eventItem.getProperties().get(EventResponseEnum.SENSOR_VALUE_FLOAT));
-                        if (!isEcho(zoneID, SensorEnum.ROOM_TEMPERATURE_CONTROL_VARIABLE, newValue)) {
-                            zoneTemperationControlListenerMap.get(zoneID).onControlValueChanged(newValue.intValue());
+                    if (SensorEnum.ROOM_TEMPERATURE_CONTROL_VARIABLE.getSensorType().toString()
+                            .equals(eventItem.getProperties().get(EventResponseEnum.SENSOR_TYPE))) {
+                        Integer zoneID = Integer
+                                .parseInt(eventItem.getSource().getOrDefault(EventResponseEnum.ZONEID, ""));
+                        if (zoneTemperationControlListenerMap.get(zoneID) != null) {
+                            Float newValue = Float.parseFloat(
+                                    eventItem.getProperties().getOrDefault(EventResponseEnum.SENSOR_VALUE_FLOAT, ""));
+                            if (!isEcho(zoneID, SensorEnum.ROOM_TEMPERATURE_CONTROL_VARIABLE, newValue)) {
+                                zoneTemperationControlListenerMap.get(zoneID)
+                                        .onControlValueChanged(newValue.intValue());
+                            }
                         }
                     }
                 }
             }
-        }
 
-        if (eventItem.getName().equals(EventNames.HEATING_CONTROL_OPERATION_MODE)) {
-            if (EVALUATE_REAL_ACTIVE_MODE.equals(eventItem.getProperties().get(EventResponseEnum.ACTIONS))) {
-                Integer zoneID = Integer.parseInt(eventItem.getProperties().get(EventResponseEnum.ZONEID));
-                TemperatureControlStatus temperationControlStatus = dSapi
-                        .getZoneTemperatureControlStatus(connectionMananager.getSessionToken(), zoneID, null);
-                if (temperationControlStatus != null) {
-                    addTemperatureControlStatus(temperationControlStatus);
+            if (eventItem.getName().equals(EventNames.HEATING_CONTROL_OPERATION_MODE)) {
+                if (EVALUATE_REAL_ACTIVE_MODE.equals(eventItem.getProperties().get(EventResponseEnum.ACTIONS))) {
+                    Integer zoneID = Integer
+                            .parseInt(eventItem.getProperties().getOrDefault(EventResponseEnum.ZONEID, ""));
+                    TemperatureControlStatus temperationControlStatus = dSapi
+                            .getZoneTemperatureControlStatus(connectionMananager.getSessionToken(), zoneID, null);
+                    if (temperationControlStatus != null) {
+                        addTemperatureControlStatus(temperationControlStatus);
+                    }
                 }
             }
-        }
 
-        if (eventItem.getName().equals(EventNames.STATE_CHANGED)) {
-            if (STATE_NAME_HEATING_WATER_SYSTEM.equals(eventItem.getProperties().get(EventResponseEnum.STATE_NAME))) {
-                currentHeatingWaterSystemStage = eventItem.getProperties().get(EventResponseEnum.STATE);
-                logger.debug("heating water system state changed to {}", currentHeatingWaterSystemStage);
-                if (systemStateChangeListener != null) {
-                    systemStateChangeListener.onSystemStateChanged(STATE_NAME_HEATING_WATER_SYSTEM,
-                            currentHeatingWaterSystemStage);
+            if (eventItem.getName().equals(EventNames.STATE_CHANGED)) {
+                if (STATE_NAME_HEATING_WATER_SYSTEM
+                        .equals(eventItem.getProperties().get(EventResponseEnum.STATE_NAME))) {
+                    currentHeatingWaterSystemStage = eventItem.getProperties().get(EventResponseEnum.STATE);
+                    logger.debug("heating water system state changed to {}", currentHeatingWaterSystemStage);
+                    if (systemStateChangeListener != null) {
+                        systemStateChangeListener.onSystemStateChanged(STATE_NAME_HEATING_WATER_SYSTEM,
+                                currentHeatingWaterSystemStage);
+                    }
                 }
             }
+        } catch (NumberFormatException e) {
+            logger.debug("Unexpected missing or invalid number while handling event", e);
         }
     }
 
index 26f4fdeb4f30019c64932bbbbd3017f002a2a98b..c88356801597bfe1f5a55c786a5c631317f55127 100644 (file)
@@ -87,20 +87,24 @@ public class DeviceSensorValue {
      * Creates a new {@link DeviceSensorValue} through the properties of a digitalSTROM
      * {@link EventNames#DEVICE_SENSOR_VALUE} event.
      *
-     * @param eventPropertie must not be null
+     * @param eventProperties must not be null
      */
-    public DeviceSensorValue(Map<EventResponseEnum, String> eventPropertie) {
-        if (eventPropertie.get(EventResponseEnum.SENSOR_VALUE_FLOAT) != null) {
-            floatValue = Float.parseFloat(eventPropertie.get(EventResponseEnum.SENSOR_VALUE_FLOAT));
+    public DeviceSensorValue(Map<EventResponseEnum, String> eventProperties) {
+        String strVal = eventProperties.get(EventResponseEnum.SENSOR_VALUE_FLOAT);
+        if (strVal != null) {
+            floatValue = Float.parseFloat(strVal);
         }
-        if (eventPropertie.get(EventResponseEnum.SENSOR_TYPE) != null) {
-            sensorType = SensorEnum.getSensor(Short.parseShort(eventPropertie.get(EventResponseEnum.SENSOR_TYPE)));
+        strVal = eventProperties.get(EventResponseEnum.SENSOR_TYPE);
+        if (strVal != null) {
+            sensorType = SensorEnum.getSensor(Short.parseShort(strVal));
         }
-        if (eventPropertie.get(EventResponseEnum.SENSOR_VALUE) != null) {
-            dsValue = Integer.parseInt(eventPropertie.get(EventResponseEnum.SENSOR_VALUE));
+        strVal = eventProperties.get(EventResponseEnum.SENSOR_VALUE);
+        if (strVal != null) {
+            dsValue = Integer.parseInt(strVal);
         }
-        if (eventPropertie.get(EventResponseEnum.SENSOR_INDEX) != null) {
-            sensorIndex = Short.parseShort(eventPropertie.get(EventResponseEnum.SENSOR_INDEX));
+        strVal = eventProperties.get(EventResponseEnum.SENSOR_INDEX);
+        if (strVal != null) {
+            sensorIndex = Short.parseShort(strVal);
         }
         timestamp = Date.from(Instant.ofEpochMilli(System.currentTimeMillis()));
         valid = true;
index 0430fd5e0f0c800c42f3a477e878551d7747d95f..6bafa0b80006ba0479bce89dd1c7ea0da845d4e5 100644 (file)
@@ -13,6 +13,7 @@
 package org.openhab.binding.draytonwiser.internal.api;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 
 /**
  * Exception thrown in case of api problems.
@@ -24,11 +25,11 @@ public class DraytonWiserApiException extends Exception {
 
     private static final long serialVersionUID = 1L;
 
-    public DraytonWiserApiException(final String message) {
+    public DraytonWiserApiException(final @Nullable String message) {
         super(message);
     }
 
-    public DraytonWiserApiException(final String message, final Throwable cause) {
+    public DraytonWiserApiException(final @Nullable String message, final @Nullable Throwable cause) {
         super(message, cause);
     }
 }
index adf1bc6694f3483be81207f35596912dac63fd98..60655d7e9c22d5d473f2be1e698c98e34aa0bd2d 100644 (file)
@@ -106,44 +106,49 @@ public class CosemObjectFactory {
 
         logger.trace("Received obisIdString {}, obisId: {}, values: {}", obisIdString, obisId, cosemStringValues);
 
-        CosemObject cosemObject = null;
-
-        if (obisLookupTableFixed.containsKey(reducedObisId)) {
-            cosemObject = getCosemObjectInternal(obisLookupTableFixed.get(reducedObisId), obisId, cosemStringValues);
+        CosemObjectType objectType = obisLookupTableFixed.get(reducedObisId);
+        if (objectType != null) {
             logger.trace("Found obisId {} in the fixed lookup table", reducedObisId);
-        } else if (obisLookupTableMultipleFixed.containsKey(reducedObisId)) {
-            for (CosemObjectType cosemObjectType : obisLookupTableMultipleFixed.get(reducedObisId)) {
-                cosemObject = getCosemObjectInternal(cosemObjectType, obisId, cosemStringValues);
+            return getCosemObjectInternal(objectType, obisId, cosemStringValues);
+        }
+
+        List<CosemObjectType> objectTypeList = obisLookupTableMultipleFixed.get(reducedObisId);
+        if (objectTypeList != null) {
+            for (CosemObjectType cosemObjectType : objectTypeList) {
+                CosemObject cosemObject = getCosemObjectInternal(cosemObjectType, obisId, cosemStringValues);
                 if (cosemObject != null) {
                     logger.trace("Found obisId {} in the fixed lookup table", reducedObisId);
-                    break;
+                    return cosemObject;
                 }
             }
-        } else if (obisLookupTableDynamic.containsKey(reducedObisId)) {
+        }
+
+        objectType = obisLookupTableDynamic.get(reducedObisId);
+        if (objectType != null) {
             logger.trace("Found obisId {} in the dynamic lookup table", reducedObisId);
-            cosemObject = getCosemObjectInternal(obisLookupTableDynamic.get(reducedObisId), obisId, cosemStringValues);
-        } else if (obisLookupTableFixed.containsKey(reducedObisIdGroupE)) {
-            cosemObject = getCosemObjectInternal(obisLookupTableFixed.get(reducedObisIdGroupE), obisId,
-                    cosemStringValues);
-        } else {
-            for (CosemObjectType obisMsgType : obisWildcardCosemTypeList) {
-                if (obisMsgType.obisId.equalsWildCard(reducedObisId)) {
-                    cosemObject = getCosemObjectInternal(obisMsgType, obisId, cosemStringValues);
-                    if (cosemObject != null) {
-                        logger.trace("Searched reducedObisId {} in the wild card type list, result: {}", reducedObisId,
-                                cosemObject);
-                        obisLookupTableDynamic.put(reducedObisId, obisMsgType);
-                        break;
-                    }
+            return getCosemObjectInternal(objectType, obisId, cosemStringValues);
+        }
+
+        objectType = obisLookupTableFixed.get(reducedObisIdGroupE);
+        if (objectType != null) {
+            return getCosemObjectInternal(objectType, obisId, cosemStringValues);
+        }
+
+        for (CosemObjectType obisMsgType : obisWildcardCosemTypeList) {
+            if (obisMsgType.obisId.equalsWildCard(reducedObisId)) {
+                CosemObject cosemObject = getCosemObjectInternal(obisMsgType, obisId, cosemStringValues);
+                if (cosemObject != null) {
+                    logger.trace("Searched reducedObisId {} in the wild card type list, result: {}", reducedObisId,
+                            cosemObject);
+                    obisLookupTableDynamic.put(reducedObisId, obisMsgType);
+                    return cosemObject;
                 }
             }
         }
 
-        if (cosemObject == null) {
-            logger.debug("Received unknown Cosem Object(OBIS id: {})", obisId);
-        }
+        logger.debug("Received unknown Cosem Object(OBIS id: {})", obisId);
 
-        return cosemObject;
+        return null;
     }
 
     /**
index 45197eeaaf5529a9185f6d3d92d1c4e37bd81adb..18392b1146c35e0ea7c0938b607375bd3302de54 100644 (file)
@@ -147,9 +147,9 @@ public class DSMRMeterDiscoveryService extends DSMRDiscoveryService implements P
                 .map(Thing::getHandler)
                 .filter(DSMRMeterHandler.class::isInstance)
                 .map(DSMRMeterHandler.class::cast)
-                .map(DSMRMeterHandler::getMeterDescriptor)
+                .map(h -> h == null ? null : h.getMeterDescriptor())
+                .map(d -> d == null ? null : d.getMeterType())
                 .filter(Objects::nonNull)
-                .map(h -> h.getMeterType())
                 .collect(Collectors.toSet());
         // @formatter:on
         // Create list of all configured meters that are not in the detected list. If not empty meters might not be
index 816ba8c2102b31793b0a1dd281fa0e7615d206f1..c2a25e6230a06e0e9377c7e4a7ca0ec415a3a744 100644 (file)
@@ -13,6 +13,7 @@
 package org.openhab.binding.enturno.internal.connection;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 
 /**
  * The {@link EnturCommunicationException} is a communication exception for the connections to Entur API.
@@ -24,11 +25,11 @@ public class EnturCommunicationException extends RuntimeException {
 
     private static final long serialVersionUID = 1L;
 
-    public EnturCommunicationException(String message) {
+    public EnturCommunicationException(@Nullable String message) {
         super(message);
     }
 
-    public EnturCommunicationException(String message, Throwable cause) {
+    public EnturCommunicationException(@Nullable String message, @Nullable Throwable cause) {
         super(message, cause);
     }
 }
index aea1bd3607a1fca08baa7f4ad81bc292b080f050..57b7b050d255deec8bae763a23eb5472e0d5fb09 100644 (file)
@@ -422,6 +422,7 @@ public class ExecHandler extends BaseThingHandler {
     }
 
     public static String getOperatingSystemName() {
-        return System.getProperty("os.name");
+        String osname = System.getProperty("os.name");
+        return osname != null ? osname : "unknown";
     }
 }
index 0da89bf057399b89788dcee5d390095dc68b3344..72ddbc4520501c96b284457b47cadf21b4e386fe 100644 (file)
@@ -83,7 +83,7 @@ public class Client {
     }
     private static final NamespaceContext NAMESPACE_CONTEXT = new NamespaceContext() {
         @Override
-        public String getNamespaceURI(@Nullable String prefix) {
+        public @Nullable String getNamespaceURI(@Nullable String prefix) {
             return NAMESPACES.get(prefix);
         }
 
index 999d669ad04cc02b9ca40cb20f655189871e3bdd..9f5d815f7a57edbcb5133b778586ae697a56087e 100644 (file)
@@ -13,6 +13,7 @@
 package org.openhab.binding.foobot.internal;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 
 /**
  * Exception thrown when problems occur with obtaining data for the foobot api.
@@ -24,7 +25,7 @@ public class FoobotApiException extends Exception {
 
     private static final long serialVersionUID = 1L;
 
-    public FoobotApiException(final int status, final String message) {
+    public FoobotApiException(final int status, final @Nullable String message) {
         super(String.format("%s (code: %s)", message, status));
     }
 }
index e21b3ec26b18156762b1180eb85e49398c049656..26498cc44b3cc5c2ea5e79ef63301de9b368d728 100644 (file)
@@ -15,10 +15,7 @@ package org.openhab.binding.foobot.internal.handler;
 import static org.openhab.binding.foobot.internal.FoobotBindingConstants.*;
 
 import java.time.Duration;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
+import java.util.*;
 import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.TimeUnit;
 import java.util.stream.Collectors;
index 73e350a0805b9cc286a3d3903635e6d668176b6a..bccdd4afcc9559f8729afc85d0ac5f06ffc9ee8f 100644 (file)
@@ -35,20 +35,20 @@ public class GreeException extends Exception {
     private static final long serialVersionUID = -2337258558995287405L;
     private static String EX_NONE = "none";
 
-    public GreeException(Exception exception) {
+    public GreeException(@Nullable Exception exception) {
         super(exception);
     }
 
-    public GreeException(String message) {
+    public GreeException(@Nullable String message) {
         super(message);
     }
 
-    public GreeException(String message, Exception exception) {
+    public GreeException(@Nullable String message, @Nullable Exception exception) {
         super(message, exception);
     }
 
     @Override
-    public String getMessage() {
+    public @Nullable String getMessage() {
         return isEmpty() ? "" : nonNullString(super.getMessage());
     }
 
index f72e12473e72af5d3ea11074cba1d11d07d70ddf..582f8ca9a3ca04f62bef3778fd314c496e50c806 100644 (file)
@@ -142,7 +142,7 @@ public class GreeDeviceFinder {
         deviceTable.put(newDevice.getId(), newDevice);
     }
 
-    public GreeAirDevice getDevice(String id) {
+    public @Nullable GreeAirDevice getDevice(String id) {
         return deviceTable.get(id);
     }
 
index 920bfed6dfc54af76fc9d1f2abbd38ec6da452ac..241b3a07009e166486e1539ea1355d6da6518fe2 100644 (file)
@@ -200,7 +200,11 @@ public class HDPowerViewShadeHandler extends AbstractHubbedThingHandler {
     }
 
     private int getShadeId() throws NumberFormatException {
-        return Integer.parseInt(getConfigAs(HDPowerViewShadeConfiguration.class).id);
+        String str = getConfigAs(HDPowerViewShadeConfiguration.class).id;
+        if (str == null) {
+            throw new NumberFormatException("null input string");
+        }
+        return Integer.parseInt(str);
     }
 
     private void stopShade() {
index 199c11cea7c5e177dfa17370eee51e472b0488ae..061f055526d3c0dd302fff924e4ae774d7625751 100644 (file)
@@ -13,6 +13,7 @@
 package org.openhab.binding.heliosventilation.internal;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 
 /**
  * The {@link HeliosPropertiesFormatException} class defines an exception to describe parsing format errors
@@ -41,7 +42,7 @@ public class HeliosPropertiesFormatException extends Exception {
     }
 
     @Override
-    public String getMessage() {
+    public @Nullable String getMessage() {
         return "Cannot parse '" + fullSpec + "' for datapoint '" + channelName + "': " + reason;
     }
 }
index 19f271399fd7c467f3a213ad2efbff26f068d01e..6f162e71936284a8dae707bd9dd1c0dffef9fb96 100644 (file)
@@ -27,10 +27,10 @@ public class HPServerResult<result> {
     private final @Nullable result data;
     private final String errorMessage;
 
-    public HPServerResult(RequestStatus status, String errorMessage) {
+    public HPServerResult(RequestStatus status, @Nullable String errorMessage) {
         this.status = status;
         this.data = null;
-        this.errorMessage = errorMessage;
+        this.errorMessage = errorMessage != null ? errorMessage : "";
     }
 
     public HPServerResult(result data) {
index b13231dd9995335b4ff0642dbffe4f2eaaa7fb56..9f981232d2e4a8f403d17f0d25ee25222b9ce010 100644 (file)
@@ -221,9 +221,12 @@ public class HueBridge {
         ArrayList<T> lightList = new ArrayList<>();
 
         for (String id : lightMap.keySet()) {
+            @Nullable
             T light = lightMap.get(id);
-            light.setId(id);
-            lightList.add(light);
+            if (light != null) {
+                light.setId(id);
+                lightList.add(light);
+            }
         }
 
         return lightList;
index 7a2b058870fe965a5b509c0428df3fc7407cc373..c2a1c29d3877776c083146ad1644232438d1b75d 100644 (file)
@@ -144,7 +144,8 @@ public class Scene {
         if (getGroupId() == null) {
             return getLightIds().stream().allMatch(id -> group.getLightIds().contains(id));
         } else {
-            return group.getId().contentEquals(getGroupId());
+            String groupId = getGroupId();
+            return groupId != null ? group.getId().contentEquals(groupId) : false;
         }
     }
 
index fd68904a9e0baf8d09561d819c3d9c09f0811d58..9ef73b4b82d68dae76685c262de5420c3404d014 100644 (file)
@@ -186,7 +186,7 @@ public class DeviceStructureManager {
      *
      * @return
      */
-    public Device getBridgeDevice() {
+    public @Nullable Device getBridgeDevice() {
         return getDeviceMap().get(bridgeDeviceId);
     }
 
index 272856b07ca20e6367aa391f3114ff7b3d15f684..005ee9df8a55d6784d34faba9d6aeb15f9b409fe 100644 (file)
@@ -291,8 +291,8 @@ public abstract class CommandHandler {
         }
 
         private int getRampLevel(InsteonChannelConfiguration conf, int defaultValue) {
-            Map<String, @Nullable String> params = conf.getParameters();
-            return params.containsKey("ramplevel") ? Integer.parseInt(params.get("ramplevel")) : defaultValue;
+            String str = conf.getParameters().get("ramplevel");
+            return str != null ? Integer.parseInt(str) : defaultValue;
         }
     }
 
@@ -642,8 +642,8 @@ public abstract class CommandHandler {
         }
 
         protected double getRampTime(InsteonChannelConfiguration conf, double defaultValue) {
-            Map<String, @Nullable String> params = conf.getParameters();
-            return params.containsKey("ramptime") ? Double.parseDouble(params.get("ramptime")) : defaultValue;
+            String str = conf.getParameters().get("ramptime");
+            return str != null ? Double.parseDouble(str) : defaultValue;
         }
     }
 
index 630cc75602c0abe140f0a584ece05a34b86d796c..c7095e226f65fb559162f27d544908da087f9b1e 100644 (file)
@@ -159,9 +159,8 @@ public abstract class MessageHandler {
      */
     protected double getDoubleParameter(String key, double def) {
         try {
-            if (parameters.get(key) != null) {
-                return Double.parseDouble(parameters.get(key));
-            }
+            String str = parameters.get(key);
+            return str != null ? Double.parseDouble(str) : def;
         } catch (NumberFormatException e) {
             logger.warn("malformed int parameter in message handler: {}", key);
         }
index bf59b6e445aa7f773af7171b2c5f784758885656..ad6adcd31c01276901f66baa5f90dee7ae891f0a 100644 (file)
@@ -102,7 +102,9 @@ public class ReadByteBuffer {
         }
 
         int b = Math.min(len, remaining());
-        System.arraycopy(buf, index, bytes, off, b);
+        if (bytes != null) {
+            System.arraycopy(buf, index, bytes, off, b);
+        }
         index += b;
         return b;
     }
index 67767228132827f456078e493f3d4358324bd3e4..fdc73156570c50b763a86d7c7f5781896e9dc855 100644 (file)
@@ -280,12 +280,13 @@ public class Msg {
      * @param len the length to copy from the src byte array
      */
     private void initialize(byte[] newData, int offset, int len) {
-        data = new byte[len];
+        byte[] data = new byte[len];
         if (offset >= 0 && offset < newData.length) {
             System.arraycopy(newData, offset, data, 0, len);
         } else {
             logger.warn("intialize(): Offset out of bounds!");
         }
+        this.data = data;
     }
 
     /**
@@ -344,7 +345,10 @@ public class Msg {
             throw new FieldException("data index out of bounds!");
         }
         byte[] section = new byte[numBytes];
-        System.arraycopy(data, offset, section, 0, numBytes);
+        byte[] data = this.data;
+        if (data != null) {
+            System.arraycopy(data, offset, section, 0, numBytes);
+        }
         return section;
     }
 
index 87ff54736358ff8d3de43bb5106f84a3c9b2f6a6..06b4dceff514e0ea9a78ec008308791ff2fd18d5 100644 (file)
@@ -18,6 +18,7 @@ import java.util.HashMap;
 import java.util.Map;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 import org.openhab.core.thing.Channel;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -35,8 +36,8 @@ public class KM200Utils {
      * Translates a service name to a service path (Replaces # through /)
      *
      */
-    public static String translatesNameToPath(String name) {
-        return name.replace("#", "/");
+    public static @Nullable String translatesNameToPath(@Nullable String name) {
+        return name == null ? null : name.replace("#", "/");
     }
 
     /**
index caa2b8c993ffbe556ff4a3324e7cfb0f29d982d3..3f993cda511a3bb5529284281d473b41250d36c0 100644 (file)
@@ -436,10 +436,10 @@ public class KM200GatewayHandler extends BaseBridgeHandler {
                     if (null != tmpSerObjekt) {
                         if (parent == null || parent.equals(tmpSerObjekt.getParent())) {
                             synchronized (sendMap) {
-                                if (sendMap.containsKey(actChannel)) {
-                                    state = dataHandler.parseJSONData(sendMap.get(actChannel),
-                                            tmpSerObjekt.getServiceType(), tmpService, actChTypes,
-                                            KM200Utils.getChannelConfigurationStrings(actChannel));
+                                JsonObject obj = sendMap.get(actChannel);
+                                if (obj != null) {
+                                    state = dataHandler.parseJSONData(obj, tmpSerObjekt.getServiceType(), tmpService,
+                                            actChTypes, KM200Utils.getChannelConfigurationStrings(actChannel));
                                 } else {
                                     state = dataHandler.getProvidersState(tmpService, actChTypes,
                                             KM200Utils.getChannelConfigurationStrings(actChannel));
@@ -548,10 +548,10 @@ public class KM200GatewayHandler extends BaseBridgeHandler {
                             synchronized (sendMap) {
                                 KM200ServiceObject serObjekt = remoteDevice.getServiceObject(service);
                                 if (null != serObjekt) {
-                                    if (sendMap.containsKey(channel)) {
-                                        state = dataHandler.parseJSONData(sendMap.get(channel),
-                                                serObjekt.getServiceType(), service, chTypes,
-                                                KM200Utils.getChannelConfigurationStrings(channel));
+                                    JsonObject obj = sendMap.get(channel);
+                                    if (obj != null) {
+                                        state = dataHandler.parseJSONData(obj, serObjekt.getServiceType(), service,
+                                                chTypes, KM200Utils.getChannelConfigurationStrings(channel));
                                     } else {
                                         state = dataHandler.getProvidersState(service, chTypes,
                                                 KM200Utils.getChannelConfigurationStrings(channel));
index e6c81aac304b4d21614da63e5a8c037e25df579b..98b330aae9b61dbee8c1546bdb5d10c8d2cffc92 100644 (file)
@@ -467,7 +467,10 @@ public class KM200ThingHandler extends BaseThingHandler {
                         continue;
                     }
                     /* Search for new services in sub path */
-                    addChannels(serObj.serviceTreeMap.get(subKey), thing, subChannels, subKey + "_");
+                    KM200ServiceObject obj = serObj.serviceTreeMap.get(subKey);
+                    if (obj != null) {
+                        addChannels(obj, thing, subChannels, subKey + "_");
+                    }
                     break;
                 case DATA_TYPE_ERROR_LIST:
                     if ("nbrErrors".equals(subKey) || "error".equals(subKey)) {
index 863a9518f360f16a1c21906f125a92aa74ca909b..00bce0df74e79c51af83ada3fb86db0e74a9ba20 100644 (file)
@@ -213,8 +213,9 @@ public abstract class AbstractKNXClient implements NetworkLinkListener, KNXClien
     private void disconnect(@Nullable Exception e) {
         releaseConnection();
         if (e != null) {
+            String message = e.getLocalizedMessage();
             statusUpdateCallback.updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
-                    e.getLocalizedMessage());
+                    message != null ? message : "");
         } else {
             statusUpdateCallback.updateStatus(ThingStatus.OFFLINE);
         }
index 94567023da142881c87b08daea50b8d76070ed19..49d066f8f1ef4af6e0f45808aa4a2974a304de02 100644 (file)
@@ -92,9 +92,10 @@ public class KostalInverterFactory extends BaseThingHandlerFactory {
             return new WebscrapeHandler(thing);
         }
         // third generation
-        if (SUPPORTED_THIRD_GENERATION_THING_TYPES_UIDS.containsKey(thing.getThingTypeUID())) {
-            return new ThirdGenerationHandler(thing, httpClient,
-                    SUPPORTED_THIRD_GENERATION_THING_TYPES_UIDS.get(thing.getThingTypeUID()));
+        ThirdGenerationInverterTypes inverterType = SUPPORTED_THIRD_GENERATION_THING_TYPES_UIDS
+                .get(thing.getThingTypeUID());
+        if (inverterType != null) {
+            return new ThirdGenerationHandler(thing, httpClient, inverterType);
         }
         return null;
     }
index 9e83f7ffeaa3b008fef8c080bb02444203670f6f..559778faa9d84329fbd2e18514028eaa47947089 100644 (file)
@@ -75,7 +75,8 @@ public class ConnectionStateMachine extends AbstractStateMachine<ConnectionState
     public void handleConnectionFailed(@Nullable Throwable e) {
         if (!(state instanceof ConnectionStateShutdown)) {
             if (e != null) {
-                connection.getCallback().onOffline(e.getMessage());
+                String message = e.getMessage();
+                connection.getCallback().onOffline(message != null ? message : "");
             } else {
                 connection.getCallback().onOffline("");
             }
index e360b6cae39e996f2b458a81c782c11e0eaf1fba..c4e36e70b1d67bd9d80826ccf3767447e4cf7951 100644 (file)
@@ -134,7 +134,8 @@ public class LGWebOSTVMouseSocket {
 
     @OnWebSocketError
     public void onError(Throwable cause) {
-        Optional.ofNullable(this.listener).ifPresent(l -> l.onError(cause.getMessage()));
+        String message = cause.getMessage();
+        Optional.ofNullable(this.listener).ifPresent(l -> l.onError(message != null ? message : ""));
         logger.debug("Connection Error.", cause);
     }
 
index a619750f6505a2f7d36cb7ee8c1b873eb70a779a..adb9eb652d249ff5ace33753dacc4876bb252682 100644 (file)
@@ -243,7 +243,8 @@ public class LGWebOSTVSocket {
             return;
         }
 
-        Optional.ofNullable(this.listener).ifPresent(l -> l.onError(cause.getMessage()));
+        String message = cause.getMessage();
+        Optional.ofNullable(this.listener).ifPresent(l -> l.onError(message != null ? message : ""));
     }
 
     @OnWebSocketClose
index ba656ec64166f992788a66884d7e5203be2e50e6..01fd10031e6b24c9863e6aaa0414dcad5d09dca7 100644 (file)
@@ -17,6 +17,7 @@ import java.net.HttpCookie;
 import java.net.URI;
 import java.time.LocalDate;
 import java.time.format.DateTimeFormatter;
+import java.util.Objects;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.TimeoutException;
 import java.util.regex.Matcher;
@@ -125,8 +126,8 @@ public class EnedisHttpApi {
 
             AuthData authData = gson.fromJson(result.getContentAsString(), AuthData.class);
             if (authData.callbacks.size() < 2 || authData.callbacks.get(0).input.size() == 0
-                    || authData.callbacks.get(1).input.size() == 0
-                    || !config.username.contentEquals(authData.callbacks.get(0).input.get(0).valueAsString())) {
+                    || authData.callbacks.get(1).input.size() == 0 || !config.username
+                            .equals(Objects.requireNonNull(authData.callbacks.get(0).input.get(0)).valueAsString())) {
                 throw new LinkyException("Authentication error, the authentication_cookie is probably wrong");
             }
 
index 6b061e894ac411cd80293afd0f1123e1c8b6b80d..9ed8377d3fc7db559555b5b5116c09f8f114c894 100644 (file)
@@ -36,7 +36,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * The {@link LogReaderHandler} is responsible for handling commands, which are
+ * The {@link LogHandler} is responsible for handling commands, which are
  * sent to one of the channels.
  *
  * @author Miika Jukka - Initial contribution
@@ -80,10 +80,15 @@ public class LogHandler extends BaseThingHandler implements FileReaderListener {
 
     @Override
     public void initialize() {
-        configuration = getConfigAs(LogReaderConfiguration.class);
+        String logDir = System.getProperty("openhab.logdir");
+        if (logDir == null) {
+            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
+                    "Cannot determine system log directory.");
+            return;
+        }
 
-        configuration.filePath = configuration.filePath.replaceFirst("\\$\\{OPENHAB_LOGDIR\\}",
-                System.getProperty("openhab.logdir"));
+        configuration = getConfigAs(LogReaderConfiguration.class);
+        configuration.filePath = configuration.filePath.replaceFirst("\\$\\{OPENHAB_LOGDIR\\}", logDir);
 
         logger.debug("Using configuration: {}", configuration);
 
index 0ff1b3d48002db763427f8d642359f64a55e8426..4a0ea241ff260282aa156a1f33f050564369e2cc 100644 (file)
@@ -531,8 +531,17 @@ public class LxServerHandler extends BaseThingHandler implements LxServerHandler
             channels.addAll(getThing().getChannels());
         }
         channels.sort((c1, c2) -> {
-            String label = c1.getLabel();
-            return label == null ? 1 : label.compareTo(c2.getLabel());
+            String label1 = c1.getLabel();
+            String label2 = c2.getLabel();
+            if (label1 == null && label2 != null) {
+                return 1;
+            } else if (label1 != null && label2 == null) {
+                return -1;
+            } else if (label1 == null && label2 == null) {
+                return 0;
+            } else {
+                return label1.compareTo(label2);
+            }
         });
         ThingBuilder builder = editThing();
         builder.withChannels(channels);
index 5de503156c1a542ade55dac1930adfd5cf3b61fc..9e39694b46ac5f8d71c79408ab8dae06302347d8 100644 (file)
@@ -50,7 +50,11 @@ public class DbXmlInfoReader {
         xstream = new XStream(driver);
 
         configureSecurity(xstream);
-        setClassLoader(Project.class.getClassLoader());
+        ClassLoader classLoader = Project.class.getClassLoader();
+        if (classLoader == null) {
+            throw new UnknownError("Cannot find classloader");
+        }
+        setClassLoader(classLoader);
         registerAliases(xstream);
     }
 
index d77438a38958a0c3604c25ae3dc77f334886b8c8..e29a41fb5342feaec367e08278225428c149aa03 100644 (file)
@@ -63,12 +63,13 @@ public class MeteoAlerteHandler extends BaseThingHandler {
             + "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=";
     private static final int TIMEOUT_MS = 30000;
+    private static final String UNKNOWN_COLOR = "b3b3b3";
     private static final Map<AlertLevel, String> ALERT_COLORS = Map.ofEntries(
             new AbstractMap.SimpleEntry<AlertLevel, String>(AlertLevel.GREEN, "00ff00"),
             new AbstractMap.SimpleEntry<AlertLevel, String>(AlertLevel.YELLOW, "ffff00"),
             new AbstractMap.SimpleEntry<AlertLevel, String>(AlertLevel.ORANGE, "ff6600"),
             new AbstractMap.SimpleEntry<AlertLevel, String>(AlertLevel.RED, "ff0000"),
-            new AbstractMap.SimpleEntry<AlertLevel, String>(AlertLevel.UNKNOWN, "b3b3b3"));
+            new AbstractMap.SimpleEntry<AlertLevel, String>(AlertLevel.UNKNOWN, UNKNOWN_COLOR));
 
     private final Logger logger = LoggerFactory.getLogger(MeteoAlerteHandler.class);
     // Time zone provider representing time zone configured in openHAB configuration
@@ -169,7 +170,7 @@ public class MeteoAlerteHandler extends BaseThingHandler {
         if (isLinked(channelIcon)) {
             String resource = getResource(String.format("picto/%s.svg", channelId));
             if (resource != null) {
-                resource = resource.replaceAll(ALERT_COLORS.get(AlertLevel.UNKNOWN), ALERT_COLORS.get(value));
+                resource = resource.replaceAll(UNKNOWN_COLOR, ALERT_COLORS.getOrDefault(value, UNKNOWN_COLOR));
             }
             updateState(channelIcon,
                     resource != null ? new RawType(resource.getBytes(), "image/svg+xml") : UnDefType.UNDEF);
index adf1663c56dd8acbb4e78916a1fdc9b47167187e..54a5757462b431933dd801cdb64b05d411c0cbf8 100644 (file)
@@ -13,6 +13,7 @@
 package org.openhab.binding.miio.internal;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 
 /**
  * Will be thrown instead of the many possible errors in the crypto module
@@ -31,11 +32,11 @@ public class MiIoCryptoException extends Exception {
         super();
     }
 
-    public MiIoCryptoException(String message) {
+    public MiIoCryptoException(@Nullable String message) {
         super(message);
     }
 
-    public MiIoCryptoException(String message, Exception e) {
+    public MiIoCryptoException(@Nullable String message, @Nullable Exception e) {
         super(message, e);
     }
 }
index 8436c1b51456dbe8d33059f6d948ad730ea5d365..69016b16f0287b3f258e6ea4583542f54d03e28d 100644 (file)
@@ -13,6 +13,7 @@
 package org.openhab.binding.miio.internal.cloud;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 
 /**
  * Will be thrown for cloud errors
@@ -30,11 +31,11 @@ public class MiCloudException extends Exception {
         super();
     }
 
-    public MiCloudException(String message) {
+    public MiCloudException(@Nullable String message) {
         super(message);
     }
 
-    public MiCloudException(String message, Exception e) {
+    public MiCloudException(@Nullable String message, @Nullable Exception e) {
         super(message, e);
     }
 }
index 0edcd422cfb4d5d2f1bd76603dccaf66cf0b8a5d..891e43a23ae705699741068bd6fa6ed1c4fc31d1 100644 (file)
@@ -278,8 +278,9 @@ public abstract class MiIoAbstractHandler extends BaseThingHandler implements Mi
         disconnected("No Response from device");
     }
 
-    protected void disconnected(String message) {
-        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, message);
+    protected void disconnected(@Nullable String message) {
+        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
+                message != null ? message : "");
         final MiIoAsyncCommunication miioCom = this.miioCom;
         if (miioCom != null) {
             lastId = miioCom.getId();
index a26cd99d05baf42d896a2d63c2aa87abc576dea0..095d06bb0d581beb4c8db19e857b44d43a70b2cd 100644 (file)
@@ -28,6 +28,7 @@ import java.util.Map;
 import java.util.zip.GZIPInputStream;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 import org.openhab.binding.miio.internal.Utils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -358,7 +359,11 @@ public class RRMapFileParser {
         return sw.toString();
     }
 
-    private void printAreaDetails(ArrayList<float[]> areas, PrintWriter pw) {
+    private void printAreaDetails(@Nullable ArrayList<float[]> areas, PrintWriter pw) {
+        if (areas == null) {
+            pw.println("null");
+            return;
+        }
         areas.forEach(area -> {
             pw.print("\tArea coordinates:");
             for (int i = 0; i < area.length; i++) {
@@ -368,7 +373,11 @@ public class RRMapFileParser {
         });
     }
 
-    private void printObstacleDetails(ArrayList<int[]> obstacle, PrintWriter pw) {
+    private void printObstacleDetails(@Nullable ArrayList<int[]> obstacle, PrintWriter pw) {
+        if (obstacle == null) {
+            pw.println("null");
+            return;
+        }
         obstacle.forEach(area -> {
             pw.print("\tObstacle coordinates:");
             for (int i = 0; i < area.length; i++) {
index 6cbafdeee7a298003d70c58e5b90cedb00d07fd9..a32f879152b4f67cc5d893d01eaf5abd8a0e3c9b 100644 (file)
@@ -196,7 +196,7 @@ public class MilightV6SessionManager implements Runnable, Closeable {
     public CompletableFuture<DatagramSocket> start() {
         if (willbeclosed) {
             CompletableFuture<DatagramSocket> f = new CompletableFuture<>();
-            f.completeExceptionally(null);
+            f.completeExceptionally(new IllegalStateException("will be closed"));
             return f;
         }
         if (sessionThread.isAlive()) {
index d77d146ca7f59106e17b64e055c79f51f227839e..4d0da544e1dd00d38d41d5454b2b3bd274c711cc 100644 (file)
@@ -339,8 +339,11 @@ public class HeliosEasyControlsHandler extends BaseThingHandler {
                     try {
                         writeValue(channelId, v);
                         if (variableMap != null) {
-                            updateState(variableMap.get(channelId), v);
-                            updateStatus(ThingStatus.ONLINE);
+                            HeliosVariable variable = variableMap.get(channelId);
+                            if (variable != null) {
+                                updateState(variable, v);
+                                updateStatus(ThingStatus.ONLINE);
+                            }
                         }
                     } catch (HeliosException e) {
                         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
index a17e0b3d11ca09554983156ab04f51f8fb799889..3a0d97412f2c1e49f86afbd46694eca9247c5bdb 100644 (file)
@@ -18,6 +18,8 @@ import java.util.ArrayList;
 import java.util.Optional;
 import java.util.Set;
 
+import javax.measure.Unit;
+
 import org.eclipse.jdt.annotation.NonNullByDefault;
 import org.eclipse.jdt.annotation.Nullable;
 import org.openhab.binding.modbus.handler.ModbusEndpointThingHandler;
@@ -38,6 +40,7 @@ import org.openhab.core.thing.ThingTypeUID;
 import org.openhab.core.thing.binding.BaseThingHandler;
 import org.openhab.core.thing.binding.ThingHandler;
 import org.openhab.core.types.Command;
+import org.openhab.core.types.State;
 import org.openhab.core.types.UnDefType;
 import org.openhab.io.transport.modbus.AsyncModbusFailure;
 import org.openhab.io.transport.modbus.ModbusCommunicationInterface;
@@ -304,8 +307,10 @@ public class StuderHandler extends BaseThingHandler {
         Float quantity = parser.hexToFloat(hexString);
         if (quantity != null) {
             if (type.equals(THING_TYPE_BSP)) {
-                updateState(CHANNELS_BSP.get(registerNumber),
-                        new QuantityType<>(quantity, UNIT_CHANNELS_BSP.get(registerNumber)));
+                Unit<?> unit = UNIT_CHANNELS_BSP.get(registerNumber);
+                if (unit != null) {
+                    internalUpdateState(CHANNELS_BSP.get(registerNumber), new QuantityType<>(quantity, unit));
+                }
             } else if (type.equals(THING_TYPE_XTENDER)) {
                 handlePolledDataXtender(registerNumber, quantity);
             } else if (type.equals(THING_TYPE_VARIOTRACK)) {
@@ -329,18 +334,20 @@ public class StuderHandler extends BaseThingHandler {
             case CHANNEL_PV2_OPERATING_MODE:
                 VSMode vsmode = StuderParser.getVSModeByCode(quantity.intValue());
                 if (vsmode == VSMode.UNKNOWN) {
-                    updateState(CHANNELS_VARIOSTRING.get(registerNumber), UnDefType.UNDEF);
+                    internalUpdateState(CHANNELS_VARIOSTRING.get(registerNumber), UnDefType.UNDEF);
                 } else {
-                    updateState(CHANNELS_VARIOSTRING.get(registerNumber), new StringType(vsmode.name()));
+                    internalUpdateState(CHANNELS_VARIOSTRING.get(registerNumber), new StringType(vsmode.name()));
                 }
                 break;
             case CHANNEL_STATE_VARIOSTRING:
                 OnOffType vsstate = StuderParser.getStateByCode(quantity.intValue());
-                updateState(CHANNELS_VARIOSTRING.get(registerNumber), vsstate);
+                internalUpdateState(CHANNELS_VARIOSTRING.get(registerNumber), vsstate);
                 break;
             default:
-                updateState(CHANNELS_VARIOSTRING.get(registerNumber),
-                        new QuantityType<>(quantity, UNIT_CHANNELS_VARIOSTRING.get(registerNumber)));
+                Unit<?> unit = UNIT_CHANNELS_VARIOSTRING.get(registerNumber);
+                if (unit != null) {
+                    internalUpdateState(CHANNELS_VARIOSTRING.get(registerNumber), new QuantityType<>(quantity, unit));
+                }
         }
     }
 
@@ -354,28 +361,30 @@ public class StuderHandler extends BaseThingHandler {
             case CHANNEL_MODEL_VARIOTRACK:
                 VTType type = StuderParser.getVTTypeByCode(quantity.intValue());
                 if (type == VTType.UNKNOWN) {
-                    updateState(CHANNELS_VARIOTRACK.get(registerNumber), UnDefType.UNDEF);
+                    internalUpdateState(CHANNELS_VARIOTRACK.get(registerNumber), UnDefType.UNDEF);
                 } else {
-                    updateState(CHANNELS_VARIOTRACK.get(registerNumber), new StringType(type.name()));
+                    internalUpdateState(CHANNELS_VARIOTRACK.get(registerNumber), new StringType(type.name()));
                 }
                 break;
 
             case CHANNEL_OPERATING_MODE:
                 VTMode vtmode = StuderParser.getVTModeByCode(quantity.intValue());
                 if (vtmode == VTMode.UNKNOWN) {
-                    updateState(CHANNELS_VARIOTRACK.get(registerNumber), UnDefType.UNDEF);
+                    internalUpdateState(CHANNELS_VARIOTRACK.get(registerNumber), UnDefType.UNDEF);
                 } else {
-                    updateState(CHANNELS_VARIOTRACK.get(registerNumber), new StringType(vtmode.name()));
+                    internalUpdateState(CHANNELS_VARIOTRACK.get(registerNumber), new StringType(vtmode.name()));
                 }
                 break;
 
             case CHANNEL_STATE_VARIOTRACK:
                 OnOffType vtstate = StuderParser.getStateByCode(quantity.intValue());
-                updateState(CHANNELS_VARIOTRACK.get(registerNumber), vtstate);
+                internalUpdateState(CHANNELS_VARIOTRACK.get(registerNumber), vtstate);
                 break;
             default:
-                updateState(CHANNELS_VARIOTRACK.get(registerNumber),
-                        new QuantityType<>(quantity, UNIT_CHANNELS_VARIOTRACK.get(registerNumber)));
+                Unit<?> unit = UNIT_CHANNELS_VARIOTRACK.get(registerNumber);
+                if (unit != null) {
+                    internalUpdateState(CHANNELS_VARIOTRACK.get(registerNumber), new QuantityType<>(quantity, unit));
+                }
         }
     }
 
@@ -389,18 +398,20 @@ public class StuderHandler extends BaseThingHandler {
             case CHANNEL_OPERATING_STATE:
                 ModeXtender mode = StuderParser.getModeXtenderByCode(quantity.intValue());
                 if (mode == ModeXtender.UNKNOWN) {
-                    updateState(CHANNELS_XTENDER.get(registerNumber), UnDefType.UNDEF);
+                    internalUpdateState(CHANNELS_XTENDER.get(registerNumber), UnDefType.UNDEF);
                 } else {
-                    updateState(CHANNELS_XTENDER.get(registerNumber), new StringType(mode.name()));
+                    internalUpdateState(CHANNELS_XTENDER.get(registerNumber), new StringType(mode.name()));
                 }
                 break;
             case CHANNEL_STATE_INVERTER:
                 OnOffType xtstate = StuderParser.getStateByCode(quantity.intValue());
-                updateState(CHANNELS_XTENDER.get(registerNumber), xtstate);
+                internalUpdateState(CHANNELS_XTENDER.get(registerNumber), xtstate);
                 break;
             default:
-                updateState(CHANNELS_XTENDER.get(registerNumber),
-                        new QuantityType<>(quantity, UNIT_CHANNELS_XTENDER.get(registerNumber)));
+                Unit<?> unit = UNIT_CHANNELS_XTENDER.get(registerNumber);
+                if (unit != null) {
+                    internalUpdateState(CHANNELS_XTENDER.get(registerNumber), new QuantityType<>(quantity, unit));
+                }
         }
     }
 
@@ -439,4 +450,10 @@ public class StuderHandler extends BaseThingHandler {
             updateStatus(ThingStatus.ONLINE);
         }
     }
+
+    protected void internalUpdateState(@Nullable String channelUID, @Nullable State state) {
+        if (channelUID != null && state != null) {
+            super.updateState(channelUID, state);
+        }
+    }
 }
index 2a486c41d491a00a1baff15b9eeefb6a9c028155..8627133e3e08b66999e47238f9a74e59e636cd25 100644 (file)
@@ -31,6 +31,7 @@ import org.openhab.binding.modbus.sunspec.internal.parser.CommonModelParser;
 import org.openhab.core.config.discovery.DiscoveryResult;
 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
 import org.openhab.core.library.types.DecimalType;
+import org.openhab.core.thing.ThingTypeUID;
 import org.openhab.core.thing.ThingUID;
 import org.openhab.io.transport.modbus.AsyncModbusFailure;
 import org.openhab.io.transport.modbus.ModbusBitUtilities;
@@ -282,8 +283,12 @@ public class SunspecDiscoveryProcess {
             return;
         }
 
-        ThingUID thingUID = new ThingUID(SUPPORTED_THING_TYPES_UIDS.get(block.moduleID), handler.getUID(),
-                Integer.toString(block.address));
+        ThingTypeUID thingTypeUID = SUPPORTED_THING_TYPES_UIDS.get(block.moduleID);
+        if (thingTypeUID == null) {
+            logger.warn("Found model block but no corresponding thing type UID present: {}", block.moduleID);
+            return;
+        }
+        ThingUID thingUID = new ThingUID(thingTypeUID, handler.getUID(), Integer.toString(block.address));
 
         Map<String, Object> properties = new HashMap<>();
         properties.put(PROPERTY_VENDOR, commonBlock.manufacturer);
index a9401ae3d74b793adab723a1e005d9c37f3a749e..2f720ba5a7c7ef608be2a825cc8650700a400618 100644 (file)
@@ -171,8 +171,8 @@ public abstract class AbstractSunSpecHandler extends BaseThingHandler {
         }
         try {
             ModelBlock block = new ModelBlock();
-            block.address = (int) Double.parseDouble(thing.getProperties().get(PROPERTY_BLOCK_ADDRESS));
-            block.length = (int) Double.parseDouble(thing.getProperties().get(PROPERTY_BLOCK_LENGTH));
+            block.address = (int) Double.parseDouble(thing.getProperties().getOrDefault(PROPERTY_BLOCK_ADDRESS, ""));
+            block.length = (int) Double.parseDouble(thing.getProperties().getOrDefault(PROPERTY_BLOCK_LENGTH, ""));
             return block;
         } catch (NumberFormatException ex) {
             logger.debug("Could not parse address and length properties, error: {}", ex.getMessage());
index b781ffbdfe66616be7e409048d12f1a78699f512..c2106041d6c2225f89f08d34d75d5acf40fa3c9c 100644 (file)
@@ -255,7 +255,12 @@ public class MonopriceAudioHandler extends BaseThingHandler implements Monoprice
             }
 
             if (command instanceof RefreshType) {
-                updateChannelState(zone, channelType, zoneDataMap.get(zone.getZoneId()));
+                MonopriceAudioZoneDTO zoneDTO = zoneDataMap.get(zone.getZoneId());
+                if (zoneDTO != null) {
+                    updateChannelState(zone, channelType, zoneDTO);
+                } else {
+                    logger.info("Could not execute REFRESH command for zone {}: null", zone.getZoneId());
+                }
                 return;
             }
 
@@ -462,12 +467,12 @@ public class MonopriceAudioHandler extends BaseThingHandler implements Monoprice
 
                 case MonopriceAudioConnector.KEY_ZONE_UPDATE:
                     String zoneId = updateData.substring(0, 2);
-
-                    if (MonopriceAudioZone.VALID_ZONE_IDS.contains(zoneId)) {
+                    MonopriceAudioZoneDTO zoneDTO = zoneDataMap.get(zoneId);
+                    if (MonopriceAudioZone.VALID_ZONE_IDS.contains(zoneId) && zoneDTO != null) {
                         MonopriceAudioZone targetZone = MonopriceAudioZone.fromZoneId(zoneId);
-                        processZoneUpdate(targetZone, zoneDataMap.get(zoneId), updateData);
+                        processZoneUpdate(targetZone, zoneDTO, updateData);
                     } else {
-                        logger.warn("invalid event: {} for key: {}", evt.getValue(), key);
+                        logger.warn("invalid event: {} for key: {} or zone data null", evt.getValue(), key);
                     }
                     break;
                 default:
index 93edfc1c3d16a4cffd58e30f69e4d89ea07cf478..04c6bcacd23990b40501f1182caa5e1873066b77 100644 (file)
@@ -61,10 +61,12 @@ public class NumberValue extends Value {
     }
 
     protected boolean checkConditions(BigDecimal newValue, DecimalType oldvalue) {
+        BigDecimal min = this.min;
         if (min != null && newValue.compareTo(min) == -1) {
             logger.trace("Number not accepted as it is below the configured minimum");
             return false;
         }
+        BigDecimal max = this.max;
         if (max != null && newValue.compareTo(max) == 1) {
             logger.trace("Number not accepted as it is above the configured maximum");
             return false;
index b101a02c091c33bf4de8dd3aaa7ea3071d3024e0..a8ace980970c9e005acfa1fc221f768228523117 100644 (file)
@@ -145,7 +145,10 @@ public class OpenAPIUtils {
         }
     }
 
-    public static boolean checkRequiredFirmware(String modelId, String currentFirmwareVersion) {
+    public static boolean checkRequiredFirmware(@Nullable String modelId, @Nullable String currentFirmwareVersion) {
+        if (modelId == null || currentFirmwareVersion == null) {
+            return false;
+        }
         int[] currentVer = getFirmwareVersionNumbers(currentFirmwareVersion);
 
         int[] requiredVer = getFirmwareVersionNumbers(
index 76d27617c9e31c5efa9417d6255ce7fc190fc28b..27742b152c06b5f2f40e99100b75bc607730c568 100644 (file)
@@ -123,16 +123,17 @@ public class NanoleafControllerHandler extends BaseBridgeHandler {
         setDeviceType(config.deviceType);
 
         try {
+            Map<String, String> properties = getThing().getProperties();
             if (StringUtils.isEmpty(getAddress()) || StringUtils.isEmpty(String.valueOf(getPort()))) {
                 logger.warn("No IP address and port configured for the Nanoleaf controller");
                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING,
                         "@text/error.nanoleaf.controller.noIp");
                 stopAllJobs();
-            } else if (!StringUtils.isEmpty(getThing().getProperties().get(Thing.PROPERTY_FIRMWARE_VERSION))
-                    && !OpenAPIUtils.checkRequiredFirmware(getThing().getProperties().get(Thing.PROPERTY_MODEL_ID),
-                            getThing().getProperties().get(Thing.PROPERTY_FIRMWARE_VERSION))) {
+            } else if (!StringUtils.isEmpty(properties.get(Thing.PROPERTY_FIRMWARE_VERSION))
+                    && !OpenAPIUtils.checkRequiredFirmware(properties.get(Thing.PROPERTY_MODEL_ID),
+                            properties.get(Thing.PROPERTY_FIRMWARE_VERSION))) {
                 logger.warn("Nanoleaf controller firmware is too old: {}. Must be equal or higher than {}",
-                        getThing().getProperties().get(Thing.PROPERTY_FIRMWARE_VERSION), API_MIN_FW_VER_LIGHTPANELS);
+                        properties.get(Thing.PROPERTY_FIRMWARE_VERSION), API_MIN_FW_VER_LIGHTPANELS);
                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
                         "@text/error.nanoleaf.controller.incompatibleFirmware");
                 stopAllJobs();
index 5f1f958d602748975e7a85d2327cef628d2ccb97..909dddaeb8d93b5d3d0cd8b56e1f83906d88b694 100644 (file)
@@ -75,9 +75,9 @@ public class HttpResponse {
      * @param httpCode the http code
      * @param msg the msg
      */
-    HttpResponse(int httpCode, String msg) {
+    HttpResponse(int httpCode, @Nullable String msg) {
         httpStatus = httpCode;
-        httpReason = msg;
+        httpReason = msg != null ? msg : "";
         contents = null;
     }
 
index 7a55fba9093178dc87f2085489a6f4b237b171e4..53e26aa058d37a8c419cf6d9a1afc1bf1b3b5cd0 100644 (file)
@@ -105,12 +105,10 @@ public abstract class AbstractNetatmoThingHandler extends BaseThingHandler {
             if (bridgeStatus == ThingStatus.ONLINE) {
                 config = getThing().getConfiguration();
 
-                radioHelper = thing.getProperties().containsKey(PROPERTY_SIGNAL_LEVELS)
-                        ? new RadioHelper(thing.getProperties().get(PROPERTY_SIGNAL_LEVELS))
-                        : null;
-                batteryHelper = thing.getProperties().containsKey(PROPERTY_BATTERY_LEVELS)
-                        ? new BatteryHelper(thing.getProperties().get(PROPERTY_BATTERY_LEVELS))
-                        : null;
+                String signalLevel = thing.getProperties().get(PROPERTY_SIGNAL_LEVELS);
+                radioHelper = signalLevel != null ? new RadioHelper(signalLevel) : null;
+                String batteryLevel = thing.getProperties().get(PROPERTY_BATTERY_LEVELS);
+                batteryHelper = batteryLevel != null ? new BatteryHelper(batteryLevel) : null;
                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, "Pending parent object initialization");
 
                 initializeThing();
index 2240b1af00de1aa9f4fe93859e7271b70085f69d..1ba917e40c73af67309fbe3d2756b06cdf9015e7 100644 (file)
@@ -47,9 +47,10 @@ public class CommunicationStatus {
 
     public final String getMessage() {
         Exception err = error;
+        String errMsg = err == null ? err.getMessage() : null;
         String msg = getHttpCode().getMessage();
-        if (err != null && err.getMessage() != null && !err.getMessage().isEmpty()) {
-            return err.getMessage();
+        if (errMsg != null && !errMsg.isEmpty()) {
+            return errMsg;
         } else if (msg != null && !msg.isEmpty()) {
             return msg;
         }
index c84d7ab0289774f760bbca989f6aec5a03840e13..c0b369f1855b11af996664593f61bd2624fb6e20 100644 (file)
@@ -22,6 +22,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ScheduledExecutorService;
+import java.util.function.Consumer;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
 import org.eclipse.jdt.annotation.Nullable;
@@ -274,39 +275,26 @@ public class NikoHomeControlCommunication1 extends NikoHomeControlCommunication
         }
     }
 
+    private void setIfPresent(Map<String, String> data, String key, Consumer<String> consumer) {
+        String val = data.get(key);
+        if (val != null) {
+            consumer.accept(val);
+        }
+    }
+
     private synchronized void cmdSystemInfo(Map<String, String> data) {
         logger.debug("Niko Home Control: systeminfo");
 
-        if (data.containsKey("swversion")) {
-            systemInfo.setSwVersion(data.get("swversion"));
-        }
-        if (data.containsKey("api")) {
-            systemInfo.setApi(data.get("api"));
-        }
-        if (data.containsKey("time")) {
-            systemInfo.setTime(data.get("time"));
-        }
-        if (data.containsKey("language")) {
-            systemInfo.setLanguage(data.get("language"));
-        }
-        if (data.containsKey("currency")) {
-            systemInfo.setCurrency(data.get("currency"));
-        }
-        if (data.containsKey("units")) {
-            systemInfo.setUnits(data.get("units"));
-        }
-        if (data.containsKey("DST")) {
-            systemInfo.setDst(data.get("DST"));
-        }
-        if (data.containsKey("TZ")) {
-            systemInfo.setTz(data.get("TZ"));
-        }
-        if (data.containsKey("lastenergyerase")) {
-            systemInfo.setLastEnergyErase(data.get("lastenergyerase"));
-        }
-        if (data.containsKey("lastconfig")) {
-            systemInfo.setLastConfig(data.get("lastconfig"));
-        }
+        setIfPresent(data, "swversion", systemInfo::setSwVersion);
+        setIfPresent(data, "api", systemInfo::setApi);
+        setIfPresent(data, "time", systemInfo::setTime);
+        setIfPresent(data, "language", systemInfo::setLanguage);
+        setIfPresent(data, "currency", systemInfo::setCurrency);
+        setIfPresent(data, "units", systemInfo::setUnits);
+        setIfPresent(data, "DST", systemInfo::setDst);
+        setIfPresent(data, "TZ", systemInfo::setTz);
+        setIfPresent(data, "lastenergyerase", systemInfo::setLastEnergyErase);
+        setIfPresent(data, "lastconfig", systemInfo::setLastConfig);
     }
 
     /**
@@ -319,12 +307,16 @@ public class NikoHomeControlCommunication1 extends NikoHomeControlCommunication
     }
 
     private void cmdStartEvents(Map<String, String> data) {
-        int errorCode = Integer.parseInt(data.get("error"));
-
-        if (errorCode == 0) {
-            logger.debug("Niko Home Control: start events success");
+        String errorCodeString = data.get("error");
+        if (errorCodeString != null) {
+            int errorCode = Integer.parseInt(errorCodeString);
+            if (errorCode == 0) {
+                logger.debug("Niko Home Control: start events success");
+            } else {
+                logger.warn("Niko Home Control: error code {} returned on start events", errorCode);
+            }
         } else {
-            logger.warn("Niko Home Control: error code {} returned on start events", errorCode);
+            logger.warn("Niko Home Control: could not determine error code returned on start events");
         }
     }
 
@@ -347,7 +339,8 @@ public class NikoHomeControlCommunication1 extends NikoHomeControlCommunication
         for (Map<String, String> action : data) {
 
             String id = action.get("id");
-            int state = Integer.parseInt(action.get("value1"));
+            String value1 = action.get("value1");
+            int state = ((value1 == null) || value1.isEmpty() ? 0 : Integer.parseInt(value1));
             String value2 = action.get("value2");
             int closeTime = ((value2 == null) || value2.isEmpty() ? 0 : Integer.parseInt(value2));
             String value3 = action.get("value3");
@@ -396,121 +389,156 @@ public class NikoHomeControlCommunication1 extends NikoHomeControlCommunication
         }
     }
 
+    private int parseIntOrThrow(@Nullable String str) throws IllegalArgumentException {
+        if (str == null)
+            throw new IllegalArgumentException("String is null");
+        try {
+            return Integer.parseInt(str);
+        } catch (NumberFormatException e) {
+            throw new IllegalArgumentException(e);
+        }
+    }
+
     private void cmdListThermostat(List<Map<String, String>> data) {
         logger.debug("Niko Home Control: list thermostats");
 
         for (Map<String, String> thermostat : data) {
-
-            String id = thermostat.get("id");
-            int measured = Integer.parseInt(thermostat.get("measured"));
-            int setpoint = Integer.parseInt(thermostat.get("setpoint"));
-            int mode = Integer.parseInt(thermostat.get("mode"));
-            int overrule = Integer.parseInt(thermostat.get("overrule"));
-            // overruletime received in "HH:MM" format
-            String[] overruletimeStrings = thermostat.get("overruletime").split(":");
-            int overruletime = 0;
-            if (overruletimeStrings.length == 2) {
-                overruletime = Integer.parseInt(overruletimeStrings[0]) * 60 + Integer.parseInt(overruletimeStrings[1]);
-            }
-            int ecosave = Integer.parseInt(thermostat.get("ecosave"));
-
-            // For parity with NHC II, assume heating/cooling if thermostat is on and setpoint different from measured
-            int demand = (mode != 3) ? (setpoint > measured ? 1 : (setpoint < measured ? -1 : 0)) : 0;
-
-            if (!thermostats.containsKey(id)) {
-                // Initial instantiation of NhcThermostat class for thermostat object
-                String name = thermostat.get("name");
-                String locationId = thermostat.get("location");
-                String location = "";
-                if (!locationId.isEmpty()) {
-                    location = locations.get(locationId).getName();
+            try {
+                String id = thermostat.get("id");
+                int measured = parseIntOrThrow(thermostat.get("measured"));
+                int setpoint = parseIntOrThrow(thermostat.get("setpoint"));
+                int mode = parseIntOrThrow(thermostat.get("mode"));
+                int overrule = parseIntOrThrow(thermostat.get("overrule"));
+                // overruletime received in "HH:MM" format
+                String[] overruletimeStrings = thermostat.getOrDefault("overruletime", "").split(":");
+                int overruletime = 0;
+                if (overruletimeStrings.length == 2) {
+                    overruletime = Integer.parseInt(overruletimeStrings[0]) * 60
+                            + Integer.parseInt(overruletimeStrings[1]);
                 }
-                NhcThermostat nhcThermostat = new NhcThermostat1(id, name, location, this);
-                nhcThermostat.updateState(measured, setpoint, mode, overrule, overruletime, ecosave, demand);
-                thermostats.put(id, nhcThermostat);
-            } else {
-                // Thermostat object already exists, so only update state.
-                // If we would re-instantiate thermostat, we would lose pointer back from thermostat to thing handler
-                // that was set in thing handler initialize().
-                thermostats.get(id).updateState(measured, setpoint, mode, overrule, overruletime, ecosave, demand);
+                int ecosave = parseIntOrThrow(thermostat.get("ecosave"));
+
+                // For parity with NHC II, assume heating/cooling if thermostat is on and setpoint different from
+                // measured
+                int demand = (mode != 3) ? (setpoint > measured ? 1 : (setpoint < measured ? -1 : 0)) : 0;
+
+                NhcThermostat t = thermostats.computeIfAbsent(id, i -> {
+                    // Initial instantiation of NhcThermostat class for thermostat object
+                    String name = thermostat.get("name");
+                    String locationId = thermostat.get("location");
+                    String location = "";
+                    if (!locationId.isEmpty()) {
+                        location = locations.get(locationId).getName();
+                    }
+                    if (name != null) {
+                        return new NhcThermostat1(i, name, location, this);
+                    }
+                    throw new IllegalArgumentException();
+                });
+                if (t != null) {
+                    t.updateState(measured, setpoint, mode, overrule, overruletime, ecosave, demand);
+                }
+            } catch (IllegalArgumentException e) {
+                // do nothing
             }
         }
     }
 
     private void cmdExecuteActions(Map<String, String> data) {
-        int errorCode = Integer.parseInt(data.get("error"));
-        if (errorCode == 0) {
-            logger.debug("Niko Home Control: execute action success");
-        } else {
-            logger.warn("Niko Home Control: error code {} returned on command execution", errorCode);
+        try {
+            int errorCode = parseIntOrThrow(data.get("error"));
+            if (errorCode == 0) {
+                logger.debug("Niko Home Control: execute action success");
+            } else {
+                logger.warn("Niko Home Control: error code {} returned on command execution", errorCode);
+            }
+        } catch (IllegalArgumentException e) {
+            logger.warn("Niko Home Control: no error code returned on command execution");
         }
     }
 
     private void cmdExecuteThermostat(Map<String, String> data) {
-        int errorCode = Integer.parseInt(data.get("error"));
-        if (errorCode == 0) {
-            logger.debug("Niko Home Control: execute thermostats success");
-        } else {
-            logger.warn("Niko Home Control: error code {} returned on command execution", errorCode);
+        try {
+            int errorCode = parseIntOrThrow(data.get("error"));
+            if (errorCode == 0) {
+                logger.debug("Niko Home Control: execute thermostats success");
+            } else {
+                logger.warn("Niko Home Control: error code {} returned on command execution", errorCode);
+            }
+        } catch (IllegalArgumentException e) {
+            logger.warn("Niko Home Control: no error code returned on command execution");
         }
     }
 
     private void eventListActions(List<Map<String, String>> data) {
         for (Map<String, String> action : data) {
             String id = action.get("id");
-            if (!actions.containsKey(id)) {
+            if (id == null || !actions.containsKey(id)) {
                 logger.warn("Niko Home Control: action in controller not known {}", id);
                 return;
             }
-            int state = Integer.parseInt(action.get("value1"));
-            logger.debug("Niko Home Control: event execute action {} with state {}", id, state);
-            actions.get(id).setState(state);
+            String stateString = action.get("value1");
+            if (stateString != null) {
+                int state = Integer.parseInt(stateString);
+                logger.debug("Niko Home Control: event execute action {} with state {}", id, state);
+                NhcAction action1 = actions.get(id);
+                if (action1 != null) {
+                    action1.setState(state);
+                }
+            }
         }
     }
 
     private void eventListThermostat(List<Map<String, String>> data) {
         for (Map<String, String> thermostat : data) {
-            String id = thermostat.get("id");
-            if (!thermostats.containsKey(id)) {
-                logger.warn("Niko Home Control: thermostat in controller not known {}", id);
-                return;
-            }
+            try {
+                String id = thermostat.get("id");
+                if (!thermostats.containsKey(id)) {
+                    logger.warn("Niko Home Control: thermostat in controller not known {}", id);
+                    return;
+                }
 
-            int measured = Integer.parseInt(thermostat.get("measured"));
-            int setpoint = Integer.parseInt(thermostat.get("setpoint"));
-            int mode = Integer.parseInt(thermostat.get("mode"));
-            int overrule = Integer.parseInt(thermostat.get("overrule"));
-            // overruletime received in "HH:MM" format
-            String[] overruletimeStrings = thermostat.get("overruletime").split(":");
-            int overruletime = 0;
-            if (overruletimeStrings.length == 2) {
-                overruletime = Integer.parseInt(overruletimeStrings[0]) * 60 + Integer.parseInt(overruletimeStrings[1]);
-            }
-            int ecosave = Integer.parseInt(thermostat.get("ecosave"));
+                int measured = parseIntOrThrow(thermostat.get("measured"));
+                int setpoint = parseIntOrThrow(thermostat.get("setpoint"));
+                int mode = parseIntOrThrow(thermostat.get("mode"));
+                int overrule = parseIntOrThrow(thermostat.get("overrule"));
+                // overruletime received in "HH:MM" format
+                String[] overruletimeStrings = thermostat.getOrDefault("overruletime", "").split(":");
+                int overruletime = 0;
+                if (overruletimeStrings.length == 2) {
+                    overruletime = Integer.parseInt(overruletimeStrings[0]) * 60
+                            + Integer.parseInt(overruletimeStrings[1]);
+                }
+                int ecosave = parseIntOrThrow(thermostat.get("ecosave"));
 
-            int demand = (mode != 3) ? (setpoint > measured ? 1 : (setpoint < measured ? -1 : 0)) : 0;
+                int demand = (mode != 3) ? (setpoint > measured ? 1 : (setpoint < measured ? -1 : 0)) : 0;
 
-            logger.debug(
-                    "Niko Home Control: event execute thermostat {} with measured {}, setpoint {}, mode {}, overrule {}, overruletime {}, ecosave {}, demand {}",
-                    id, measured, setpoint, mode, overrule, overruletime, ecosave, demand);
-            thermostats.get(id).updateState(measured, setpoint, mode, overrule, overruletime, ecosave, demand);
+                logger.debug(
+                        "Niko Home Control: event execute thermostat {} with measured {}, setpoint {}, mode {}, overrule {}, overruletime {}, ecosave {}, demand {}",
+                        id, measured, setpoint, mode, overrule, overruletime, ecosave, demand);
+                NhcThermostat t = thermostats.get(id);
+                if (t != null) {
+                    t.updateState(measured, setpoint, mode, overrule, overruletime, ecosave, demand);
+                }
+            } catch (IllegalArgumentException e) {
+                // do nothing
+            }
         }
     }
 
     private void eventGetAlarms(Map<String, String> data) {
-        int type = Integer.parseInt(data.get("type"));
         String alarmText = data.get("text");
-        switch (type) {
-            case 0:
+        switch (data.getOrDefault("type", "")) {
+            case "0":
                 logger.debug("Niko Home Control: alarm - {}", alarmText);
                 handler.alarmEvent(alarmText);
                 break;
-            case 1:
+            case "1":
                 logger.debug("Niko Home Control: notice - {}", alarmText);
                 handler.noticeEvent(alarmText);
                 break;
             default:
-                logger.debug("Niko Home Control: unexpected message type {}", type);
+                logger.debug("Niko Home Control: unexpected message type {}", data.get("type"));
         }
     }
 
index 8ab2d426950b310d86fa0c2b73f0d7ceda6dc532..b3e195b3d587bb8de30a5f7744032ac89179405d 100644 (file)
@@ -486,9 +486,12 @@ public class NikoHomeControlCommunication2 extends NikoHomeControlCommunication
         }
 
         if (dimmerProperty.isPresent()) {
-            action.setState(Integer.parseInt(dimmerProperty.get().brightness));
-            logger.debug("Niko Home Control: setting action {} internally to {}", action.getId(),
-                    dimmerProperty.get().brightness);
+            String brightness = dimmerProperty.get().brightness;
+            if (brightness != null) {
+                action.setState(Integer.parseInt(brightness));
+                logger.debug("Niko Home Control: setting action {} internally to {}", action.getId(),
+                        dimmerProperty.get().brightness);
+            }
         }
     }
 
@@ -507,15 +510,19 @@ public class NikoHomeControlCommunication2 extends NikoHomeControlCommunication
         Optional<Boolean> overruleActiveProperty = deviceProperties.stream().map(p -> p.overruleActive)
                 .filter(Objects::nonNull).map(t -> Boolean.parseBoolean(t)).findFirst();
         Optional<Integer> overruleSetpointProperty = deviceProperties.stream().map(p -> p.overruleSetpoint)
-                .filter(s -> !((s == null) || s.isEmpty())).map(t -> Math.round(Float.parseFloat(t) * 10)).findFirst();
+                .map(s -> (!((s == null) || s.isEmpty())) ? Math.round(Float.parseFloat(s) * 10) : null)
+                .filter(Objects::nonNull).findFirst();
         Optional<Integer> overruleTimeProperty = deviceProperties.stream().map(p -> p.overruleTime)
-                .filter(s -> !((s == null) || s.isEmpty())).map(t -> Math.round(Float.parseFloat(t))).findFirst();
+                .map(s -> (!((s == null) || s.isEmpty())) ? Math.round(Float.parseFloat(s)) : null)
+                .filter(Objects::nonNull).findFirst();
         Optional<Integer> setpointTemperatureProperty = deviceProperties.stream().map(p -> p.setpointTemperature)
-                .filter(s -> !((s == null) || s.isEmpty())).map(t -> Math.round(Float.parseFloat(t) * 10)).findFirst();
-        Optional<Boolean> ecoSaveProperty = deviceProperties.stream().map(p -> p.ecoSave).filter(Objects::nonNull)
-                .map(t -> Boolean.parseBoolean(t)).findFirst();
+                .map(s -> (!((s == null) || s.isEmpty())) ? Math.round(Float.parseFloat(s) * 10) : null)
+                .filter(Objects::nonNull).findFirst();
+        Optional<Boolean> ecoSaveProperty = deviceProperties.stream().map(p -> p.ecoSave)
+                .map(s -> s != null ? Boolean.parseBoolean(s) : null).filter(Objects::nonNull).findFirst();
         Optional<Integer> ambientTemperatureProperty = deviceProperties.stream().map(p -> p.ambientTemperature)
-                .filter(s -> !(s == null || s.isEmpty())).map(t -> Math.round(Float.parseFloat(t) * 10)).findFirst();
+                .map(s -> (!((s == null) || s.isEmpty())) ? Math.round(Float.parseFloat(s) * 10) : null)
+                .filter(Objects::nonNull).findFirst();
         Optional<@Nullable String> demandProperty = deviceProperties.stream().map(p -> p.demand)
                 .filter(Objects::nonNull).findFirst();
         Optional<@Nullable String> operationModeProperty = deviceProperties.stream().map(p -> p.operationMode)
index a914db2e0d6af0d3b4b18f63034f78b9ba5693fc..7ad55b5c5687c8dbf89a607b2268f8469fa20390 100644 (file)
@@ -158,7 +158,7 @@ public class ThermostatHandler extends BaseThingHandler {
         updateState(BindingConstants.CHANNEL_OWD5_GROUPNAME, StringType.valueOf(thermostat.groupName));
     }
 
-    private String getRegulationMode(int regulationMode) {
+    private @Nullable String getRegulationMode(int regulationMode) {
         return REGULATION_MODES.get(regulationMode);
     }
 
index ec2e39a03cd99d159f1ab93c580c8765178a9326..a2d51b4cc29fb13e6084276e3cf9e14e54456941 100644 (file)
@@ -43,7 +43,10 @@ public class SensorId {
      * - characters are case-insensitive
      * - hubs ("1F.xxxxxxxxxxxx/aux/") may be repeated
      */
-    public SensorId(String fullPath) {
+    public SensorId(@Nullable String fullPath) {
+        if (fullPath == null) {
+            throw new IllegalArgumentException();
+        }
         Matcher matcher = SENSOR_ID_PATTERN.matcher(fullPath);
         if (matcher.matches() && matcher.groupCount() == 2) {
             path = matcher.group(1) == null ? "" : matcher.group(1);
index 6ce94388cd1039c7ffef4ba3319b67dcf2426653..30abd9636f2d979629d73e5edc666b2dda23502a 100644 (file)
@@ -118,8 +118,8 @@ public class OwDiscoveryItem {
      * @return ThingTypeUID if mapping successful
      */
     public ThingTypeUID getThingTypeUID() throws OwException {
-        if (THING_TYPE_MAP.containsKey(sensorType)) {
-            thingTypeUID = THING_TYPE_MAP.get(sensorType);
+        ThingTypeUID thingTypeUID = THING_TYPE_MAP.get(sensorType);
+        if (thingTypeUID != null) {
             return thingTypeUID;
         } else {
             throw new OwException(sensorType + " cannot be mapped to thing type");
index 7e177740cb9daaee9150d0fe76a466a1f8347ea8..a063f28ba7ae0ef29f691e069ae83954f3d1e504 100644 (file)
@@ -90,17 +90,20 @@ public class AdvancedMultisensorThingHandler extends OwBaseThingHandler {
             return;
         }
 
-        hwRevision = Integer.valueOf(properties.get(PROPERTY_HW_REVISION));
+        hwRevision = Integer.valueOf(properties.getOrDefault(PROPERTY_HW_REVISION, "0"));
 
-        sensors.add(new DS2438(sensorId, this));
-        sensors.add(new DS18x20(new SensorId(properties.get(PROPERTY_DS18B20)), this));
-        if (THING_TYPE_AMS.equals(thingType)) {
-            sensors.add(new DS2438(new SensorId(properties.get(PROPERTY_DS2438)), this));
-            sensors.add(new DS2406_DS2413(new SensorId(properties.get(PROPERTY_DS2413)), this));
-            digitalRefreshInterval = configuration.digitalRefresh * 1000;
-            digitalLastRefresh = 0;
+        try {
+            sensors.add(new DS2438(sensorId, this));
+            sensors.add(new DS18x20(new SensorId(properties.get(PROPERTY_DS18B20)), this));
+            if (THING_TYPE_AMS.equals(thingType)) {
+                sensors.add(new DS2438(new SensorId(properties.get(PROPERTY_DS2438)), this));
+                sensors.add(new DS2406_DS2413(new SensorId(properties.get(PROPERTY_DS2413)), this));
+                digitalRefreshInterval = configuration.digitalRefresh * 1000;
+                digitalLastRefresh = 0;
+            }
+        } catch (IllegalArgumentException e) {
+            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "properties invalid");
         }
-
         scheduler.execute(() -> {
             configureThingChannels();
         });
index ca2daef757a5822672e85fe0ec3c375233858914..4c4101297293f602e204847791a3e958e07909d6 100644 (file)
@@ -13,6 +13,7 @@
 package org.openhab.binding.openweathermap.internal.connection;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 
 /**
  * The {@link OpenWeatherMapCommunicationException} is a communication exception for the connections to OpenWeatherMap
@@ -37,7 +38,7 @@ public class OpenWeatherMapCommunicationException extends RuntimeException {
      *
      * @param message Detail message
      */
-    public OpenWeatherMapCommunicationException(String message) {
+    public OpenWeatherMapCommunicationException(@Nullable String message) {
         super(message);
     }
 
@@ -46,7 +47,7 @@ public class OpenWeatherMapCommunicationException extends RuntimeException {
      *
      * @param cause The cause
      */
-    public OpenWeatherMapCommunicationException(Throwable cause) {
+    public OpenWeatherMapCommunicationException(@Nullable Throwable cause) {
         super(cause);
     }
 
@@ -56,7 +57,7 @@ public class OpenWeatherMapCommunicationException extends RuntimeException {
      * @param message Detail message
      * @param cause The cause
      */
-    public OpenWeatherMapCommunicationException(String message, Throwable cause) {
+    public OpenWeatherMapCommunicationException(@Nullable String message, @Nullable Throwable cause) {
         super(message, cause);
     }
 }
index c5a64388eb4edea1291e8bd484e7b4a5fc072d02..71397d23c6bbf1dd47563c94d43c918130c452b7 100644 (file)
@@ -13,6 +13,7 @@
 package org.openhab.binding.openweathermap.internal.connection;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 
 /**
  * The {@link OpenWeatherMapConfigurationException} is a configuration exception for the connections to OpenWeatherMap
@@ -37,7 +38,7 @@ public class OpenWeatherMapConfigurationException extends IllegalArgumentExcepti
      *
      * @param message Detail message
      */
-    public OpenWeatherMapConfigurationException(String message) {
+    public OpenWeatherMapConfigurationException(@Nullable String message) {
         super(message);
     }
 
@@ -46,7 +47,7 @@ public class OpenWeatherMapConfigurationException extends IllegalArgumentExcepti
      *
      * @param cause The cause
      */
-    public OpenWeatherMapConfigurationException(Throwable cause) {
+    public OpenWeatherMapConfigurationException(@Nullable Throwable cause) {
         super(cause);
     }
 
@@ -56,7 +57,7 @@ public class OpenWeatherMapConfigurationException extends IllegalArgumentExcepti
      * @param message Detail message
      * @param cause The cause
      */
-    public OpenWeatherMapConfigurationException(String message, Throwable cause) {
+    public OpenWeatherMapConfigurationException(@Nullable String message, @Nullable Throwable cause) {
         super(message, cause);
     }
 }
index d2705e68a0f367b192a2c69fb240756e04190169..264ad1c1e9ea13325539411a15b9fee9ebdeb313 100644 (file)
@@ -278,7 +278,10 @@ public class OpenWeatherMapConnection {
                 .collect(joining("&", url + "?", ""));
     }
 
-    private String encodeParam(String value) {
+    private String encodeParam(@Nullable String value) {
+        if (value == null) {
+            return "";
+        }
         try {
             return URLEncoder.encode(value, StandardCharsets.UTF_8.name());
         } catch (UnsupportedEncodingException e) {
index 7a8c945f210fa6e0b8b9935731e1d747aebfdb1d..114f9cae91fbc5cfa1932ed71505448bc56bf0be 100644 (file)
@@ -126,8 +126,9 @@ public class PJLinkDevice {
         Instant now = Instant.now();
         Socket socket = this.socket;
         boolean connectionTooOld = false;
-        if (this.socketCreatedOn != null) {
-            long millisecondsSinceLastConnect = Duration.between(this.socketCreatedOn, now).toMillis();
+        Instant socketCreatedOn = this.socketCreatedOn;
+        if (socketCreatedOn != null) {
+            long millisecondsSinceLastConnect = Duration.between(socketCreatedOn, now).toMillis();
             // according to the PJLink specification, the device closes the connection after 30s idle (without notice),
             // so to be on the safe side we do not reuse sockets older than 20s
             connectionTooOld = millisecondsSinceLastConnect > 20 * 1000;
index 56a9ca80d85883d37aabea159ddeab0b50989121..0996192e9f8dda68012e371d4737f4e1f89f7761 100644 (file)
@@ -280,6 +280,10 @@ public abstract class PLCCommonHandler extends BaseThingHandler {
     }
 
     protected static String getBlockFromChannel(final @Nullable Channel channel) {
-        return channel == null ? NOT_SUPPORTED : channel.getProperties().get(BLOCK_PROPERTY);
+        if (channel == null) {
+            return NOT_SUPPORTED;
+        }
+        String block = channel.getProperties().get(BLOCK_PROPERTY);
+        return block == null ? NOT_SUPPORTED : block;
     }
 }
index a22582e11d13e0e1f2faeed79b5ebd9b2172a643..789cc555c143bf2055c1c0bd9af9729d4d004932 100644 (file)
@@ -164,6 +164,7 @@ public abstract class AbstractPlugwiseThingHandler extends BaseThingHandler impl
     }
 
     protected boolean recentlySendConfigurationUpdate() {
+        LocalDateTime lastConfigurationUpdateSend = this.lastConfigurationUpdateSend;
         return lastConfigurationUpdateSend != null
                 && LocalDateTime.now().minus(Duration.ofMillis(500)).isBefore(lastConfigurationUpdateSend);
     }
index 9284011b7d57965c8167d9221ccb65c6858fd8fa..2c493fe5eb54c28c9d3b9c684d1a8af4ec25bc0d 100644 (file)
@@ -265,10 +265,11 @@ public class Parser {
                     source.setMuted(properties.get("muted").equalsIgnoreCase("yes"));
                 }
                 if (properties.containsKey("volume")) {
-                    source.setVolume(Integer.valueOf(parseVolume(properties.get("volume"))));
+                    source.setVolume(parseVolume(properties.get("volume")));
                 }
-                if (properties.containsKey("monitor_of")) {
-                    source.setMonitorOf(client.getSink(Integer.valueOf(properties.get("monitor_of"))));
+                String monitorOf = properties.get("monitor_of");
+                if (monitorOf != null) {
+                    source.setMonitorOf(client.getSink(Integer.valueOf(monitorOf)));
                 }
                 sources.add(source);
             }
index e46b9b5247680fedb5f68e9aa1558da1fc32b5f1..abcf0adf306345f49d33d0a15430932cc166bebf 100644 (file)
@@ -152,6 +152,10 @@ public class RadioThermostatConnector {
      * @return a valid URL for the thermostat's JSON interface
      */
     private String buildRequestURL(String resource) {
+        String hostName = this.hostName;
+        if (hostName == null) {
+            throw new IllegalStateException("hostname must not be null");
+        }
         String urlStr = URL.replace("%hostName%", hostName);
         urlStr = urlStr.replace("%resource%", resource);
 
index 2f8d2dd4a4eefe376fba83d49576964e9304216f..7b63add9ef24f0002ab3f34dfc4ffb369f7e7ee1 100644 (file)
@@ -13,6 +13,7 @@
 package org.openhab.binding.remoteopenhab.internal.exceptions;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 
 /**
  * Exceptions thrown by this binding.
@@ -23,15 +24,15 @@ import org.eclipse.jdt.annotation.NonNullByDefault;
 @SuppressWarnings("serial")
 public class RemoteopenhabException extends Exception {
 
-    public RemoteopenhabException(String message) {
+    public RemoteopenhabException(@Nullable String message) {
         super(message);
     }
 
-    public RemoteopenhabException(String message, Throwable cause) {
+    public RemoteopenhabException(@Nullable String message, @Nullable Throwable cause) {
         super(message, cause);
     }
 
-    public RemoteopenhabException(Throwable cause) {
+    public RemoteopenhabException(@Nullable Throwable cause) {
         super(cause);
     }
 }
index 10322902c60e65f79f18f06172fd9ffd02b24ba6..4c2bfee85eb289a4c451831ee0f54465e36c1cd3 100644 (file)
@@ -39,7 +39,7 @@ class ExpiringMap<T> {
         values.put(now, newValue);
         Optional<Long> eldestKey = values.keySet().stream().filter(key -> key < now - eldestAge).findFirst();
         if (eldestKey.isPresent()) {
-            agedValue = Optional.of(values.get(eldestKey.get()));
+            agedValue = Optional.ofNullable(values.get(eldestKey.get()));
             values.entrySet().removeIf(map -> map.getKey() <= eldestKey.get());
         }
     }
index bf524e70f9ec39d097faf2ad9e305f49e0ba12ec..21c5ae3d15ee9dc7f77a775794d9e1d9263ab7c9 100644 (file)
@@ -248,7 +248,7 @@ public class MediaRendererService implements UpnpIOParticipant, SamsungTvService
 
         try {
             newValue = DataConverters.convertCommandToIntValue(command, 0, 100,
-                    Integer.valueOf(stateMap.get("CurrentVolume")));
+                    Integer.valueOf(stateMap.getOrDefault("CurrentVolume", "")));
         } catch (NumberFormatException e) {
             throw new NumberFormatException("Command '" + command + "' not supported");
         }
@@ -281,7 +281,7 @@ public class MediaRendererService implements UpnpIOParticipant, SamsungTvService
 
         try {
             newValue = DataConverters.convertCommandToIntValue(command, 0, 100,
-                    Integer.valueOf(stateMap.get("CurrentBrightness")));
+                    Integer.valueOf(stateMap.getOrDefault("CurrentBrightness", "")));
         } catch (NumberFormatException e) {
             throw new NumberFormatException("Command '" + command + "' not supported");
         }
@@ -297,7 +297,7 @@ public class MediaRendererService implements UpnpIOParticipant, SamsungTvService
 
         try {
             newValue = DataConverters.convertCommandToIntValue(command, 0, 100,
-                    Integer.valueOf(stateMap.get("CurrentContrast")));
+                    Integer.valueOf(stateMap.getOrDefault("CurrentContrast", "")));
         } catch (NumberFormatException e) {
             throw new NumberFormatException("Command '" + command + "' not supported");
         }
@@ -313,7 +313,7 @@ public class MediaRendererService implements UpnpIOParticipant, SamsungTvService
 
         try {
             newValue = DataConverters.convertCommandToIntValue(command, 0, 100,
-                    Integer.valueOf(stateMap.get("CurrentSharpness")));
+                    Integer.valueOf(stateMap.getOrDefault("CurrentSharpness", "")));
         } catch (NumberFormatException e) {
             throw new NumberFormatException("Command '" + command + "' not supported");
         }
@@ -329,7 +329,7 @@ public class MediaRendererService implements UpnpIOParticipant, SamsungTvService
 
         try {
             newValue = DataConverters.convertCommandToIntValue(command, 0, 4,
-                    Integer.valueOf(stateMap.get("CurrentColorTemperature")));
+                    Integer.valueOf(stateMap.getOrDefault("CurrentColorTemperature", "")));
         } catch (NumberFormatException e) {
             throw new NumberFormatException("Command '" + command + "' not supported");
         }
index a709aac9a677b27b79e42d9140e9a6473b654025..66b700d95831d6af847082b47ab77e4ca8914cb5 100644 (file)
@@ -86,7 +86,7 @@ public class ServiceFactory {
      * @param serviceName Name of the service
      * @return Class of the service
      */
-    public static Class<? extends SamsungTvService> getClassByServiceName(String serviceName) {
+    public static @Nullable Class<? extends SamsungTvService> getClassByServiceName(String serviceName) {
         return SERVICEMAP.get(serviceName);
     }
 }
index f3ea9699ecedf8ad36dba34a3ac4e47dee0d8d0c..be8cb08082273f3c4ae27fc8103778fdfa55b692 100644 (file)
@@ -59,6 +59,7 @@ public class SatelEventLogActions implements ThingActions {
         logger.debug("satel.readEvent called with input: index={}", index);
 
         Map<String, Object> result = new HashMap<>();
+        SatelEventLogHandler handler = this.handler;
         if (handler != null) {
             handler.readEvent(index == null ? -1 : index.intValue()).ifPresent(event -> {
                 result.put("index", event.getIndex());
index 4f9928955b7eb7b2c536163f3315efdfee80bd7f..0735382cb551b86a3eead37b947a955a757e8baf 100644 (file)
@@ -58,8 +58,8 @@ public abstract class SatelThingHandler extends BaseThingHandler implements Sate
         if (bridge != null) {
             final ThingHandler handler = bridge.getHandler();
             if (handler != null && handler instanceof SatelBridgeHandler) {
+                ((SatelBridgeHandler) handler).addEventListener(this);
                 this.bridgeHandler = (SatelBridgeHandler) handler;
-                this.bridgeHandler.addEventListener(this);
             }
             if (bridge.getStatus() == ThingStatus.ONLINE) {
                 updateStatus(ThingStatus.ONLINE);
index 224b8adc35848127a9163c80426876880208d19b..20e272725504efe0952f2898b4b73b9c522278df 100644 (file)
@@ -351,8 +351,8 @@ public abstract class SatelModule extends EventDispatcher implements SatelEventL
     private synchronized void disconnect(@Nullable String reason) {
         // remove all pending commands from the queue
         // notifying about send failure
-        while (!this.sendQueue.isEmpty()) {
-            SatelCommand cmd = this.sendQueue.poll();
+        SatelCommand cmd;
+        while ((cmd = this.sendQueue.poll()) != null) {
             cmd.setState(State.FAILED);
         }
         final CommunicationChannel channel = this.channel;
@@ -503,13 +503,13 @@ public abstract class SatelModule extends EventDispatcher implements SatelEventL
         }
 
         private void startCommunication() {
-            final Thread thread = this.thread;
+            Thread thread = this.thread;
             if (thread != null && thread.isAlive()) {
                 logger.error("Start communication canceled: communication thread is still alive");
                 return;
             }
             // start new thread
-            this.thread = new Thread(new Runnable() {
+            thread = new Thread(new Runnable() {
                 @Override
                 public void run() {
                     logger.debug("Communication thread started");
@@ -517,7 +517,8 @@ public abstract class SatelModule extends EventDispatcher implements SatelEventL
                     logger.debug("Communication thread stopped");
                 }
             });
-            this.thread.start();
+            thread.start();
+            this.thread = thread;
             // if module is not initialized yet, send version command
             if (!SatelModule.this.isInitialized()) {
                 SatelModule.this.sendCommand(new IntegraVersionCommand());
index 1f7f42dbca143de39829198c6ec48467ef060720..f1e5a4457b89d20ec1d70d9359d72048aca9da9c 100644 (file)
@@ -59,7 +59,7 @@ public class ShellyApiException extends Exception {
     }
 
     @Override
-    public String getMessage() {
+    public @Nullable String getMessage() {
         return isEmpty() ? "" : nonNullString(super.getMessage());
     }
 
index 08a4d02ae35d5ffd0e3a11a15f5d34f2a48db247..fcf633c5f10c452f05401f52f683bc09e725cf14 100644 (file)
@@ -235,7 +235,7 @@ public class ShellyCoIoTProtocol {
             Double brightness = -1.0;
             Double power = -1.0;
             for (CoIotSensor update : allUpdates) {
-                CoIotDescrSen d = fixDescription(sensorMap.get(update.id), blkMap);
+                CoIotDescrSen d = fixDescription(sensorMap.getOrDefault(update.id, new CoIotDescrSen()), blkMap);
                 if (!checkL.isEmpty() && !d.links.equals(checkL)) {
                     // continue until we find the correct one
                     continue;
index 2f23146344321b4b00774769078e33fb9039de77..b4e8233604cd2fa55206b680f20590f5166bacf8 100644 (file)
@@ -124,12 +124,13 @@ public class ShellyThingCreator {
         }
 
         // Check general mapping
-        if (!deviceType.isEmpty() && THING_TYPE_MAPPING.containsKey(deviceType)) {
-            return THING_TYPE_MAPPING.get(deviceType);
-        }
-        if (THING_TYPE_MAPPING.containsKey(type)) {
-            return THING_TYPE_MAPPING.get(type);
+        if (!deviceType.isEmpty()) {
+            String str = THING_TYPE_MAPPING.get(deviceType);
+            if (str != null) {
+                return str;
+            }
         }
-        return THING_TYPE_SHELLYUNKNOWN_STR;
+
+        return THING_TYPE_MAPPING.getOrDefault(type, THING_TYPE_SHELLYUNKNOWN_STR);
     }
 }
index a92119a4f7cf6cf5aa98a7517ff5237a2538c00e..3aa0bb0c74a7b72d033c9ef5939017176c4a58b9 100644 (file)
@@ -120,10 +120,7 @@ public class ShellyChannelCache {
     }
 
     public State getValue(String channelId) {
-        if (channelData.containsKey(channelId)) {
-            return channelData.get(channelId);
-        }
-        return UnDefType.NULL;
+        return channelData.getOrDefault(channelId, UnDefType.NULL);
     }
 
     public void resetChannel(String channelId) {
index 09ecde9adccfdebec0e3e0cf6861491afec1e4d6..1e8e387e02106573355d90be1adb7e9e1e28fef0 100644 (file)
@@ -70,7 +70,7 @@ public abstract class BasePoint {
     @SerializedName("presentPriority")
     protected int presentPriority;
 
-    private @Nullable String @Nullable [] enumVals;
+    private String @Nullable [] enumVals;
     private boolean enumParsed = false;
     protected boolean isEnum = false;
 
index 1124a461c5d166f48288fd836ec9a1f801706500..1d722c00c989cebb6a237edd6ffa6393289b90d1 100644 (file)
@@ -34,10 +34,14 @@ public class StringPoint extends BasePoint {
     @Override
     public int asInt() {
         try {
-            return Integer.parseInt(value);
-        } catch (Exception e) {
-            return UNDEFINED_VALUE;
+            String value = this.value;
+            if (value != null) {
+                return Integer.parseInt(value);
+            }
+        } catch (NumberFormatException e) {
+            // default value
         }
+        return UNDEFINED_VALUE;
     }
 
     @Override
index c0e0213dc1f68b8599075af0e0b818e2d3d88099..91c691d9beefce2fe093f88cedf86ea959fb54e8 100644 (file)
@@ -113,8 +113,8 @@ public enum Conformity {
         boolean shouldNegateState = NegateHandler.shouldNegateState(negateProperty, channelId -> {
             Channel negateChannel = thing.getChannel(channelId);
             if (negateChannel != null) {
-                return device.getMeterValue(
-                        negateChannel.getProperties().get(SmartMeterBindingConstants.CHANNEL_PROPERTY_OBIS));
+                String property = negateChannel.getProperties().get(SmartMeterBindingConstants.CHANNEL_PROPERTY_OBIS);
+                return property != null ? device.getMeterValue(property) : null;
             }
             return null;
         });
index b83f311a92807e357b6eb1817bd38e10e44cf8ed..080bd76a2bde63e110282c3e5d89e953f5318990 100644 (file)
@@ -73,7 +73,7 @@ public class SmartthingsHue100Converter extends SmartthingsConverter {
             return UnDefType.UNDEF;
         }
 
-        if ("Number".contentEquals(acceptedChannelType)) {
+        if (acceptedChannelType != null && "Number".contentEquals(acceptedChannelType)) {
             if (deviceValue instanceof String) {
                 double d = Double.parseDouble((String) deviceValue);
                 d *= 3.6;
index 01f059515aeffa28b558268e72e65e6aa62aa09d..1c00872dccc6fc4b96ecf72c41ac7cff4faa21bf 100644 (file)
@@ -146,7 +146,7 @@ public abstract class AbstractSnmpTargetHandlerTest extends JavaTest {
 
         if (refresh) {
             ArgumentCaptor<PDU> pduCaptor = ArgumentCaptor.forClass(PDU.class);
-            verify(snmpService, atLeast(1)).send(pduCaptor.capture(), any(), eq(null), eq(thingHandler));
+            verify(snmpService, timeout(500).atLeast(1)).send(pduCaptor.capture(), any(), eq(null), eq(thingHandler));
             Vector<? extends VariableBinding> variables = pduCaptor.getValue().getVariableBindings();
             assertTrue(variables.stream().filter(v -> v.getOid().toDottedString().equals(TEST_OID)).findFirst()
                     .isPresent());
index db877ec8dadf9cf7f834111d3f5fdfa06563c57a..25673f36a9311e0a7b90732b9b3ccebf15283102 100644 (file)
@@ -48,8 +48,11 @@ public class CommunicationStatus {
     public final String getMessage() {
         Code httpCode = this.httpCode;
         Exception error = this.error;
-        if (error != null && error.getMessage() != null && !error.getMessage().isEmpty()) {
-            return error.getMessage();
+        if (error != null) {
+            String message = error.getMessage();
+            if (message != null && !message.isEmpty()) {
+                return message;
+            }
         } else if (httpCode != null && httpCode.getMessage() != null && !httpCode.getMessage().isEmpty()) {
             return httpCode.getMessage();
         }
index ce04c67f5093944f0e1320f153b75118684a187b..4f9665e96176eb1749931556fccfe0db49166220 100644 (file)
@@ -328,7 +328,7 @@ public class SonosXMLParser {
         @Override
         public void characters(char @Nullable [] ch, int start, int length) throws SAXException {
             Element elt = element;
-            if (elt == null) {
+            if (elt == null || ch == null) {
                 return;
             }
             switch (elt) {
@@ -446,7 +446,7 @@ public class SonosXMLParser {
         @Override
         public void characters(char @Nullable [] ch, int start, int length) throws SAXException {
             Element elt = element;
-            if (elt == null) {
+            if (elt == null || ch == null) {
                 return;
             }
             switch (elt) {
@@ -530,9 +530,17 @@ public class SonosXMLParser {
                 boolean finalIncludeLinkedZones = !"0".equals(includeLinkedZones);
 
                 try {
+                    String id = this.id;
+                    if (id == null) {
+                        throw new NumberFormatException();
+                    }
                     finalID = Integer.parseInt(id);
+                    String volume = this.volume;
+                    if (volume == null) {
+                        throw new NumberFormatException();
+                    }
                     finalVolume = Integer.parseInt(volume);
-                } catch (Exception e) {
+                } catch (NumberFormatException e) {
                     LOGGER.debug("Error parsing Integer");
                 }
 
@@ -790,7 +798,7 @@ public class SonosXMLParser {
         @Override
         public void characters(char @Nullable [] ch, int start, int length) throws SAXException {
             CurrentElement elt = currentElement;
-            if (elt == null) {
+            if (elt == null || ch == null) {
                 return;
             }
             switch (elt) {
@@ -875,7 +883,7 @@ public class SonosXMLParser {
 
         @Override
         public void characters(char @Nullable [] ch, int start, int length) throws SAXException {
-            if (getPresetName) {
+            if (getPresetName && ch != null) {
                 presetName = new String(ch, start, length);
             }
         }
@@ -944,7 +952,7 @@ public class SonosXMLParser {
 
         @Override
         public void characters(char @Nullable [] ch, int start, int length) throws SAXException {
-            if (roomNameTag) {
+            if (roomNameTag && ch != null) {
                 roomName = new String(ch, start, length);
                 roomNameTag = false;
             }
@@ -983,7 +991,7 @@ public class SonosXMLParser {
 
         @Override
         public void characters(char @Nullable [] ch, int start, int length) throws SAXException {
-            if (modelNameTag) {
+            if (modelNameTag && ch != null) {
                 modelName = new String(ch, start, length);
                 modelNameTag = false;
             }
index 7f73e186e504f0121c8b47756442879ee32ab453..25b5d358f6a3d64e4d21e51432b6533286a520b2 100644 (file)
@@ -1393,7 +1393,11 @@ public class ZonePlayerHandler extends BaseThingHandler implements UpnpIOPartici
         }
 
         try {
-            result = Long.valueOf(resultInput.get(requestedKey));
+            String resultString = resultInput.get(requestedKey);
+            if (resultString == null) {
+                throw new NumberFormatException("Requested key is null.");
+            }
+            result = Long.valueOf(resultString);
         } catch (NumberFormatException ex) {
             logger.debug("Could not fetch {} result for type: {} and filter: {}. Using default value '0': {}",
                     requestedKey, entriesType, entriesFilter, ex.getMessage(), ex);
index b37441d35a3d13b96b9a808e8d3a60897a2bc166..c3b0246ff8b022eea47c9a2cd4ed8a10007e7a2c 100644 (file)
@@ -13,6 +13,7 @@
 package org.openhab.binding.sonyprojector.internal;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 
 /**
  * The {@link SonyProjectorException} class is used for any exception thrown by the binding
@@ -28,7 +29,7 @@ public class SonyProjectorException extends Exception {
     }
 
     // Constructor that accepts a message
-    public SonyProjectorException(String message) {
+    public SonyProjectorException(@Nullable String message) {
         super(message);
     }
 }
index d03843e2d7612c3a022d7997bc4b3e7913d8bc17..f61dc915a2d870a4b40f081a37666fe70f091b65 100644 (file)
@@ -149,7 +149,12 @@ class SpotifyConnector {
                     }
                 }
             } catch (ExecutionException e) {
-                future.completeExceptionally(e.getCause());
+                Throwable cause = e.getCause();
+                if (cause != null) {
+                    future.completeExceptionally(cause);
+                } else {
+                    future.completeExceptionally(e);
+                }
             } catch (RuntimeException | TimeoutException e) {
                 future.completeExceptionally(e);
             } catch (InterruptedException e) {
index bd12ddc5692df6547c10ed2f90e86841d36a7894..ee16d76160ae9476b88895802103825da8acb880 100644 (file)
@@ -218,7 +218,7 @@ public class SpotifyBridgeHandler extends BaseBridgeHandler
 
     @Override
     public String getUser() {
-        return thing.getProperties().get(PROPERTY_SPOTIFY_USER);
+        return thing.getProperties().getOrDefault(PROPERTY_SPOTIFY_USER, "");
     }
 
     @Override
index f872893dd2784ec6e343558bf7ff63ec1e5f5004..f8ec698afc54b3397e1f5ecbe7ec7ea250028e09 100644 (file)
@@ -189,8 +189,9 @@ public class SqueezeBoxPlayerHandler extends BaseThingHandler implements Squeeze
         // Some of the code below is not designed to handle REFRESH, only reply to channels where cached values exist
         if (command == RefreshType.REFRESH) {
             String channelID = channelUID.getId();
-            if (stateMap.containsKey(channelID)) {
-                updateState(channelID, stateMap.get(channelID));
+            State newState = stateMap.get(channelID);
+            if (newState != null) {
+                updateState(channelID, newState);
             }
             return;
         }
index 74036683ef5c7330dc527d51cc7d90d06eb8d32b..d9bf61a53dec5cc23e22e33b16c33767705e9163 100644 (file)
@@ -46,7 +46,7 @@ public class TACmiChannelTypeProvider implements ChannelTypeProvider {
         return channelTypesByUID.get(channelTypeUID);
     }
 
-    public ChannelType getInternalChannelType(ChannelTypeUID channelTypeUID) {
+    public @Nullable ChannelType getInternalChannelType(ChannelTypeUID channelTypeUID) {
         return channelTypesByUID.get(channelTypeUID);
     }
 
index e6eceb98194105d7d3f0734adcab3e60798919bb..562e300981b1e11fe007563df1345286f92a6253 100644 (file)
@@ -243,13 +243,15 @@ public class ApiPageParser extends AbstractSimpleMarkupHandler {
     @Override
     public void handleComment(final char @Nullable [] buffer, final int offset, final int len, final int line,
             final int col) throws ParseException {
-        logger.debug("Unexpected comment in {}:{}: {}", line, col, new String(buffer, offset, len));
+        logger.debug("Unexpected comment in {}:{}: {}", line, col,
+                buffer == null ? "<null>" : new String(buffer, offset, len));
     }
 
     @Override
     public void handleCDATASection(final char @Nullable [] buffer, final int offset, final int len, final int line,
             final int col) throws ParseException {
-        logger.debug("Unexpected CDATA in {}:{}: {}", line, col, new String(buffer, offset, len));
+        logger.debug("Unexpected CDATA in {}:{}: {}", line, col,
+                buffer == null ? "<null>" : new String(buffer, offset, len));
     }
 
     @Override
index 3270c1e5d22fb4909e472e410436daa881a0787d..aeea36440c8473a86a76770b22ca6745edf9561d 100644 (file)
@@ -170,13 +170,15 @@ public class ChangerX2Parser extends AbstractSimpleMarkupHandler {
     @Override
     public void handleAutoCloseElement(final @Nullable String elementName, final int line, final int col)
             throws ParseException {
-        logger.debug("Unexpected AutoCloseElement in {}:{}: {}", line, col, elementName);
+        logger.debug("Unexpected AutoCloseElement in {}:{}: {}", line, col,
+                elementName == null ? "<null>" : elementName);
     }
 
     @Override
     public void handleUnmatchedCloseElement(final @Nullable String elementName, final int line, final int col)
             throws ParseException {
-        logger.debug("Unexpected UnmatchedCloseElement in {}:{}: {}", line, col, elementName);
+        logger.debug("Unexpected UnmatchedCloseElement in {}:{}: {}", line, col,
+                elementName == null ? "<null>" : elementName);
     }
 
     @Override
@@ -190,13 +192,15 @@ public class ChangerX2Parser extends AbstractSimpleMarkupHandler {
     @Override
     public void handleComment(final char @Nullable [] buffer, final int offset, final int len, final int line,
             final int col) throws ParseException {
-        logger.debug("Unexpected comment in {}:{}: {}", line, col, new String(buffer, offset, len));
+        logger.debug("Unexpected comment in {}:{}: {}", line, col,
+                buffer == null ? "<null>" : new String(buffer, offset, len));
     }
 
     @Override
     public void handleCDATASection(final char @Nullable [] buffer, final int offset, final int len, final int line,
             final int col) throws ParseException {
-        logger.debug("Unexpected CDATA in {}:{}: {}", line, col, new String(buffer, offset, len));
+        logger.debug("Unexpected CDATA in {}:{}: {}", line, col,
+                buffer == null ? "<null>" : new String(buffer, offset, len));
     }
 
     @Override
index e28432b72565c9a68b7810c0e0ff300c6263da1d..025bc8de7d0b5db2d5587d7c9267b36e27cf47f4 100644 (file)
@@ -408,7 +408,7 @@ public class TelegramHandler extends BaseThingHandler {
         return replyIdToCallbackId.get(new ReplyKey(chatId, replyId));
     }
 
-    public Integer removeMessageId(Long chatId, String replyId) {
+    public @Nullable Integer removeMessageId(Long chatId, String replyId) {
         return replyIdToMessageId.remove(new ReplyKey(chatId, replyId));
     }
 
index e155d6b52a81e26ae9907fb76323ed55c9d35a48..a0412d5a8d156ba6feee17fe49dda4f1fbc7b154 100644 (file)
@@ -255,6 +255,9 @@ public class TelegramActions implements ThingActions {
     public boolean sendTelegram(@ActionInput(name = "chatId") @Nullable Long chatId,
             @ActionInput(name = "message") @Nullable String message,
             @ActionInput(name = "args") @Nullable Object... args) {
+        if (message == null) {
+            return false;
+        }
         return sendTelegram(chatId, String.format(message, args));
     }
 
@@ -444,7 +447,14 @@ public class TelegramActions implements ThingActions {
 
     public static boolean sendTelegramAnswer(ThingActions actions, @Nullable String chatId, @Nullable String replyId,
             @Nullable String message) {
-        return ((TelegramActions) actions).sendTelegramAnswer(Long.valueOf(chatId), replyId, message);
+        if (actions instanceof TelegramActions) {
+            if (chatId == null) {
+                return false;
+            }
+            return ((TelegramActions) actions).sendTelegramAnswer(Long.valueOf(chatId), replyId, message);
+        } else {
+            throw new IllegalArgumentException("Actions is not an instance of TelegramActions");
+        }
     }
 
     @Override
index 67df801922c430e0fd1b098ebebc0c54c236fda8..6c8f024be58963fd92d0c334f166b7c55732ae5f 100644 (file)
@@ -416,8 +416,9 @@ public class TibberHandler extends BaseThingHandler {
 
         @OnWebSocketError
         public void onWebSocketError(Throwable e) {
-            logger.debug("Error during websocket communication: {}", e.getMessage());
-            onClose(0, e.getMessage());
+            String message = e.getMessage();
+            logger.debug("Error during websocket communication: {}", message);
+            onClose(0, message != null ? message : "null");
         }
 
         @OnWebSocketMessage
index d1b1de3dcc0e3b7a9e388b5af2f479570920075b..61703e5362e9ce3ff918267c9e9fea2702f6c9b4 100644 (file)
@@ -85,7 +85,12 @@ public abstract class TouchWandBaseUnitHandler extends BaseThingHandler implemen
 
         bridgeHandler = (TouchWandBridgeHandler) bridge.getHandler();
 
-        unitId = getThing().getProperties().get(HANDLER_PROPERTIES_ID); // TouchWand unit id
+        String unitId = getThing().getProperties().get(HANDLER_PROPERTIES_ID); // TouchWand unit id
+        if (unitId == null) {
+            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "unitID missing");
+            return;
+        }
+        this.unitId = unitId;
 
         TouchWandBridgeHandler myTmpBridgeHandler = bridgeHandler;
         if (myTmpBridgeHandler != null) {
index 2f46a5bcf5ba0b6754414549186d610b541c015d..f983180296d8d57cd1d760d68e1acaa21435ee67 100644 (file)
@@ -262,7 +262,7 @@ public class UpnpXMLParser {
         @Override
         public void characters(char @Nullable [] ch, int start, int length) throws SAXException {
             Element el = element;
-            if (el == null) {
+            if (el == null || ch == null) {
                 return;
             }
             switch (el) {
index c9c93687f6c03bf6387fee55e59c0aeae5071960..ee5a3483348d7a1c91fa2a91dc0919d72f84dfd0 100644 (file)
@@ -165,12 +165,12 @@ public abstract class UpnpHandler extends BaseThingHandler implements UpnpIOPart
 
     @Override
     public void onValueReceived(@Nullable String variable, @Nullable String value, @Nullable String service) {
-        if (variable == null) {
+        if (variable == null || value == null) {
             return;
         }
         switch (variable) {
             case "CurrentTransportState":
-                if (!((value == null) || (value.isEmpty()))) {
+                if (!value.isEmpty()) {
                     transportState = value;
                 }
                 break;
index 3443c03b7913a293781aad70d37b46002eb69980..3bbe561a72a57eb21613a0743b3afa57d2bf5069 100644 (file)
@@ -590,7 +590,7 @@ public class UpnpRendererHandler extends UpnpHandler {
                     playing = true;
                     updateState(CONTROL, PlayPauseType.PLAY);
                     scheduleTrackPositionRefresh();
-                } else if ("PAUSED_PLAYBACK".contentEquals(value)) {
+                } else if ("PAUSED_PLAYBACK".equals(value)) {
                     updateState(CONTROL, PlayPauseType.PAUSE);
                 }
                 break;
index db1eacb48b59b81aadfb736432a2b1018f5ca7e0..1b5715a4bfa943eadc94d435a69df2dc070fef07 100644 (file)
@@ -207,7 +207,13 @@ public class UpnpServerHandler extends UpnpHandler {
                                 // No parent found, so make it the root directory
                                 browseTarget = DIRECTORY_ROOT;
                             }
-                            currentEntry = parentMap.get(browseTarget);
+                            UpnpEntry entry = parentMap.get(browseTarget);
+                            if (entry == null) {
+                                logger.info("Browse target not found. Exiting.");
+                                return;
+                            }
+                            currentEntry = entry;
+
                         }
                         updateState(CURRENTID, StringType.valueOf(currentEntry.getId()));
                         logger.debug("Browse target {}", browseTarget);
@@ -349,8 +355,8 @@ public class UpnpServerHandler extends UpnpHandler {
     }
 
     /**
-     * Method that does a UPnP browse on a content directory. Results will be retrieved in the {@link onValueReceived}
-     * method.
+     * Method that does a UPnP browse on a content directory. Results will be retrieved in the
+     * {@link #onValueReceived(String, String, String)} method.
      *
      * @param objectID content directory object
      * @param browseFlag BrowseMetaData or BrowseDirectChildren
@@ -373,8 +379,8 @@ public class UpnpServerHandler extends UpnpHandler {
     }
 
     /**
-     * Method that does a UPnP search on a content directory. Results will be retrieved in the {@link onValueReceived}
-     * method.
+     * Method that does a UPnP search on a content directory. Results will be retrieved in the
+     * {@link #onValueReceived(String, String, String)} method.
      *
      * @param containerID content directory container
      * @param searchCriteria search criteria, examples:
index 4932027213367f29e47b3fb7183d08092d4f88b7..60e2557d7a46d5c7125684df9aabcce84c9a47d3 100644 (file)
@@ -204,6 +204,6 @@ public class VeluxRSBindingConfig extends VeluxBindingConfig {
     public String getSceneName(Integer level) {
         logger.trace("getSceneName({}) called.", level);
         logger.trace("getSceneName() returning {}.", mapDescending.get(level));
-        return mapDescending.get(level);
+        return mapDescending.getOrDefault(level, "null");
     }
 }
index bfcd098368cc3531b6d26c152c9a9c637127f49d..9f277ed1eeb23794a316eb8b2dad17540746c35b 100644 (file)
@@ -86,10 +86,8 @@ public class VeluxExistingProducts {
 
     public boolean isRegistered(ProductBridgeIndex bridgeProductIndex) {
         logger.trace("isRegisteredProductBridgeIndex {}) called.", bridgeProductIndex.toString());
-        if (!bridgeIndexToSerialNumber.containsKey(bridgeProductIndex.toInt())) {
-            return false;
-        }
-        return isRegistered(bridgeIndexToSerialNumber.get(bridgeProductIndex.toInt()));
+        String serialNumber = bridgeIndexToSerialNumber.get(bridgeProductIndex.toInt());
+        return serialNumber != null && isRegistered(serialNumber);
     }
 
     public boolean register(VeluxProduct newProduct) {
@@ -148,15 +146,16 @@ public class VeluxExistingProducts {
         if (!isRegistered(productUniqueIndexOrSerialNumber)) {
             return VeluxProduct.UNKNOWN;
         }
-        return existingProductsByUniqueIndex.get(productUniqueIndexOrSerialNumber);
+        return existingProductsByUniqueIndex.getOrDefault(productUniqueIndexOrSerialNumber, VeluxProduct.UNKNOWN);
     }
 
     public VeluxProduct get(ProductBridgeIndex bridgeProductIndex) {
         logger.trace("get({}) called.", bridgeProductIndex);
-        if (!isRegistered(bridgeProductIndex)) {
+        String serialNumber = bridgeIndexToSerialNumber.get(bridgeProductIndex.toInt());
+        if (!isRegistered(bridgeProductIndex) || serialNumber == null) {
             return VeluxProduct.UNKNOWN;
         }
-        return existingProductsByUniqueIndex.get(bridgeIndexToSerialNumber.get(bridgeProductIndex.toInt()));
+        return existingProductsByUniqueIndex.getOrDefault(serialNumber, VeluxProduct.UNKNOWN);
     }
 
     public VeluxProduct[] values() {
index 217b86f75881c5685739c35549e20259dde7cfc8..2563e414b94000e08a520d2962fff0bfee714ade 100644 (file)
@@ -84,7 +84,7 @@ public class VeluxExistingScenes {
         if (!isRegistered(sceneName)) {
             return VeluxScene.UNKNOWN;
         }
-        return existingScenesBySceneName.get(sceneName.toString());
+        return existingScenesBySceneName.getOrDefault(sceneName.toString(), VeluxScene.UNKNOWN);
     }
 
     public VeluxScene[] values() {
index 8936beebb4f66599a6404e2d6867f78073eb88d6..56e10b6d030dc3cf06901fe31c445d00dfaad329 100644 (file)
@@ -135,11 +135,7 @@ public class VeluxGwState {
         }
 
         public static VeluxGatewaySubState get(int stateValue) {
-            if (LOOKUPTYPEID2ENUM.containsKey(stateValue)) {
-                return LOOKUPTYPEID2ENUM.get(stateValue);
-            } else {
-                return VeluxGatewaySubState.UNDEFTYPE;
-            }
+            return LOOKUPTYPEID2ENUM.getOrDefault(stateValue, VeluxGatewaySubState.UNDEFTYPE);
         }
     }
 
index e996293cf80e332340368c9246b87a09c46e4beb..d39da7b9b1660659881278454142518d4fb77adb 100644 (file)
@@ -343,11 +343,7 @@ public class VeluxKLFAPI {
         }
 
         public static Command get(short thisTypeId) {
-            if (LOOKUPTYPEID2ENUM.containsKey(thisTypeId)) {
-                return LOOKUPTYPEID2ENUM.get(thisTypeId);
-            } else {
-                return Command.UNDEFTYPE;
-            }
+            return LOOKUPTYPEID2ENUM.getOrDefault(thisTypeId, Command.UNDEFTYPE);
         }
     }
 }
index ba98283a42d509c3b3f9ba1365d86bbc23297886..a6675bb0058e381e43cf9cb19b220d692b39e833 100644 (file)
@@ -341,7 +341,8 @@ public class VenstarThermostatHandler extends ConfigStatusThingHandler {
             }
         } catch (VenstarCommunicationException | JsonSyntaxException e) {
             log.debug("Unable to fetch info data", e);
-            goOffline(ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
+            String message = e.getMessage();
+            goOffline(ThingStatusDetail.COMMUNICATION_ERROR, message != null ? message : "");
         } catch (VenstarAuthenticationException e) {
             goOffline(ThingStatusDetail.CONFIGURATION_ERROR, "Authorization Failed");
         }
@@ -376,7 +377,8 @@ public class VenstarThermostatHandler extends ConfigStatusThingHandler {
             goOnline();
         } catch (VenstarCommunicationException | JsonSyntaxException e) {
             log.debug("Unable to fetch info data", e);
-            goOffline(ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
+            String message = e.getMessage();
+            goOffline(ThingStatusDetail.COMMUNICATION_ERROR, message != null ? message : "");
         } catch (VenstarAuthenticationException e) {
             goOffline(ThingStatusDetail.CONFIGURATION_ERROR, "Authorization Failed");
         }
index 406f5216e823d331664c5c731b6404d6dc3f433f..24eeb78028b4af19524b35830ab73499f2415566 100644 (file)
@@ -151,7 +151,12 @@ public class VerisureEventLogThingHandler extends VerisureThingHandler<VerisureE
         Collections.reverse(newEventList);
         ArrayList<Event> events = new ArrayList<>();
         for (PagedList newEvent : newEventList) {
-            long eventTime = ZonedDateTime.parse(newEvent.getEventTime()).toEpochSecond();
+            String eventTimeString = newEvent.getEventTime();
+            if (eventTimeString == null) {
+                logger.debug("Event-Time is null: {}", newEvent);
+                continue;
+            }
+            long eventTime = ZonedDateTime.parse(eventTimeString).toEpochSecond();
             logger.trace("Event time: {} Last Event time: {}", eventTime, lastEventTime);
             if (eventTime > lastEventTime) {
                 logger.debug("Create event {} for event time {}", newEvent.getEventType(), eventTime);
index 97a3e36603b4a245183477f0e624caf796a7132d..36a3331aa2a370a710006584317d02a074b696aa 100644 (file)
@@ -67,8 +67,9 @@ public class VerisureGatewayThingHandler extends VerisureThingHandler<VerisureGa
                                 updateState(channelUID, state);
                             } else {
                                 String timestamp = communicationState.getTestDate();
-                                if (timestamp != null && channelUID.toString()
-                                        .contains(communicationState.getHardwareCarrierType())) {
+                                String carrierType = communicationState.getHardwareCarrierType();
+                                if (timestamp != null && carrierType != null
+                                        && channelUID.toString().contains(carrierType)) {
                                     updateTimeStamp(timestamp, channelUID);
                                 }
                             }
index a75beecece0413ed38015c96f315c57e373127f7..7920e6cce5ac969c6c163a9bd8c207a14cb65bc0 100644 (file)
@@ -17,6 +17,7 @@ import static org.openhab.binding.volvooncall.internal.VolvoOnCallBindingConstan
 import java.time.Duration;
 import java.time.ZoneId;
 import java.time.ZonedDateTime;
+import java.time.temporal.Temporal;
 import java.util.Optional;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
@@ -73,8 +74,14 @@ public class TripDetail {
         return getPositionAsState(endPosition);
     }
 
-    public long getDurationInMinutes() {
-        return Duration.between(startTime, endTime).toMinutes();
+    public Optional<Long> getDurationInMinutes() {
+        Temporal start = startTime;
+        Temporal end = endTime;
+        if (start == null || end == null) {
+            return Optional.empty();
+        } else {
+            return Optional.of(Duration.between(start, end).toMinutes());
+        }
     }
 
     public Optional<Integer> getFuelConsumption() {
index c14427db9f1bfbaa5d5c4d16dd20b73624546d65..3a21f01b3054cc7badc9860b5356ceae2a89345d 100644 (file)
@@ -131,8 +131,9 @@ public class VehicleHandler extends BaseThingHandler {
                                 thing.getProperties().entrySet().stream().filter(p -> "true".equals(p.getValue()))
                                         .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
 
-                        if (thing.getProperties().containsKey(LAST_TRIP_ID)) {
-                            lastTripId = Long.parseLong(thing.getProperties().get(LAST_TRIP_ID));
+                        String lastTripIdString = thing.getProperties().get(LAST_TRIP_ID);
+                        if (lastTripIdString != null) {
+                            lastTripId = Long.parseLong(lastTripIdString);
                         }
 
                         updateStatus(ThingStatus.ONLINE);
@@ -294,7 +295,8 @@ public class VehicleHandler extends BaseThingHandler {
             case TRIP_END_TIME:
                 return tripDetails.getEndTime();
             case TRIP_DURATION:
-                return new QuantityType<>(tripDetails.getDurationInMinutes(), MINUTE);
+                return tripDetails.getDurationInMinutes().map(value -> (State) new QuantityType<>(value, MINUTE))
+                        .orElse(UnDefType.UNDEF);
             case TRIP_START_ODOMETER:
                 return new QuantityType<>((double) tripDetails.startOdometer / 1000, KILO(METRE));
             case TRIP_STOP_ODOMETER:
index 42725d7fe819dfcea035c42be38750b50b3ce611..74ad11e644ba3f4e35f69edd8d31b174f0a68b7f 100644 (file)
@@ -264,7 +264,8 @@ public class YamahaBridgeHandler extends BaseBridgeHandler
             onConnectivityError(e);
             return;
         } catch (ReceivedMessageParseException e) {
-            updateProperty(PROPERTY_MENU_ERROR, e.getMessage());
+            String message = e.getMessage();
+            updateProperty(PROPERTY_MENU_ERROR, message != null ? message : "");
             // Some AVRs send unexpected responses. We log parser exceptions therefore.
             logger.debug("Parse error!", e);
         } finally {
index 1da33f9189b4dda4fd17c0bc493b025e8131d101..2ecbc45df2ab71ed416e9406550f92b9d9b28117 100644 (file)
@@ -727,7 +727,8 @@ public class YamahaZoneThingHandler extends BaseThingHandler
                 logger.debug("State update error. Changing thing to offline", e);
                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
             } catch (ReceivedMessageParseException e) {
-                updateProperty(PROPERTY_LAST_PARSE_ERROR, e.getMessage());
+                String message = e.getMessage();
+                updateProperty(PROPERTY_LAST_PARSE_ERROR, message != null ? message : "");
                 // Some AVRs send unexpected responses. We log parser exceptions therefore.
                 logger.debug("Parse error!", e);
             }
index 9ea687d9dc0cd3ee25f3959f349f95aef6cafb7e..648edd5072218c2ceaf5d67dacab8fe43d3cc591 100644 (file)
@@ -304,14 +304,26 @@ public class DeviceManager {
         device.setAddress(addressInfo[1].substring(2));
         device.setPort(Integer.parseInt(addressInfo[2]));
         device.setOnline(true);
-        Color color = new Color(Integer.parseInt(bulbInfo.get("rgb")));
         DeviceStatus status = device.getDeviceStatus();
-        status.setR(color.getRed());
-        status.setG(color.getGreen());
-        status.setB(color.getBlue());
-        status.setCt(Integer.parseInt(bulbInfo.get("ct")));
-        status.setHue(Integer.parseInt(bulbInfo.get("hue")));
-        status.setSat(Integer.parseInt(bulbInfo.get("sat")));
+        String rgb = bulbInfo.get("rgb");
+        if (rgb != null) {
+            Color color = new Color(Integer.parseInt(rgb));
+            status.setR(color.getRed());
+            status.setG(color.getGreen());
+            status.setB(color.getBlue());
+        }
+        String ct = bulbInfo.get("ct");
+        if (ct != null) {
+            status.setCt(Integer.parseInt(ct));
+        }
+        String hue = bulbInfo.get("hue");
+        if (hue != null) {
+            status.setHue(Integer.parseInt(hue));
+        }
+        String sat = bulbInfo.get("sat");
+        if (sat != null) {
+            status.setSat(Integer.parseInt(sat));
+        }
     }
 
     public static String getDefaultName(DeviceBase device) {
index fc5a48c6e64137775693abaa65ad181c90289d1e..8d6fed1d44da926928392a7ca7e1e7a236c82c20 100644 (file)
@@ -319,9 +319,9 @@ public abstract class ZWayDeviceHandler extends BaseThingHandler {
             // Channel thermostat mode
             if (channel.getUID().equals(new ChannelUID(getThing().getUID(), THERMOSTAT_MODE_CC_CHANNEL))) {
                 // Load physical device
-                Integer nodeId = Integer.parseInt(channel.getProperties().get("nodeId"));
-                ZWaveDevice physicalDevice = zwayBridgeHandler.getZWayApi().getZWaveDevice(nodeId);
-
+                String nodeIdString = channel.getProperties().get("nodeId");
+                ZWaveDevice physicalDevice = nodeIdString == null ? null
+                        : zwayBridgeHandler.getZWayApi().getZWaveDevice(Integer.parseInt(nodeIdString));
                 if (physicalDevice != null) {
                     updateState(channel.getUID(), new DecimalType(physicalDevice.getInstances().get0()
                             .getCommandClasses().get64().getData().getMode().getValue()));
@@ -507,15 +507,15 @@ public abstract class ZWayDeviceHandler extends BaseThingHandler {
             }
         } else if (channel.getUID().equals(new ChannelUID(getThing().getUID(), THERMOSTAT_MODE_CC_CHANNEL))) {
             // Load physical device
-            Integer nodeId = Integer.parseInt(channel.getProperties().get("nodeId"));
             if (command instanceof DecimalType) {
+                String nodeIdString = channel.getProperties().get("nodeId");
                 logger.debug("Handle command: DecimalType");
-
-                zwayBridgeHandler.getZWayApi().getZWaveDeviceThermostatModeSet(nodeId,
-                        Integer.parseInt(command.toString()));
+                if (nodeIdString != null) {
+                    zwayBridgeHandler.getZWayApi().getZWaveDeviceThermostatModeSet(Integer.parseInt(nodeIdString),
+                            Integer.parseInt(command.toString()));
+                }
             } else if (command instanceof RefreshType) {
                 logger.debug("Handle command: RefreshType");
-
                 refreshChannel(channel);
             }
         }
index 99fc4162cee6ae28030da317e072f5e006b73ed2..c3a3aef27aaa9a785364fe58b70bcac087629cfa 100644 (file)
@@ -92,13 +92,21 @@ public class HomekitChangeListener implements ItemRegistryChangeListener {
     private void initialiseRevision() {
         int revision;
         try {
-            revision = Integer.parseInt(storage.get(REVISION_CONFIG));
+            String revisionString = storage.get(REVISION_CONFIG);
+            if (revisionString == null) {
+                throw new NumberFormatException();
+            }
+            revision = Integer.parseInt(revisionString);
         } catch (NumberFormatException e) {
             revision = 1;
             storage.put(REVISION_CONFIG, "" + revision);
         }
         try {
-            lastAccessoryCount = Integer.parseInt(storage.get(ACCESSORY_COUNT));
+            String accessoryCountString = storage.get(ACCESSORY_COUNT);
+            if (accessoryCountString == null) {
+                throw new NumberFormatException();
+            }
+            lastAccessoryCount = Integer.parseInt(accessoryCountString);
         } catch (NumberFormatException e) {
             lastAccessoryCount = 0;
             storage.put(ACCESSORY_COUNT, "" + accessoryRegistry.getAllAccessories().size());
index 69c13a0aa70f3bd09b5af1ca00a3427061834f9d..5cde5abc6d4fb11ae438d3fd358ff2bdb5623ddc 100644 (file)
@@ -454,8 +454,6 @@ public class HomekitAccessoryFactory {
      * @return new characteristic type
      */
     private static HomekitCharacteristicType legacyCheck(HomekitCharacteristicType characteristicType) {
-        if (LEGACY_CHARACTERISTICS_MAPPING.containsKey(characteristicType))
-            return LEGACY_CHARACTERISTICS_MAPPING.get(characteristicType);
-        return characteristicType;
+        return LEGACY_CHARACTERISTICS_MAPPING.getOrDefault(characteristicType, characteristicType);
     }
 }
index 032ce3516ea2df4be66588b673128cdc212454b8..c21b4762046c2c0b44d388c4f1ca849d13a149be 100644 (file)
@@ -25,6 +25,7 @@ import javax.ws.rs.core.Response.ResponseBuilder;
 import javax.ws.rs.core.UriInfo;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 import org.openhab.io.hueemulation.internal.dto.response.HueResponse;
 import org.openhab.io.hueemulation.internal.dto.response.HueResponse.HueErrorMessage;
 import org.openhab.io.hueemulation.internal.dto.response.HueResponseSuccessSimple;
@@ -91,8 +92,9 @@ public class NetworkUtils {
      * @param message A message
      * @return
      */
-    public static Response singleError(Gson gson, UriInfo uri, int type, String message) {
-        HueResponse e = new HueResponse(new HueErrorMessage(type, uri.getPath().replace("/api", ""), message));
+    public static Response singleError(Gson gson, UriInfo uri, int type, @Nullable String message) {
+        HueResponse e = new HueResponse(
+                new HueErrorMessage(type, uri.getPath().replace("/api", ""), message != null ? message : ""));
         String str = gson.toJson(Collections.singleton(e), new TypeToken<List<?>>() {
         }.getType());
         int httpCode = 500;
index 16ae0d477c76c16311c9760ae626f7a98b79bcda..865c868bf4812eaa6b3671ace6f622136b0be2a4 100644 (file)
@@ -308,10 +308,11 @@ public class Scenes implements RegistryChangeListener<Rule> {
             return NetworkUtils.singleError(cs.gson, uri, HueResponse.ARGUMENTS_INVALID, e.getMessage());
         }
 
+        List<String> lightsList = changeRequest.lights;
         return NetworkUtils.successList(cs.gson, Arrays.asList( //
                 new HueSuccessGeneric(changeRequest.name, "/scenes/" + id + "/name"), //
                 new HueSuccessGeneric(changeRequest.description, "/scenes/" + id + "/description"), //
-                new HueSuccessGeneric(changeRequest.lights != null ? String.join(",", changeRequest.lights) : null,
+                new HueSuccessGeneric(lightsList != null ? String.join(",", lightsList) : null,
                         "/scenes/" + id + "/lights") //
         ));
     }
index a5868fbf2be781f87a5b1ae607251beb2dcb712d..7317f27e1e01aa2c3f7eb19fdb51548f73b7662d 100644 (file)
@@ -23,6 +23,7 @@ import org.eclipse.jdt.annotation.NonNullByDefault;
 import org.eclipse.jdt.annotation.Nullable;
 import org.openhab.core.common.registry.RegistryChangeListener;
 import org.openhab.core.items.Item;
+import org.openhab.core.items.ItemNotFoundException;
 import org.openhab.core.items.ItemRegistry;
 import org.openhab.core.items.RegistryHook;
 
@@ -87,13 +88,21 @@ public class DummyItemRegistry implements ItemRegistry {
     }
 
     @Override
-    public Item getItem(String name) {
-        return items.get(name);
+    public Item getItem(String name) throws ItemNotFoundException {
+        Item item = items.get(name);
+        if (item == null) {
+            throw new ItemNotFoundException(name);
+        }
+        return item;
     }
 
     @Override
-    public Item getItemByPattern(String name) {
-        return items.get(name);
+    public Item getItemByPattern(String name) throws ItemNotFoundException {
+        Item item = items.get(name);
+        if (item == null) {
+            throw new ItemNotFoundException(name);
+        }
+        return item;
     }
 
     @Override
index be26429f085ee6468e81aa2b48eb9444b36d7059..5d9738817bb51c6a64a3fa2f9bfd31555bfef4ea 100644 (file)
@@ -135,9 +135,9 @@ class OpenHabToDeviceConverter {
             final String manufacturer = StringUtils.isEmpty(properties.get("Manufacturer")) ? "openHAB"
                     : properties.get("Manufacturer");
 
-            final Integer standbyDelay = parseInteger(properties.get("Standby Command Delay"));
-            final Integer switchDelay = parseInteger(properties.get("Source Switch Delay"));
-            final Integer shutDownDelay = parseInteger(properties.get("Shutdown Delay"));
+            final Integer standbyDelay = parseInteger(properties.getOrDefault("Standby Command Delay", "0"));
+            final Integer switchDelay = parseInteger(properties.getOrDefault("Source Switch Delay", "0"));
+            final Integer shutDownDelay = parseInteger(properties.getOrDefault("Shutdown Delay", "0"));
 
             final NeeoDeviceTiming timing = new NeeoDeviceTiming(standbyDelay, switchDelay, shutDownDelay);
 
index 030c6a8b09c7a3e868a7a11e5ee118aec02d5da0..bac60524fb69b87896c76567f0457829437767c4 100644 (file)
@@ -74,7 +74,8 @@ public class HttpRequest implements AutoCloseable {
                 content.close();
             }
         } catch (IOException | IllegalStateException | ProcessingException e) {
-            return new HttpResponse(HttpStatus.SERVICE_UNAVAILABLE_503, e.getMessage());
+            String message = e.getMessage();
+            return new HttpResponse(HttpStatus.SERVICE_UNAVAILABLE_503, message != null ? message : "");
         }
     }
 
@@ -100,7 +101,8 @@ public class HttpRequest implements AutoCloseable {
                 content.close();
             }
         } catch (IOException | IllegalStateException | ProcessingException e) {
-            return new HttpResponse(HttpStatus.SERVICE_UNAVAILABLE_503, e.getMessage());
+            String message = e.getMessage();
+            return new HttpResponse(HttpStatus.SERVICE_UNAVAILABLE_503, message != null ? message : "");
         }
     }
 
index 8e47c241484a1a302980ac6deff46a0b97602061..9535e7324c65d191bc147c9ea05ef8ac3437284d 100644 (file)
@@ -101,7 +101,7 @@ public class HttpResponse {
             return "";
         }
 
-        return new String(contents, StandardCharsets.UTF_8);
+        return new String(localContents, StandardCharsets.UTF_8);
     }
 
     /**
index ebd6c6ec00cb526c4978722a63cb8291a29df220..c18669630d59e993dfb200aa8cb3b1e4af37ce69 100644 (file)
@@ -13,6 +13,7 @@
 package org.openhab.io.transport.modbus.exception;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 import org.openhab.io.transport.modbus.endpoint.ModbusSlaveEndpoint;
 
 /**
@@ -45,7 +46,7 @@ public class ModbusConnectionException extends ModbusTransportException {
     }
 
     @Override
-    public String getMessage() {
+    public @Nullable String getMessage() {
         return String.format("Error connecting to endpoint %s", endpoint);
     }
 
index 7f472f7a5aa061a5fd9f24bd8c94a230af24a017..ff9e2f6fa11d8818e4418f0fccf3cae88afec29c 100644 (file)
@@ -13,6 +13,7 @@
 package org.openhab.io.transport.modbus.exception;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 
 /**
  * Exception representing situation where function code of the response does not match request
@@ -33,7 +34,7 @@ public class ModbusUnexpectedResponseFunctionCodeException extends ModbusTranspo
     }
 
     @Override
-    public String getMessage() {
+    public @Nullable String getMessage() {
         return String.format("Function code of request (%d) does not equal response (%d)", requestFunctionCode,
                 responseFunctionCode);
     }
index 16ba3adc59fc233c73574c892abdbe5ad2f958eb..76a8cef11f34f9170382a0a80ec976f2ebe8c8fb 100644 (file)
@@ -13,6 +13,7 @@
 package org.openhab.io.transport.modbus.exception;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 
 /**
  * Exception representing situation where data length of the response does not match request
@@ -33,7 +34,7 @@ public class ModbusUnexpectedResponseSizeException extends ModbusTransportExcept
     }
 
     @Override
-    public String getMessage() {
+    public @Nullable String getMessage() {
         return String.format("Data length of the request (%d) does not equal response (%d). Slave response is invalid.",
                 requestSize, responseSize);
     }
index 312c9fdfd7d3e4d40356d114c9d4a815fcd35b78..36d8fc3c5b5425a921dbbb90da20d63a9fb4d3f0 100644 (file)
@@ -13,6 +13,7 @@
 package org.openhab.io.transport.modbus.exception;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 
 /**
  * Exception representing situation where transaction id of the response does not match request
@@ -33,7 +34,7 @@ public class ModbusUnexpectedTransactionIdException extends ModbusTransportExcep
     }
 
     @Override
-    public String getMessage() {
+    public @Nullable String getMessage() {
         return String.format("Transaction id of request (%d) does not equal response (%d). Slave response is invalid.",
                 requestId, responseId);
     }
index e8a11bde06c3aab7e2c87c638ab405973270b804..505f704c303cfc8f8fe9340fc13c574939a8d333 100644 (file)
@@ -13,6 +13,7 @@
 package org.openhab.io.transport.modbus.internal;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 import org.openhab.io.transport.modbus.exception.ModbusSlaveErrorResponseException;
 
 import net.wimpi.modbus.ModbusSlaveException;
@@ -43,7 +44,7 @@ public class ModbusSlaveErrorResponseExceptionImpl extends ModbusSlaveErrorRespo
     }
 
     @Override
-    public String getMessage() {
+    public @Nullable String getMessage() {
         return String.format("Slave responsed with error=%d", type);
     }
 
index 27efbd7f461cf64268b183bc2280cb96e9f4b5e0..24e8b0c09d75a00e6da1ef32acd4c345a64550d0 100644 (file)
@@ -15,6 +15,7 @@ package org.openhab.io.transport.modbus.internal;
 import java.io.IOException;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
 import org.openhab.io.transport.modbus.exception.ModbusSlaveIOException;
 
 import net.wimpi.modbus.ModbusIOException;
@@ -40,7 +41,7 @@ public class ModbusSlaveIOExceptionImpl extends ModbusSlaveIOException {
     }
 
     @Override
-    public String getMessage() {
+    public @Nullable String getMessage() {
         return String.format("Modbus IO Error with cause=%s, EOF=%s, message='%s', cause2=%s",
                 error.getClass().getSimpleName(),
                 error instanceof ModbusIOException ? ((ModbusIOException) error).isEOF() : "?", error.getMessage(),
index ca0f1f8661443382e1eb2a0a1a26c19e2cac4ec2..97ee8f0f4b2b01b2a437bde6a55666226fe05775 100644 (file)
@@ -422,7 +422,7 @@ public class DynamoDBPersistenceService extends AbstractBufferedPersistenceServi
             String tableName = tableNameResolver.fromItem(dynamoItem);
             Deque<DynamoDBItem<?>> batch = batchesByTable.computeIfAbsent(tableName, new Function<>() {
                 @Override
-                public Deque<DynamoDBItem<?>> apply(String t) {
+                public Deque<DynamoDBItem<?>> apply(@Nullable String t) {
                     return new ArrayDeque<>();
                 }
             });
index d409ea24385435a48c15968a2ba7497fabad0768..33e5212f6960313f20a8c80ebd795d4b2f2646f9 100644 (file)
@@ -15,6 +15,7 @@ package org.openhab.persistence.dynamodb.internal;
 import static org.junit.jupiter.api.Assertions.*;
 import static org.junit.jupiter.api.Assumptions.assumeTrue;
 
+import java.time.ZoneId;
 import java.time.ZonedDateTime;
 import java.util.Iterator;
 
@@ -53,9 +54,9 @@ import org.openhab.core.types.State;
 @NonNullByDefault
 public abstract class AbstractTwoItemIntegrationTest extends BaseIntegrationTest {
 
-    protected static @Nullable ZonedDateTime beforeStore;
-    protected static @Nullable ZonedDateTime afterStore1;
-    protected static @Nullable ZonedDateTime afterStore2;
+    protected static ZonedDateTime beforeStore = ZonedDateTime.of(2100, 1, 1, 0, 0, 0, 0, ZoneId.systemDefault());
+    protected static ZonedDateTime afterStore1 = ZonedDateTime.of(1900, 1, 1, 0, 0, 0, 0, ZoneId.systemDefault());
+    protected static ZonedDateTime afterStore2 = ZonedDateTime.of(1900, 1, 1, 0, 0, 0, 0, ZoneId.systemDefault());
 
     protected abstract String getItemName();
 
index 50bf179e8b38ef768aa1f9d3bf3cf25a8710daee..8554f5769106a4c3ffe03c4b76df23bad2ee54c0 100644 (file)
@@ -175,16 +175,19 @@ public class BaseIntegrationTest {
         });
 
         Map<String, Object> config = new HashMap<>();
-        config.put("region", System.getProperty("DYNAMODBTEST_REGION"));
-        config.put("accessKey", System.getProperty("DYNAMODBTEST_ACCESS"));
-        config.put("secretKey", System.getProperty("DYNAMODBTEST_SECRET"));
+        String value = System.getProperty("DYNAMODBTEST_REGION");
+        config.put("region", value != null ? value : "");
+        value = System.getProperty("DYNAMODBTEST_ACCESS");
+        config.put("accessKey", value != null ? value : "");
+        value = System.getProperty("DYNAMODBTEST_SECRET");
+        config.put("secretKey", value != null ? value : "");
         config.put("tablePrefix", "dynamodb-integration-tests-");
 
         // Disable buffering
         config.put("bufferSize", "0");
 
         for (Entry<String, Object> entry : config.entrySet()) {
-            if (entry.getValue() == null) {
+            if (((String) entry.getValue()).isEmpty()) {
                 LOGGER.warn(String.format(
                         "Expecting %s to have value for integration tests. Integration tests will be skipped",
                         entry.getKey()));
index 5c31a461f9c30fe08010939d6407928385255b2a..303e31719140c9a4cd644a7192b9046dc7380f64 100644 (file)
@@ -57,9 +57,10 @@ public class JavaScriptEngineManager {
      */
     protected CompiledScript getScript(final String filename) throws TransformationException {
         synchronized (compiledScriptMap) {
-            if (compiledScriptMap.containsKey(filename)) {
+            CompiledScript compiledScript = compiledScriptMap.get(filename);
+            if (compiledScript != null) {
                 logger.debug("Loading JavaScript {} from cache.", filename);
-                return compiledScriptMap.get(filename);
+                return compiledScript;
             } else {
                 final String path = TransformationScriptWatcher.TRANSFORM_FOLDER + File.separator + filename;
                 logger.debug("Loading script {} from storage ", path);
index 7189186b0a98148bbd4d6dd743b1c85d4f94c5ec..489f2062c724750036ca67ea4532cbb31d8a8a59 100644 (file)
@@ -14,10 +14,7 @@ package org.openhab.transform.map.internal;
 
 import static org.junit.jupiter.api.Assertions.*;
 
-import java.io.File;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
+import java.io.*;
 import java.util.Locale;
 import java.util.Properties;
 import java.util.concurrent.Callable;
@@ -125,7 +122,10 @@ public class MapTransformationServiceTest {
                 }
             }, 10000, 100);
         } catch (IOException e1) {
-            e1.printStackTrace(System.err);
+            PrintStream err = System.err;
+            if (err != null) {
+                e1.printStackTrace(err);
+            }
         }
 
         // Checks that an unknown input in an existing file give the expected
index e39d791514dbd796fc5e4198a7ee4f23da2d5aa0..afb37fa9f35af8b4d050a6c70d1d3f28c445460f 100644 (file)
     <module>org.openhab.voice.voicerss</module>
   </modules>
 
+  <properties>
+    <m2e.jdt.annotationpath>target/dependency</m2e.jdt.annotationpath>
+    <dep.noembedding/>
+  </properties>
+
   <dependencies>
+    <dependency>
+      <groupId>org.lastnpe.eea</groupId>
+      <artifactId>eea-all</artifactId>
+      <version>2.1.0</version>
+    </dependency>
     <!-- openHAB core -->
     <dependency>
       <groupId>org.openhab.core.bom</groupId>
     </dependency>
   </dependencies>
 
-  <properties>
-    <dep.noembedding/>
-  </properties>
-
   <build>
     <pluginManagement>
       <plugins>
             <configuration>
               <includeScope>runtime</includeScope>
               <includeTypes>jar</includeTypes>
-              <excludeGroupIds>javax.activation,org.apache.karaf.features</excludeGroupIds>
+              <excludeGroupIds>javax.activation,org.apache.karaf.features,org.lastnpe.eea</excludeGroupIds>
               <excludeArtifactIds>${dep.noembedding}</excludeArtifactIds>
               <outputDirectory>${project.build.directory}/classes</outputDirectory>
               <overWriteReleases>true</overWriteReleases>
               <type>jar</type>
             </configuration>
           </execution>
+          <execution>
+            <id>unpack-eea</id>
+            <goals>
+              <goal>unpack</goal>
+            </goals>
+            <configuration>
+              <artifactItems>
+                <artifactItem>
+                  <groupId>org.lastnpe.eea</groupId>
+                  <artifactId>eea-all</artifactId>
+                  <version>2.1.0</version>
+                  <overWrite>true</overWrite>
+                </artifactItem>
+              </artifactItems>
+            </configuration>
+          </execution>
         </executions>
       </plugin>
     </plugins>
index 1c457a3b01401968d02bb517ccdf3b80669b9e3d..efbc79ad63fdf81e7d347fd5c781d76e14ba1735 100644 (file)
@@ -211,7 +211,7 @@ public abstract class AbstractModbusOSGiTest extends JavaOSGiTest {
         addedLinks.add(link);
     }
 
-    protected List<State> getStateUpdates(String itemName) {
+    protected @Nullable List<State> getStateUpdates(String itemName) {
         return stateSubscriber.stateUpdates.get(itemName);
     }
 
index a051f813435cf1f402ab0a54b872201deaf6ac12..5930e170f18366f0eae3bb48608b7baeb7b64dc0 100644 (file)
     <module>org.openhab.persistence.mapdb.tests</module>
   </modules>
 
+  <properties>
+    <m2e.jdt.annotationpath>target/dependency</m2e.jdt.annotationpath>
+  </properties>
+
   <dependencies>
     <dependency>
       <groupId>org.openhab.core.bom</groupId>
         <groupId>biz.aQute.bnd</groupId>
         <artifactId>bnd-maven-plugin</artifactId>
       </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-dependency-plugin</artifactId>
+        <version>3.1.1</version>
+        <executions>
+          <execution>
+            <id>unpack-eea</id>
+            <goals>
+              <goal>unpack</goal>
+            </goals>
+            <configuration>
+              <artifactItems>
+                <artifactItem>
+                  <groupId>org.lastnpe.eea</groupId>
+                  <artifactId>eea-all</artifactId>
+                  <version>2.1.0</version>
+                  <overWrite>true</overWrite>
+                </artifactItem>
+              </artifactItems>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
     </plugins>
   </build>
 
diff --git a/pom.xml b/pom.xml
index 1e47ed4d078b9cef5dbfd4f7d7b06f73b74363a3..6cdc99711a1f590bbc4be615ad2cd70df78f2a01 100644 (file)
--- a/pom.xml
+++ b/pom.xml
@@ -284,6 +284,10 @@ Import-Package: \\
           <version>3.8.1</version>
           <configuration>
             <compilerId>eclipse</compilerId>
+            <compilerArguments>
+              <annotationpath>CLASSPATH</annotationpath>
+              <classpath>${project.build.directory}/dependency</classpath>
+            </compilerArguments>
             <compilerArgs>
               <arg>-err:+nullAnnot(org.eclipse.jdt.annotation.Nullable|org.eclipse.jdt.annotation.NonNull|org.eclipse.jdt.annotation.NonNullByDefault),+inheritNullAnnot,-nullUncheckedConversion</arg>
               <arg>-warn:+null,+inheritNullAnnot,+nullAnnotConflict,-nullUncheckedConversion,+nullAnnotRedundant,+nullDereference</arg>