diff --git a/bundles/org.openhab.automation.jrubyscripting/src/main/java/org/openhab/automation/jrubyscripting/internal/JRubyScriptEngineConfiguration.java b/bundles/org.openhab.automation.jrubyscripting/src/main/java/org/openhab/automation/jrubyscripting/internal/JRubyScriptEngineConfiguration.java index 73c2991099349..b6989e8222a5e 100644 --- a/bundles/org.openhab.automation.jrubyscripting/src/main/java/org/openhab/automation/jrubyscripting/internal/JRubyScriptEngineConfiguration.java +++ b/bundles/org.openhab.automation.jrubyscripting/src/main/java/org/openhab/automation/jrubyscripting/internal/JRubyScriptEngineConfiguration.java @@ -379,7 +379,7 @@ private enum Type { private final String defaultValue; private final Optional mappedTo; private final Type type; - private Optional value; + private @Nullable String value; private OptionalConfigurationElement(String defaultValue) { this(Type.OTHER, defaultValue, null); @@ -389,19 +389,19 @@ private OptionalConfigurationElement(Type type, String defaultValue, @Nullable S this.type = type; this.defaultValue = defaultValue; this.mappedTo = Optional.ofNullable(mappedTo); - value = Optional.empty(); } private String getValue() { - return value.orElse(defaultValue); + String value = this.value; + return value != null ? value : this.defaultValue; } - private void setValue(String value) { - this.value = Optional.of(value); + private void setValue(@Nullable String value) { + this.value = value; } private void clearValue() { - this.value = Optional.empty(); + this.value = null; } private Optional mappedTo() { diff --git a/bundles/org.openhab.automation.jsscripting/src/main/java/org/openhab/automation/jsscripting/internal/fs/watch/JSScriptFileWatcher.java b/bundles/org.openhab.automation.jsscripting/src/main/java/org/openhab/automation/jsscripting/internal/fs/watch/JSScriptFileWatcher.java index 098c93ac97562..cde752d3bcdde 100644 --- a/bundles/org.openhab.automation.jsscripting/src/main/java/org/openhab/automation/jsscripting/internal/fs/watch/JSScriptFileWatcher.java +++ b/bundles/org.openhab.automation.jsscripting/src/main/java/org/openhab/automation/jsscripting/internal/fs/watch/JSScriptFileWatcher.java @@ -48,9 +48,10 @@ public JSScriptFileWatcher(final @Reference(target = WatchService.CONFIG_WATCHER @Override protected Optional getScriptType(Path scriptFilePath) { - String scriptType = super.getScriptType(scriptFilePath).orElse(null); - if (!scriptFilePath.startsWith(getWatchPath().resolve("node_modules")) && ("js".equals(scriptType))) { - return Optional.of(scriptType); + Optional scriptType = super.getScriptType(scriptFilePath); + if (scriptType.isPresent() && !scriptFilePath.startsWith(getWatchPath().resolve("node_modules")) + && ("js".equals(scriptType.get()))) { + return scriptType; } return Optional.empty(); } diff --git a/bundles/org.openhab.automation.jythonscripting/src/main/java/org/openhab/automation/jythonscripting/internal/watch/JythonScriptFileWatcher.java b/bundles/org.openhab.automation.jythonscripting/src/main/java/org/openhab/automation/jythonscripting/internal/watch/JythonScriptFileWatcher.java index 3682dea1d5980..bebbc80378756 100644 --- a/bundles/org.openhab.automation.jythonscripting/src/main/java/org/openhab/automation/jythonscripting/internal/watch/JythonScriptFileWatcher.java +++ b/bundles/org.openhab.automation.jythonscripting/src/main/java/org/openhab/automation/jythonscripting/internal/watch/JythonScriptFileWatcher.java @@ -48,9 +48,10 @@ public JythonScriptFileWatcher( @Override protected Optional getScriptType(Path scriptFilePath) { - String scriptType = super.getScriptType(scriptFilePath).orElse(null); - if (!scriptFilePath.startsWith(getWatchPath().resolve("lib")) && ("py".equals(scriptType))) { - return Optional.of(scriptType); + Optional scriptType = super.getScriptType(scriptFilePath); + if (scriptType.isPresent() && !scriptFilePath.startsWith(getWatchPath().resolve("lib")) + && ("py".equals(scriptType.get()))) { + return scriptType; } return Optional.empty(); } diff --git a/bundles/org.openhab.binding.airquality/src/main/java/org/openhab/binding/airquality/internal/api/dto/AirQualityData.java b/bundles/org.openhab.binding.airquality/src/main/java/org/openhab/binding/airquality/internal/api/dto/AirQualityData.java index 4e7671e0f7132..2b37e3db4837e 100644 --- a/bundles/org.openhab.binding.airquality/src/main/java/org/openhab/binding/airquality/internal/api/dto/AirQualityData.java +++ b/bundles/org.openhab.binding.airquality/src/main/java/org/openhab/binding/airquality/internal/api/dto/AirQualityData.java @@ -62,8 +62,8 @@ public int getStationId() { * * @return {AirQualityJsonTime} */ - public Optional getTime() { - return Optional.ofNullable(time); + public @Nullable AirQualityTime getTime() { + return time; } /** diff --git a/bundles/org.openhab.binding.airquality/src/main/java/org/openhab/binding/airquality/internal/handler/AirQualityStationHandler.java b/bundles/org.openhab.binding.airquality/src/main/java/org/openhab/binding/airquality/internal/handler/AirQualityStationHandler.java index 8e2b55075097a..f5fede8b12e17 100644 --- a/bundles/org.openhab.binding.airquality/src/main/java/org/openhab/binding/airquality/internal/handler/AirQualityStationHandler.java +++ b/bundles/org.openhab.binding.airquality/src/main/java/org/openhab/binding/airquality/internal/handler/AirQualityStationHandler.java @@ -35,6 +35,7 @@ import org.openhab.binding.airquality.internal.api.Pollutant; import org.openhab.binding.airquality.internal.api.Pollutant.SensitiveGroup; import org.openhab.binding.airquality.internal.api.dto.AirQualityData; +import org.openhab.binding.airquality.internal.api.dto.AirQualityTime; import org.openhab.binding.airquality.internal.config.AirQualityConfiguration; import org.openhab.binding.airquality.internal.config.SensitiveGroupConfiguration; import org.openhab.core.config.core.Configuration; @@ -261,10 +262,10 @@ private State getValue(String channelId, @Nullable String groupId, AirQualityDat double hum = data.getIaqiValue("h"); return hum != -1 ? new QuantityType<>(hum, Units.PERCENT) : UnDefType.NULL; case TIMESTAMP: - return data.getTime() - .map(time -> (State) new DateTimeType( - time.getObservationTime().withZoneSameLocal(timeZoneProvider.getTimeZone()))) - .orElse(UnDefType.NULL); + AirQualityTime time = data.getTime(); + return time != null + ? new DateTimeType(time.getObservationTime().withZoneSameLocal(timeZoneProvider.getTimeZone())) + : UnDefType.NULL; case DOMINENT: return new StringType(data.getDominentPol()); case DEW_POINT: diff --git a/bundles/org.openhab.binding.androidtv/src/main/java/org/openhab/binding/androidtv/internal/protocol/philipstv/PhilipsTVConnectionManager.java b/bundles/org.openhab.binding.androidtv/src/main/java/org/openhab/binding/androidtv/internal/protocol/philipstv/PhilipsTVConnectionManager.java index 30c49311eacce..c811573d9ab00 100644 --- a/bundles/org.openhab.binding.androidtv/src/main/java/org/openhab/binding/androidtv/internal/protocol/philipstv/PhilipsTVConnectionManager.java +++ b/bundles/org.openhab.binding.androidtv/src/main/java/org/openhab/binding/androidtv/internal/protocol/philipstv/PhilipsTVConnectionManager.java @@ -230,9 +230,9 @@ private void readConfigs() { Map configMap = OBJECT_MAPPER.readValue(configJson, new TypeReference>() { }); - this.username = Optional.ofNullable(configMap.get("username")).orElse(""); - this.password = Optional.ofNullable(configMap.get("password")).orElse(""); - this.macAddress = Optional.ofNullable(configMap.get("macAddress")).orElse(""); + this.username = configMap.getOrDefault("username", ""); + this.password = configMap.getOrDefault("password", ""); + this.macAddress = configMap.getOrDefault("macAddress", ""); logger.debug("Processed configJson as {} {} {}", this.username, this.password, this.macAddress); } catch (IOException ex) { logger.debug("IOException when reading configJson from file {}", ex.getMessage()); diff --git a/bundles/org.openhab.binding.androidtv/src/main/java/org/openhab/binding/androidtv/internal/protocol/philipstv/service/TvChannelService.java b/bundles/org.openhab.binding.androidtv/src/main/java/org/openhab/binding/androidtv/internal/protocol/philipstv/service/TvChannelService.java index 53ae7fb3c39aa..e0479e5630e43 100644 --- a/bundles/org.openhab.binding.androidtv/src/main/java/org/openhab/binding/androidtv/internal/protocol/philipstv/service/TvChannelService.java +++ b/bundles/org.openhab.binding.androidtv/src/main/java/org/openhab/binding/androidtv/internal/protocol/philipstv/service/TvChannelService.java @@ -18,7 +18,6 @@ import java.io.IOException; import java.util.Map; -import java.util.Optional; import java.util.concurrent.ConcurrentMap; import java.util.function.Function; import java.util.stream.Collectors; @@ -122,7 +121,8 @@ private Map getAvailableTvChannelListFromTv() throws IOException private String getCurrentTvChannel() throws IOException { TvChannelDTO tvChannelDTO = OBJECT_MAPPER.readValue(connectionManager.doHttpsGet(TV_CHANNEL_PATH), TvChannelDTO.class); - return Optional.ofNullable(tvChannelDTO.getChannel()).map(ChannelDTO::getName).orElse("NA"); + ChannelDTO channel = tvChannelDTO.getChannel(); + return channel != null ? channel.getName() : "NA"; } private void switchTvChannel(Command command) throws IOException { diff --git a/bundles/org.openhab.binding.argoclima/src/main/java/org/openhab/binding/argoclima/internal/configuration/ArgoClimaConfigurationBase.java b/bundles/org.openhab.binding.argoclima/src/main/java/org/openhab/binding/argoclima/internal/configuration/ArgoClimaConfigurationBase.java index 73f0ffb388081..c7a16a71d4c64 100644 --- a/bundles/org.openhab.binding.argoclima/src/main/java/org/openhab/binding/argoclima/internal/configuration/ArgoClimaConfigurationBase.java +++ b/bundles/org.openhab.binding.argoclima/src/main/java/org/openhab/binding/argoclima/internal/configuration/ArgoClimaConfigurationBase.java @@ -373,13 +373,10 @@ public final String validate() { validateInternal(); return ""; } catch (Exception e) { - var msg = Optional.ofNullable(e.getLocalizedMessage()); + var msg = e.getLocalizedMessage(); var cause = Optional.ofNullable(e.getCause()); - return msg.orElse("Unknown exception, message is null") // The message theoretically can be null - // (Exception's i-face) but in practice never is, so - // keeping cryptic non-i18nized text instead of - // throwing - .concat(cause.map(c -> "\n\t[" + c.getClass().getSimpleName() + "]").orElse("")); + return Objects.requireNonNullElse(msg, "Unknown exception, message is null").concat( + Objects.requireNonNull(cause.map(c -> "\n\t[" + c.getClass().getSimpleName() + "]").orElse(""))); } } } diff --git a/bundles/org.openhab.binding.argoclima/src/main/java/org/openhab/binding/argoclima/internal/device/api/ArgoClimaRemoteDevice.java b/bundles/org.openhab.binding.argoclima/src/main/java/org/openhab/binding/argoclima/internal/device/api/ArgoClimaRemoteDevice.java index 7cf852c3c63ba..dd83f04b1c3fc 100644 --- a/bundles/org.openhab.binding.argoclima/src/main/java/org/openhab/binding/argoclima/internal/device/api/ArgoClimaRemoteDevice.java +++ b/bundles/org.openhab.binding.argoclima/src/main/java/org/openhab/binding/argoclima/internal/device/api/ArgoClimaRemoteDevice.java @@ -18,7 +18,6 @@ import java.nio.charset.StandardCharsets; import java.text.MessageFormat; import java.util.Objects; -import java.util.Optional; import java.util.SortedMap; import java.util.function.Consumer; import java.util.regex.Pattern; @@ -142,8 +141,8 @@ protected DeviceStatus extractDeviceStatusFromResponse(String apiResponse) throw // Group names must match regex above var properties = new DeviceProperties(Objects.requireNonNull(matcher.group("localIP")), - Objects.requireNonNull(matcher.group("lastSeen")), Optional.of( - getWebUiUrl(Objects.requireNonNull(this.oemServerHostname.getHostName()), this.oemServerPort))); + Objects.requireNonNull(matcher.group("lastSeen")), + getWebUiUrl(Objects.requireNonNull(this.oemServerHostname.getHostName()), this.oemServerPort)); return new DeviceStatus(Objects.requireNonNull(matcher.group("commands")), properties, i18nProvider); } diff --git a/bundles/org.openhab.binding.argoclima/src/main/java/org/openhab/binding/argoclima/internal/device/api/DeviceStatus.java b/bundles/org.openhab.binding.argoclima/src/main/java/org/openhab/binding/argoclima/internal/device/api/DeviceStatus.java index 0d738ced246a2..b094f3ec3a637 100644 --- a/bundles/org.openhab.binding.argoclima/src/main/java/org/openhab/binding/argoclima/internal/device/api/DeviceStatus.java +++ b/bundles/org.openhab.binding.argoclima/src/main/java/org/openhab/binding/argoclima/internal/device/api/DeviceStatus.java @@ -20,11 +20,12 @@ import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; import java.util.Collections; -import java.util.Optional; +import java.util.Objects; import java.util.SortedMap; import java.util.TreeMap; import org.eclipse.jdt.annotation.NonNullByDefault; +import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.argoclima.internal.ArgoClimaBindingConstants; import org.openhab.binding.argoclima.internal.ArgoClimaTranslationProvider; import org.openhab.binding.argoclima.internal.configuration.ArgoClimaConfigurationRemote; @@ -53,17 +54,29 @@ class DeviceStatus { */ static class DeviceProperties { private static final Logger LOGGER = LoggerFactory.getLogger(DeviceProperties.class); - private final Optional localIP; - private final Optional lastSeen; - private final Optional vendorUiUrl; - private Optional cpuId = Optional.empty(); - private Optional webUiUsername = Optional.empty(); - private Optional webUiPassword = Optional.empty(); - private Optional unitFWVersion = Optional.empty(); - private Optional wifiFWVersion = Optional.empty(); - private Optional wifiSSID = Optional.empty(); - private Optional wifiPassword = Optional.empty(); - private Optional localTime = Optional.empty(); + + private OffsetDateTime lastSeen = OffsetDateTime.MIN; + + @Nullable + private final String localIP; + @Nullable + private final URL vendorUiUrl; + @Nullable + private String cpuId; + @Nullable + private String webUiUsername; + @Nullable + private String webUiPassword; + @Nullable + private String unitFWVersion; + @Nullable + private String wifiFWVersion; + @Nullable + private String wifiSSID; + @Nullable + private String wifiPassword; + @Nullable + private String localTime; /** * C-tor (from remote server query response) @@ -72,8 +85,8 @@ static class DeviceProperties { * @param lastSeenStr The ISO-8601-formatted date/time of last update (or empty string if N/A) * @param vendorUiAddress The optional full URL to vendor's web UI */ - public DeviceProperties(String localIP, String lastSeenStr, Optional vendorUiAddress) { - this.localIP = localIP.isEmpty() ? Optional.empty() : Optional.of(localIP); + public DeviceProperties(String localIP, String lastSeenStr, URL vendorUiAddress) { + this.localIP = !localIP.isBlank() ? localIP : null; this.vendorUiUrl = vendorUiAddress; this.lastSeen = dateFromISOString(lastSeenStr, "LastSeen"); } @@ -84,9 +97,9 @@ public DeviceProperties(String localIP, String lastSeenStr, Optional vendor * @param lastSeen The date/time of last update (when the response got received) */ public DeviceProperties(OffsetDateTime lastSeen) { - this.localIP = Optional.empty(); - this.lastSeen = Optional.of(lastSeen); - this.vendorUiUrl = Optional.empty(); + this.localIP = null; + this.lastSeen = lastSeen; + this.vendorUiUrl = null; } /** @@ -96,31 +109,32 @@ public DeviceProperties(OffsetDateTime lastSeen) { * @param properties The intercepted device-side request (most rich with properties) */ public DeviceProperties(OffsetDateTime lastSeen, DeviceSideUpdateDTO properties) { - this.localIP = Optional.of(properties.setup.localIP.orElse(properties.deviceIp)); - this.lastSeen = Optional.of(lastSeen); - this.vendorUiUrl = Optional.of(ArgoClimaRemoteDevice.getWebUiUrl(properties.remoteServerId, 80)); - this.cpuId = Optional.of(properties.cpuId); - this.webUiUsername = Optional.of(properties.setup.username.orElse(properties.username)); - this.webUiPassword = properties.setup.password; - this.unitFWVersion = Optional.of(properties.setup.unitVersionInstalled.orElse(properties.unitFirmware)); - this.wifiFWVersion = Optional.of(properties.setup.wifiVersionInstalled.orElse(properties.wifiFirmware)); - this.wifiSSID = properties.setup.wifiSSID; - this.wifiPassword = properties.setup.wifiPassword; - this.localTime = properties.setup.localTime; + this.localIP = Objects.requireNonNull(properties.setup.localIP.orElse(properties.deviceIp)); + this.lastSeen = lastSeen; + this.vendorUiUrl = ArgoClimaRemoteDevice.getWebUiUrl(properties.remoteServerId, 80); + this.cpuId = properties.cpuId; + this.webUiUsername = properties.setup.username.orElse(properties.username); + this.webUiPassword = properties.setup.password.get(); + this.unitFWVersion = Objects + .requireNonNull(properties.setup.unitVersionInstalled.orElse(properties.unitFirmware)); + this.wifiFWVersion = properties.setup.wifiVersionInstalled.orElse(properties.wifiFirmware); + this.wifiSSID = properties.setup.wifiSSID.get(); + this.wifiPassword = properties.setup.wifiPassword.get(); + this.localTime = properties.setup.localTime.get(); } - private static Optional dateFromISOString(String isoDateTime, String contextualName) { + private static OffsetDateTime dateFromISOString(String isoDateTime, String contextualName) { if (isoDateTime.isEmpty()) { - return Optional.empty(); + return OffsetDateTime.MIN; } try { - return Optional.of(OffsetDateTime.from(DateTimeFormatter.ISO_DATE_TIME.parse(isoDateTime))); + return OffsetDateTime.from(DateTimeFormatter.ISO_DATE_TIME.parse(isoDateTime)); } catch (DateTimeException ex) { // Swallowing exception (no need to handle - proceed as if the date was never provided) LOGGER.debug("Failed to parse [{}] timestamp: {}. Exception: {}", contextualName, isoDateTime, ex.getMessage()); - return Optional.empty(); + return OffsetDateTime.MIN; } } @@ -135,7 +149,7 @@ private static String dateTimeToStringLocal(OffsetDateTime toConvert, TimeZonePr * @return Time elapsed since last device-side update */ Duration getLastSeenDelta() { - return Duration.between(lastSeen.orElse(OffsetDateTime.MIN).toInstant(), Instant.now()); + return Duration.between(lastSeen.toInstant(), Instant.now()); } /** @@ -147,18 +161,50 @@ Duration getLastSeenDelta() { SortedMap asPropertiesRaw(TimeZoneProvider timeZoneProvider) { var result = new TreeMap(); - this.lastSeen.map((value) -> result.put(ArgoClimaBindingConstants.PROPERTY_LAST_SEEN, - dateTimeToStringLocal(value, timeZoneProvider))); - this.localIP.map(value -> result.put(ArgoClimaBindingConstants.PROPERTY_LOCAL_IP_ADDRESS, value)); - this.vendorUiUrl.map(value -> result.put(ArgoClimaBindingConstants.PROPERTY_WEB_UI, value.toString())); - this.cpuId.map(value -> result.put(ArgoClimaBindingConstants.PROPERTY_CPU_ID, value)); - this.webUiUsername.map(value -> result.put(ArgoClimaBindingConstants.PROPERTY_WEB_UI_USERNAME, value)); - this.webUiPassword.map(value -> result.put(ArgoClimaBindingConstants.PROPERTY_WEB_UI_PASSWORD, value)); - this.unitFWVersion.map(value -> result.put(ArgoClimaBindingConstants.PROPERTY_UNIT_FW, value)); - this.wifiFWVersion.map(value -> result.put(ArgoClimaBindingConstants.PROPERTY_WIFI_FW, value)); - this.wifiSSID.map(value -> result.put(ArgoClimaBindingConstants.PROPERTY_WIFI_SSID, value)); - this.wifiPassword.map(value -> result.put(ArgoClimaBindingConstants.PROPERTY_WIFI_PASSWORD, value)); - this.localTime.map(value -> result.put(ArgoClimaBindingConstants.PROPERTY_LOCAL_TIME, value)); + String localIP = this.localIP; + String cpuId = this.cpuId; + URL vendorUiUrl = this.vendorUiUrl; + String webUiUsername = this.webUiUsername; + String webUiPassword = this.webUiPassword; + String unitFWVersion = this.unitFWVersion; + String wifiFWVersion = this.wifiFWVersion; + String wifiSSID = this.wifiSSID; + String wifiPassword = this.wifiPassword; + String localTime = this.localTime; + + result.put(ArgoClimaBindingConstants.PROPERTY_LAST_SEEN, + dateTimeToStringLocal(this.lastSeen, timeZoneProvider)); + + if (localIP != null) { + result.put(ArgoClimaBindingConstants.PROPERTY_LOCAL_IP_ADDRESS, localIP); + } + if (cpuId != null) { + result.put(ArgoClimaBindingConstants.PROPERTY_CPU_ID, cpuId); + } + if (vendorUiUrl != null) { + result.put(ArgoClimaBindingConstants.PROPERTY_WEB_UI, vendorUiUrl.toString()); + } + if (webUiUsername != null) { + result.put(ArgoClimaBindingConstants.PROPERTY_WEB_UI_USERNAME, webUiUsername); + } + if (webUiPassword != null) { + result.put(ArgoClimaBindingConstants.PROPERTY_WEB_UI_PASSWORD, webUiPassword); + } + if (unitFWVersion != null) { + result.put(ArgoClimaBindingConstants.PROPERTY_UNIT_FW, unitFWVersion); + } + if (wifiFWVersion != null) { + result.put(ArgoClimaBindingConstants.PROPERTY_WIFI_FW, wifiFWVersion); + } + if (wifiSSID != null) { + result.put(ArgoClimaBindingConstants.PROPERTY_WIFI_SSID, wifiSSID); + } + if (wifiPassword != null) { + result.put(ArgoClimaBindingConstants.PROPERTY_WIFI_PASSWORD, wifiPassword); + } + if (localTime != null) { + result.put(ArgoClimaBindingConstants.PROPERTY_LOCAL_TIME, localTime); + } return Collections.unmodifiableSortedMap(result); } } diff --git a/bundles/org.openhab.binding.argoclima/src/main/java/org/openhab/binding/argoclima/internal/device/api/protocol/elements/ArgoApiElementBase.java b/bundles/org.openhab.binding.argoclima/src/main/java/org/openhab/binding/argoclima/internal/device/api/protocol/elements/ArgoApiElementBase.java index 155acd0019cf2..a7662ab1a083c 100644 --- a/bundles/org.openhab.binding.argoclima/src/main/java/org/openhab/binding/argoclima/internal/device/api/protocol/elements/ArgoApiElementBase.java +++ b/bundles/org.openhab.binding.argoclima/src/main/java/org/openhab/binding/argoclima/internal/device/api/protocol/elements/ArgoApiElementBase.java @@ -14,6 +14,7 @@ import java.time.Duration; import java.time.Instant; +import java.util.Objects; import java.util.Optional; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -413,8 +414,9 @@ public final boolean hasInFlightCommand() { private final String getInFlightCommandsRawValueOrDefault() { final String valueNotAvailablePlaceholder = "N/A"; - return inFlightCommand.map(c -> c.deviceCommandToSend.orElse(valueNotAvailablePlaceholder)) - .orElse(valueNotAvailablePlaceholder); + return Objects + .requireNonNull(inFlightCommand.map(c -> c.deviceCommandToSend.orElse(valueNotAvailablePlaceholder)) + .orElse(valueNotAvailablePlaceholder)); } ///////////// diff --git a/bundles/org.openhab.binding.argoclima/src/main/java/org/openhab/binding/argoclima/internal/device/api/protocol/elements/OnOffParam.java b/bundles/org.openhab.binding.argoclima/src/main/java/org/openhab/binding/argoclima/internal/device/api/protocol/elements/OnOffParam.java index 49cca1ee52dbb..a88211c82c709 100644 --- a/bundles/org.openhab.binding.argoclima/src/main/java/org/openhab/binding/argoclima/internal/device/api/protocol/elements/OnOffParam.java +++ b/bundles/org.openhab.binding.argoclima/src/main/java/org/openhab/binding/argoclima/internal/device/api/protocol/elements/OnOffParam.java @@ -13,6 +13,7 @@ package org.openhab.binding.argoclima.internal.device.api.protocol.elements; import java.security.InvalidParameterException; +import java.util.Objects; import java.util.Optional; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -44,7 +45,7 @@ public OnOffParam(IArgoSettingProvider settingsProvider) { } private static State valueToState(Optional value) { - return value. map(v -> OnOffType.from(v)).orElse(UnDefType.UNDEF); + return Objects.requireNonNull(value. map(v -> OnOffType.from(v)).orElse(UnDefType.UNDEF)); } @Override diff --git a/bundles/org.openhab.binding.asuswrt/src/main/java/org/openhab/binding/asuswrt/internal/api/AsuswrtHttpClient.java b/bundles/org.openhab.binding.asuswrt/src/main/java/org/openhab/binding/asuswrt/internal/api/AsuswrtHttpClient.java index bb2e9d13d2bdc..220b04cf82d92 100644 --- a/bundles/org.openhab.binding.asuswrt/src/main/java/org/openhab/binding/asuswrt/internal/api/AsuswrtHttpClient.java +++ b/bundles/org.openhab.binding.asuswrt/src/main/java/org/openhab/binding/asuswrt/internal/api/AsuswrtHttpClient.java @@ -140,7 +140,9 @@ public void onComplete(Result result) { String rBody = getContentAsString(); logger.trace("({}) requestCompleted '{}'", uid, rBody); // Handle result - handleHttpSuccessResponse(rBody, command); + if (rBody != null) { + handleHttpSuccessResponse(rBody, command); + } } } }); diff --git a/bundles/org.openhab.binding.avmfritz/src/main/java/org/openhab/binding/avmfritz/internal/hardware/FritzAhaContentExchange.java b/bundles/org.openhab.binding.avmfritz/src/main/java/org/openhab/binding/avmfritz/internal/hardware/FritzAhaContentExchange.java index 3dc704a8abad9..6747a86d44ec3 100644 --- a/bundles/org.openhab.binding.avmfritz/src/main/java/org/openhab/binding/avmfritz/internal/hardware/FritzAhaContentExchange.java +++ b/bundles/org.openhab.binding.avmfritz/src/main/java/org/openhab/binding/avmfritz/internal/hardware/FritzAhaContentExchange.java @@ -64,6 +64,8 @@ public void onFailure(@NonNullByDefault({}) Response response, @NonNullByDefault public void onComplete(@NonNullByDefault({}) Result result) { String content = getContentAsString(); logger.debug("{} response complete: {}", result.getRequest().getMethod(), content); - callback.execute(result.getResponse().getStatus(), content); + if (content != null) { + callback.execute(result.getResponse().getStatus(), content); + } } } diff --git a/bundles/org.openhab.binding.boschshc/src/main/java/org/openhab/binding/boschshc/internal/devices/bridge/BridgeHandler.java b/bundles/org.openhab.binding.boschshc/src/main/java/org/openhab/binding/boschshc/internal/devices/bridge/BridgeHandler.java index a8514f0d24b1d..8deb0578061c5 100644 --- a/bundles/org.openhab.binding.boschshc/src/main/java/org/openhab/binding/boschshc/internal/devices/bridge/BridgeHandler.java +++ b/bundles/org.openhab.binding.boschshc/src/main/java/org/openhab/binding/boschshc/internal/devices/bridge/BridgeHandler.java @@ -22,7 +22,6 @@ import java.util.Collections; import java.util.List; import java.util.Objects; -import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledFuture; @@ -358,7 +357,7 @@ public List getDevices() throws InterruptedException { Type collectionType = new TypeToken>() { }.getType(); List nullableDevices = GsonUtils.DEFAULT_GSON_INSTANCE.fromJson(content, collectionType); - return Optional.ofNullable(nullableDevices).orElse(Collections.emptyList()); + return nullableDevices != null ? nullableDevices : Collections.emptyList(); } catch (TimeoutException | ExecutionException e) { logger.debug("Request devices failed because of {}!", e.getMessage(), e); return Collections.emptyList(); @@ -391,7 +390,7 @@ public List getUserStates() throws InterruptedException { }.getType(); List nullableUserStates = GsonUtils.DEFAULT_GSON_INSTANCE.fromJson(content, collectionType); - return Optional.ofNullable(nullableUserStates).orElse(Collections.emptyList()); + return nullableUserStates != null ? nullableUserStates : Collections.emptyList(); } catch (TimeoutException | ExecutionException e) { logger.debug("Request user-defined states failed because of {}!", e.getMessage(), e); return List.of(); diff --git a/bundles/org.openhab.binding.boschshc/src/main/java/org/openhab/binding/boschshc/internal/devices/bridge/LongPolling.java b/bundles/org.openhab.binding.boschshc/src/main/java/org/openhab/binding/boschshc/internal/devices/bridge/LongPolling.java index 7924702d6be13..0cc9a13f24c0d 100644 --- a/bundles/org.openhab.binding.boschshc/src/main/java/org/openhab/binding/boschshc/internal/devices/bridge/LongPolling.java +++ b/bundles/org.openhab.binding.boschshc/src/main/java/org/openhab/binding/boschshc/internal/devices/bridge/LongPolling.java @@ -181,7 +181,7 @@ public void onComplete(@Nullable Result result) { * @param content Content of the response */ private void onLongPollComplete(BoschHttpClient httpClient, String subscriptionId, @Nullable Result result, - String content) { + @Nullable String content) { // Check if thing is still online if (this.aborted) { logger.debug("Canceling long polling for subscription id {} because it was aborted", subscriptionId); @@ -211,7 +211,7 @@ private void onLongPollComplete(BoschHttpClient httpClient, String subscriptionI * @param subscriptionId Id of subscription the response is for * @param content Content of the response */ - private void handleLongPollResponse(BoschHttpClient httpClient, String subscriptionId, String content) { + private void handleLongPollResponse(BoschHttpClient httpClient, String subscriptionId, @Nullable String content) { logger.debug("Long poll response: {}", content); try { diff --git a/bundles/org.openhab.binding.boschshc/src/main/java/org/openhab/binding/boschshc/internal/discovery/ThingDiscoveryService.java b/bundles/org.openhab.binding.boschshc/src/main/java/org/openhab/binding/boschshc/internal/discovery/ThingDiscoveryService.java index ab0a30308718b..50a9b89356849 100644 --- a/bundles/org.openhab.binding.boschshc/src/main/java/org/openhab/binding/boschshc/internal/discovery/ThingDiscoveryService.java +++ b/bundles/org.openhab.binding.boschshc/src/main/java/org/openhab/binding/boschshc/internal/discovery/ThingDiscoveryService.java @@ -16,6 +16,7 @@ import java.util.AbstractMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -214,7 +215,8 @@ protected void addDevices(List devices, List rooms) { } protected String getRoomNameForDevice(Device device, List rooms) { - return rooms.stream().filter(room -> room.id.equals(device.roomId)).findAny().map(r -> r.name).orElse(""); + return Objects.requireNonNull( + rooms.stream().filter(room -> room.id.equals(device.roomId)).findAny().map(r -> r.name).orElse("")); } protected void addDevice(Device device, String roomName) { diff --git a/bundles/org.openhab.binding.coronastats/src/main/java/org/openhab/binding/coronastats/internal/handler/CoronaStatsWorldHandler.java b/bundles/org.openhab.binding.coronastats/src/main/java/org/openhab/binding/coronastats/internal/handler/CoronaStatsWorldHandler.java index 1b54e258068f4..5b5e09e8e8b1a 100644 --- a/bundles/org.openhab.binding.coronastats/src/main/java/org/openhab/binding/coronastats/internal/handler/CoronaStatsWorldHandler.java +++ b/bundles/org.openhab.binding.coronastats/src/main/java/org/openhab/binding/coronastats/internal/handler/CoronaStatsWorldHandler.java @@ -14,6 +14,7 @@ import java.net.SocketTimeoutException; import java.net.URI; +import java.util.Objects; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; @@ -154,7 +155,8 @@ public void onComplete(Result result) { f.completeExceptionally(new CoronaStatsPollingException("Request failed", e)); } } else if (response.getStatus() != 200) { - f.completeExceptionally(new CoronaStatsPollingException(getContentAsString())); + f.completeExceptionally( + new CoronaStatsPollingException(Objects.requireNonNull(getContentAsString()))); } else { try { CoronaStats coronaStatsJSON = gson.fromJson(getContentAsString(), CoronaStats.class); diff --git a/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/api/BasicInfo.java b/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/api/BasicInfo.java index 1636eb0f7096b..f5952484f25e0 100644 --- a/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/api/BasicInfo.java +++ b/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/api/BasicInfo.java @@ -14,7 +14,6 @@ import java.util.HashMap; import java.util.Map; -import java.util.Optional; import org.eclipse.jdt.annotation.NonNullByDefault; import org.slf4j.Logger; @@ -43,9 +42,9 @@ public static BasicInfo parse(String response) { Map responseMap = InfoParser.parse(response); BasicInfo info = new BasicInfo(); - info.mac = Optional.ofNullable(responseMap.get("mac")).orElse(""); - info.ret = Optional.ofNullable(responseMap.get("ret")).orElse(""); - info.ssid = Optional.ofNullable(responseMap.get("ssid")).orElse(""); + info.mac = responseMap.getOrDefault("mac", ""); + info.ret = responseMap.getOrDefault("ret", ""); + info.ssid = responseMap.getOrDefault("ssid", ""); return info; } diff --git a/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/api/ControlInfo.java b/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/api/ControlInfo.java index fe2da507117b8..81734c5634afb 100644 --- a/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/api/ControlInfo.java +++ b/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/api/ControlInfo.java @@ -14,6 +14,7 @@ import java.util.HashMap; import java.util.Map; +import java.util.Objects; import java.util.Optional; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -59,23 +60,23 @@ public static ControlInfo parse(String response) { Map responseMap = InfoParser.parse(response); ControlInfo info = new ControlInfo(); - info.ret = Optional.ofNullable(responseMap.get("ret")).orElse(""); + info.ret = responseMap.getOrDefault("ret", ""); info.power = "1".equals(responseMap.get("pow")); - info.mode = Optional.ofNullable(responseMap.get("mode")).flatMap(value -> InfoParser.parseInt(value)) - .map(value -> Mode.fromValue(value)).orElse(Mode.AUTO); + info.mode = Objects.requireNonNull(Optional.ofNullable(responseMap.get("mode")) + .flatMap(value -> InfoParser.parseInt(value)).map(value -> Mode.fromValue(value)).orElse(Mode.AUTO)); // Normalize AUTO1 and AUTO7 to AUTO if (info.mode == Mode.AUTO1 || info.mode == Mode.AUTO7) { info.autoModeValue = info.mode.getValue(); info.mode = Mode.AUTO; } info.temp = Optional.ofNullable(responseMap.get("stemp")).flatMap(value -> InfoParser.parseDouble(value)); - info.fanSpeed = Optional.ofNullable(responseMap.get("f_rate")).map(value -> FanSpeed.fromValue(value)) - .orElse(FanSpeed.AUTO); + info.fanSpeed = Objects.requireNonNull(Optional.ofNullable(responseMap.get("f_rate")) + .map(value -> FanSpeed.fromValue(value)).orElse(FanSpeed.AUTO)); // determine if device has combined direction (f_dir) or separated directions (f_dir_ud/f_dir_lr) if (response.contains("f_dir=")) { - info.fanMovement = Optional.ofNullable(responseMap.get("f_dir")) - .flatMap(value -> InfoParser.parseInt(value)).map(value -> FanMovement.fromValue(value)) - .orElse(FanMovement.STOPPED); + info.fanMovement = Objects.requireNonNull( + Optional.ofNullable(responseMap.get("f_dir")).flatMap(value -> InfoParser.parseInt(value)) + .map(value -> FanMovement.fromValue(value)).orElse(FanMovement.STOPPED)); } else { info.separatedDirectionParams = true; String ud = responseMap.get("f_dir_ud"); @@ -89,8 +90,8 @@ public static ControlInfo parse(String response) { info.targetHumidity = Optional.ofNullable(responseMap.get("shum")).flatMap(value -> InfoParser.parseInt(value)); - info.advancedMode = Optional.ofNullable(responseMap.get("adv")).map(value -> AdvancedMode.fromValue(value)) - .orElse(AdvancedMode.UNKNOWN); + info.advancedMode = Objects.requireNonNull(Optional.ofNullable(responseMap.get("adv")) + .map(value -> AdvancedMode.fromValue(value)).orElse(AdvancedMode.UNKNOWN)); return info; } @@ -110,7 +111,7 @@ public Map getParamString() { params.put("f_dir", Integer.toString(fanMovement.getValue())); } params.put("stemp", temp.orElse(20.0).toString()); - params.put("shum", targetHumidity.map(value -> value.toString()).orElse("")); + params.put("shum", Objects.requireNonNull(targetHumidity.map(value -> value.toString()).orElse(""))); return params; } diff --git a/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/api/airbase/AirbaseBasicInfo.java b/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/api/airbase/AirbaseBasicInfo.java index 486e8683f1541..361e0b56538c9 100644 --- a/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/api/airbase/AirbaseBasicInfo.java +++ b/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/api/airbase/AirbaseBasicInfo.java @@ -14,7 +14,6 @@ import java.util.HashMap; import java.util.Map; -import java.util.Optional; import org.eclipse.jdt.annotation.NonNullByDefault; import org.openhab.binding.daikin.internal.api.InfoParser; @@ -44,9 +43,9 @@ public static AirbaseBasicInfo parse(String response) { Map responseMap = InfoParser.parse(response); AirbaseBasicInfo info = new AirbaseBasicInfo(); - info.mac = Optional.ofNullable(responseMap.get("mac")).orElse(""); - info.ret = Optional.ofNullable(responseMap.get("ret")).orElse(""); - info.ssid = Optional.ofNullable(responseMap.get("ssid")).orElse(""); + info.mac = responseMap.getOrDefault("mac", ""); + info.ret = responseMap.getOrDefault("ret", ""); + info.ssid = responseMap.getOrDefault("ssid", ""); return info; } diff --git a/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/api/airbase/AirbaseControlInfo.java b/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/api/airbase/AirbaseControlInfo.java index 01f2b6ec03b52..aece069cb6aaa 100644 --- a/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/api/airbase/AirbaseControlInfo.java +++ b/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/api/airbase/AirbaseControlInfo.java @@ -14,6 +14,7 @@ import java.util.HashMap; import java.util.Map; +import java.util.Objects; import java.util.Optional; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -54,18 +55,20 @@ public static AirbaseControlInfo parse(String response) { Map responseMap = InfoParser.parse(response); AirbaseControlInfo info = new AirbaseControlInfo(); - info.ret = Optional.ofNullable(responseMap.get("ret")).orElse(""); + info.ret = responseMap.getOrDefault("ret", ""); info.power = "1".equals(responseMap.get("pow")); - info.mode = Optional.ofNullable(responseMap.get("mode")).flatMap(value -> InfoParser.parseInt(value)) - .map(value -> AirbaseMode.fromValue(value)).orElse(AirbaseMode.AUTO); + info.mode = Objects.requireNonNull( + Optional.ofNullable(responseMap.get("mode")).flatMap(value -> InfoParser.parseInt(value)) + .map(value -> AirbaseMode.fromValue(value)).orElse(AirbaseMode.AUTO)); info.temp = Optional.ofNullable(responseMap.get("stemp")).flatMap(value -> InfoParser.parseDouble(value)); int fRate = Optional.ofNullable(responseMap.get("f_rate")).flatMap(value -> InfoParser.parseInt(value)) .orElse(1); boolean fAuto = "1".equals(responseMap.getOrDefault("f_auto", "0")); boolean fAirside = "1".equals(responseMap.getOrDefault("f_airside", "0")); info.fanSpeed = AirbaseFanSpeed.fromValue(fRate, fAuto, fAirside); - info.fanMovement = Optional.ofNullable(responseMap.get("f_dir")).flatMap(value -> InfoParser.parseInt(value)) - .map(value -> AirbaseFanMovement.fromValue(value)).orElse(AirbaseFanMovement.STOPPED); + info.fanMovement = Objects.requireNonNull( + Optional.ofNullable(responseMap.get("f_dir")).flatMap(value -> InfoParser.parseInt(value)) + .map(value -> AirbaseFanMovement.fromValue(value)).orElse(AirbaseFanMovement.STOPPED)); info.targetHumidity = Optional.ofNullable(responseMap.get("shum")).flatMap(value -> InfoParser.parseInt(value)); return info; } @@ -79,7 +82,7 @@ public Map getParamString() { params.put("f_airside", fanSpeed.getAirside() ? "1" : "0"); params.put("f_dir", Integer.toString(fanMovement.getValue())); params.put("stemp", temp.orElse(20.0).toString()); - params.put("shum", targetHumidity.map(value -> value.toString()).orElse("")); + params.put("shum", Objects.requireNonNull(targetHumidity.map(value -> value.toString()).orElse(""))); return params; } diff --git a/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/api/airbase/AirbaseModelInfo.java b/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/api/airbase/AirbaseModelInfo.java index 4fb618a6e5905..615fa0913dd0f 100644 --- a/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/api/airbase/AirbaseModelInfo.java +++ b/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/api/airbase/AirbaseModelInfo.java @@ -48,7 +48,7 @@ public static AirbaseModelInfo parse(String response) { Map responseMap = InfoParser.parse(response); AirbaseModelInfo info = new AirbaseModelInfo(); - info.ret = Optional.ofNullable(responseMap.get("ret")).orElse(""); + info.ret = responseMap.getOrDefault("ret", ""); info.zonespresent = Optional.ofNullable(responseMap.get("en_zone")).flatMap(value -> InfoParser.parseInt(value)) .orElse(0); info.commonzone = Optional.ofNullable(responseMap.get("en_common_zone")) diff --git a/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/api/airbase/AirbaseZoneInfo.java b/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/api/airbase/AirbaseZoneInfo.java index de3b1199861dd..d713db6c1ff69 100644 --- a/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/api/airbase/AirbaseZoneInfo.java +++ b/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/api/airbase/AirbaseZoneInfo.java @@ -14,7 +14,6 @@ import java.util.LinkedHashMap; import java.util.Map; -import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -46,8 +45,8 @@ public static AirbaseZoneInfo parse(String response) { Map responseMap = InfoParser.parse(response); AirbaseZoneInfo info = new AirbaseZoneInfo(); - info.zonenames = Optional.ofNullable(responseMap.get("zone_name")).orElse(""); - String zoneinfo = Optional.ofNullable(responseMap.get("zone_onoff")).orElse(""); + info.zonenames = responseMap.getOrDefault("zone_name", ""); + String zoneinfo = responseMap.getOrDefault("zone_onoff", ""); String[] zones = zoneinfo.split(";"); diff --git a/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/discovery/DaikinACUnitDiscoveryService.java b/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/discovery/DaikinACUnitDiscoveryService.java index 1a2417f4e3c55..cb37507296252 100644 --- a/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/discovery/DaikinACUnitDiscoveryService.java +++ b/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/discovery/DaikinACUnitDiscoveryService.java @@ -20,7 +20,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.ScheduledFuture; @@ -133,8 +132,8 @@ private boolean receivePacketAndDiscover(DatagramSocket socket) { Map parsedData = InfoParser.parse(data); Boolean secure = "1".equals(parsedData.get("en_secure")); - String thingId = Optional.ofNullable(parsedData.get("ssid")).orElse(host.replace(".", "_")); - String mac = Optional.ofNullable(parsedData.get("mac")).orElse(""); + String thingId = parsedData.getOrDefault("ssid", host.replace(".", "_")); + String mac = parsedData.getOrDefault("mac", ""); String uuid = mac.isEmpty() ? UUID.randomUUID().toString() : UUID.nameUUIDFromBytes(mac.getBytes()).toString(); diff --git a/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/handler/DaikinAcUnitHandler.java b/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/handler/DaikinAcUnitHandler.java index 511de601968ce..21bab3dda4a27 100644 --- a/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/handler/DaikinAcUnitHandler.java +++ b/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/handler/DaikinAcUnitHandler.java @@ -13,6 +13,7 @@ package org.openhab.binding.daikin.internal.handler; import java.math.BigDecimal; +import java.util.Objects; import java.util.Optional; import java.util.stream.IntStream; @@ -273,9 +274,9 @@ protected void changeStreamer(boolean streamerMode) throws DaikinCommunicationEx protected void updateEnergyYearChannel(String channel, Optional maybePower) { IntStream.range(1, 13).forEach(i -> updateState( String.format(DaikinBindingConstants.CHANNEL_ENERGY_STRING_FORMAT, channel, i), - maybePower. map( + Objects.requireNonNull(maybePower. map( t -> new QuantityType<>(BigDecimal.valueOf(t[i - 1].longValue(), 1), Units.KILOWATT_HOUR)) - .orElse(UnDefType.UNDEF)) + .orElse(UnDefType.UNDEF))) ); } @@ -288,8 +289,9 @@ maybePower. map( protected void updateEnergyDayAndWeekChannel(String channel, Optional maybePower) { if (maybePower.isPresent()) { updateState(channel, - maybePower. map(t -> new QuantityType<>(new DecimalType(t), Units.KILOWATT_HOUR)) - .orElse(UnDefType.UNDEF)); + Objects.requireNonNull( + maybePower. map(t -> new QuantityType<>(new DecimalType(t), Units.KILOWATT_HOUR)) + .orElse(UnDefType.UNDEF))); } } diff --git a/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/handler/DaikinBaseHandler.java b/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/handler/DaikinBaseHandler.java index 80339cc910639..a427459337e35 100644 --- a/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/handler/DaikinBaseHandler.java +++ b/bundles/org.openhab.binding.daikin/src/main/java/org/openhab/binding/daikin/internal/handler/DaikinBaseHandler.java @@ -12,6 +12,7 @@ */ package org.openhab.binding.daikin.internal.handler; +import java.util.Objects; import java.util.Optional; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -205,8 +206,8 @@ private synchronized void poll() { } protected void updateTemperatureChannel(String channel, Optional maybeTemperature) { - updateState(channel, - maybeTemperature. map(t -> new QuantityType<>(t, SIUnits.CELSIUS)).orElse(UnDefType.UNDEF)); + updateState(channel, Objects.requireNonNull( + maybeTemperature. map(t -> new QuantityType<>(t, SIUnits.CELSIUS)).orElse(UnDefType.UNDEF))); } /** diff --git a/bundles/org.openhab.binding.digiplex/src/main/java/org/openhab/binding/digiplex/internal/communication/AreaStatus.java b/bundles/org.openhab.binding.digiplex/src/main/java/org/openhab/binding/digiplex/internal/communication/AreaStatus.java index 1bf21cf3df435..532e633608856 100644 --- a/bundles/org.openhab.binding.digiplex/src/main/java/org/openhab/binding/digiplex/internal/communication/AreaStatus.java +++ b/bundles/org.openhab.binding.digiplex/src/main/java/org/openhab/binding/digiplex/internal/communication/AreaStatus.java @@ -13,6 +13,7 @@ package org.openhab.binding.digiplex.internal.communication; import java.util.Arrays; +import java.util.Objects; import org.eclipse.jdt.annotation.NonNullByDefault; import org.openhab.core.library.types.OpenClosedType; @@ -44,8 +45,8 @@ public OpenClosedType toOpenClosedType() { } public static AreaStatus fromMessage(char indicator) { - return Arrays.stream(AreaStatus.values()).filter(type -> type.indicator == indicator).findFirst() - .orElse(UNKNOWN); + return Objects.requireNonNull(Arrays.stream(AreaStatus.values()).filter(type -> type.indicator == indicator) + .findFirst().orElse(UNKNOWN)); } public StringType toStringType() { diff --git a/bundles/org.openhab.binding.digiplex/src/main/java/org/openhab/binding/digiplex/internal/communication/ArmDisarmType.java b/bundles/org.openhab.binding.digiplex/src/main/java/org/openhab/binding/digiplex/internal/communication/ArmDisarmType.java index 511f93da01cdd..0c987d0ed1b42 100644 --- a/bundles/org.openhab.binding.digiplex/src/main/java/org/openhab/binding/digiplex/internal/communication/ArmDisarmType.java +++ b/bundles/org.openhab.binding.digiplex/src/main/java/org/openhab/binding/digiplex/internal/communication/ArmDisarmType.java @@ -13,6 +13,7 @@ package org.openhab.binding.digiplex.internal.communication; import java.util.Arrays; +import java.util.Objects; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -37,7 +38,7 @@ public enum ArmDisarmType { } public static ArmDisarmType fromMessage(String indicator) { - return Arrays.stream(ArmDisarmType.values()).filter(type -> type.indicator.equals(indicator)).findFirst() - .orElse(UNKNOWN); + return Objects.requireNonNull(Arrays.stream(ArmDisarmType.values()) + .filter(type -> type.indicator.equals(indicator)).findFirst().orElse(UNKNOWN)); } } diff --git a/bundles/org.openhab.binding.digiplex/src/main/java/org/openhab/binding/digiplex/internal/communication/ArmType.java b/bundles/org.openhab.binding.digiplex/src/main/java/org/openhab/binding/digiplex/internal/communication/ArmType.java index b6cbcabbe7436..9ba23bbe2a7f3 100644 --- a/bundles/org.openhab.binding.digiplex/src/main/java/org/openhab/binding/digiplex/internal/communication/ArmType.java +++ b/bundles/org.openhab.binding.digiplex/src/main/java/org/openhab/binding/digiplex/internal/communication/ArmType.java @@ -13,6 +13,7 @@ package org.openhab.binding.digiplex.internal.communication; import java.util.Arrays; +import java.util.Objects; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -41,6 +42,7 @@ public char getIndicator() { } public static ArmType fromMessage(char indicator) { - return Arrays.stream(values()).filter(type -> type.indicator == indicator).findFirst().orElse(UNKNOWN); + return Objects.requireNonNull( + Arrays.stream(values()).filter(type -> type.indicator == indicator).findFirst().orElse(UNKNOWN)); } } diff --git a/bundles/org.openhab.binding.digiplex/src/main/java/org/openhab/binding/digiplex/internal/communication/ZoneStatus.java b/bundles/org.openhab.binding.digiplex/src/main/java/org/openhab/binding/digiplex/internal/communication/ZoneStatus.java index cd264745beb60..be56b56f36187 100644 --- a/bundles/org.openhab.binding.digiplex/src/main/java/org/openhab/binding/digiplex/internal/communication/ZoneStatus.java +++ b/bundles/org.openhab.binding.digiplex/src/main/java/org/openhab/binding/digiplex/internal/communication/ZoneStatus.java @@ -13,6 +13,7 @@ package org.openhab.binding.digiplex.internal.communication; import java.util.Arrays; +import java.util.Objects; import org.eclipse.jdt.annotation.NonNullByDefault; import org.openhab.core.library.types.OpenClosedType; @@ -42,7 +43,7 @@ public OpenClosedType toOpenClosedType() { } public static ZoneStatus fromMessage(char indicator) { - return Arrays.stream(ZoneStatus.values()).filter(type -> type.indicator == indicator).findFirst() - .orElse(UNKNOWN); + return Objects.requireNonNull(Arrays.stream(ZoneStatus.values()).filter(type -> type.indicator == indicator) + .findFirst().orElse(UNKNOWN)); } } diff --git a/bundles/org.openhab.binding.digiplex/src/main/java/org/openhab/binding/digiplex/internal/communication/events/SpecialAlarmType.java b/bundles/org.openhab.binding.digiplex/src/main/java/org/openhab/binding/digiplex/internal/communication/events/SpecialAlarmType.java index 3280b63356281..a7d0a1d082567 100644 --- a/bundles/org.openhab.binding.digiplex/src/main/java/org/openhab/binding/digiplex/internal/communication/events/SpecialAlarmType.java +++ b/bundles/org.openhab.binding.digiplex/src/main/java/org/openhab/binding/digiplex/internal/communication/events/SpecialAlarmType.java @@ -13,6 +13,7 @@ package org.openhab.binding.digiplex.internal.communication.events; import java.util.Arrays; +import java.util.Objects; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -39,6 +40,7 @@ public enum SpecialAlarmType { } public static SpecialAlarmType fromMessage(int indicator) { - return Arrays.stream(values()).filter(type -> type.indicator == indicator).findFirst().orElse(UNKNOWN); + return Objects.requireNonNull( + Arrays.stream(values()).filter(type -> type.indicator == indicator).findFirst().orElse(UNKNOWN)); } } diff --git a/bundles/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/device/DSMRDeviceRunnable.java b/bundles/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/device/DSMRDeviceRunnable.java index 9939ba53faf63..ff96c7e385e9a 100644 --- a/bundles/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/device/DSMRDeviceRunnable.java +++ b/bundles/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/device/DSMRDeviceRunnable.java @@ -12,7 +12,7 @@ */ package org.openhab.binding.dsmr.internal.device; -import java.util.Optional; +import java.util.Objects; import java.util.concurrent.Semaphore; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -88,7 +88,7 @@ public void run() { } catch (final RuntimeException e) { logger.warn("DSMRDeviceRunnable stopped with a RuntimeException", e); portEventListener.onError(DSMRErrorStatus.SERIAL_DATA_READ_ERROR, - Optional.ofNullable(e.getMessage()).orElse("")); + Objects.requireNonNullElse(e.getMessage(), "")); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } finally { diff --git a/bundles/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/device/SmartyDecrypter.java b/bundles/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/device/SmartyDecrypter.java index b232ce79fd631..4e29f4893a749 100644 --- a/bundles/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/device/SmartyDecrypter.java +++ b/bundles/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/device/SmartyDecrypter.java @@ -17,7 +17,7 @@ import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; -import java.util.Optional; +import java.util.Objects; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; @@ -227,7 +227,7 @@ private void processCompleted() { logger.warn("Exception of failed decryption of telegram: ", e); } telegramListener.onError(DSMRErrorStatus.INVALID_DECRYPTION_KEY, - Optional.ofNullable(e.getMessage()).orElse("")); + Objects.requireNonNullElse(e.getMessage(), "")); } return null; } diff --git a/bundles/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/device/connector/DSMRBaseConnector.java b/bundles/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/device/connector/DSMRBaseConnector.java index d2e0165d2fc28..aede43f06a418 100644 --- a/bundles/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/device/connector/DSMRBaseConnector.java +++ b/bundles/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/device/connector/DSMRBaseConnector.java @@ -15,7 +15,7 @@ import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; -import java.util.Optional; +import java.util.Objects; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; @@ -125,7 +125,7 @@ protected void handleDataAvailable() { } } catch (final IOException e) { dsmrConnectorListener.handleError(DSMRErrorStatus.SERIAL_DATA_READ_ERROR, - Optional.ofNullable(e.getMessage()).orElse("")); + Objects.requireNonNullElse(e.getMessage(), "")); logger.debug("Exception on read data", e); } } diff --git a/bundles/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/device/connector/DSMRSerialConnector.java b/bundles/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/device/connector/DSMRSerialConnector.java index 6de5568f9e4e5..550325e00ca2c 100644 --- a/bundles/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/device/connector/DSMRSerialConnector.java +++ b/bundles/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/device/connector/DSMRSerialConnector.java @@ -14,7 +14,7 @@ import java.io.IOException; import java.io.InputStream; -import java.util.Optional; +import java.util.Objects; import java.util.TooManyListenersException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; @@ -245,7 +245,7 @@ public void setSerialPortParams(final DSMRSerialSettings portSettings) { "Port does {} not support requested port settings (invalid dsmr:portsettings parameter?): {}", serialPortName, portSettings); dsmrConnectorListener.handleError(DSMRErrorStatus.PORT_NOT_COMPATIBLE, - Optional.ofNullable(e.getMessage()).orElse("")); + Objects.requireNonNullElse(e.getMessage(), "")); } } else { restart(portSettings); diff --git a/bundles/org.openhab.binding.dwdpollenflug/src/main/java/org/openhab/binding/dwdpollenflug/internal/handler/DWDPollenflugBridgeHandler.java b/bundles/org.openhab.binding.dwdpollenflug/src/main/java/org/openhab/binding/dwdpollenflug/internal/handler/DWDPollenflugBridgeHandler.java index d80a3d08119ae..8bddaffd5422c 100644 --- a/bundles/org.openhab.binding.dwdpollenflug/src/main/java/org/openhab/binding/dwdpollenflug/internal/handler/DWDPollenflugBridgeHandler.java +++ b/bundles/org.openhab.binding.dwdpollenflug/src/main/java/org/openhab/binding/dwdpollenflug/internal/handler/DWDPollenflugBridgeHandler.java @@ -14,6 +14,7 @@ import java.net.SocketTimeoutException; import java.net.URI; +import java.util.Objects; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; @@ -153,7 +154,7 @@ public void onComplete(Result result) { f.completeExceptionally(new DWDPollingException("Request failed", e)); } } else if (response.getStatus() != 200) { - f.completeExceptionally(new DWDPollingException(getContentAsString())); + f.completeExceptionally(new DWDPollingException(Objects.requireNonNull(getContentAsString()))); } else { try { DWDPollenflug pollenflugJSON = gson.fromJson(getContentAsString(), DWDPollenflug.class); diff --git a/bundles/org.openhab.binding.easee/src/main/java/org/openhab/binding/easee/internal/command/AbstractCommand.java b/bundles/org.openhab.binding.easee/src/main/java/org/openhab/binding/easee/internal/command/AbstractCommand.java index 446a76003e932..dcd321d5c8e15 100644 --- a/bundles/org.openhab.binding.easee/src/main/java/org/openhab/binding/easee/internal/command/AbstractCommand.java +++ b/bundles/org.openhab.binding.easee/src/main/java/org/openhab/binding/easee/internal/command/AbstractCommand.java @@ -125,7 +125,7 @@ public AbstractCommand(EaseeThingHandler handler, RetryOnFailure retryOnFailure, * Log request success */ @Override - public final void onSuccess(@Nullable Response response) { + public final void onSuccess(Response response) { super.onSuccess(response); if (response != null) { communicationStatus.setHttpCode(HttpStatus.getCode(response.getStatus())); @@ -138,7 +138,9 @@ public final void onSuccess(@Nullable Response response) { */ @Override public final void onFailure(@Nullable Response response, @Nullable Throwable failure) { - super.onFailure(response, failure); + if (response != null && failure != null) { + super.onFailure(response, failure); + } if (failure != null) { logger.info("Request failed: {}", failure.toString()); communicationStatus.setError((Exception) failure); @@ -161,7 +163,7 @@ public final void onFailure(@Nullable Response response, @Nullable Throwable fai * just for logging of content */ @Override - public void onContent(@Nullable Response response, @Nullable ByteBuffer content) { + public void onContent(Response response, ByteBuffer content) { super.onContent(response, content); logger.debug("received content, length: {}", getContentAsString().length()); } diff --git a/bundles/org.openhab.binding.ecovacs/src/main/java/org/openhab/binding/ecovacs/internal/api/commands/GetActiveMapIdCommand.java b/bundles/org.openhab.binding.ecovacs/src/main/java/org/openhab/binding/ecovacs/internal/api/commands/GetActiveMapIdCommand.java index 16adbcf9547f0..e88db5bd918fe 100644 --- a/bundles/org.openhab.binding.ecovacs/src/main/java/org/openhab/binding/ecovacs/internal/api/commands/GetActiveMapIdCommand.java +++ b/bundles/org.openhab.binding.ecovacs/src/main/java/org/openhab/binding/ecovacs/internal/api/commands/GetActiveMapIdCommand.java @@ -12,6 +12,8 @@ */ package org.openhab.binding.ecovacs.internal.api.commands; +import java.util.Objects; + import org.eclipse.jdt.annotation.NonNullByDefault; import org.openhab.binding.ecovacs.internal.api.impl.ProtocolVersion; import org.openhab.binding.ecovacs.internal.api.impl.dto.response.deviceapi.json.CachedMapInfoReport; @@ -42,7 +44,8 @@ public String convertResponse(AbstractPortalIotCommandResponse response, Protoco throws DataParsingException { if (response instanceof PortalIotCommandJsonResponse jsonResponse) { CachedMapInfoReport resp = jsonResponse.getResponsePayloadAs(gson, CachedMapInfoReport.class); - return resp.mapInfos.stream().filter(i -> i.used != 0).map(i -> i.mapId).findFirst().orElse(""); + return Objects.requireNonNull( + resp.mapInfos.stream().filter(i -> i.used != 0).map(i -> i.mapId).findFirst().orElse("")); } else { String payload = ((PortalIotCommandXmlResponse) response).getResponsePayloadXml(); return XPathUtils.getFirstXPathMatch(payload, "//@i").getNodeValue(); diff --git a/bundles/org.openhab.binding.ecovacs/src/main/java/org/openhab/binding/ecovacs/internal/handler/EcovacsVacuumHandler.java b/bundles/org.openhab.binding.ecovacs/src/main/java/org/openhab/binding/ecovacs/internal/handler/EcovacsVacuumHandler.java index 0a24b2eaa58a5..ea4b782091c96 100644 --- a/bundles/org.openhab.binding.ecovacs/src/main/java/org/openhab/binding/ecovacs/internal/handler/EcovacsVacuumHandler.java +++ b/bundles/org.openhab.binding.ecovacs/src/main/java/org/openhab/binding/ecovacs/internal/handler/EcovacsVacuumHandler.java @@ -20,6 +20,7 @@ import java.util.Collection; import java.util.List; import java.util.Locale; +import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; @@ -320,7 +321,7 @@ public void onCleaningModeUpdated(EcovacsDevice device, CleanMode newMode, Optio } return new StringType(def); }); - updateState(CHANNEL_ID_CLEANING_SPOT_DEFINITION, areaDefState.orElse(UnDefType.UNDEF)); + updateState(CHANNEL_ID_CLEANING_SPOT_DEFINITION, Objects.requireNonNull(areaDefState.orElse(UnDefType.UNDEF))); if (newMode == CleanMode.RETURNING) { scheduleNextPoll(30); } else if (newMode.isIdle()) { @@ -597,7 +598,7 @@ private void pollData() { lastDownloadedCleanMapUrl = record.mapImageUrl; return new RawType(bytes, "image/png"); }); - updateState(CHANNEL_ID_LAST_CLEAN_MAP, content.orElse(UnDefType.NULL)); + updateState(CHANNEL_ID_LAST_CLEAN_MAP, Objects.requireNonNull(content.orElse(UnDefType.NULL))); } } } @@ -713,7 +714,7 @@ private String determineStateChannelValue(boolean charging, CleanMode cleanMode) private State stringToState(@Nullable String value) { Optional stateOpt = Optional.ofNullable(value).map(v -> StringType.valueOf(v)); - return stateOpt.orElse(UnDefType.UNDEF); + return Objects.requireNonNull(stateOpt.orElse(UnDefType.UNDEF)); } private @Nullable AbstractNoResponseCommand determineDeviceCommand(EcovacsDevice device, String command) { diff --git a/bundles/org.openhab.binding.ekey/src/main/java/org/openhab/binding/ekey/internal/handler/EkeyHandler.java b/bundles/org.openhab.binding.ekey/src/main/java/org/openhab/binding/ekey/internal/handler/EkeyHandler.java index 599038e120ee6..cc9b3cbe369b1 100644 --- a/bundles/org.openhab.binding.ekey/src/main/java/org/openhab/binding/ekey/internal/handler/EkeyHandler.java +++ b/bundles/org.openhab.binding.ekey/src/main/java/org/openhab/binding/ekey/internal/handler/EkeyHandler.java @@ -18,7 +18,7 @@ import java.util.Arrays; import java.util.Collection; import java.util.List; -import java.util.Optional; +import java.util.Objects; import java.util.stream.Collectors; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -85,7 +85,7 @@ public void initialize() { String readerThreadName = "OH-binding-" + getThing().getUID().getAsString(); EkeyUdpPacketReceiver localReceiver = receiver = new EkeyUdpPacketReceiver( - Optional.ofNullable(config.natIp).orElse(config.ipAddress), config.port, readerThreadName); + Objects.requireNonNullElse(config.natIp, config.ipAddress), config.port, readerThreadName); localReceiver.addEkeyPacketListener(this); try { localReceiver.openConnection(); diff --git a/bundles/org.openhab.binding.enigma2/src/main/java/org/openhab/binding/enigma2/internal/Enigma2Client.java b/bundles/org.openhab.binding.enigma2/src/main/java/org/openhab/binding/enigma2/internal/Enigma2Client.java index 087075db9c57a..709779ce188a5 100644 --- a/bundles/org.openhab.binding.enigma2/src/main/java/org/openhab/binding/enigma2/internal/Enigma2Client.java +++ b/bundles/org.openhab.binding.enigma2/src/main/java/org/openhab/binding/enigma2/internal/Enigma2Client.java @@ -17,6 +17,7 @@ import java.time.LocalDateTime; import java.util.Collection; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; @@ -297,8 +298,8 @@ private void processAllServicesResult(Document document) { } private String getString(Document document, String elementId) { - return Optional.ofNullable(document.getElementsByTagName(elementId)).map(nodeList -> nodeList.item(0)) - .map(Node::getTextContent).map(String::trim).orElse(""); + return Objects.requireNonNull(Optional.ofNullable(document.getElementsByTagName(elementId)) + .map(nodeList -> nodeList.item(0)).map(Node::getTextContent).map(String::trim).orElse("")); } private boolean getBoolean(Document document, String elementId) { diff --git a/bundles/org.openhab.binding.enocean/src/main/java/org/openhab/binding/enocean/internal/messages/EventMessage.java b/bundles/org.openhab.binding.enocean/src/main/java/org/openhab/binding/enocean/internal/messages/EventMessage.java index c13a6de02530e..aed7ec3d2b1e5 100644 --- a/bundles/org.openhab.binding.enocean/src/main/java/org/openhab/binding/enocean/internal/messages/EventMessage.java +++ b/bundles/org.openhab.binding.enocean/src/main/java/org/openhab/binding/enocean/internal/messages/EventMessage.java @@ -12,6 +12,7 @@ */ package org.openhab.binding.enocean.internal.messages; +import java.util.Objects; import java.util.stream.Stream; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -50,7 +51,8 @@ public int getDataLength() { } public static EventMessageType getEventMessageType(byte value) { - return Stream.of(EventMessageType.values()).filter(t -> t.value == value).findFirst().orElse(UNKNOWN); + return Objects.requireNonNull( + Stream.of(EventMessageType.values()).filter(t -> t.value == value).findFirst().orElse(UNKNOWN)); } } diff --git a/bundles/org.openhab.binding.fineoffsetweatherstation/src/main/java/org/openhab/binding/fineoffsetweatherstation/internal/domain/Measurand.java b/bundles/org.openhab.binding.fineoffsetweatherstation/src/main/java/org/openhab/binding/fineoffsetweatherstation/internal/domain/Measurand.java index 12d97a3baf063..6de3d6911fcfb 100644 --- a/bundles/org.openhab.binding.fineoffsetweatherstation/src/main/java/org/openhab/binding/fineoffsetweatherstation/internal/domain/Measurand.java +++ b/bundles/org.openhab.binding.fineoffsetweatherstation/src/main/java/org/openhab/binding/fineoffsetweatherstation/internal/domain/Measurand.java @@ -22,6 +22,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; @@ -372,8 +373,8 @@ public MeasureType getMeasureType(@Nullable ParserCustomizationType customizatio if (customizationType == null) { return measureType; } - return Optional.ofNullable(customizations).map(m -> m.get(customizationType)) - .map(ParserCustomization::getMeasureType).orElse(measureType); + return Objects.requireNonNull(Optional.ofNullable(customizations).map(m -> m.get(customizationType)) + .map(ParserCustomization::getMeasureType).orElse(measureType)); } } } diff --git a/bundles/org.openhab.binding.fmiweather/src/test/java/org/openhab/binding/fmiweather/AbstractWeatherHandlerTest.java b/bundles/org.openhab.binding.fmiweather/src/test/java/org/openhab/binding/fmiweather/AbstractWeatherHandlerTest.java index 1150097826af2..b80df6c02f64e 100644 --- a/bundles/org.openhab.binding.fmiweather/src/test/java/org/openhab/binding/fmiweather/AbstractWeatherHandlerTest.java +++ b/bundles/org.openhab.binding.fmiweather/src/test/java/org/openhab/binding/fmiweather/AbstractWeatherHandlerTest.java @@ -45,7 +45,7 @@ protected static long floorToEvenMinutes(long epochSeconds, int roundMinutes) { try { method = AbstractWeatherHandler.class.getDeclaredMethod("floorToEvenMinutes", long.class, int.class); method.setAccessible(true); - Object res = method.invoke(null, epochSeconds, roundMinutes); + Object res = method.invoke("", epochSeconds, roundMinutes); assertNotNull(res); return (long) res; } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException @@ -60,7 +60,7 @@ protected static long ceilToEvenMinutes(long epochSeconds, int roundMinutes) { try { method = AbstractWeatherHandler.class.getDeclaredMethod("ceilToEvenMinutes", long.class, int.class); method.setAccessible(true); - Object res = method.invoke(null, epochSeconds, roundMinutes); + Object res = method.invoke("", epochSeconds, roundMinutes); assertNotNull(res); return (long) res; } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException @@ -85,7 +85,7 @@ protected static int lastValidIndex(Data data) { try { method = AbstractWeatherHandler.class.getDeclaredMethod("lastValidIndex", Data.class); method.setAccessible(true); - Object res = method.invoke(null, data); + Object res = method.invoke("", data); assertNotNull(res); return (int) res; } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException diff --git a/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/api/rest/PlayerManager.java b/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/api/rest/PlayerManager.java index f3b9bff3a010a..d8ba8698a7173 100644 --- a/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/api/rest/PlayerManager.java +++ b/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/api/rest/PlayerManager.java @@ -18,6 +18,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import javax.ws.rs.core.UriBuilder; @@ -226,7 +227,7 @@ public PlayerManager(FreeboxOsSession session) throws FreeboxException { // The player API does not allow to directly request a given player like others api parts @Override public Player getDevice(int id) throws FreeboxException { - return getDevices().stream().filter(player -> player.id == id).findFirst().orElse(null); + return Objects.requireNonNull(getDevices().stream().filter(player -> player.id == id).findFirst().orElse(null)); } public @Nullable Configuration getConfig(int id) throws FreeboxException { diff --git a/bundles/org.openhab.binding.gce/src/main/java/org/openhab/binding/gce/internal/model/StatusFileInterpreter.java b/bundles/org.openhab.binding.gce/src/main/java/org/openhab/binding/gce/internal/model/StatusFileInterpreter.java index 6536a7944356e..6449ffb3e4559 100644 --- a/bundles/org.openhab.binding.gce/src/main/java/org/openhab/binding/gce/internal/model/StatusFileInterpreter.java +++ b/bundles/org.openhab.binding.gce/src/main/java/org/openhab/binding/gce/internal/model/StatusFileInterpreter.java @@ -17,6 +17,7 @@ import java.io.InputStream; import java.util.Comparator; import java.util.List; +import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -104,8 +105,9 @@ private void pushDatas() { } public String getElement(StatusEntry entry) { - return getRoot().map(root -> root.getElementsByTagName(entry.name().toLowerCase()).item(0).getTextContent()) - .orElse(""); + return Objects.requireNonNull( + getRoot().map(root -> root.getElementsByTagName(entry.name().toLowerCase()).item(0).getTextContent()) + .orElse("")); } private List getMatchingNodes(NodeList nodeList, String criteria) { diff --git a/bundles/org.openhab.binding.haassohnpelletstove/src/main/java/org/openhab/binding/haassohnpelletstove/internal/HaasSohnpelletstoveJSONCommunication.java b/bundles/org.openhab.binding.haassohnpelletstove/src/main/java/org/openhab/binding/haassohnpelletstove/internal/HaasSohnpelletstoveJSONCommunication.java index f5fd2b16710df..3eb56e9893afe 100644 --- a/bundles/org.openhab.binding.haassohnpelletstove/src/main/java/org/openhab/binding/haassohnpelletstove/internal/HaasSohnpelletstoveJSONCommunication.java +++ b/bundles/org.openhab.binding.haassohnpelletstove/src/main/java/org/openhab/binding/haassohnpelletstove/internal/HaasSohnpelletstoveJSONCommunication.java @@ -16,6 +16,7 @@ import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; +import java.util.Objects; import java.util.Properties; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -39,13 +40,12 @@ public class HaasSohnpelletstoveJSONCommunication { private HaasSohnpelletstoveConfiguration config; private Gson gson; - private @Nullable String xhspin; + private String xhspin = ""; private @Nullable HaasSohnpelletstoveJsonDataDTO ovenData; public HaasSohnpelletstoveJSONCommunication() { gson = new Gson(); ovenData = new HaasSohnpelletstoveJsonDataDTO(); - xhspin = ""; config = new HaasSohnpelletstoveConfiguration(); } @@ -160,7 +160,7 @@ public boolean updateOvenData(@Nullable String postData, Helper helper, String t */ private Properties createHeader(@Nullable String postData) { Properties httpHeader = new Properties(); - httpHeader.setProperty("Host", config.hostIP); + httpHeader.setProperty("Host", Objects.requireNonNull(config.hostIP)); httpHeader.setProperty("Accept", "*/*"); httpHeader.setProperty("Proxy-Connection", "keep-alive"); httpHeader.setProperty("X-BACKEND-IP", "https://app.haassohn.com"); @@ -182,16 +182,16 @@ private Properties createHeader(@Nullable String postData) { * Generate the valid encrypted string to communicate with the oven. * * @param ovenData - * @return + * @return XHSPIN or empty when it cannot be determined */ - private @Nullable String getValidXHSPIN(@Nullable HaasSohnpelletstoveJsonDataDTO ovenData) { + private String getValidXHSPIN(@Nullable HaasSohnpelletstoveJsonDataDTO ovenData) { if (ovenData != null && config.hostPIN != null) { String nonce = ovenData.getNonce(); String hostPIN = config.hostPIN; String ePin = MD5Utils.getMD5String(hostPIN); return MD5Utils.getMD5String(nonce + ePin); } else { - return null; + return ""; } } diff --git a/bundles/org.openhab.binding.heliosventilation/src/main/java/org/openhab/binding/heliosventilation/internal/HeliosVentilationBindingConstants.java b/bundles/org.openhab.binding.heliosventilation/src/main/java/org/openhab/binding/heliosventilation/internal/HeliosVentilationBindingConstants.java index ecda2ef4cc36c..a8c2dfd5daeb6 100644 --- a/bundles/org.openhab.binding.heliosventilation/src/main/java/org/openhab/binding/heliosventilation/internal/HeliosVentilationBindingConstants.java +++ b/bundles/org.openhab.binding.heliosventilation/src/main/java/org/openhab/binding/heliosventilation/internal/HeliosVentilationBindingConstants.java @@ -17,6 +17,7 @@ import java.util.Enumeration; import java.util.HashMap; import java.util.Map; +import java.util.Objects; import java.util.Properties; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -68,7 +69,8 @@ private static Map readChannelProperties() { String channel = (String) keys.nextElement(); HeliosVentilationDataPoint dp; try { - dp = new HeliosVentilationDataPoint(channel, properties.getProperty(channel)); + dp = new HeliosVentilationDataPoint(channel, + Objects.requireNonNull(properties.getProperty(channel))); if (result.containsKey(dp.address())) { result.get(dp.address()).append(dp); } else { diff --git a/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/handler/HeosDynamicStateDescriptionProvider.java b/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/handler/HeosDynamicStateDescriptionProvider.java index 982dfb537f382..86b3b3c60d8b8 100644 --- a/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/handler/HeosDynamicStateDescriptionProvider.java +++ b/bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/handler/HeosDynamicStateDescriptionProvider.java @@ -13,6 +13,7 @@ package org.openhab.binding.heos.internal.handler; import java.util.List; +import java.util.Objects; import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; @@ -42,7 +43,7 @@ String getValueByLabel(ChannelUID channelUID, String input) { .filter(o -> input.equals(o.getLabel())).map(StateOption::getValue).findFirst(); // if no match was found we assume that it already was a value and not a label - return optionalValueByLabel.orElse(input); + return Objects.requireNonNull(optionalValueByLabel.orElse(input)); } public void setFavorites(ChannelUID channelUID, List favorites) { diff --git a/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/handler/Clip2ThingHandler.java b/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/handler/Clip2ThingHandler.java index f66b05a85cdd0..1a69b30c4d931 100644 --- a/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/handler/Clip2ThingHandler.java +++ b/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/handler/Clip2ThingHandler.java @@ -1233,8 +1233,8 @@ public synchronized boolean updateSceneContributors(List allScenes) { sceneContributorsCache.putAll(scenes.stream().collect(Collectors.toMap(s -> s.getId(), s -> s))); sceneResourceEntries.putAll(scenes.stream().collect(Collectors.toMap(s -> s.getName(), s -> s))); - State state = scenes.stream().filter(s -> s.getSceneActive().orElse(false)).map(s -> s.getSceneState()) - .findAny().orElse(UnDefType.UNDEF); + State state = Objects.requireNonNull(scenes.stream().filter(s -> s.getSceneActive().orElse(false)) + .map(s -> s.getSceneState()).findAny().orElse(UnDefType.UNDEF)); // create scene channel if it is missing if (getThing().getChannel(CHANNEL_2_SCENE) == null) { diff --git a/bundles/org.openhab.binding.knx/src/main/java/org/openhab/binding/knx/internal/client/AbstractKNXClient.java b/bundles/org.openhab.binding.knx/src/main/java/org/openhab/binding/knx/internal/client/AbstractKNXClient.java index 79f4fb2f1d071..87ef9245163e5 100644 --- a/bundles/org.openhab.binding.knx/src/main/java/org/openhab/binding/knx/internal/client/AbstractKNXClient.java +++ b/bundles/org.openhab.binding.knx/src/main/java/org/openhab/binding/knx/internal/client/AbstractKNXClient.java @@ -15,7 +15,6 @@ import static org.openhab.binding.knx.internal.dpt.DPTUtil.NORMALIZED_DPT; import java.time.Duration; -import java.util.Optional; import java.util.Set; import java.util.concurrent.CancellationException; import java.util.concurrent.CopyOnWriteArraySet; @@ -273,19 +272,20 @@ private synchronized boolean connect() { return false; } catch (KNXIllegalArgumentException e) { logger.debug("Bridge {} cannot connect: {}", thingUID, e.getMessage()); - disconnect(e, Optional.of(ThingStatusDetail.CONFIGURATION_ERROR)); + disconnect(e, ThingStatusDetail.CONFIGURATION_ERROR); return false; } } private void disconnect(@Nullable Exception e) { - disconnect(e, Optional.empty()); + disconnect(e, null); } - private synchronized void disconnect(@Nullable Exception e, Optional detail) { + private synchronized void disconnect(@Nullable Exception e, @Nullable ThingStatusDetail detail) { releaseConnection(); if (e != null) { - statusUpdateCallback.updateStatus(ThingStatus.OFFLINE, detail.orElse(ThingStatusDetail.COMMUNICATION_ERROR), + statusUpdateCallback.updateStatus(ThingStatus.OFFLINE, + detail != null ? detail : ThingStatusDetail.COMMUNICATION_ERROR, KNXTranslationProvider.I18N.getLocalizedException(e)); } else { statusUpdateCallback.updateStatus(ThingStatus.OFFLINE); diff --git a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/LcnModuleActions.java b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/LcnModuleActions.java index c99e9669ab3ae..2ff0f9ce14b64 100644 --- a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/LcnModuleActions.java +++ b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/LcnModuleActions.java @@ -14,6 +14,7 @@ import java.nio.ByteBuffer; import java.util.Arrays; +import java.util.Objects; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; @@ -203,10 +204,10 @@ public void beep( localCount = 1; } - String filteredTonality = LcnBindingConstants.ALLOWED_BEEP_TONALITIES.stream() // + String filteredTonality = Objects.requireNonNull(LcnBindingConstants.ALLOWED_BEEP_TONALITIES.stream() // .filter(t -> t.equals(tonality)) // .findAny() // - .orElse("N"); + .orElse("N")); getHandler().sendPck(PckGenerator.beep(filteredTonality, Math.min(localCount, MAX_BEEP_COUNT))); } catch (LcnException e) { diff --git a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleThresholdSubHandler.java b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleThresholdSubHandler.java index e9161e498a6e9..01d5f51d99485 100644 --- a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleThresholdSubHandler.java +++ b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/subhandler/LcnModuleThresholdSubHandler.java @@ -14,7 +14,6 @@ import java.util.Arrays; import java.util.Collection; -import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.IntStream; @@ -72,16 +71,16 @@ public void handleCommandDecimal(DecimalType command, LcnChannelGroup channelGro @Override public void handleStatusMessage(Matcher matcher) { IntStream stream; - Optional groupSuffix; + String groupSuffix; int registerNumber; if (matcher.pattern() == PATTERN) { int thresholdId = Integer.parseInt(matcher.group("thresholdId")) - 1; registerNumber = Integer.parseInt(matcher.group("registerId")) - 1; stream = IntStream.rangeClosed(thresholdId, thresholdId); - groupSuffix = Optional.of(""); + groupSuffix = ""; } else if (matcher.pattern() == PATTERN_BEFORE_2013) { stream = IntStream.range(0, LcnDefs.THRESHOLD_COUNT_BEFORE_2013); - groupSuffix = Optional.empty(); + groupSuffix = null; registerNumber = 0; } else { logger.warn("Unexpected pattern: {}", matcher.pattern()); @@ -90,7 +89,7 @@ public void handleStatusMessage(Matcher matcher) { stream.forEach(i -> { try { - fireUpdateAndReset(matcher, groupSuffix.orElse(String.valueOf(i)), + fireUpdateAndReset(matcher, groupSuffix != null ? groupSuffix : String.valueOf(i), Variable.thrsIdToVar(registerNumber, i)); } catch (LcnException e) { logger.warn("Parse error: {}", e.getMessage()); diff --git a/bundles/org.openhab.binding.luxom/src/main/java/org/openhab/binding/luxom/internal/protocol/LuxomAction.java b/bundles/org.openhab.binding.luxom/src/main/java/org/openhab/binding/luxom/internal/protocol/LuxomAction.java index 720875d3c3337..af3e3bab6d45b 100644 --- a/bundles/org.openhab.binding.luxom/src/main/java/org/openhab/binding/luxom/internal/protocol/LuxomAction.java +++ b/bundles/org.openhab.binding.luxom/src/main/java/org/openhab/binding/luxom/internal/protocol/LuxomAction.java @@ -13,6 +13,7 @@ package org.openhab.binding.luxom.internal.protocol; import java.util.Arrays; +import java.util.Objects; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -55,8 +56,8 @@ public enum LuxomAction { } public static LuxomAction of(String command) { - return Arrays.stream(LuxomAction.values()).filter(a -> a.getCommand().equals(command)).findFirst() - .orElse(INVALID_ACTION); + return Objects.requireNonNull(Arrays.stream(LuxomAction.values()).filter(a -> a.getCommand().equals(command)) + .findFirst().orElse(INVALID_ACTION)); } public String getCommand() { diff --git a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVOAuth.java b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVOAuth.java index cdab8fe213e00..a60e70d1a935b 100644 --- a/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVOAuth.java +++ b/bundles/org.openhab.binding.magentatv/src/main/java/org/openhab/binding/magentatv/internal/network/MagentaTVOAuth.java @@ -22,6 +22,7 @@ import java.util.ArrayList; import java.util.Enumeration; import java.util.List; +import java.util.Objects; import java.util.Properties; import java.util.UUID; import java.util.concurrent.ExecutionException; @@ -215,7 +216,7 @@ private String httpRequest(String method, String url, Properties headers, String TimeUnit.MILLISECONDS); for (Enumeration e = headers.keys(); e.hasMoreElements();) { String key = (String) e.nextElement(); - String val = (String) headers.get(key); + String val = (String) headers.get(Objects.requireNonNull(key)); request.header(key, val); } if (method.equals(HttpMethod.POST)) { diff --git a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/config/servlet/PairAccountServlet.java b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/config/servlet/PairAccountServlet.java index c6625b9644c06..6fe77041d7c1a 100644 --- a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/config/servlet/PairAccountServlet.java +++ b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/config/servlet/PairAccountServlet.java @@ -13,7 +13,7 @@ package org.openhab.binding.mielecloud.internal.config.servlet; import java.io.IOException; -import java.util.Optional; +import java.util.Objects; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -68,9 +68,9 @@ protected String handleGetRequest(HttpServletRequest request, HttpServletRespons } private String renderClientIdAndClientSecret(HttpServletRequest request, String skeleton) { - String prefilledClientId = Optional.ofNullable(request.getParameter(CLIENT_ID_PARAMETER_NAME)).orElse(""); - String prefilledClientSecret = Optional.ofNullable(request.getParameter(CLIENT_SECRET_PARAMETER_NAME)) - .orElse(""); + String prefilledClientId = Objects.requireNonNullElse(request.getParameter(CLIENT_ID_PARAMETER_NAME), ""); + String prefilledClientSecret = Objects.requireNonNullElse(request.getParameter(CLIENT_SECRET_PARAMETER_NAME), + ""); return skeleton.replace(CLIENT_ID_PLACEHOLDER, prefilledClientId).replace(CLIENT_SECRET_PLACEHOLDER, prefilledClientSecret); } diff --git a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/config/servlet/SuccessServlet.java b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/config/servlet/SuccessServlet.java index 2ebb634b71764..918fc097156b1 100644 --- a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/config/servlet/SuccessServlet.java +++ b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/config/servlet/SuccessServlet.java @@ -14,6 +14,7 @@ import java.io.IOException; import java.util.Locale; +import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -148,7 +149,7 @@ private String createOptionTag(Language language, boolean selected) { private String renderBridgeConfigurationTemplate(String skeleton, ThingUID bridgeUid, String email) { String bridgeTemplate = templateGenerator.createBridgeConfigurationTemplate(bridgeUid.getId(), email, - languageProvider.getLanguage().orElse("en")); + Objects.requireNonNull(languageProvider.getLanguage().orElse("en"))); return skeleton.replace(THINGS_TEMPLATE_CODE_PLACEHOLDER, bridgeTemplate); } diff --git a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/discovery/ThingDiscoveryService.java b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/discovery/ThingDiscoveryService.java index d95927023c1aa..8ea01c9d5f0da 100644 --- a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/discovery/ThingDiscoveryService.java +++ b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/discovery/ThingDiscoveryService.java @@ -16,6 +16,7 @@ import static org.openhab.binding.mielecloud.internal.handler.MieleHandlerFactory.SUPPORTED_THING_TYPES; import java.util.Map; +import java.util.Objects; import java.util.Optional; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -189,7 +190,8 @@ private String getLabel(DeviceState deviceState) { return deviceName.get(); } - return ThingInformationExtractor.getDeviceAndTechType(deviceState).orElse("Miele Device"); + return Objects + .requireNonNull(ThingInformationExtractor.getDeviceAndTechType(deviceState).orElse("Miele Device")); } @Override diff --git a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/discovery/ThingInformationExtractor.java b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/discovery/ThingInformationExtractor.java index 7ea32c6f88ec6..dcc80783a1a21 100644 --- a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/discovery/ThingInformationExtractor.java +++ b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/discovery/ThingInformationExtractor.java @@ -14,6 +14,7 @@ import java.util.HashMap; import java.util.Map; +import java.util.Objects; import java.util.Optional; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -58,11 +59,11 @@ public static Map extractProperties(ThingTypeUID thingTypeUid, D } private static String getSerialNumber(DeviceState deviceState) { - return deviceState.getFabNumber().orElse(deviceState.getDeviceIdentifier()); + return Objects.requireNonNull(deviceState.getFabNumber().orElse(deviceState.getDeviceIdentifier())); } private static String getModelId(DeviceState deviceState) { - return getDeviceAndTechType(deviceState).orElse("Unknown"); + return Objects.requireNonNull(getDeviceAndTechType(deviceState).orElse("Unknown")); } /** diff --git a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/handler/AbstractMieleThingHandler.java b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/handler/AbstractMieleThingHandler.java index 262f6dae969e5..bea911d2ed1af 100644 --- a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/handler/AbstractMieleThingHandler.java +++ b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/handler/AbstractMieleThingHandler.java @@ -17,6 +17,7 @@ import static org.openhab.binding.mielecloud.internal.webservice.api.ProgramStatus.*; import static org.openhab.binding.mielecloud.internal.webservice.api.json.ProcessAction.*; +import java.util.Objects; import java.util.Optional; import java.util.function.Consumer; @@ -88,8 +89,8 @@ private Optional getMieleBridgeHandler() { } protected MieleWebservice getWebservice() { - return getMieleBridgeHandler().map(MieleBridgeHandler::getWebservice) - .orElse(UnavailableMieleWebservice.INSTANCE); + return Objects.requireNonNull(getMieleBridgeHandler().map(MieleBridgeHandler::getWebservice) + .orElse(UnavailableMieleWebservice.INSTANCE)); } @Override diff --git a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/handler/channel/ChannelTypeUtil.java b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/handler/channel/ChannelTypeUtil.java index c704be8c9c583..d9bfe1f495910 100644 --- a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/handler/channel/ChannelTypeUtil.java +++ b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/handler/channel/ChannelTypeUtil.java @@ -15,6 +15,7 @@ import java.math.BigDecimal; import java.text.NumberFormat; import java.util.Locale; +import java.util.Objects; import java.util.Optional; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -46,29 +47,31 @@ private ChannelTypeUtil() { * Converts an {@link Optional} of {@link String} to {@link State}. */ public static State stringToState(Optional value) { - return value.filter(v -> !v.isEmpty()).filter(v -> !"null".equals(v)).map(v -> (State) new StringType(v)) - .orElse(UnDefType.UNDEF); + return Objects.requireNonNull(value.filter(v -> !v.isEmpty()).filter(v -> !"null".equals(v)) + .map(v -> (State) new StringType(v)).orElse(UnDefType.UNDEF)); } /** * Converts an {@link Optional} of {@link Boolean} to {@link State}. */ public static State booleanToState(Optional value) { - return value.map(v -> (State) OnOffType.from(v)).orElse(UnDefType.UNDEF); + return Objects.requireNonNull(value.map(v -> (State) OnOffType.from(v)).orElse(UnDefType.UNDEF)); } /** * Converts an {@link Optional} of {@link Integer} to {@link State}. */ public static State intToState(Optional value) { - return value.map(v -> (State) new DecimalType(new BigDecimal(v))).orElse(UnDefType.UNDEF); + return Objects + .requireNonNull(value.map(v -> (State) new DecimalType(new BigDecimal(v))).orElse(UnDefType.UNDEF)); } /** * Converts an {@link Optional} of {@link Long} to {@link State}. */ public static State longToState(Optional value) { - return value.map(v -> (State) new DecimalType(new BigDecimal(v))).orElse(UnDefType.UNDEF); + return Objects + .requireNonNull(value.map(v -> (State) new DecimalType(new BigDecimal(v))).orElse(UnDefType.UNDEF)); } /** @@ -76,15 +79,16 @@ public static State longToState(Optional value) { */ public static State intToTemperatureState(Optional value) { // The Miele 3rd Party API always provides temperatures in °C (even if the device uses another unit). - return value.map(v -> (State) new QuantityType<>(v, SIUnits.CELSIUS)).orElse(UnDefType.UNDEF); + return Objects + .requireNonNull(value.map(v -> (State) new QuantityType<>(v, SIUnits.CELSIUS)).orElse(UnDefType.UNDEF)); } /** * Converts an {@link Optional} of {@link Quantity} to {@link State}. */ public static State quantityToState(Optional value) { - return value.flatMap(ChannelTypeUtil::formatQuantity).flatMap(ChannelTypeUtil::parseQuantityType) - .orElse(UnDefType.UNDEF); + return Objects.requireNonNull(value.flatMap(ChannelTypeUtil::formatQuantity) + .flatMap(ChannelTypeUtil::parseQuantityType).orElse(UnDefType.UNDEF)); } /** diff --git a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/api/DeviceState.java b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/api/DeviceState.java index deff78be92a7e..9f89ebfdd6df2 100644 --- a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/api/DeviceState.java +++ b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/api/DeviceState.java @@ -518,8 +518,8 @@ public Optional getType() { * @return The raw device type. */ public DeviceType getRawType() { - return device.flatMap(Device::getIdent).flatMap(Ident::getType).map(Type::getValueRaw) - .orElse(DeviceType.UNKNOWN); + return Objects.requireNonNull(device.flatMap(Device::getIdent).flatMap(Ident::getType).map(Type::getValueRaw) + .orElse(DeviceType.UNKNOWN)); } /** diff --git a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/api/json/Type.java b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/api/json/Type.java index b32af3c885baf..527b85446d957 100644 --- a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/api/json/Type.java +++ b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/webservice/api/json/Type.java @@ -42,7 +42,7 @@ public Optional getKeyLocalized() { } public DeviceType getValueRaw() { - return Optional.ofNullable(valueRaw).orElse(DeviceType.UNKNOWN); + return Objects.requireNonNullElse(valueRaw, DeviceType.UNKNOWN); } public Optional getValueLocalized() { diff --git a/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/webservice/sse/SseConnectionTest.java b/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/webservice/sse/SseConnectionTest.java index ff7e03e696986..250cce13ad05a 100644 --- a/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/webservice/sse/SseConnectionTest.java +++ b/bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/webservice/sse/SseConnectionTest.java @@ -112,7 +112,8 @@ private void setUpRunningConnection() { getSseConnection().addSseListener(getMockedSseListener()); getSseConnection().connect(); - getRegisteredHeadersListener().onHeaders(null); + Response response = mock(Response.class); + getRegisteredHeadersListener().onHeaders(response); } private Request getMockedRequest() { @@ -206,7 +207,8 @@ public void whenHeadersAreReceivedAfterTheSseConnectionWasConnectedThenTheEventS assertNotNull(headersListener); // when: - headersListener.onHeaders(null); + Response response = mock(Response.class); + headersListener.onHeaders(response); // then: verify(scheduler).schedule(ArgumentMatchers. any(), anyLong(), any()); @@ -266,7 +268,8 @@ public void whenTheSseRequestCompletesWithoutResultThenAReconnectIsScheduledAndT setUpRunningConnection(); // when: - getRegisteredCompleteListener().onComplete(null); + Result result = mock(Result.class); + getRegisteredCompleteListener().onComplete(result); // then: verify(getMockedScheduler(), times(2)).schedule(ArgumentMatchers. any(), anyLong(), any()); @@ -505,7 +508,8 @@ public void whenAServerSentEventIsReceivedThenItIsForwardedToTheListenersAndTheF HeadersListener headersListener = registeredHeadersListener; assertNotNull(headersListener); - headersListener.onHeaders(null); + Response response = mock(Response.class); + headersListener.onHeaders(response); ServerSentEvent serverSentEvent = new ServerSentEvent("ping", "ping"); diff --git a/bundles/org.openhab.binding.modbus.helioseasycontrols/src/main/java/org/openhab/binding/modbus/helioseasycontrols/internal/HeliosEasyControlsActions.java b/bundles/org.openhab.binding.modbus.helioseasycontrols/src/main/java/org/openhab/binding/modbus/helioseasycontrols/internal/HeliosEasyControlsActions.java index e4f77652636f5..f65167f134faf 100644 --- a/bundles/org.openhab.binding.modbus.helioseasycontrols/src/main/java/org/openhab/binding/modbus/helioseasycontrols/internal/HeliosEasyControlsActions.java +++ b/bundles/org.openhab.binding.modbus.helioseasycontrols/src/main/java/org/openhab/binding/modbus/helioseasycontrols/internal/HeliosEasyControlsActions.java @@ -56,6 +56,7 @@ public void setThingHandler(@Nullable ThingHandler handler) { private void triggerSwitch(String variableName) { try { + HeliosEasyControlsHandler handler = this.handler; if (handler != null) { handler.writeValue(variableName, "1"); } @@ -159,6 +160,7 @@ public static void setBypassTo(ThingActions actions, int day, int month) { @RuleAction(label = "@text/action.getErrorMessages.label", description = "@text/action.getErrorMessages.description") public @ActionOutput(name = "errorMessages", type = "java.util.List") List getErrorMessages() { + HeliosEasyControlsHandler handler = this.handler; return (handler != null) ? handler.getErrorMessages() : new ArrayList<>(); } @@ -168,6 +170,7 @@ public static List getErrorMessages(ThingActions actions) { @RuleAction(label = "@text/action.getWarningMessages.label", description = "@text/action.getWarningMessages.description") public @ActionOutput(name = "warningMessages", type = "java.util.List") List getWarningMessages() { + HeliosEasyControlsHandler handler = this.handler; return (handler != null) ? handler.getWarningMessages() : new ArrayList<>(); } @@ -177,6 +180,7 @@ public static List getWarningMessages(ThingActions actions) { @RuleAction(label = "@text/action.getInfoMessages.label", description = "@text/action.getInfoMessages.description") public @ActionOutput(name = "infoMessages", type = "java.util.List") List getInfoMessages() { + HeliosEasyControlsHandler handler = this.handler; return (handler != null) ? handler.getInfoMessages() : new ArrayList<>(); } @@ -186,6 +190,7 @@ public static List getInfoMessages(ThingActions actions) { @RuleAction(label = "@text/action.getStatusMessages.label", description = "@text/action.getStatusMessages.description") public @ActionOutput(name = "statusMessages", type = "java.util.List") List getStatusMessages() { + HeliosEasyControlsHandler handler = this.handler; return (handler != null) ? handler.getStatusMessages() : new ArrayList<>(); } diff --git a/bundles/org.openhab.binding.modbus.helioseasycontrols/src/main/java/org/openhab/binding/modbus/helioseasycontrols/internal/HeliosEasyControlsHandler.java b/bundles/org.openhab.binding.modbus.helioseasycontrols/src/main/java/org/openhab/binding/modbus/helioseasycontrols/internal/HeliosEasyControlsHandler.java index 8a9061b4eed06..3b8dad53beca3 100644 --- a/bundles/org.openhab.binding.modbus.helioseasycontrols/src/main/java/org/openhab/binding/modbus/helioseasycontrols/internal/HeliosEasyControlsHandler.java +++ b/bundles/org.openhab.binding.modbus.helioseasycontrols/src/main/java/org/openhab/binding/modbus/helioseasycontrols/internal/HeliosEasyControlsHandler.java @@ -168,9 +168,10 @@ private void readVariableDefinition() { } catch (IOException e) { this.handleError("Error reading variable definition file", ThingStatusDetail.CONFIGURATION_ERROR); } + Map variableMap = this.variableMap; if (variableMap != null) { // add the name to the variable itself - for (Map.Entry entry : this.variableMap.entrySet()) { + for (Map.Entry entry : variableMap.entrySet()) { entry.getValue().setName(entry.getKey()); // workaround to set the variable name inside the // HeliosVariable object if (!entry.getValue().isOk()) { @@ -225,7 +226,6 @@ private void connectEndpoint() { ModbusEndpointThingHandler slaveEndpointThingHandler = getEndpointThingHandler(); if (slaveEndpointThingHandler == null) { - @SuppressWarnings("null") String label = Optional.ofNullable(getBridge()).map(b -> b.getLabel()).orElse(""); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE, String.format("Bridge '%s' is offline", label)); @@ -236,7 +236,6 @@ private void connectEndpoint() { comms = slaveEndpointThingHandler.getCommunicationInterface(); if (comms == null) { - @SuppressWarnings("null") String label = Optional.ofNullable(getBridge()).map(b -> b.getLabel()).orElse(""); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE, String.format("Bridge '%s' not completely initialized", label)); @@ -250,8 +249,9 @@ public void initialize() { this.config = getConfigAs(HeliosEasyControlsConfiguration.class); this.readVariableDefinition(); this.connectEndpoint(); - if ((this.comms != null) && (this.variableMap != null) && (this.config != null)) { - this.transactionLocks.putIfAbsent(this.comms.getEndpoint(), new Semaphore(1, true)); + ModbusCommunicationInterface comms = this.comms; + if (comms != null && this.variableMap != null && this.config != null) { + this.transactionLocks.putIfAbsent(comms.getEndpoint(), new Semaphore(1, true)); updateStatus(ThingStatus.UNKNOWN); // background initialization @@ -264,6 +264,7 @@ public void initialize() { HeliosEasyControlsConfiguration config = this.config; if (config != null) { this.pollingJob = scheduler.scheduleWithFixedDelay(() -> { + Map variableMap = this.variableMap; if (variableMap != null) { for (Map.Entry entry : variableMap.entrySet()) { if (this.isProperty(entry.getKey()) || isLinked(entry.getValue().getGroupAndName()) @@ -293,8 +294,10 @@ public void initialize() { @Override public void dispose() { - if (this.pollingJob != null) { - this.pollingJob.cancel(true); + ScheduledFuture pollingJob = this.pollingJob; + if (pollingJob != null) { + pollingJob.cancel(true); + this.pollingJob = null; } this.comms = null; } @@ -382,6 +385,7 @@ public void handleCommand(ChannelUID channelUID, Command command) { scheduler.submit(() -> { try { writeValue(channelId, v); + Map variableMap = this.variableMap; if (variableMap != null) { HeliosVariable variable = variableMap.get(channelId); if (variable != null) { diff --git a/bundles/org.openhab.binding.modbus.helioseasycontrols/src/test/java/org/openhab/binding/modbus/helioseasycontrols/internal/PreparePayloadTest.java b/bundles/org.openhab.binding.modbus.helioseasycontrols/src/test/java/org/openhab/binding/modbus/helioseasycontrols/internal/PreparePayloadTest.java index 84beb827505fb..8dfe70377d5d2 100644 --- a/bundles/org.openhab.binding.modbus.helioseasycontrols/src/test/java/org/openhab/binding/modbus/helioseasycontrols/internal/PreparePayloadTest.java +++ b/bundles/org.openhab.binding.modbus.helioseasycontrols/src/test/java/org/openhab/binding/modbus/helioseasycontrols/internal/PreparePayloadTest.java @@ -39,7 +39,7 @@ public PreparePayloadTest() throws NoSuchMethodException, SecurityException { private ModbusRegisterArray preparePayload(String payload) { try { - return (ModbusRegisterArray) preparePayloadMethod.invoke(null, payload); + return (ModbusRegisterArray) preparePayloadMethod.invoke("", payload); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { fail("Reflection failure:" + e.getMessage()); throw new RuntimeException(); // to make compiler happy diff --git a/bundles/org.openhab.binding.modbus.stiebeleltron/src/main/java/org/openhab/binding/modbus/stiebeleltron/internal/parser/AbstractBaseParser.java b/bundles/org.openhab.binding.modbus.stiebeleltron/src/main/java/org/openhab/binding/modbus/stiebeleltron/internal/parser/AbstractBaseParser.java index 10444493841ba..6f39d970e77e9 100644 --- a/bundles/org.openhab.binding.modbus.stiebeleltron/src/main/java/org/openhab/binding/modbus/stiebeleltron/internal/parser/AbstractBaseParser.java +++ b/bundles/org.openhab.binding.modbus.stiebeleltron/src/main/java/org/openhab/binding/modbus/stiebeleltron/internal/parser/AbstractBaseParser.java @@ -12,6 +12,7 @@ */ package org.openhab.binding.modbus.stiebeleltron.internal.parser; +import java.util.Objects; import java.util.Optional; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -50,7 +51,7 @@ protected Optional extractOptionalDouble(ModbusRegisterArray raw, int in * @return the parsed value or the default if the field is not implemented */ protected Double extractDouble(ModbusRegisterArray raw, int index, double def) { - return extractOptionalDouble(raw, index).orElse(def); + return Objects.requireNonNull(extractOptionalDouble(raw, index).orElse(def)); } /** @@ -74,7 +75,7 @@ protected Optional extractOptionalInt16(ModbusRegisterArray raw, int inde * @return the parsed value or the default if the field is not implemented */ protected Short extractInt16(ModbusRegisterArray raw, int index, short def) { - return extractOptionalInt16(raw, index).orElse(def); + return Objects.requireNonNull(extractOptionalInt16(raw, index).orElse(def)); } /** @@ -98,7 +99,7 @@ protected Optional extractOptionalUInt16(ModbusRegisterArray raw, int i * @return the parsed value or the default if the field is not implemented */ protected Integer extractUInt16(ModbusRegisterArray raw, int index, int def) { - return extractOptionalUInt16(raw, index).orElse(def); + return Objects.requireNonNull(extractOptionalUInt16(raw, index).orElse(def)); } /** @@ -122,6 +123,6 @@ protected Optional extractOptionalUInt32(ModbusRegisterArray raw, int inde * @return the parsed value or default if the field is not implemented */ protected Long extractUnit32(ModbusRegisterArray raw, int index, long def) { - return extractOptionalUInt32(raw, index).orElse(def); + return Objects.requireNonNull(extractOptionalUInt32(raw, index).orElse(def)); } } diff --git a/bundles/org.openhab.binding.modbus.sunspec/src/main/java/org/openhab/binding/modbus/sunspec/internal/handler/InverterHandler.java b/bundles/org.openhab.binding.modbus.sunspec/src/main/java/org/openhab/binding/modbus/sunspec/internal/handler/InverterHandler.java index 0c61596a9ba31..95ff876e16b85 100644 --- a/bundles/org.openhab.binding.modbus.sunspec/src/main/java/org/openhab/binding/modbus/sunspec/internal/handler/InverterHandler.java +++ b/bundles/org.openhab.binding.modbus.sunspec/src/main/java/org/openhab/binding/modbus/sunspec/internal/handler/InverterHandler.java @@ -16,6 +16,7 @@ import static org.openhab.core.library.unit.SIUnits.CELSIUS; import static org.openhab.core.library.unit.Units.*; +import java.util.Objects; import java.util.Optional; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -85,7 +86,7 @@ protected void handlePolledData(ModbusRegisterArray registers) { status == null ? UnDefType.UNDEF : new StringType(status.name())); updateState(channelUID(GROUP_DEVICE_INFO, CHANNEL_STATUS_VENDOR), - block.statusVendor. map(DecimalType::new).orElse(UnDefType.UNDEF)); + Objects.requireNonNull(block.statusVendor. map(DecimalType::new).orElse(UnDefType.UNDEF))); // AC General group updateState(channelUID(GROUP_AC_GENERAL, CHANNEL_AC_TOTAL_CURRENT), diff --git a/bundles/org.openhab.binding.modbus.sunspec/src/main/java/org/openhab/binding/modbus/sunspec/internal/handler/MeterHandler.java b/bundles/org.openhab.binding.modbus.sunspec/src/main/java/org/openhab/binding/modbus/sunspec/internal/handler/MeterHandler.java index effefdce2443a..c72138bd7cb7c 100644 --- a/bundles/org.openhab.binding.modbus.sunspec/src/main/java/org/openhab/binding/modbus/sunspec/internal/handler/MeterHandler.java +++ b/bundles/org.openhab.binding.modbus.sunspec/src/main/java/org/openhab/binding/modbus/sunspec/internal/handler/MeterHandler.java @@ -15,6 +15,8 @@ import static org.openhab.binding.modbus.sunspec.internal.SunSpecConstants.*; import static org.openhab.core.library.unit.Units.*; +import java.util.Objects; + import org.eclipse.jdt.annotation.NonNullByDefault; import org.openhab.binding.modbus.sunspec.internal.dto.MeterModelBlock; import org.openhab.binding.modbus.sunspec.internal.parser.MeterModelParser; @@ -92,7 +94,7 @@ private void updateTotalValues(MeterModelBlock block) { getScaled(block.acVoltageLineToLineAverage, block.acVoltageSF, VOLT)); updateState(channelUID(GROUP_AC_GENERAL, CHANNEL_AC_FREQUENCY), - getScaled(block.acFrequency, block.acFrequencySF.orElse((short) 1), HERTZ)); + getScaled(block.acFrequency, Objects.requireNonNull(block.acFrequencySF.orElse((short) 1)), HERTZ)); updateState(channelUID(GROUP_AC_GENERAL, CHANNEL_AC_TOTAL_REAL_POWER), getScaled(block.acRealPowerTotal, block.acRealPowerSF, WATT)); diff --git a/bundles/org.openhab.binding.modbus.sunspec/src/main/java/org/openhab/binding/modbus/sunspec/internal/parser/AbstractBaseParser.java b/bundles/org.openhab.binding.modbus.sunspec/src/main/java/org/openhab/binding/modbus/sunspec/internal/parser/AbstractBaseParser.java index e653d1f3cce9a..d7fd0e7663670 100644 --- a/bundles/org.openhab.binding.modbus.sunspec/src/main/java/org/openhab/binding/modbus/sunspec/internal/parser/AbstractBaseParser.java +++ b/bundles/org.openhab.binding.modbus.sunspec/src/main/java/org/openhab/binding/modbus/sunspec/internal/parser/AbstractBaseParser.java @@ -12,6 +12,7 @@ */ package org.openhab.binding.modbus.sunspec.internal.parser; +import java.util.Objects; import java.util.Optional; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -50,7 +51,7 @@ protected Optional extractOptionalInt16(ModbusRegisterArray raw, int inde * @return the parsed value or the default if the field is not implemented */ protected Short extractInt16(ModbusRegisterArray raw, int index, short def) { - return extractOptionalInt16(raw, index).orElse(def); + return Objects.requireNonNull(extractOptionalInt16(raw, index).orElse(def)); } /** @@ -74,7 +75,7 @@ protected Optional extractOptionalUInt16(ModbusRegisterArray raw, int i * @return the parsed value or the default if the field is not implemented */ protected Integer extractUInt16(ModbusRegisterArray raw, int index, int def) { - return extractOptionalUInt16(raw, index).orElse(def); + return Objects.requireNonNull(extractOptionalUInt16(raw, index).orElse(def)); } /** @@ -98,7 +99,7 @@ protected Optional extractOptionalAcc32(ModbusRegisterArray raw, int index * @return the parsed value or default if the field is not implemented */ protected Long extractAcc32(ModbusRegisterArray raw, int index, long def) { - return extractOptionalAcc32(raw, index).orElse(def); + return Objects.requireNonNull(extractOptionalAcc32(raw, index).orElse(def)); } /** @@ -121,6 +122,6 @@ protected Optional extractOptionalSunSSF(ModbusRegisterArray raw, int ind * @return the parsed value or 1 if the field is not implemented */ protected Short extractSunSSF(ModbusRegisterArray raw, int index) { - return extractOptionalSunSSF(raw, index).orElse((short) 0); + return Objects.requireNonNull(extractOptionalSunSSF(raw, index).orElse((short) 0)); } } diff --git a/bundles/org.openhab.binding.mybmw/src/test/java/org/openhab/binding/mybmw/internal/dto/charge/ChargingStatisticsTest.java b/bundles/org.openhab.binding.mybmw/src/test/java/org/openhab/binding/mybmw/internal/dto/charge/ChargingStatisticsTest.java index 5ebe6e1ff9c8d..d413cfe43660b 100644 --- a/bundles/org.openhab.binding.mybmw/src/test/java/org/openhab/binding/mybmw/internal/dto/charge/ChargingStatisticsTest.java +++ b/bundles/org.openhab.binding.mybmw/src/test/java/org/openhab/binding/mybmw/internal/dto/charge/ChargingStatisticsTest.java @@ -25,6 +25,7 @@ import java.time.ZoneId; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -118,7 +119,8 @@ private boolean testVehicle(String statusContent, int callbacksExpected, Method updateChargeStatisticsMethod = VehicleHandler.class.getDeclaredMethod("updateChargingStatistics", ChargingStatisticsContainer.class, String.class); updateChargeStatisticsMethod.setAccessible(true); - updateChargeStatisticsMethod.invoke(vehicleHandler, + assertNotNull(vehicleHandler); + updateChargeStatisticsMethod.invoke(Objects.requireNonNull(vehicleHandler), JsonStringDeserializer.getChargingStatistics(statusContent), null); } catch (Exception e) { logger.error("chargeStatistics could not be set", e); diff --git a/bundles/org.openhab.binding.mycroft/src/main/java/org/openhab/binding/mycroft/internal/api/MessageType.java b/bundles/org.openhab.binding.mycroft/src/main/java/org/openhab/binding/mycroft/internal/api/MessageType.java index b92d8cde20766..5b1bc9c78be2e 100644 --- a/bundles/org.openhab.binding.mycroft/src/main/java/org/openhab/binding/mycroft/internal/api/MessageType.java +++ b/bundles/org.openhab.binding.mycroft/src/main/java/org/openhab/binding/mycroft/internal/api/MessageType.java @@ -12,6 +12,7 @@ */ package org.openhab.binding.mycroft.internal.api; +import java.util.Objects; import java.util.stream.Stream; import javax.validation.constraints.NotNull; @@ -100,8 +101,8 @@ public enum MessageType { @NotNull public static MessageType fromString(String asString) { - return Stream.of(values()).filter(messageType -> messageType.messageTypeName.equals(asString)).findFirst() - .orElse(any); + return Objects.requireNonNull(Stream.of(values()) + .filter(messageType -> messageType.messageTypeName.equals(asString)).findFirst().orElse(any)); } public String getMessageTypeName() { diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/api/data/ModuleType.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/api/data/ModuleType.java index b1f4cbadf037b..d2f4c3a8b358c 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/api/data/ModuleType.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/api/data/ModuleType.java @@ -18,7 +18,7 @@ import java.net.URI; import java.util.EnumSet; import java.util.List; -import java.util.Optional; +import java.util.Objects; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -170,7 +170,7 @@ ChannelGroup.BATTERY_EXT, new ChannelGroup(Therm1ChannelHelper.class, GROUP_TYPE public static final EnumSet AS_SET = EnumSet.allOf(ModuleType.class); - private final Optional bridgeType; + private final @Nullable ModuleType bridgeType; public final Set channelGroups; public final Set> capabilities; public final ThingTypeUID thingTypeUID; @@ -181,7 +181,7 @@ ChannelGroup.BATTERY_EXT, new ChannelGroup(Therm1ChannelHelper.class, GROUP_TYPE ModuleType(FeatureArea feature, String apiName, int thingTypeVersion, String config, @Nullable ModuleType bridge, Set> capabilities, ChannelGroup... channelGroups) { - this.bridgeType = Optional.ofNullable(bridge); + this.bridgeType = bridge; this.feature = feature; this.capabilities = capabilities; this.apiName = apiName; @@ -219,7 +219,7 @@ public int[] getSignalLevels() { } public ModuleType getBridge() { - return bridgeType.orElse(UNKNOWN); + return Objects.requireNonNullElse(this.bridgeType, UNKNOWN); } public int getDepth() { diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/api/dto/NAThing.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/api/dto/NAThing.java index c327e759c56a1..04c0b462b31cf 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/api/dto/NAThing.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/api/dto/NAThing.java @@ -67,8 +67,8 @@ public int getRadioStatus() { return radioStatus; } - public Optional getLastSeen() { - return Optional.ofNullable(lastSeen); + public @Nullable ZonedDateTime getLastSeen() { + return lastSeen; } /** diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/deserialization/NAPushTypeDeserializer.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/deserialization/NAPushTypeDeserializer.java index c4c5a8fd4a44e..14157500983f1 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/deserialization/NAPushTypeDeserializer.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/deserialization/NAPushTypeDeserializer.java @@ -13,6 +13,7 @@ package org.openhab.binding.netatmo.internal.deserialization; import java.lang.reflect.Type; +import java.util.Objects; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; @@ -62,8 +63,8 @@ class NAPushTypeDeserializer implements JsonDeserializer { * @return moduletype value if found, or else Unknown */ public static ModuleType fromNetatmoObject(String apiName) { - return ModuleType.AS_SET.stream().filter(mt -> apiName.equals(mt.apiName)).findFirst() - .orElse(ModuleType.UNKNOWN); + return Objects.requireNonNull(ModuleType.AS_SET.stream().filter(mt -> apiName.equals(mt.apiName)).findFirst() + .orElse(ModuleType.UNKNOWN)); } /** @@ -71,7 +72,7 @@ public static ModuleType fromNetatmoObject(String apiName) { * @return eventType value if found, or else Unknown */ public static EventType fromEvent(String apiName) { - return EventType.AS_SET.stream().filter(et -> apiName.equalsIgnoreCase(et.name())).findFirst() - .orElse(EventType.UNKNOWN); + return Objects.requireNonNull(EventType.AS_SET.stream().filter(et -> apiName.equalsIgnoreCase(et.name())) + .findFirst().orElse(EventType.UNKNOWN)); } } diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/CommonInterface.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/CommonInterface.java index 51beb8de5ccd8..aac0f4b004133 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/CommonInterface.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/CommonInterface.java @@ -15,6 +15,7 @@ import java.time.Duration; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.Optional; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; @@ -169,8 +170,8 @@ default Stream getActiveChildren(FeatureArea area) { } default > Optional getHomeCapability(Class clazz) { - return recurseUpToHomeHandler(this).map(handler -> handler.getCapabilities().get(clazz)) - .orElse(Optional.empty()); + return Objects.requireNonNull(recurseUpToHomeHandler(this).map(handler -> handler.getCapabilities().get(clazz)) + .orElse(Optional.empty())); } default void setNewData(NAObject newData) { diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/capability/AlarmEventCapability.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/capability/AlarmEventCapability.java index 8e7c3a922bb86..44a27ccb1b375 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/capability/AlarmEventCapability.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/capability/AlarmEventCapability.java @@ -16,6 +16,7 @@ import static org.openhab.binding.netatmo.internal.utils.ChannelTypeUtils.*; import java.util.List; +import java.util.Objects; import org.eclipse.jdt.annotation.NonNullByDefault; import org.openhab.binding.netatmo.internal.api.dto.NAObject; @@ -46,8 +47,8 @@ protected void updateWebhookEvent(WebhookEvent event) { handler.updateState(GROUP_LAST_EVENT, CHANNEL_EVENT_TYPE, toStringType(event.getEventType())); handler.updateState(GROUP_LAST_EVENT, CHANNEL_EVENT_TIME, toDateTimeType(event.getTime())); - handler.updateState(GROUP_LAST_EVENT, CHANNEL_EVENT_SUBTYPE, - event.getSubTypeDescription().map(ChannelTypeUtils::toStringType).orElse(UnDefType.NULL)); + handler.updateState(GROUP_LAST_EVENT, CHANNEL_EVENT_SUBTYPE, Objects.requireNonNull( + event.getSubTypeDescription().map(ChannelTypeUtils::toStringType).orElse(UnDefType.NULL))); final String message = event.getName(); handler.updateState(GROUP_LAST_EVENT, CHANNEL_EVENT_MESSAGE, message == null || message.isBlank() ? UnDefType.NULL : toStringType(message)); @@ -55,7 +56,8 @@ protected void updateWebhookEvent(WebhookEvent event) { @Override public List updateReadings() { - return getSecurityCapability().map(cap -> cap.getDeviceLastEvent(handler.getId(), moduleType.apiName)) - .map(event -> List.of((NAObject) event)).orElse(List.of()); + return Objects.requireNonNull( + getSecurityCapability().map(cap -> cap.getDeviceLastEvent(handler.getId(), moduleType.apiName)) + .map(event -> List.of((NAObject) event)).orElse(List.of())); } } diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/capability/CameraCapability.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/capability/CameraCapability.java index d110659c86823..ed16125019798 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/capability/CameraCapability.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/capability/CameraCapability.java @@ -18,6 +18,7 @@ import java.net.URI; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriBuilderException; @@ -129,7 +130,7 @@ private void updateSubGroup(WebhookEvent event, String group) { handler.updateState(group, CHANNEL_EVENT_VIGNETTE, toRawType(event.getVignetteUrl())); handler.updateState(group, CHANNEL_EVENT_VIGNETTE_URL, toStringType(event.getVignetteUrl())); handler.updateState(group, CHANNEL_EVENT_SUBTYPE, - event.getSubTypeDescription().map(d -> toStringType(d)).orElse(UnDefType.NULL)); + Objects.requireNonNull(event.getSubTypeDescription().map(d -> toStringType(d)).orElse(UnDefType.NULL))); final String message = event.getName(); handler.updateState(group, CHANNEL_EVENT_MESSAGE, message == null || message.isBlank() ? UnDefType.NULL : toStringType(message)); diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/capability/PersonCapability.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/capability/PersonCapability.java index 5d12b72997a54..60b9f3fe51175 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/capability/PersonCapability.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/capability/PersonCapability.java @@ -18,6 +18,7 @@ import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.stream.Stream; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -79,7 +80,7 @@ protected void updateWebhookEvent(WebhookEvent event) { super.updateWebhookEvent(event); handler.updateState(GROUP_LAST_EVENT, CHANNEL_EVENT_SUBTYPE, - event.getSubTypeDescription().map(d -> toStringType(d)).orElse(UnDefType.NULL)); + Objects.requireNonNull(event.getSubTypeDescription().map(d -> toStringType(d)).orElse(UnDefType.NULL))); final String message = event.getName(); handler.updateState(GROUP_LAST_EVENT, CHANNEL_EVENT_MESSAGE, @@ -100,8 +101,8 @@ public void updateEvent(Event event) { return; // ignore incoming events if they are deprecated } lastEventTime = eventTime; - handler.triggerChannel(CHANNEL_HOME_EVENT, - event.getSubTypeDescription().map(EventSubType::name).orElse(event.getEventType().name())); + handler.triggerChannel(CHANNEL_HOME_EVENT, Objects.requireNonNull( + event.getSubTypeDescription().map(EventSubType::name).orElse(event.getEventType().name()))); } @Override diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/capability/RefreshAutoCapability.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/capability/RefreshAutoCapability.java index d230df57f202a..549f463304cf2 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/capability/RefreshAutoCapability.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/capability/RefreshAutoCapability.java @@ -69,7 +69,8 @@ protected Duration calcDelay() { @Override protected void updateNAThing(NAThing newData) { super.updateNAThing(newData); - dataTimeStamp = newData.getLastSeen().map(ZonedDateTime::toInstant).orElse(Instant.MIN); + ZonedDateTime lastSeen = newData.getLastSeen(); + dataTimeStamp = lastSeen != null ? lastSeen.toInstant() : Instant.MIN; } @Override diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/capability/SecurityCapability.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/capability/SecurityCapability.java index 624606606ab04..50473750efb00 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/capability/SecurityCapability.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/capability/SecurityCapability.java @@ -18,6 +18,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; @@ -175,25 +176,25 @@ public NAObjectMap getModules() { } private Collection requestDeviceEvents(String moduleId, String deviceType) { - return getApi().map(api -> { + return Objects.requireNonNull(getApi().map(api -> { try { return api.getDeviceEvents(securityId, moduleId, deviceType); } catch (NetatmoException e) { logger.warn("Error retrieving last events of camera '{}' : {}", moduleId, e.getMessage()); return null; } - }).orElse(List.of()); + }).orElse(List.of())); } private Collection requestPersonEvents(String personId) { - return getApi().map(api -> { + return Objects.requireNonNull(getApi().map(api -> { try { return api.getPersonEvents(securityId, personId); } catch (NetatmoException e) { logger.warn("Error retrieving last events of person '{}' : {}", personId, e.getMessage()); return null; } - }).orElse(List.of()); + }).orElse(List.of())); } public void setPersonAway(String personId, boolean away) { diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/TimestampChannelHelper.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/TimestampChannelHelper.java index 26ca297b68c55..63b2dcdb9ba22 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/TimestampChannelHelper.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/handler/channelhelper/TimestampChannelHelper.java @@ -16,7 +16,6 @@ import static org.openhab.binding.netatmo.internal.utils.ChannelTypeUtils.toDateTimeType; import java.time.ZonedDateTime; -import java.util.Optional; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -42,8 +41,8 @@ public TimestampChannelHelper(Set providedGroups) { @Override protected @Nullable State internalGetProperty(String channelId, NAThing naThing, Configuration config) { - Optional lastSeen = naThing.getLastSeen(); - return CHANNEL_LAST_SEEN.equals(channelId) && lastSeen.isPresent() ? toDateTimeType(lastSeen) : null; + ZonedDateTime lastSeen = naThing.getLastSeen(); + return CHANNEL_LAST_SEEN.equals(channelId) && lastSeen != null ? toDateTimeType(lastSeen) : null; } @Override diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/utils/ChannelTypeUtils.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/utils/ChannelTypeUtils.java index 8fe4c3bf09efe..34ebca9cd2c62 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/utils/ChannelTypeUtils.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/utils/ChannelTypeUtils.java @@ -15,7 +15,6 @@ import java.math.BigDecimal; import java.math.RoundingMode; import java.time.ZonedDateTime; -import java.util.Optional; import javax.measure.Unit; @@ -71,10 +70,6 @@ public static State toDateTimeType(@Nullable ZonedDateTime zonedDateTime) { return (zonedDateTime == null) ? UnDefType.NULL : new DateTimeType(zonedDateTime); } - public static State toDateTimeType(Optional zonedDateTime) { - return zonedDateTime.map(zdt -> (State) new DateTimeType(zdt)).orElse(UnDefType.NULL); - } - public static State toQuantityType(@Nullable Double value, MeasureClass measureClass) { if (value != null && !value.isNaN()) { Measure measureDef = measureClass.measureDefinition; diff --git a/bundles/org.openhab.binding.nibeuplink/src/main/java/org/openhab/binding/nibeuplink/internal/callback/AbstractUplinkCommandCallback.java b/bundles/org.openhab.binding.nibeuplink/src/main/java/org/openhab/binding/nibeuplink/internal/callback/AbstractUplinkCommandCallback.java index e3b00beac48a8..c770a617789be 100644 --- a/bundles/org.openhab.binding.nibeuplink/src/main/java/org/openhab/binding/nibeuplink/internal/callback/AbstractUplinkCommandCallback.java +++ b/bundles/org.openhab.binding.nibeuplink/src/main/java/org/openhab/binding/nibeuplink/internal/callback/AbstractUplinkCommandCallback.java @@ -94,7 +94,7 @@ public AbstractUplinkCommandCallback(NibeUplinkConfiguration config, StatusUpdat * Log request success */ @Override - public final void onSuccess(@Nullable Response response) { + public final void onSuccess(Response response) { super.onSuccess(response); if (response != null) { communicationStatus.setHttpCode(HttpStatus.getCode(response.getStatus())); @@ -107,7 +107,9 @@ public final void onSuccess(@Nullable Response response) { */ @Override public final void onFailure(@Nullable Response response, @Nullable Throwable failure) { - super.onFailure(response, failure); + if (response != null && failure != null) { + super.onFailure(response, failure); + } if (failure != null) { logger.debug("Request failed: {}", failure.toString()); communicationStatus.setError((Exception) failure); @@ -123,9 +125,10 @@ public final void onFailure(@Nullable Response response, @Nullable Throwable fai } @Override - public void onContent(@Nullable Response response, @Nullable ByteBuffer content) { + public void onContent(Response response, ByteBuffer content) { super.onContent(response, content); - logger.debug("received content, length: {}", getContentAsString().length()); + String contentAsString = getContentAsString(); + logger.debug("received content, length: {}", contentAsString != null ? getContentAsString().length() : 0); } @Override diff --git a/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/protocol/nhc2/NhcSystemInfo2.java b/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/protocol/nhc2/NhcSystemInfo2.java index 7ee52b68fac79..b9a075e474b6e 100644 --- a/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/protocol/nhc2/NhcSystemInfo2.java +++ b/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/protocol/nhc2/NhcSystemInfo2.java @@ -13,6 +13,7 @@ package org.openhab.binding.nikohomecontrol.internal.protocol.nhc2; import java.util.ArrayList; +import java.util.Objects; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -45,14 +46,16 @@ static class NhcSwVersion { * @return the NhcVersion */ public String getNhcVersion() { - return swVersions.stream().map(p -> p.nhcVersion).filter(v -> !v.isEmpty()).findFirst().orElse(""); + return Objects.requireNonNull( + swVersions.stream().map(p -> p.nhcVersion).filter(v -> !v.isEmpty()).findFirst().orElse("")); } /** * @return the CocoImage version */ public String getCocoImage() { - return swVersions.stream().map(p -> p.cocoImage).filter(v -> !v.isEmpty()).findFirst().orElse(""); + return Objects.requireNonNull( + swVersions.stream().map(p -> p.cocoImage).filter(v -> !v.isEmpty()).findFirst().orElse("")); } /** diff --git a/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/handler/OmnilinkBridgeHandler.java b/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/handler/OmnilinkBridgeHandler.java index 890b583e42004..c7bcadfe69119 100644 --- a/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/handler/OmnilinkBridgeHandler.java +++ b/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/handler/OmnilinkBridgeHandler.java @@ -19,6 +19,7 @@ import java.time.ZonedDateTime; import java.util.Collection; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.ScheduledFuture; @@ -239,9 +240,9 @@ private void makeOmnilinkConnection() { * HAI only supports one audio player - cycle through features until we find a feature that is an audio * player. */ - audioPlayer = reqSystemFeatures().getFeatures().stream() + audioPlayer = Objects.requireNonNull(reqSystemFeatures().getFeatures().stream() .map(featureCode -> AudioPlayer.getAudioPlayerForFeatureCode(featureCode)) - .filter(Optional::isPresent).findFirst().orElse(Optional.empty()); + .filter(Optional::isPresent).findFirst().orElse(Optional.empty())); systemType = SystemType.getType(reqSystemInformation().getModel()); diff --git a/bundles/org.openhab.binding.pentair/src/main/java/org/openhab/binding/pentair/internal/handler/helpers/PentairControllerCircuit.java b/bundles/org.openhab.binding.pentair/src/main/java/org/openhab/binding/pentair/internal/handler/helpers/PentairControllerCircuit.java index f7088bf846a50..8c36177445bf8 100644 --- a/bundles/org.openhab.binding.pentair/src/main/java/org/openhab/binding/pentair/internal/handler/helpers/PentairControllerCircuit.java +++ b/bundles/org.openhab.binding.pentair/src/main/java/org/openhab/binding/pentair/internal/handler/helpers/PentairControllerCircuit.java @@ -13,6 +13,7 @@ package org.openhab.binding.pentair.internal.handler.helpers; import java.util.Arrays; +import java.util.Objects; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -156,8 +157,8 @@ public String getFriendlyName() { } public static CircuitName valueOfModeNumber(int number) { - return Arrays.stream(values()).filter(value -> (value.getCode() == number)).findFirst() - .orElse(CircuitName.EMPTY); + return Objects.requireNonNull(Arrays.stream(values()).filter(value -> (value.getCode() == number)) + .findFirst().orElse(CircuitName.EMPTY)); } } @@ -197,8 +198,8 @@ public String getFriendlyName() { } public static CircuitFunction valueOfModeNumber(int number) { - return Arrays.stream(values()).filter(value -> (value.getCode() == number)).findFirst() - .orElse(CircuitFunction.EMPTY); + return Objects.requireNonNull(Arrays.stream(values()).filter(value -> (value.getCode() == number)) + .findFirst().orElse(CircuitFunction.EMPTY)); } } diff --git a/bundles/org.openhab.binding.pentair/src/main/java/org/openhab/binding/pentair/internal/handler/helpers/PentairControllerLightMode.java b/bundles/org.openhab.binding.pentair/src/main/java/org/openhab/binding/pentair/internal/handler/helpers/PentairControllerLightMode.java index f10923dc5877a..aaa5f6a26796c 100644 --- a/bundles/org.openhab.binding.pentair/src/main/java/org/openhab/binding/pentair/internal/handler/helpers/PentairControllerLightMode.java +++ b/bundles/org.openhab.binding.pentair/src/main/java/org/openhab/binding/pentair/internal/handler/helpers/PentairControllerLightMode.java @@ -13,6 +13,7 @@ package org.openhab.binding.pentair.internal.handler.helpers; import java.util.Arrays; +import java.util.Objects; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -58,6 +59,7 @@ public String getName() { } public static PentairControllerLightMode valueOfModeNumber(int modeNumber) { - return Arrays.stream(values()).filter(value -> (value.getModeNumber() == modeNumber)).findFirst().orElse(EMPTY); + return Objects.requireNonNull(Arrays.stream(values()).filter(value -> (value.getModeNumber() == modeNumber)) + .findFirst().orElse(EMPTY)); } } diff --git a/bundles/org.openhab.binding.pentair/src/main/java/org/openhab/binding/pentair/internal/handler/helpers/PentairHeatStatus.java b/bundles/org.openhab.binding.pentair/src/main/java/org/openhab/binding/pentair/internal/handler/helpers/PentairHeatStatus.java index 44b48b35ef027..aa6ff1f871bf4 100644 --- a/bundles/org.openhab.binding.pentair/src/main/java/org/openhab/binding/pentair/internal/handler/helpers/PentairHeatStatus.java +++ b/bundles/org.openhab.binding.pentair/src/main/java/org/openhab/binding/pentair/internal/handler/helpers/PentairHeatStatus.java @@ -13,6 +13,7 @@ package org.openhab.binding.pentair.internal.handler.helpers; import java.util.Arrays; +import java.util.Objects; import org.eclipse.jdt.annotation.NonNullByDefault; import org.openhab.binding.pentair.internal.parser.PentairStandardPacket; @@ -49,7 +50,8 @@ public String getFriendlyName() { } public static HeatMode valueOfCode(int code) { - return Arrays.stream(values()).filter(value -> (value.getCode() == code)).findFirst().orElse(EMPTY); + return Objects.requireNonNull( + Arrays.stream(values()).filter(value -> (value.getCode() == code)).findFirst().orElse(EMPTY)); } } diff --git a/bundles/org.openhab.binding.pixometer/src/main/java/org/openhab/binding/pixometer/handler/MeterHandler.java b/bundles/org.openhab.binding.pixometer/src/main/java/org/openhab/binding/pixometer/handler/MeterHandler.java index 10919e6724c2f..184e4b87b2b51 100644 --- a/bundles/org.openhab.binding.pixometer/src/main/java/org/openhab/binding/pixometer/handler/MeterHandler.java +++ b/bundles/org.openhab.binding.pixometer/src/main/java/org/openhab/binding/pixometer/handler/MeterHandler.java @@ -246,7 +246,12 @@ private void updateMeter(@Nullable MeterState meterState) { Properties urlHeader = new Properties(); urlHeader.put("CONTENT-TYPE", "application/json"); - urlHeader.put("Authorization", getTokenFromBridge()); + String token = getTokenFromBridge(); + if (token == null) { + logger.debug("Unable to get the token from the bridge"); + return null; + } + urlHeader.put("Authorization", token); String urlResponse = HttpUtil.executeUrl("GET", url, urlHeader, null, null, 2000); diff --git a/bundles/org.openhab.binding.pushsafer/src/main/java/org/openhab/binding/pushsafer/internal/connection/PushsaferMessageBuilder.java b/bundles/org.openhab.binding.pushsafer/src/main/java/org/openhab/binding/pushsafer/internal/connection/PushsaferMessageBuilder.java index 34b8cf920bcf6..89143ed0933ca 100644 --- a/bundles/org.openhab.binding.pushsafer/src/main/java/org/openhab/binding/pushsafer/internal/connection/PushsaferMessageBuilder.java +++ b/bundles/org.openhab.binding.pushsafer/src/main/java/org/openhab/binding/pushsafer/internal/connection/PushsaferMessageBuilder.java @@ -308,7 +308,7 @@ public ContentProvider build() throws PushsaferCommunicationException { body.addFieldPart(MESSAGE_KEY_ANSWER, new StringContentProvider(String.valueOf(answer)), null); body.addFieldPart(MESSAGE_KEY_TIME2LIVE, new StringContentProvider(String.valueOf(time2live)), null); - + String attachment = this.attachment; if (attachment != null) { String localAttachment = attachment; final String encodedString; diff --git a/bundles/org.openhab.binding.radiothermostat/src/main/java/org/openhab/binding/radiothermostat/internal/communication/RadioThermostatConnector.java b/bundles/org.openhab.binding.radiothermostat/src/main/java/org/openhab/binding/radiothermostat/internal/communication/RadioThermostatConnector.java index ed90d59be0cfd..81da5ad1d0cae 100644 --- a/bundles/org.openhab.binding.radiothermostat/src/main/java/org/openhab/binding/radiothermostat/internal/communication/RadioThermostatConnector.java +++ b/bundles/org.openhab.binding.radiothermostat/src/main/java/org/openhab/binding/radiothermostat/internal/communication/RadioThermostatConnector.java @@ -158,11 +158,15 @@ private String buildRequestURL(String resource) { /** * Dispatch an event (key, value) to the event listeners + * Events with a null value are discarded * * @param key the key * @param value the value */ - private void dispatchKeyValue(String key, String value) { + private void dispatchKeyValue(String key, @Nullable String value) { + if (value == null) { + return; + } RadioThermostatEvent event = new RadioThermostatEvent(this, key, value); for (RadioThermostatEventListener listener : listeners) { listener.onNewMessageEvent(event); diff --git a/bundles/org.openhab.binding.revogi/src/main/java/org/openhab/binding/revogi/internal/api/StatusService.java b/bundles/org.openhab.binding.revogi/src/main/java/org/openhab/binding/revogi/internal/api/StatusService.java index 2b9aff1f91632..7e2613566f0ce 100644 --- a/bundles/org.openhab.binding.revogi/src/main/java/org/openhab/binding/revogi/internal/api/StatusService.java +++ b/bundles/org.openhab.binding.revogi/src/main/java/org/openhab/binding/revogi/internal/api/StatusService.java @@ -56,13 +56,13 @@ public CompletableFuture queryStatus(String serialNumber, String ipAd } private StatusDTO getStatus(final List singleResponse) { - return singleResponse.stream() + return Objects.requireNonNull(singleResponse.stream() .filter(response -> !response.getAnswer().isEmpty() && response.getAnswer().contains(VERSION_STRING)) .map(response -> deserializeString(response.getAnswer())) .filter(statusRaw -> statusRaw.getCode() == 200 && statusRaw.getResponse() == 90) .map(statusRaw -> new StatusDTO(true, statusRaw.getCode(), statusRaw.getData().getSwitchValue(), statusRaw.getData().getWatt(), statusRaw.getData().getAmp())) - .findFirst().orElse(new StatusDTO(false, 503, null, null, null)); + .findFirst().orElse(new StatusDTO(false, 503, null, null, null))); } private StatusRawDTO deserializeString(String response) { diff --git a/bundles/org.openhab.binding.revogi/src/main/java/org/openhab/binding/revogi/internal/api/SwitchService.java b/bundles/org.openhab.binding.revogi/src/main/java/org/openhab/binding/revogi/internal/api/SwitchService.java index ec523b2c23029..ab03b7cf79eb3 100644 --- a/bundles/org.openhab.binding.revogi/src/main/java/org/openhab/binding/revogi/internal/api/SwitchService.java +++ b/bundles/org.openhab.binding.revogi/src/main/java/org/openhab/binding/revogi/internal/api/SwitchService.java @@ -66,10 +66,10 @@ public CompletableFuture switchPort(String serialNumber, Stri } private SwitchResponseDTO getSwitchResponse(final List singleResponse) { - return singleResponse.stream().filter(response -> !response.getAnswer().isEmpty()) + return Objects.requireNonNull(singleResponse.stream().filter(response -> !response.getAnswer().isEmpty()) .map(response -> deserializeString(response.getAnswer())) .filter(switchResponse -> switchResponse.getCode() == 200 && switchResponse.getResponse() == 20) - .findFirst().orElse(new SwitchResponseDTO(0, 503)); + .findFirst().orElse(new SwitchResponseDTO(0, 503))); } private SwitchResponseDTO deserializeString(String response) { diff --git a/bundles/org.openhab.binding.sagercaster/src/main/java/org/openhab/binding/sagercaster/internal/caster/SagerWeatherCaster.java b/bundles/org.openhab.binding.sagercaster/src/main/java/org/openhab/binding/sagercaster/internal/caster/SagerWeatherCaster.java index cbe752830c7d5..5f55faf38b719 100644 --- a/bundles/org.openhab.binding.sagercaster/src/main/java/org/openhab/binding/sagercaster/internal/caster/SagerWeatherCaster.java +++ b/bundles/org.openhab.binding.sagercaster/src/main/java/org/openhab/binding/sagercaster/internal/caster/SagerWeatherCaster.java @@ -58,10 +58,11 @@ import java.io.IOException; import java.io.InputStream; import java.util.Arrays; -import java.util.Optional; +import java.util.Objects; import java.util.Properties; import org.eclipse.jdt.annotation.NonNullByDefault; +import org.eclipse.jdt.annotation.Nullable; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ServiceScope; @@ -89,7 +90,7 @@ public class SagerWeatherCaster { private final Logger logger = LoggerFactory.getLogger(SagerWeatherCaster.class); private final Properties forecaster = new Properties(); - private Optional prevision = Optional.empty(); + private @Nullable SagerPrediction prevision; private String[] usedDirections = NTZDIRECTIONS; // Defaulted to Northern Zone private int currentBearing = -1; @@ -107,7 +108,7 @@ public class SagerWeatherCaster { public SagerWeatherCaster() { try (InputStream input = Thread.currentThread().getContextClassLoader() .getResourceAsStream("/sagerForecaster.properties")) { - forecaster.load(input); + forecaster.load(Objects.requireNonNull(input)); } catch (IOException e) { logger.warn("Error during Sager Forecaster startup", e); } @@ -319,27 +320,31 @@ private void updatePrediction() { } } String forecast = forecaster.getProperty(d1 + sagerPressure + pressureEvolution + nubes); - prevision = Optional.ofNullable(forecast != null ? new SagerPrediction(forecast) : null); + prevision = forecast != null ? new SagerPrediction(forecast) : null; } public String getForecast() { - return prevision.map(p -> p.getForecast()).orElse(UNDEF); + return Objects.requireNonNullElse(this.prevision.getForecast(), UNDEF); } public String getWindVelocity() { - return prevision.map(p -> p.getWindVelocity()).orElse(UNDEF); + SagerPrediction prevision = this.prevision; + return prevision != null ? prevision.getWindVelocity() : UNDEF; } public String getWindDirection() { - return prevision.map(p -> p.getWindDirection()).orElse(UNDEF); + SagerPrediction prevision = this.prevision; + return prevision != null ? prevision.getWindDirection() : UNDEF; } public String getWindDirection2() { - return prevision.map(p -> p.getWindDirection2()).orElse(UNDEF); + SagerPrediction prevision = this.prevision; + return prevision != null ? prevision.getWindDirection2() : UNDEF; } public String getSagerCode() { - return prevision.map(p -> p.getSagerCode()).orElse(UNDEF); + SagerPrediction prevision = this.prevision; + return prevision != null ? prevision.getSagerCode() : UNDEF; } public void setLatitude(double latitude) { diff --git a/bundles/org.openhab.binding.saicismart/src/main/java/org/openhab/binding/saicismart/internal/SAICiSMARTBridgeHandler.java b/bundles/org.openhab.binding.saicismart/src/main/java/org/openhab/binding/saicismart/internal/SAICiSMARTBridgeHandler.java index 2b9d564ca0d35..c43e78c1bbb9b 100644 --- a/bundles/org.openhab.binding.saicismart/src/main/java/org/openhab/binding/saicismart/internal/SAICiSMARTBridgeHandler.java +++ b/bundles/org.openhab.binding.saicismart/src/main/java/org/openhab/binding/saicismart/internal/SAICiSMARTBridgeHandler.java @@ -23,7 +23,6 @@ import java.util.Collection; import java.util.Collections; import java.util.Objects; -import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; @@ -272,7 +271,8 @@ public String getToken() { } public Collection getVinList() { - return Optional.ofNullable(vinList).orElse(Collections.emptyList()); + Collection vinList = this.vinList; + return vinList != null ? vinList : Collections.emptyList(); } public String sendRequest(String request, String endpoint) diff --git a/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/Utils.java b/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/Utils.java index fd7924c26893d..5b5029725565b 100755 --- a/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/Utils.java +++ b/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/Utils.java @@ -15,6 +15,7 @@ import java.io.IOException; import java.io.StringReader; import java.util.Base64; +import java.util.Objects; import java.util.Optional; import javax.xml.parsers.DocumentBuilderFactory; @@ -52,7 +53,7 @@ private static DocumentBuilderFactory getDocumentBuilder() { } catch (ParserConfigurationException e) { LOGGER.debug("XMLParser Configuration Error: {}", e.getMessage()); } - return Optional.ofNullable(factory).orElse(DocumentBuilderFactory.newInstance()); + return factory; } /** @@ -85,30 +86,32 @@ public static String truncCmd(Command command) { } public static String getModelName(@Nullable RemoteDevice device) { - return Optional.ofNullable(device).map(a -> a.getDetails()).map(a -> a.getModelDetails()) - .map(a -> a.getModelName()).orElse(""); + return Objects.requireNonNull(Optional.ofNullable(device).map(a -> a.getDetails()).map(a -> a.getModelDetails()) + .map(a -> a.getModelName()).orElse("")); } public static String getManufacturer(@Nullable RemoteDevice device) { - return Optional.ofNullable(device).map(a -> a.getDetails()).map(a -> a.getManufacturerDetails()) - .map(a -> a.getManufacturer()).orElse(""); + return Objects.requireNonNull(Optional.ofNullable(device).map(a -> a.getDetails()) + .map(a -> a.getManufacturerDetails()).map(a -> a.getManufacturer()).orElse("")); } public static String getFriendlyName(@Nullable RemoteDevice device) { - return Optional.ofNullable(device).map(a -> a.getDetails()).map(a -> a.getFriendlyName()).orElse(""); + return Objects.requireNonNull( + Optional.ofNullable(device).map(a -> a.getDetails()).map(a -> a.getFriendlyName()).orElse("")); } public static String getUdn(@Nullable RemoteDevice device) { - return Optional.ofNullable(device).map(a -> a.getIdentity()).map(a -> a.getUdn()) - .map(a -> a.getIdentifierString()).orElse(""); + return Objects.requireNonNull(Optional.ofNullable(device).map(a -> a.getIdentity()).map(a -> a.getUdn()) + .map(a -> a.getIdentifierString()).orElse("")); } public static String getHost(@Nullable RemoteDevice device) { - return Optional.ofNullable(device).map(a -> a.getIdentity()).map(a -> a.getDescriptorURL()) - .map(a -> a.getHost()).orElse(""); + return Objects.requireNonNull(Optional.ofNullable(device).map(a -> a.getIdentity()) + .map(a -> a.getDescriptorURL()).map(a -> a.getHost()).orElse("")); } public static String getType(@Nullable RemoteDevice device) { - return Optional.ofNullable(device).map(a -> a.getType()).map(a -> a.getType()).orElse(""); + return Objects + .requireNonNull(Optional.ofNullable(device).map(a -> a.getType()).map(a -> a.getType()).orElse("")); } } diff --git a/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/protocol/RemoteControllerWebSocket.java b/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/protocol/RemoteControllerWebSocket.java index 2c03e111defbb..3fbe15e3e6bdc 100755 --- a/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/protocol/RemoteControllerWebSocket.java +++ b/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/protocol/RemoteControllerWebSocket.java @@ -105,11 +105,11 @@ public String toString() { } public String getAppId() { - return Optional.ofNullable(appId).orElse(""); + return appId != null ? appId : ""; } public String getName() { - return Optional.ofNullable(name).orElse(""); + return name != null ? name : ""; } public void setName(String name) { diff --git a/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/service/MainTVServerService.java b/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/service/MainTVServerService.java index 30fab9d126de3..8f98acbc21a75 100755 --- a/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/service/MainTVServerService.java +++ b/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/service/MainTVServerService.java @@ -18,6 +18,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -277,9 +278,9 @@ protected Map updateResourceState(String actionId) { } protected synchronized Map updateResourceState(String actionId, Map inputs) { - Map result = Optional.of(service) - .map(a -> a.invokeAction(this, SERVICE_MAIN_AGENT, actionId, inputs)).filter(a -> !a.isEmpty()) - .orElse(Map.of("Result", "Command Failed")); + Map result = Objects.requireNonNull( + Optional.of(service).map(a -> a.invokeAction(this, SERVICE_MAIN_AGENT, actionId, inputs)) + .filter(a -> !a.isEmpty()).orElse(Map.of("Result", "Command Failed"))); if (isOk(result)) { result.keySet().stream().filter(a -> !"Result".equals(a)).forEach(a -> { String val = result.getOrDefault(a, ""); @@ -305,8 +306,8 @@ private boolean setSourceName(Command command) { if (sources.isEmpty()) { getSourceMap(); } - String source = sources.entrySet().stream().filter(a -> a.getValue().equals(tmpSource)).map(a -> a.getKey()) - .findFirst().orElse(tmpSource); + String source = Objects.requireNonNull(sources.entrySet().stream().filter(a -> a.getValue().equals(tmpSource)) + .map(a -> a.getKey()).findFirst().orElse(tmpSource)); Map result = updateResourceState("SetMainTVSource", Map.of("Source", source, "ID", sources.getOrDefault(source, "0"), "UiID", "0")); logResult(result.getOrDefault("Result", "Unable to Set Source Name: " + source)); @@ -334,25 +335,25 @@ private void logResult(String ok) { } private String parseCurrentChannel(String xml) { - return Utils.loadXMLFromString(xml, host).map(a -> a.getDocumentElement()) - .map(a -> getFirstNodeValue(a, "MajorCh", "-1")).orElse("-1"); + return Objects.requireNonNull(Utils.loadXMLFromString(xml, host).map(a -> a.getDocumentElement()) + .map(a -> getFirstNodeValue(a, "MajorCh", "-1")).orElse("-1")); } private void getSourceMap() { // NodeList doesn't have a stream, so do this - sources = Optional.of(updateResourceState("GetSourceList")).filter(a -> "OK".equals(a.get("Result"))) - .map(a -> a.get("SourceList")).flatMap(xml -> Utils.loadXMLFromString(xml, host)) - .map(a -> a.getDocumentElement()).map( - a -> a.getElementsByTagName("Source")) - .map(nList -> IntStream.range(0, nList.getLength()).boxed().map(i -> (Element) nList.item(i)) - .collect(Collectors.toMap(a -> getFirstNodeValue(a, "SourceType", ""), - a -> getFirstNodeValue(a, "ID", ""), (key1, key2) -> key2))) - .orElse(Map.of()); + sources = Objects.requireNonNull( + Optional.of(updateResourceState("GetSourceList")).filter(a -> "OK".equals(a.get("Result"))) + .map(a -> a.get("SourceList")).flatMap(xml -> Utils.loadXMLFromString(xml, host)) + .map(a -> a.getDocumentElement()).map(a -> a.getElementsByTagName("Source")).map( + nList -> IntStream.range(0, nList.getLength()).boxed().map(i -> (Element) nList.item(i)) + .collect(Collectors.toMap(a -> getFirstNodeValue(a, "SourceType", ""), + a -> getFirstNodeValue(a, "ID", ""), (key1, key2) -> key2))) + .orElse(Map.of())); } private String getFirstNodeValue(Element nodeList, String node, String ifNone) { - return Optional.ofNullable(nodeList).map(a -> a.getElementsByTagName(node)).filter(a -> a.getLength() > 0) - .map(a -> a.item(0)).map(a -> a.getTextContent()).orElse(ifNone); + return Objects.requireNonNull(Optional.ofNullable(nodeList).map(a -> a.getElementsByTagName(node)) + .filter(a -> a.getLength() > 0).map(a -> a.item(0)).map(a -> a.getTextContent()).orElse(ifNone)); } /** diff --git a/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/service/SmartThingsApiService.java b/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/service/SmartThingsApiService.java index 68c125a92283c..4c61b74d68745 100755 --- a/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/service/SmartThingsApiService.java +++ b/bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/service/SmartThingsApiService.java @@ -470,11 +470,12 @@ public String getTvChannelName() { } } - public Number parseTVChannel(String channel) { + public Number parseTVChannel(@Nullable String channel) { try { - return Optional.ofNullable(channel) - .map(a -> a.replaceAll("\\D+", ".").replaceFirst("^\\D*((\\d+\\.\\d+)|(\\d+)).*", "$1")) - .map(Float::parseFloat).orElse(-1f); + return channel != null + ? Float.parseFloat( + channel.replaceAll("\\D+", ".").replaceFirst("^\\D*((\\d+\\.\\d+)|(\\d+)).*", "$1")) + : -1f; } catch (NumberFormatException ignore) { } return -1; diff --git a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelSystemHandler.java b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelSystemHandler.java index 23422070a1667..a27f01eb6d86c 100644 --- a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelSystemHandler.java +++ b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/handler/SatelSystemHandler.java @@ -16,6 +16,7 @@ import java.util.Collection; import java.util.LinkedList; +import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -81,8 +82,9 @@ public void incomingEvent(IntegraStatusEvent event) { return; } updateState(CHANNEL_DATE_TIME, - event.getIntegraTime().map(dt -> (State) new DateTimeType(dt.atZone(getBridgeHandler().getZoneId()))) - .orElse(UnDefType.UNDEF)); + Objects.requireNonNull(event.getIntegraTime() + .map(dt -> (State) new DateTimeType(dt.atZone(getBridgeHandler().getZoneId()))) + .orElse(UnDefType.UNDEF))); updateSwitch(CHANNEL_SERVICE_MODE, event.inServiceMode()); updateSwitch(CHANNEL_TROUBLES, event.troublesPresent()); updateSwitch(CHANNEL_TROUBLES_MEMORY, event.troublesMemory()); diff --git a/bundles/org.openhab.binding.sensorcommunity/src/main/java/org/openhab/binding/sensorcommunity/internal/handler/HTTPHandler.java b/bundles/org.openhab.binding.sensorcommunity/src/main/java/org/openhab/binding/sensorcommunity/internal/handler/HTTPHandler.java index d33c5ac7dacaa..cc8499e4e6b11 100644 --- a/bundles/org.openhab.binding.sensorcommunity/src/main/java/org/openhab/binding/sensorcommunity/internal/handler/HTTPHandler.java +++ b/bundles/org.openhab.binding.sensorcommunity/src/main/java/org/openhab/binding/sensorcommunity/internal/handler/HTTPHandler.java @@ -73,7 +73,8 @@ public void onComplete(org.eclipse.jetty.client.api.Result result) { } callback.onError(Objects.requireNonNullElse(failure, "Unknown error")); } else { - callback.onResponse(getContentAsString()); + + callback.onResponse(Objects.requireNonNull(getContentAsString())); } } }); diff --git a/bundles/org.openhab.binding.serial/src/main/java/org/openhab/binding/serial/internal/util/Parity.java b/bundles/org.openhab.binding.serial/src/main/java/org/openhab/binding/serial/internal/util/Parity.java index 0967723c87b8a..20f735a66f9da 100644 --- a/bundles/org.openhab.binding.serial/src/main/java/org/openhab/binding/serial/internal/util/Parity.java +++ b/bundles/org.openhab.binding.serial/src/main/java/org/openhab/binding/serial/internal/util/Parity.java @@ -13,6 +13,7 @@ package org.openhab.binding.serial.internal.util; import java.util.Arrays; +import java.util.Objects; import org.eclipse.jdt.annotation.NonNullByDefault; import org.openhab.core.io.transport.serial.SerialPort; @@ -54,6 +55,7 @@ public int getSerialPortValue() { * @return the enum value */ public static Parity fromConfig(final String configValue) { - return Arrays.asList(values()).stream().filter(p -> p.configValue.equals(configValue)).findFirst().orElse(NONE); + return Objects.requireNonNull(Arrays.asList(values()).stream().filter(p -> p.configValue.equals(configValue)) + .findFirst().orElse(NONE)); } } diff --git a/bundles/org.openhab.binding.serial/src/main/java/org/openhab/binding/serial/internal/util/StopBits.java b/bundles/org.openhab.binding.serial/src/main/java/org/openhab/binding/serial/internal/util/StopBits.java index 1daf52e82089c..5e2f8fa2aa65d 100644 --- a/bundles/org.openhab.binding.serial/src/main/java/org/openhab/binding/serial/internal/util/StopBits.java +++ b/bundles/org.openhab.binding.serial/src/main/java/org/openhab/binding/serial/internal/util/StopBits.java @@ -13,6 +13,7 @@ package org.openhab.binding.serial.internal.util; import java.util.Arrays; +import java.util.Objects; import org.eclipse.jdt.annotation.NonNullByDefault; import org.openhab.core.io.transport.serial.SerialPort; @@ -52,7 +53,7 @@ public int getSerialPortValue() { * @return the enum value */ public static StopBits fromConfig(final String configValue) { - return Arrays.asList(values()).stream().filter(p -> p.configValue.equals(configValue)).findFirst() - .orElse(STOPBITS_1); + return Objects.requireNonNull(Arrays.asList(values()).stream().filter(p -> p.configValue.equals(configValue)) + .findFirst().orElse(STOPBITS_1)); } } diff --git a/bundles/org.openhab.binding.smhi/src/main/java/org/openhab/binding/smhi/internal/ForecastAggregator.java b/bundles/org.openhab.binding.smhi/src/main/java/org/openhab/binding/smhi/internal/ForecastAggregator.java index 16d4556c22e87..6f4eac2cb506e 100644 --- a/bundles/org.openhab.binding.smhi/src/main/java/org/openhab/binding/smhi/internal/ForecastAggregator.java +++ b/bundles/org.openhab.binding.smhi/src/main/java/org/openhab/binding/smhi/internal/ForecastAggregator.java @@ -16,6 +16,7 @@ import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.Optional; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -76,8 +77,8 @@ public static Optional total(TimeSeries timeSeries, int dayOffset, S } else { hours = dayForecasts.get(i - 1).getValidTime().until(current.getValidTime(), ChronoUnit.HOURS); } - values.add(current.getParameter(parameter).map(value -> value.multiply(BigDecimal.valueOf(hours))) - .orElse(BigDecimal.ZERO)); + values.add(Objects.requireNonNull(current.getParameter(parameter) + .map(value -> value.multiply(BigDecimal.valueOf(hours))).orElse(BigDecimal.ZERO))); } return values.stream().reduce(BigDecimal::add); } diff --git a/bundles/org.openhab.binding.smsmodem/src/3rdparty/java/org/smslib/driver/AbstractModemDriver.java b/bundles/org.openhab.binding.smsmodem/src/3rdparty/java/org/smslib/driver/AbstractModemDriver.java index 05ed3d9c259a2..5c5e2fb967a71 100644 --- a/bundles/org.openhab.binding.smsmodem/src/3rdparty/java/org/smslib/driver/AbstractModemDriver.java +++ b/bundles/org.openhab.binding.smsmodem/src/3rdparty/java/org/smslib/driver/AbstractModemDriver.java @@ -5,6 +5,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.io.StringReader; +import java.util.Objects; import java.util.Properties; import java.util.StringTokenizer; import java.util.concurrent.TimeoutException; @@ -63,7 +64,7 @@ public AbstractModemDriver(Modem modem) { ClassLoader classLoader = this.getClass().getClassLoader(); if (classLoader != null) { try (InputStream inputStream = classLoader.getResourceAsStream("modem.properties")) { - modemProperties.load(inputStream); + modemProperties.load(Objects.requireNonNull(inputStream)); } } } catch (IOException e) { diff --git a/bundles/org.openhab.binding.solaredge/src/main/java/org/openhab/binding/solaredge/internal/command/AbstractCommand.java b/bundles/org.openhab.binding.solaredge/src/main/java/org/openhab/binding/solaredge/internal/command/AbstractCommand.java index b762fe841f4c8..0f89fc5399d4c 100644 --- a/bundles/org.openhab.binding.solaredge/src/main/java/org/openhab/binding/solaredge/internal/command/AbstractCommand.java +++ b/bundles/org.openhab.binding.solaredge/src/main/java/org/openhab/binding/solaredge/internal/command/AbstractCommand.java @@ -91,7 +91,7 @@ public AbstractCommand(SolarEdgeConfiguration config, StatusUpdateListener liste * Log request success */ @Override - public final void onSuccess(@Nullable Response response) { + public final void onSuccess(Response response) { super.onSuccess(response); if (response != null) { communicationStatus.setHttpCode(HttpStatus.getCode(response.getStatus())); @@ -104,7 +104,9 @@ public final void onSuccess(@Nullable Response response) { */ @Override public final void onFailure(@Nullable Response response, @Nullable Throwable failure) { - super.onFailure(response, failure); + if (response != null && failure != null) { + super.onFailure(response, failure); + } if (failure != null) { logger.debug("Request failed: {}", failure.toString()); communicationStatus.setError((Exception) failure); @@ -122,7 +124,7 @@ public final void onFailure(@Nullable Response response, @Nullable Throwable fai } @Override - public void onContent(@Nullable Response response, @Nullable ByteBuffer content) { + public void onContent(Response response, ByteBuffer content) { super.onContent(response, content); logger.debug("received content, length: {}", getContentAsString().length()); } diff --git a/bundles/org.openhab.binding.solax/src/main/java/org/openhab/binding/solax/internal/model/InverterType.java b/bundles/org.openhab.binding.solax/src/main/java/org/openhab/binding/solax/internal/model/InverterType.java index d2d3fb96653e7..17a88adecbbab 100644 --- a/bundles/org.openhab.binding.solax/src/main/java/org/openhab/binding/solax/internal/model/InverterType.java +++ b/bundles/org.openhab.binding.solax/src/main/java/org/openhab/binding/solax/internal/model/InverterType.java @@ -13,6 +13,7 @@ package org.openhab.binding.solax.internal.model; import java.util.HashSet; +import java.util.Objects; import java.util.Set; import java.util.stream.Stream; @@ -78,7 +79,8 @@ public enum InverterType { public static InverterType fromIndex(int index) { InverterType[] values = InverterType.values(); - return Stream.of(values).filter(value -> value.typeIndex == index).findFirst().orElse(UNKNOWN); + return Objects.requireNonNull( + Stream.of(values).filter(value -> value.typeIndex == index).findFirst().orElse(UNKNOWN)); } public @Nullable RawDataParser getParser() { diff --git a/bundles/org.openhab.binding.sonnen/src/main/java/org/openhab/binding/sonnen/internal/SonnenConfiguration.java b/bundles/org.openhab.binding.sonnen/src/main/java/org/openhab/binding/sonnen/internal/SonnenConfiguration.java index 38051fb198635..103effc829f26 100644 --- a/bundles/org.openhab.binding.sonnen/src/main/java/org/openhab/binding/sonnen/internal/SonnenConfiguration.java +++ b/bundles/org.openhab.binding.sonnen/src/main/java/org/openhab/binding/sonnen/internal/SonnenConfiguration.java @@ -13,7 +13,6 @@ package org.openhab.binding.sonnen.internal; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; /** * The {@link SonnenConfiguration} class contains fields mapping thing configuration parameters. @@ -23,7 +22,7 @@ @NonNullByDefault public class SonnenConfiguration { - public @Nullable String hostIP = null; + public String hostIP = ""; public int refreshInterval = 30; public String authToken = ""; } diff --git a/bundles/org.openhab.binding.sonnen/src/main/java/org/openhab/binding/sonnen/internal/SonnenHandler.java b/bundles/org.openhab.binding.sonnen/src/main/java/org/openhab/binding/sonnen/internal/SonnenHandler.java index ae27263f04ceb..a7a927d84f08b 100644 --- a/bundles/org.openhab.binding.sonnen/src/main/java/org/openhab/binding/sonnen/internal/SonnenHandler.java +++ b/bundles/org.openhab.binding.sonnen/src/main/java/org/openhab/binding/sonnen/internal/SonnenHandler.java @@ -79,7 +79,7 @@ public void initialize() { "Parameter 'refresh Rate' msut be in the range 0-1000!"); return; } - if (config.hostIP == null) { + if (config.hostIP.isBlank()) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "IP Address must be configured!"); return; } diff --git a/bundles/org.openhab.binding.surepetcare/src/main/java/org/openhab/binding/surepetcare/internal/dto/SurePetcareDevice.java b/bundles/org.openhab.binding.surepetcare/src/main/java/org/openhab/binding/surepetcare/internal/dto/SurePetcareDevice.java index ccafd3d78e65a..a14ff86d40593 100644 --- a/bundles/org.openhab.binding.surepetcare/src/main/java/org/openhab/binding/surepetcare/internal/dto/SurePetcareDevice.java +++ b/bundles/org.openhab.binding.surepetcare/src/main/java/org/openhab/binding/surepetcare/internal/dto/SurePetcareDevice.java @@ -15,6 +15,7 @@ import java.time.ZonedDateTime; import java.util.Arrays; import java.util.Map; +import java.util.Objects; import org.eclipse.jdt.annotation.NonNull; import org.openhab.core.thing.Thing; @@ -44,7 +45,8 @@ private ProductType(int id, String name) { } public static @NonNull ProductType findByTypeId(final int id) { - return Arrays.stream(values()).filter(value -> value.id.equals(id)).findFirst().orElse(UNKNOWN); + return Objects.requireNonNull( + Arrays.stream(values()).filter(value -> value.id.equals(id)).findFirst().orElse(UNKNOWN)); } } diff --git a/bundles/org.openhab.binding.tapocontrol/src/main/java/org/openhab/binding/tapocontrol/internal/api/protocol/aes/SecurePassthrough.java b/bundles/org.openhab.binding.tapocontrol/src/main/java/org/openhab/binding/tapocontrol/internal/api/protocol/aes/SecurePassthrough.java index 4bb3f6689e25b..a08fdb7b453da 100644 --- a/bundles/org.openhab.binding.tapocontrol/src/main/java/org/openhab/binding/tapocontrol/internal/api/protocol/aes/SecurePassthrough.java +++ b/bundles/org.openhab.binding.tapocontrol/src/main/java/org/openhab/binding/tapocontrol/internal/api/protocol/aes/SecurePassthrough.java @@ -171,7 +171,7 @@ public void onComplete(Result result) { httpDelegator.handleError(new TapoErrorHandler(ERR_BINDING_HTTP_RESPONSE, getContentAsString())); } else { /* request successful */ - String rBody = getContentAsString(); + String rBody = Objects.requireNonNull(getContentAsString()); try { asyncResponseReceived(rBody, command); } catch (TapoErrorHandler tapoError) { @@ -242,7 +242,7 @@ protected TapoResponse getTapoResponse(String responseString) throws TapoErrorHa return tapoResponse; } else { logger.debug("({}) invalid response received", uid); - throw new TapoErrorHandler(ERR_BINDING_HTTP_RESPONSE, "invalid response receicved"); + throw new TapoErrorHandler(ERR_BINDING_HTTP_RESPONSE, "invalid response received"); } } diff --git a/bundles/org.openhab.binding.tapocontrol/src/main/java/org/openhab/binding/tapocontrol/internal/api/protocol/passthrough/PassthroughProtocol.java b/bundles/org.openhab.binding.tapocontrol/src/main/java/org/openhab/binding/tapocontrol/internal/api/protocol/passthrough/PassthroughProtocol.java index 205e348640a8b..9af9329f641ed 100644 --- a/bundles/org.openhab.binding.tapocontrol/src/main/java/org/openhab/binding/tapocontrol/internal/api/protocol/passthrough/PassthroughProtocol.java +++ b/bundles/org.openhab.binding.tapocontrol/src/main/java/org/openhab/binding/tapocontrol/internal/api/protocol/passthrough/PassthroughProtocol.java @@ -160,7 +160,7 @@ public void onComplete(Result result) { httpDelegator.handleError(new TapoErrorHandler(ERR_BINDING_HTTP_RESPONSE, getContentAsString())); } else { /* request successful */ - String rBody = getContentAsString(); + String rBody = Objects.requireNonNull(getContentAsString()); try { asyncResponseReceived(rBody, command); } catch (TapoErrorHandler tapoError) { diff --git a/bundles/org.openhab.binding.tr064/src/main/java/org/openhab/binding/tr064/internal/soap/SOAPConnector.java b/bundles/org.openhab.binding.tr064/src/main/java/org/openhab/binding/tr064/internal/soap/SOAPConnector.java index 078dae4f6205f..5571d10c048d5 100644 --- a/bundles/org.openhab.binding.tr064/src/main/java/org/openhab/binding/tr064/internal/soap/SOAPConnector.java +++ b/bundles/org.openhab.binding.tr064/src/main/java/org/openhab/binding/tr064/internal/soap/SOAPConnector.java @@ -192,7 +192,8 @@ public synchronized SOAPMessage doSOAPRequestUncached(SOAPRequest soapRequest) t SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(null, is); if (soapMessage.getSOAPBody().hasFault()) { - String soapError = getSOAPElement(soapMessage, "errorCode").orElse("unknown"); + String soapError = Objects + .requireNonNull(getSOAPElement(soapMessage, "errorCode").orElse("unknown")); String soapReason = getSOAPElement(soapMessage, "errorDescription").orElse("unknown"); String error = String.format("HTTP-Response-Code %d (%s), SOAP-Fault: %s (%s)", response.getStatus(), response.getReason(), soapError, soapReason); diff --git a/bundles/org.openhab.binding.upnpcontrol/src/main/java/org/openhab/binding/upnpcontrol/internal/queue/UpnpEntry.java b/bundles/org.openhab.binding.upnpcontrol/src/main/java/org/openhab/binding/upnpcontrol/internal/queue/UpnpEntry.java index 3caf6363f406f..959b20c776e28 100644 --- a/bundles/org.openhab.binding.upnpcontrol/src/main/java/org/openhab/binding/upnpcontrol/internal/queue/UpnpEntry.java +++ b/bundles/org.openhab.binding.upnpcontrol/src/main/java/org/openhab/binding/upnpcontrol/internal/queue/UpnpEntry.java @@ -150,7 +150,8 @@ public String getParentId() { * @return a URI for this entry. Thumbnail resources are not considered. */ public String getRes() { - return resList.stream().filter(res -> !res.isThumbnailRes()).map(UpnpEntryRes::getRes).findAny().orElse(""); + return Objects.requireNonNull( + resList.stream().filter(res -> !res.isThumbnailRes()).map(UpnpEntryRes::getRes).findAny().orElse("")); } public List getProtocolList() { diff --git a/bundles/org.openhab.binding.volvooncall/src/main/java/org/openhab/binding/volvooncall/internal/dto/Status.java b/bundles/org.openhab.binding.volvooncall/src/main/java/org/openhab/binding/volvooncall/internal/dto/Status.java index 73b375d2b90dd..b4f4d6040970f 100644 --- a/bundles/org.openhab.binding.volvooncall/src/main/java/org/openhab/binding/volvooncall/internal/dto/Status.java +++ b/bundles/org.openhab.binding.volvooncall/src/main/java/org/openhab/binding/volvooncall/internal/dto/Status.java @@ -15,7 +15,6 @@ import static org.openhab.binding.volvooncall.internal.VolvoOnCallBindingConstants.UNDEFINED; import java.util.List; -import java.util.Optional; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; @@ -63,32 +62,32 @@ public enum FluidLevel { public String serviceWarningStatus = ""; private @NonNullByDefault({}) List bulbFailures; - public Optional getWindows() { - return Optional.ofNullable(windows); + public @Nullable WindowsStatus getWindows() { + return windows; } - public Optional getDoors() { - return Optional.ofNullable(doors); + public @Nullable DoorsStatus getDoors() { + return doors; } - public Optional getTyrePressure() { - return Optional.ofNullable(tyrePressure); + public @Nullable TyrePressure getTyrePressure() { + return tyrePressure; } - public Optional getHvBattery() { - return Optional.ofNullable(hvBattery); + public @Nullable HvBattery getHvBattery() { + return hvBattery; } - public Optional getHeater() { - return Optional.ofNullable(heater); + public @Nullable Heater getHeater() { + return heater; } - public Optional getCarLocked() { - return Optional.ofNullable(carLocked); + public @Nullable OnOffType getCarLocked() { + return carLocked; } - public Optional getEngineRunning() { - return Optional.ofNullable(engineRunning); + public @Nullable OnOffType getEngineRunning() { + return engineRunning; } public boolean aFailedBulb() { diff --git a/bundles/org.openhab.binding.volvooncall/src/main/java/org/openhab/binding/volvooncall/internal/handler/VehicleHandler.java b/bundles/org.openhab.binding.volvooncall/src/main/java/org/openhab/binding/volvooncall/internal/handler/VehicleHandler.java index 4f78ec4f57f78..01d0c190214ee 100644 --- a/bundles/org.openhab.binding.volvooncall/src/main/java/org/openhab/binding/volvooncall/internal/handler/VehicleHandler.java +++ b/bundles/org.openhab.binding.volvooncall/src/main/java/org/openhab/binding/volvooncall/internal/handler/VehicleHandler.java @@ -23,6 +23,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Stack; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -207,8 +208,9 @@ private void queryApiAndUpdateChannels(VocHttpApi service) { // We will update trips only if car position has changed to save server queries updateTrips(service); } - if (!vehicleStatus.getEngineRunning().equals(newVehicleStatus.getEngineRunning()) - && newVehicleStatus.getEngineRunning().get() == OnOffType.ON) { + OnOffType newEngineRunning = newVehicleStatus.getEngineRunning(); + if (newEngineRunning != null && !newEngineRunning.equals(vehicleStatus.getEngineRunning()) + && newEngineRunning == OnOffType.ON) { triggerChannel(GROUP_OTHER + "#" + CAR_EVENT, EVENT_CAR_STARTED); } vehicleStatus = newVehicleStatus; @@ -286,9 +288,9 @@ public void handleCommand(ChannelUID channelUID, Command command) { private State getTripValue(String channelId, TripDetail tripDetails) { switch (channelId) { case TRIP_CONSUMPTION: - return tripDetails.getFuelConsumption() + return Objects.requireNonNull(tripDetails.getFuelConsumption() .map(value -> (State) new QuantityType<>(value.floatValue() / 100, LITRE)) - .orElse(UnDefType.UNDEF); + .orElse(UnDefType.UNDEF)); case TRIP_DISTANCE: return new QuantityType<>((double) tripDetails.distance / 1000, KILO(METRE)); case TRIP_START_TIME: @@ -296,8 +298,8 @@ private State getTripValue(String channelId, TripDetail tripDetails) { case TRIP_END_TIME: return tripDetails.getEndTime(); case TRIP_DURATION: - return tripDetails.getDurationInMinutes().map(value -> (State) new QuantityType<>(value, MINUTE)) - .orElse(UnDefType.UNDEF); + return Objects.requireNonNull(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: @@ -435,9 +437,9 @@ private State getValue(String groupId, String channelId, Status status, VehicleP case CAR_LOCKED: // Warning : carLocked is in the Doors group but is part of general status informations. // Did not change it to avoid breaking change for users - return status.getCarLocked().map(State.class::cast).orElse(UnDefType.UNDEF); + return Objects.requireNonNullElse((State) status.getCarLocked(), UnDefType.UNDEF); case ENGINE_RUNNING: - return status.getEngineRunning().map(State.class::cast).orElse(UnDefType.UNDEF); + return Objects.requireNonNullElse((State) status.getEngineRunning(), UnDefType.UNDEF); case BRAKE_FLUID_LEVEL: return fluidLevelToState(status.brakeFluidLevel); case WASHER_FLUID_LEVEL: @@ -451,7 +453,8 @@ private State getValue(String groupId, String channelId, Status status, VehicleP return OnOffType.from(status.aFailedBulb()); case REMOTE_HEATER: case PRECLIMATIZATION: - return status.getHeater().map(heater -> getHeaterValue(channelId, heater)).orElse(UnDefType.NULL); + Heater heater = status.getHeater(); + return heater != null ? getHeaterValue(channelId, heater) : UnDefType.NULL; } switch (groupId) { case GROUP_TANK: @@ -461,14 +464,17 @@ private State getValue(String groupId, String channelId, Status status, VehicleP case GROUP_POSITION: return getPositionValue(channelId, position); case GROUP_DOORS: - return status.getDoors().map(doors -> getDoorsValue(channelId, doors)).orElse(UnDefType.NULL); + DoorsStatus doors = status.getDoors(); + return doors != null ? getDoorsValue(channelId, doors) : UnDefType.NULL; case GROUP_WINDOWS: - return status.getWindows().map(windows -> getWindowsValue(channelId, windows)).orElse(UnDefType.NULL); + WindowsStatus windows = status.getWindows(); + return windows != null ? getWindowsValue(channelId, windows) : UnDefType.NULL; case GROUP_TYRES: - return status.getTyrePressure().map(tyres -> getTyresValue(channelId, tyres)).orElse(UnDefType.NULL); + TyrePressure tyres = status.getTyrePressure(); + return tyres != null ? getTyresValue(channelId, tyres) : UnDefType.NULL; case GROUP_BATTERY: - return status.getHvBattery().map(batteries -> getBatteryValue(channelId, batteries)) - .orElse(UnDefType.NULL); + HvBattery batteries = status.getHvBattery(); + return batteries != null ? getBatteryValue(channelId, batteries) : UnDefType.NULL; } return UnDefType.NULL; } @@ -564,7 +570,7 @@ private void post(String url, @Nullable String param) { public void actionOpenClose(String action, OnOffType controlState) { if (activeOptions.containsKey(action)) { - if (vehicleStatus.getCarLocked().isEmpty() || vehicleStatus.getCarLocked().get() != controlState) { + if (vehicleStatus.getCarLocked() == null || vehicleStatus.getCarLocked() != controlState) { post(String.format("vehicles/%s/%s", configuration.vin, action), "{}"); } else { logger.info("The car {} is already {}ed", configuration.vin, action); diff --git a/bundles/org.openhab.binding.volvooncall/src/main/java/org/openhab/binding/volvooncall/internal/wrapper/VehiclePositionWrapper.java b/bundles/org.openhab.binding.volvooncall/src/main/java/org/openhab/binding/volvooncall/internal/wrapper/VehiclePositionWrapper.java index aee786ad666e9..1fdfe7e27f6d2 100644 --- a/bundles/org.openhab.binding.volvooncall/src/main/java/org/openhab/binding/volvooncall/internal/wrapper/VehiclePositionWrapper.java +++ b/bundles/org.openhab.binding.volvooncall/src/main/java/org/openhab/binding/volvooncall/internal/wrapper/VehiclePositionWrapper.java @@ -13,6 +13,7 @@ package org.openhab.binding.volvooncall.internal.wrapper; import java.time.ZoneId; +import java.util.Objects; import java.util.Optional; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -33,18 +34,18 @@ */ @NonNullByDefault public class VehiclePositionWrapper { - private final Optional position; + private final @Nullable PositionData position; private boolean isCalculated; public VehiclePositionWrapper(Position vehicle) { if (vehicle.calculatedPosition != null && vehicle.position.latitude != null) { - position = Optional.of(vehicle.position); + position = vehicle.position; isCalculated = false; } else if (vehicle.calculatedPosition != null && vehicle.calculatedPosition.latitude != null) { - position = Optional.of(vehicle.calculatedPosition); + position = vehicle.calculatedPosition; isCalculated = true; } else { - position = Optional.empty(); + position = null; } } @@ -56,15 +57,17 @@ private State getPositionAsState(PositionData details) { } public State getPosition() { - return position.map(pos -> getPositionAsState(pos)).orElse(UnDefType.UNDEF); + PositionData position = this.position; + return position != null ? getPositionAsState(position) : UnDefType.UNDEF; } public @Nullable String getPositionAsJSon() { - if (getPosition() != UnDefType.UNDEF) { + PositionData position = this.position; + if (position != null) { StringBuilder json = new StringBuilder("{\"clientLatitude\":"); - json.append(position.get().latitude); + json.append(position.latitude); json.append(",\"clientLongitude\":"); - json.append(position.get().longitude); + json.append(position.longitude); json.append(",\"clientAccuracy\":0}"); return json.toString(); @@ -73,16 +76,17 @@ public State getPosition() { } public State isCalculated() { - return position.map(pos -> (State) OnOffType.from(isCalculated)).orElse(UnDefType.UNDEF); + return position != null ? (State) OnOffType.from(isCalculated) : UnDefType.UNDEF; } public State isHeading() { - return position.map(pos -> (State) OnOffType.from(pos.isHeading())).orElse(UnDefType.UNDEF); + PositionData position = this.position; + return position != null ? (State) OnOffType.from(position.isHeading()) : UnDefType.UNDEF; } public State getTimestamp() { - return position.flatMap(pos -> pos.getTimestamp()) + return Objects.requireNonNull(Optional.ofNullable(this.position).flatMap(pos -> pos.getTimestamp()) .map(dt -> (State) new DateTimeType(dt.withZoneSameInstant(ZoneId.systemDefault()))) - .orElse(UnDefType.NULL); + .orElse(UnDefType.NULL)); } } diff --git a/bundles/org.openhab.io.homekit/src/main/java/org/openhab/io/homekit/internal/accessories/HomekitAccessoryFactory.java b/bundles/org.openhab.io.homekit/src/main/java/org/openhab/io/homekit/internal/accessories/HomekitAccessoryFactory.java index 9968d3e4db2c4..f84d11f0ff021 100644 --- a/bundles/org.openhab.io.homekit/src/main/java/org/openhab/io/homekit/internal/accessories/HomekitAccessoryFactory.java +++ b/bundles/org.openhab.io.homekit/src/main/java/org/openhab/io/homekit/internal/accessories/HomekitAccessoryFactory.java @@ -251,8 +251,8 @@ public static List> getAc HomekitAccessoryType type = accessoryType.get(); if (meta.length > 1) { // it has characteristic as well - accessories.add(new SimpleEntry<>(type, - HomekitCharacteristicType.valueOfTag(meta[1].trim()).orElse(EMPTY))); + accessories.add(new SimpleEntry<>(type, Objects + .requireNonNull(HomekitCharacteristicType.valueOfTag(meta[1].trim()).orElse(EMPTY)))); } else {// it has no characteristic accessories.add(new SimpleEntry<>(type, EMPTY)); } diff --git a/bundles/org.openhab.persistence.influxdb/src/main/java/org/openhab/persistence/influxdb/internal/InfluxDBConfiguration.java b/bundles/org.openhab.persistence.influxdb/src/main/java/org/openhab/persistence/influxdb/internal/InfluxDBConfiguration.java index 210859c4481c1..3fbe95d140e2a 100644 --- a/bundles/org.openhab.persistence.influxdb/src/main/java/org/openhab/persistence/influxdb/internal/InfluxDBConfiguration.java +++ b/bundles/org.openhab.persistence.influxdb/src/main/java/org/openhab/persistence/influxdb/internal/InfluxDBConfiguration.java @@ -13,7 +13,6 @@ package org.openhab.persistence.influxdb.internal; import java.util.Map; -import java.util.Optional; import java.util.StringJoiner; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -69,7 +68,7 @@ public InfluxDBConfiguration(Map config) { private InfluxDBVersion parseInfluxVersion(@Nullable String value) { try { - return Optional.ofNullable(value).map(InfluxDBVersion::valueOf).orElse(InfluxDBVersion.UNKNOWN); + return value != null ? InfluxDBVersion.valueOf(value) : InfluxDBVersion.UNKNOWN; } catch (RuntimeException e) { logger.warn("Invalid version {}", value); return InfluxDBVersion.UNKNOWN; diff --git a/bundles/org.openhab.persistence.jdbc/src/main/java/org/openhab/persistence/jdbc/internal/JdbcConfiguration.java b/bundles/org.openhab.persistence.jdbc/src/main/java/org/openhab/persistence/jdbc/internal/JdbcConfiguration.java index a155dfcd1e58b..f5df1dbf8609c 100644 --- a/bundles/org.openhab.persistence.jdbc/src/main/java/org/openhab/persistence/jdbc/internal/JdbcConfiguration.java +++ b/bundles/org.openhab.persistence.jdbc/src/main/java/org/openhab/persistence/jdbc/internal/JdbcConfiguration.java @@ -16,6 +16,7 @@ import java.util.Collections; import java.util.Enumeration; import java.util.Map; +import java.util.Objects; import java.util.Properties; import java.util.Set; import java.util.regex.Matcher; @@ -125,8 +126,9 @@ private boolean updateConfig() { logger.debug("JDBC::updateConfig: url={}", url); // set database type and database type class - setDBDAOClass(parsedURL.getProperty("dbShortcut")); // derby, h2, hsqldb, mariadb, mysql, postgresql, - // sqlite, timescaledb + setDBDAOClass(Objects.requireNonNull(parsedURL.getProperty("dbShortcut"))); // derby, h2, hsqldb, mariadb, + // mysql, postgresql, + // sqlite, timescaledb // set user if (user != null && !user.isBlank()) { dBDAO.databaseProps.setProperty("dataSource.user", user); @@ -234,7 +236,7 @@ private boolean updateConfig() { } // test if JDBC driver bundle is available - testJDBCDriver(dn); + testJDBCDriver(Objects.requireNonNull(dn)); logger.debug("JDBC::updateConfig: configuration complete. service={}", getName()); diff --git a/bundles/org.openhab.transform.scale/src/main/java/org/openhab/transform/scale/internal/ScaleTransformationService.java b/bundles/org.openhab.transform.scale/src/main/java/org/openhab/transform/scale/internal/ScaleTransformationService.java index a483adc0024ca..f1f0f33dc8efe 100644 --- a/bundles/org.openhab.transform.scale/src/main/java/org/openhab/transform/scale/internal/ScaleTransformationService.java +++ b/bundles/org.openhab.transform.scale/src/main/java/org/openhab/transform/scale/internal/ScaleTransformationService.java @@ -24,6 +24,7 @@ import java.util.LinkedHashSet; import java.util.Locale; import java.util.Map; +import java.util.Objects; import java.util.Properties; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @@ -134,7 +135,7 @@ static class OrderedProperties extends Properties { } @Override - public @Nullable Object put(@Nullable Object key, @Nullable Object value) { + public @Nullable Object put(Object key, Object value) { keys.add(key); return super.put(key, value); } @@ -207,8 +208,8 @@ private void importConfiguration(@Nullable Transformation configuration) { properties.load(new StringReader(function)); for (Object orderedKey : properties.orderedKeys()) { - final String entry = (String) orderedKey; - final String value = properties.getProperty(entry); + final String entry = Objects.requireNonNull((String) orderedKey); + final String value = Objects.requireNonNull(properties.getProperty(entry)); final Matcher matcher = LIMITS_PATTERN.matcher(entry); if (matcher.matches() && (matcher.groupCount() == 4)) { final boolean lowerInclusive = "[".equals(matcher.group(1)); diff --git a/bundles/org.openhab.voice.mimictts/src/main/java/org/openhab/voice/mimic/internal/InputStreamAudioStream.java b/bundles/org.openhab.voice.mimictts/src/main/java/org/openhab/voice/mimic/internal/InputStreamAudioStream.java index ee1598d685b0e..4fbe50fc299b5 100644 --- a/bundles/org.openhab.voice.mimictts/src/main/java/org/openhab/voice/mimic/internal/InputStreamAudioStream.java +++ b/bundles/org.openhab.voice.mimictts/src/main/java/org/openhab/voice/mimic/internal/InputStreamAudioStream.java @@ -107,7 +107,7 @@ public boolean markSupported() { } @Override - public long transferTo(@Nullable OutputStream out) throws IOException { + public long transferTo(OutputStream out) throws IOException { return innerInputStream.transferTo(out); } diff --git a/bundles/org.openhab.voice.pollytts/src/main/java/org/openhab/voice/pollytts/internal/PollyTTSAudioStream.java b/bundles/org.openhab.voice.pollytts/src/main/java/org/openhab/voice/pollytts/internal/PollyTTSAudioStream.java index 7614253accc7c..b877fc427510f 100644 --- a/bundles/org.openhab.voice.pollytts/src/main/java/org/openhab/voice/pollytts/internal/PollyTTSAudioStream.java +++ b/bundles/org.openhab.voice.pollytts/src/main/java/org/openhab/voice/pollytts/internal/PollyTTSAudioStream.java @@ -106,7 +106,7 @@ public boolean markSupported() { } @Override - public long transferTo(@Nullable OutputStream out) throws IOException { + public long transferTo(OutputStream out) throws IOException { return innerInputStream.transferTo(out); } } diff --git a/pom.xml b/pom.xml index 9ed2fa04c6365..c760b31437a35 100644 --- a/pom.xml +++ b/pom.xml @@ -69,7 +69,7 @@ 4.3.0-SNAPSHOT 7.0.0 3.9.0 - 2.2.1 + 2.4.0 2.17.1 5.14.0 4.4.6