private final String defaultValue;
private final Optional<String> mappedTo;
private final Type type;
- private Optional<String> value;
+ private @Nullable String value;
private OptionalConfigurationElement(String defaultValue) {
this(Type.OTHER, defaultValue, null);
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<String> mappedTo() {
@Override
protected Optional<String> 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<String> scriptType = super.getScriptType(scriptFilePath);
+ if (scriptType.isPresent() && !scriptFilePath.startsWith(getWatchPath().resolve("node_modules"))
+ && ("js".equals(scriptType.get()))) {
+ return scriptType;
}
return Optional.empty();
}
@Override
protected Optional<String> getScriptType(Path scriptFilePath) {
- String scriptType = super.getScriptType(scriptFilePath).orElse(null);
- if (!scriptFilePath.startsWith(getWatchPath().resolve("lib")) && ("py".equals(scriptType))) {
- return Optional.of(scriptType);
+ Optional<String> scriptType = super.getScriptType(scriptFilePath);
+ if (scriptType.isPresent() && !scriptFilePath.startsWith(getWatchPath().resolve("lib"))
+ && ("py".equals(scriptType.get()))) {
+ return scriptType;
}
return Optional.empty();
}
*
* @return {AirQualityJsonTime}
*/
- public Optional<AirQualityTime> getTime() {
- return Optional.ofNullable(time);
+ public @Nullable AirQualityTime getTime() {
+ return time;
}
/**
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;
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:
Map<String, String> configMap = OBJECT_MAPPER.readValue(configJson,
new TypeReference<HashMap<String, String>>() {
});
- 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());
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;
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 {
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("")));
}
}
}
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;
// 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);
}
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;
*/
static class DeviceProperties {
private static final Logger LOGGER = LoggerFactory.getLogger(DeviceProperties.class);
- private final Optional<String> localIP;
- private final Optional<OffsetDateTime> lastSeen;
- private final Optional<URL> vendorUiUrl;
- private Optional<String> cpuId = Optional.empty();
- private Optional<String> webUiUsername = Optional.empty();
- private Optional<String> webUiPassword = Optional.empty();
- private Optional<String> unitFWVersion = Optional.empty();
- private Optional<String> wifiFWVersion = Optional.empty();
- private Optional<String> wifiSSID = Optional.empty();
- private Optional<String> wifiPassword = Optional.empty();
- private Optional<String> 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)
* @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<URL> 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");
}
* @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;
}
/**
* @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<OffsetDateTime> 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;
}
}
* @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());
}
/**
SortedMap<String, String> asPropertiesRaw(TimeZoneProvider timeZoneProvider) {
var result = new TreeMap<String, String>();
- 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);
}
}
import java.time.Duration;
import java.time.Instant;
+import java.util.Objects;
import java.util.Optional;
import org.eclipse.jdt.annotation.NonNullByDefault;
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));
}
/////////////
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;
}
private static State valueToState(Optional<Boolean> value) {
- return value.<State> map(v -> OnOffType.from(v)).orElse(UnDefType.UNDEF);
+ return Objects.requireNonNull(value.<State> map(v -> OnOffType.from(v)).orElse(UnDefType.UNDEF));
}
@Override
String rBody = getContentAsString();
logger.trace("({}) requestCompleted '{}'", uid, rBody);
// Handle result
- handleHttpSuccessResponse(rBody, command);
+ if (rBody != null) {
+ handleHttpSuccessResponse(rBody, command);
+ }
}
}
});
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);
+ }
}
}
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;
Type collectionType = new TypeToken<ArrayList<Device>>() {
}.getType();
List<Device> 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();
}.getType();
List<UserDefinedState> 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();
* @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);
* @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 {
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;
}
protected String getRoomNameForDevice(Device device, List<Room> 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) {
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;
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);
import java.util.HashMap;
import java.util.Map;
-import java.util.Optional;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.slf4j.Logger;
Map<String, String> 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;
}
import java.util.HashMap;
import java.util.Map;
+import java.util.Objects;
import java.util.Optional;
import org.eclipse.jdt.annotation.NonNullByDefault;
Map<String, String> 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");
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;
}
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;
}
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;
Map<String, String> 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;
}
import java.util.HashMap;
import java.util.Map;
+import java.util.Objects;
import java.util.Optional;
import org.eclipse.jdt.annotation.NonNullByDefault;
Map<String, String> 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;
}
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;
}
Map<String, String> 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"))
import java.util.LinkedHashMap;
import java.util.Map;
-import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
Map<String, String> 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(";");
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;
Map<String, String> 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();
package org.openhab.binding.daikin.internal.handler;
import java.math.BigDecimal;
+import java.util.Objects;
import java.util.Optional;
import java.util.stream.IntStream;
protected void updateEnergyYearChannel(String channel, Optional<Integer[]> maybePower) {
IntStream.range(1, 13).forEach(i -> updateState(
String.format(DaikinBindingConstants.CHANNEL_ENERGY_STRING_FORMAT, channel, i),
- maybePower.<State> map(
+ Objects.requireNonNull(maybePower.<State> map(
t -> new QuantityType<>(BigDecimal.valueOf(t[i - 1].longValue(), 1), Units.KILOWATT_HOUR))
- .orElse(UnDefType.UNDEF))
+ .orElse(UnDefType.UNDEF)))
);
}
protected void updateEnergyDayAndWeekChannel(String channel, Optional<Double> maybePower) {
if (maybePower.isPresent()) {
updateState(channel,
- maybePower.<State> map(t -> new QuantityType<>(new DecimalType(t), Units.KILOWATT_HOUR))
- .orElse(UnDefType.UNDEF));
+ Objects.requireNonNull(
+ maybePower.<State> map(t -> new QuantityType<>(new DecimalType(t), Units.KILOWATT_HOUR))
+ .orElse(UnDefType.UNDEF)));
}
}
*/
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;
}
protected void updateTemperatureChannel(String channel, Optional<Double> maybeTemperature) {
- updateState(channel,
- maybeTemperature.<State> map(t -> new QuantityType<>(t, SIUnits.CELSIUS)).orElse(UnDefType.UNDEF));
+ updateState(channel, Objects.requireNonNull(
+ maybeTemperature.<State> map(t -> new QuantityType<>(t, SIUnits.CELSIUS)).orElse(UnDefType.UNDEF)));
}
/**
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;
}
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() {
package org.openhab.binding.digiplex.internal.communication;
import java.util.Arrays;
+import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault;
}
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));
}
}
package org.openhab.binding.digiplex.internal.communication;
import java.util.Arrays;
+import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault;
}
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));
}
}
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;
}
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));
}
}
package org.openhab.binding.digiplex.internal.communication.events;
import java.util.Arrays;
+import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault;
}
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));
}
}
*/
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;
} 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 {
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;
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;
}
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;
}
} 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);
}
}
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;
"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);
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;
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);
* 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()));
*/
@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);
* 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());
}
*/
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;
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();
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;
}
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()) {
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)));
}
}
}
private State stringToState(@Nullable String value) {
Optional<State> 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) {
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;
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();
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;
}
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) {
*/
package org.openhab.binding.enocean.internal.messages;
+import java.util.Objects;
import java.util.stream.Stream;
import org.eclipse.jdt.annotation.NonNullByDefault;
}
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));
}
}
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;
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));
}
}
}
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
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
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
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import javax.ws.rs.core.UriBuilder;
// 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 {
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;
}
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<Node> getMatchingNodes(NodeList nodeList, String criteria) {
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;
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();
}
*/
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");
* 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 "";
}
}
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;
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 {
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;
.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<BrowseResult> favorites) {
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) {
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;
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<ThingStatusDetail> 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);
import java.nio.ByteBuffer;
import java.util.Arrays;
+import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
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) {
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;
@Override
public void handleStatusMessage(Matcher matcher) {
IntStream stream;
- Optional<String> 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());
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());
package org.openhab.binding.luxom.internal.protocol;
import java.util.Arrays;
+import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault;
}
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() {
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;
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)) {
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;
}
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);
}
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;
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);
}
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;
return deviceName.get();
}
- return ThingInformationExtractor.getDeviceAndTechType(deviceState).orElse("Miele Device");
+ return Objects
+ .requireNonNull(ThingInformationExtractor.getDeviceAndTechType(deviceState).orElse("Miele Device"));
}
@Override
import java.util.HashMap;
import java.util.Map;
+import java.util.Objects;
import java.util.Optional;
import org.eclipse.jdt.annotation.NonNullByDefault;
}
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"));
}
/**
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;
}
protected MieleWebservice getWebservice() {
- return getMieleBridgeHandler().map(MieleBridgeHandler::getWebservice)
- .orElse(UnavailableMieleWebservice.INSTANCE);
+ return Objects.requireNonNull(getMieleBridgeHandler().map(MieleBridgeHandler::getWebservice)
+ .orElse(UnavailableMieleWebservice.INSTANCE));
}
@Override
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;
* Converts an {@link Optional} of {@link String} to {@link State}.
*/
public static State stringToState(Optional<String> 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<Boolean> 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<Integer> 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<Long> 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));
}
/**
*/
public static State intToTemperatureState(Optional<Integer> 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<Quantity> 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));
}
/**
* @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));
}
/**
}
public DeviceType getValueRaw() {
- return Optional.ofNullable(valueRaw).orElse(DeviceType.UNKNOWN);
+ return Objects.requireNonNullElse(valueRaw, DeviceType.UNKNOWN);
}
public Optional<String> getValueLocalized() {
getSseConnection().addSseListener(getMockedSseListener());
getSseConnection().connect();
- getRegisteredHeadersListener().onHeaders(null);
+ Response response = mock(Response.class);
+ getRegisteredHeadersListener().onHeaders(response);
}
private Request getMockedRequest() {
assertNotNull(headersListener);
// when:
- headersListener.onHeaders(null);
+ Response response = mock(Response.class);
+ headersListener.onHeaders(response);
// then:
verify(scheduler).schedule(ArgumentMatchers.<Runnable> any(), anyLong(), any());
setUpRunningConnection();
// when:
- getRegisteredCompleteListener().onComplete(null);
+ Result result = mock(Result.class);
+ getRegisteredCompleteListener().onComplete(result);
// then:
verify(getMockedScheduler(), times(2)).schedule(ArgumentMatchers.<Runnable> any(), anyLong(), any());
HeadersListener headersListener = registeredHeadersListener;
assertNotNull(headersListener);
- headersListener.onHeaders(null);
+ Response response = mock(Response.class);
+ headersListener.onHeaders(response);
ServerSentEvent serverSentEvent = new ServerSentEvent("ping", "ping");
private void triggerSwitch(String variableName) {
try {
+ HeliosEasyControlsHandler handler = this.handler;
if (handler != null) {
handler.writeValue(variableName, "1");
}
@RuleAction(label = "@text/action.getErrorMessages.label", description = "@text/action.getErrorMessages.description")
public @ActionOutput(name = "errorMessages", type = "java.util.List<String>") List<String> getErrorMessages() {
+ HeliosEasyControlsHandler handler = this.handler;
return (handler != null) ? handler.getErrorMessages() : new ArrayList<>();
}
@RuleAction(label = "@text/action.getWarningMessages.label", description = "@text/action.getWarningMessages.description")
public @ActionOutput(name = "warningMessages", type = "java.util.List<String>") List<String> getWarningMessages() {
+ HeliosEasyControlsHandler handler = this.handler;
return (handler != null) ? handler.getWarningMessages() : new ArrayList<>();
}
@RuleAction(label = "@text/action.getInfoMessages.label", description = "@text/action.getInfoMessages.description")
public @ActionOutput(name = "infoMessages", type = "java.util.List<String>") List<String> getInfoMessages() {
+ HeliosEasyControlsHandler handler = this.handler;
return (handler != null) ? handler.getInfoMessages() : new ArrayList<>();
}
@RuleAction(label = "@text/action.getStatusMessages.label", description = "@text/action.getStatusMessages.description")
public @ActionOutput(name = "statusMessages", type = "java.util.List<String>") List<String> getStatusMessages() {
+ HeliosEasyControlsHandler handler = this.handler;
return (handler != null) ? handler.getStatusMessages() : new ArrayList<>();
}
} catch (IOException e) {
this.handleError("Error reading variable definition file", ThingStatusDetail.CONFIGURATION_ERROR);
}
+ Map<String, HeliosVariable> variableMap = this.variableMap;
if (variableMap != null) {
// add the name to the variable itself
- for (Map.Entry<String, HeliosVariable> entry : this.variableMap.entrySet()) {
+ for (Map.Entry<String, HeliosVariable> entry : variableMap.entrySet()) {
entry.getValue().setName(entry.getKey()); // workaround to set the variable name inside the
// HeliosVariable object
if (!entry.getValue().isOk()) {
ModbusEndpointThingHandler slaveEndpointThingHandler = getEndpointThingHandler();
if (slaveEndpointThingHandler == null) {
- @SuppressWarnings("null")
String label = Optional.ofNullable(getBridge()).map(b -> b.getLabel()).orElse("<null>");
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE,
String.format("Bridge '%s' is offline", label));
comms = slaveEndpointThingHandler.getCommunicationInterface();
if (comms == null) {
- @SuppressWarnings("null")
String label = Optional.ofNullable(getBridge()).map(b -> b.getLabel()).orElse("<null>");
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE,
String.format("Bridge '%s' not completely initialized", label));
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
HeliosEasyControlsConfiguration config = this.config;
if (config != null) {
this.pollingJob = scheduler.scheduleWithFixedDelay(() -> {
+ Map<String, HeliosVariable> variableMap = this.variableMap;
if (variableMap != null) {
for (Map.Entry<String, HeliosVariable> entry : variableMap.entrySet()) {
if (this.isProperty(entry.getKey()) || isLinked(entry.getValue().getGroupAndName())
@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;
}
scheduler.submit(() -> {
try {
writeValue(channelId, v);
+ Map<String, HeliosVariable> variableMap = this.variableMap;
if (variableMap != null) {
HeliosVariable variable = variableMap.get(channelId);
if (variable != null) {
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
*/
package org.openhab.binding.modbus.stiebeleltron.internal.parser;
+import java.util.Objects;
import java.util.Optional;
import org.eclipse.jdt.annotation.NonNullByDefault;
* @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));
}
/**
* @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));
}
/**
* @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));
}
/**
* @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));
}
}
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;
status == null ? UnDefType.UNDEF : new StringType(status.name()));
updateState(channelUID(GROUP_DEVICE_INFO, CHANNEL_STATUS_VENDOR),
- block.statusVendor.<State> map(DecimalType::new).orElse(UnDefType.UNDEF));
+ Objects.requireNonNull(block.statusVendor.<State> map(DecimalType::new).orElse(UnDefType.UNDEF)));
// AC General group
updateState(channelUID(GROUP_AC_GENERAL, CHANNEL_AC_TOTAL_CURRENT),
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;
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));
*/
package org.openhab.binding.modbus.sunspec.internal.parser;
+import java.util.Objects;
import java.util.Optional;
import org.eclipse.jdt.annotation.NonNullByDefault;
* @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));
}
/**
* @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));
}
/**
* @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));
}
/**
* @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));
}
}
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;
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);
*/
package org.openhab.binding.mycroft.internal.api;
+import java.util.Objects;
import java.util.stream.Stream;
import javax.validation.constraints.NotNull;
@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() {
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;
public static final EnumSet<ModuleType> AS_SET = EnumSet.allOf(ModuleType.class);
- private final Optional<ModuleType> bridgeType;
+ private final @Nullable ModuleType bridgeType;
public final Set<ChannelGroup> channelGroups;
public final Set<Class<? extends Capability>> capabilities;
public final ThingTypeUID thingTypeUID;
ModuleType(FeatureArea feature, String apiName, int thingTypeVersion, String config, @Nullable ModuleType bridge,
Set<Class<? extends Capability>> capabilities, ChannelGroup... channelGroups) {
- this.bridgeType = Optional.ofNullable(bridge);
+ this.bridgeType = bridge;
this.feature = feature;
this.capabilities = capabilities;
this.apiName = apiName;
}
public ModuleType getBridge() {
- return bridgeType.orElse(UNKNOWN);
+ return Objects.requireNonNullElse(this.bridgeType, UNKNOWN);
}
public int getDepth() {
return radioStatus;
}
- public Optional<ZonedDateTime> getLastSeen() {
- return Optional.ofNullable(lastSeen);
+ public @Nullable ZonedDateTime getLastSeen() {
+ return lastSeen;
}
/**
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;
* @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));
}
/**
* @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));
}
}
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;
}
default <T extends RestCapability<?>> Optional<T> getHomeCapability(Class<T> 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) {
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;
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));
@Override
public List<NAObject> 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()));
}
}
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;
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));
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;
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,
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
@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
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;
}
private Collection<HomeEvent> 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<HomeEvent> 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) {
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;
@Override
protected @Nullable State internalGetProperty(String channelId, NAThing naThing, Configuration config) {
- Optional<ZonedDateTime> 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
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.ZonedDateTime;
-import java.util.Optional;
import javax.measure.Unit;
return (zonedDateTime == null) ? UnDefType.NULL : new DateTimeType(zonedDateTime);
}
- public static State toDateTimeType(Optional<ZonedDateTime> 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;
* 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()));
*/
@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);
}
@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
package org.openhab.binding.nikohomecontrol.internal.protocol.nhc2;
import java.util.ArrayList;
+import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault;
* @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(""));
}
/**
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;
* 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());
package org.openhab.binding.pentair.internal.handler.helpers;
import java.util.Arrays;
+import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault;
}
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));
}
}
}
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));
}
}
package org.openhab.binding.pentair.internal.handler.helpers;
import java.util.Arrays;
+import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault;
}
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));
}
}
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;
}
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));
}
}
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);
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;
/**
* 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);
}
private StatusDTO getStatus(final List<UdpResponseDTO> 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) {
}
private SwitchResponseDTO getSwitchResponse(final List<UdpResponseDTO> 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) {
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;
private final Logger logger = LoggerFactory.getLogger(SagerWeatherCaster.class);
private final Properties forecaster = new Properties();
- private Optional<SagerPrediction> prevision = Optional.empty();
+ private @Nullable SagerPrediction prevision;
private String[] usedDirections = NTZDIRECTIONS; // Defaulted to Northern Zone
private int currentBearing = -1;
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);
}
}
}
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) {
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;
}
public Collection<VinInfo> getVinList() {
- return Optional.ofNullable(vinList).orElse(Collections.emptyList());
+ Collection<VinInfo> vinList = this.vinList;
+ return vinList != null ? vinList : Collections.emptyList();
}
public String sendRequest(String request, String endpoint)
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;
} catch (ParserConfigurationException e) {
LOGGER.debug("XMLParser Configuration Error: {}", e.getMessage());
}
- return Optional.ofNullable(factory).orElse(DocumentBuilderFactory.newInstance());
+ return factory;
}
/**
}
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(""));
}
}
}
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) {
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;
}
protected synchronized Map<String, String> updateResourceState(String actionId, Map<String, String> inputs) {
- Map<String, String> 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<String, String> 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, "");
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<String, String> result = updateResourceState("SetMainTVSource",
Map.of("Source", source, "ID", sources.getOrDefault(source, "0"), "UiID", "0"));
logResult(result.getOrDefault("Result", "Unable to Set Source Name: " + source));
}
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));
}
/**
}
}
- 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;
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;
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());
}
callback.onError(Objects.requireNonNullElse(failure, "Unknown error"));
} else {
- callback.onResponse(getContentAsString());
+
+ callback.onResponse(Objects.requireNonNull(getContentAsString()));
}
}
});
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;
* @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));
}
}
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;
* @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));
}
}
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;
} 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);
}
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;
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) {
* 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()));
*/
@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);
}
@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());
}
package org.openhab.binding.solax.internal.model;
import java.util.HashSet;
+import java.util.Objects;
import java.util.Set;
import java.util.stream.Stream;
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() {
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.
@NonNullByDefault
public class SonnenConfiguration {
- public @Nullable String hostIP = null;
+ public String hostIP = "";
public int refreshInterval = 30;
public String authToken = "";
}
"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;
}
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;
}
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));
}
}
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) {
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");
}
}
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) {
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);
* @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<String> getProtocolList() {
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;
public String serviceWarningStatus = "";
private @NonNullByDefault({}) List<Object> bulbFailures;
- public Optional<WindowsStatus> getWindows() {
- return Optional.ofNullable(windows);
+ public @Nullable WindowsStatus getWindows() {
+ return windows;
}
- public Optional<DoorsStatus> getDoors() {
- return Optional.ofNullable(doors);
+ public @Nullable DoorsStatus getDoors() {
+ return doors;
}
- public Optional<TyrePressure> getTyrePressure() {
- return Optional.ofNullable(tyrePressure);
+ public @Nullable TyrePressure getTyrePressure() {
+ return tyrePressure;
}
- public Optional<HvBattery> getHvBattery() {
- return Optional.ofNullable(hvBattery);
+ public @Nullable HvBattery getHvBattery() {
+ return hvBattery;
}
- public Optional<Heater> getHeater() {
- return Optional.ofNullable(heater);
+ public @Nullable Heater getHeater() {
+ return heater;
}
- public Optional<OnOffType> getCarLocked() {
- return Optional.ofNullable(carLocked);
+ public @Nullable OnOffType getCarLocked() {
+ return carLocked;
}
- public Optional<OnOffType> getEngineRunning() {
- return Optional.ofNullable(engineRunning);
+ public @Nullable OnOffType getEngineRunning() {
+ return engineRunning;
}
public boolean aFailedBulb() {
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;
// 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;
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:
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:
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:
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:
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;
}
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);
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;
*/
@NonNullByDefault
public class VehiclePositionWrapper {
- private final Optional<PositionData> 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;
}
}
}
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();
}
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));
}
}
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));
}
package org.openhab.persistence.influxdb.internal;
import java.util.Map;
-import java.util.Optional;
import java.util.StringJoiner;
import org.eclipse.jdt.annotation.NonNullByDefault;
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;
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;
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);
}
// test if JDBC driver bundle is available
- testJDBCDriver(dn);
+ testJDBCDriver(Objects.requireNonNull(dn));
logger.debug("JDBC::updateConfig: configuration complete. service={}", getName());
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;
}
@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);
}
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));
}
@Override
- public long transferTo(@Nullable OutputStream out) throws IOException {
+ public long transferTo(OutputStream out) throws IOException {
return innerInputStream.transferTo(out);
}
}
@Override
- public long transferTo(@Nullable OutputStream out) throws IOException {
+ public long transferTo(OutputStream out) throws IOException {
return innerInputStream.transferTo(out);
}
}
<ohc.version>4.3.0-SNAPSHOT</ohc.version>
<bnd.version>7.0.0</bnd.version>
<commons.net.version>3.9.0</commons.net.version>
- <eea.version>2.2.1</eea.version>
+ <eea.version>2.4.0</eea.version>
<jackson.version>2.17.1</jackson.version>
<jna.version>5.14.0</jna.version>
<karaf.version>4.4.6</karaf.version>