import java.util.ArrayList;
import java.util.List;
+import java.util.stream.Collectors;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
}
public String getGeo() {
- List<String> list = new ArrayList<>();
- geo.forEach(item -> list.add(item.toString()));
- return String.join(",", list);
+ return geo.stream().map(Object::toString).collect(Collectors.joining(", "));
}
}
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.stream.Collectors;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
* @return {String}
*/
public String getAttributions() {
- List<String> list = new ArrayList<>();
- attributions.forEach(item -> list.add(item.getName()));
- return "Attributions : " + String.join(", ", list);
+ String attributionsString = attributions.stream().map(Attribute::getName).collect(Collectors.joining(", "));
+ return "Attributions : " + attributionsString;
}
public String getDominentPol() {
private static class MessageParseException extends Exception {
private static final long serialVersionUID = 1L;
- public MessageParseException(String msg) {
+ public MessageParseException(@Nullable String msg) {
super(msg);
}
}
}
}
- void returnError(HttpServletResponse resp, String errorMessage) {
+ void returnError(HttpServletResponse resp, @Nullable String errorMessage) {
try {
- resp.getWriter().write("<html>" + StringEscapeUtils.escapeHtml(errorMessage) + "<br><a href='" + servletUrl
+ String message = errorMessage != null ? errorMessage : "null";
+ resp.getWriter().write("<html>" + StringEscapeUtils.escapeHtml(message) + "<br><a href='" + servletUrl
+ "'>Try again</a></html>");
} catch (IOException e) {
logger.info("Returning error message failed", e);
import org.openhab.binding.amazonechocontrol.internal.Connection;
import org.openhab.binding.amazonechocontrol.internal.handler.AccountHandler;
import org.openhab.binding.amazonechocontrol.internal.handler.SmartHomeDeviceHandler;
+import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.DriverIdentity;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeGroups.SmartHomeGroup;
continue;
}
- if (Stream.of(shd.capabilities).noneMatch(capability -> capability != null
+ JsonSmartHomeCapabilities.SmartHomeCapability[] capabilities = shd.capabilities;
+ if (capabilities == null || Stream.of(capabilities).noneMatch(capability -> capability != null
&& Constants.SUPPORTED_INTERFACES.contains(capability.interfaceName))) {
// No supported interface found
continue;
}
}
if (handler != null) {
- Collection<ChannelInfo> required = handler.initialize(this, capabilities.get(interfaceName));
+ Collection<ChannelInfo> required = handler.initialize(this,
+ capabilities.getOrDefault(interfaceName, Collections.emptyList()));
for (ChannelInfo channelInfo : required) {
unusedChannels.remove(channelInfo.channelId);
if (addChannelToDevice(thingBuilder, channelInfo.channelId, channelInfo.itemType,
private ScheduledFuture<?> validateKeysJob;
// Application key is granted only by request from developer
- @Nullable
- private String applicationKey;
+ private String applicationKey = "";
// API key assigned to user in ambientweather.net dashboard
- @Nullable
- private String apiKey;
+ private String apiKey = "";
// Used Ambient Weather real-time API to retrieve weather data
// for weather stations assigned to an API key
return true;
}
- public void setThingOfflineWithCommError(String errorDetail, String statusDescription) {
- updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, statusDescription);
+ public void setThingOfflineWithCommError(@Nullable String errorDetail, @Nullable String statusDescription) {
+ String status = statusDescription != null ? statusDescription : "null";
+ updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, status);
}
@Override
updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
}
- public @Nullable String getApplicationKey() {
+ public String getApplicationKey() {
return applicationKey;
}
- public @Nullable String getApiKey() {
+ public String getApiKey() {
return apiKey;
}
*/
private String convertSoilMoistureToString(double soilMoisture) {
Double key = soilMoistureMap.ceilingKey(soilMoisture);
- return key == null ? "UNKNOWN" : soilMoistureMap.get(key);
+ return key == null ? "UNKNOWN" : soilMoistureMap.getOrDefault(key, "UNKNOWN");
}
}
import java.io.IOException;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
/**
* An exception that occurred while communicating with an automower or an automower bridge
}
@Override
- public String getMessage() {
- return "Rest call failed: statusCode=" + statusCode + ", message=" + super.getMessage();
+ public @Nullable String getMessage() {
+ String message = super.getMessage();
+ return message == null ? null : "Rest call failed: statusCode=" + statusCode + ", message=" + message;
}
@Override
initMapping();
}
- if (codeMapping.get(eirDataType) == null) {
- return UNKNOWN;
- }
-
- return codeMapping.get(eirDataType);
+ return codeMapping.getOrDefault(eirDataType, UNKNOWN);
}
/**
initMapping();
}
- if (codeMapping.get(eirFlag) == null) {
- return UNKNOWN;
- }
-
- return codeMapping.get(eirFlag);
+ return codeMapping.getOrDefault(eirFlag, UNKNOWN);
}
/**
}
public void removeBluetoothDevice(BluetoothDevice device) {
- device.removeListener(devices.remove(device));
+ BluetoothDeviceListener listener = devices.remove(device);
+ if (listener != null) {
+ device.removeListener(listener);
+ }
}
@Override
}
}
} catch (ExecutionException e) {
- future.completeExceptionally(e.getCause());
+ Throwable cause = e.getCause();
+ future.completeExceptionally(cause != null ? cause : e);
} catch (SmartherGatewayException e) {
future.completeExceptionally(e);
} catch (RuntimeException | TimeoutException e) {
public static <E extends Enum<E> & TypeWithIntProperty> E lookup(Class<E> en, int value)
throws SmartherIllegalPropertyValueException {
- for (E constant : en.getEnumConstants()) {
- if (constant.getValue() == value) {
- return constant;
+ E[] constants = en.getEnumConstants();
+ if (constants != null) {
+ for (E constant : constants) {
+ if (constant.getValue() == value) {
+ return constant;
+ }
}
}
throw new SmartherIllegalPropertyValueException(en.getSimpleName(), String.valueOf(value));
public static <E extends Enum<E> & TypeWithStringProperty> E lookup(Class<E> en, String value)
throws SmartherIllegalPropertyValueException {
- for (E constant : en.getEnumConstants()) {
- if (constant.getValue().equals(value)) {
- return constant;
+ E[] constants = en.getEnumConstants();
+ if (constants != null) {
+ for (E constant : constants) {
+ if (constant.getValue().equals(value)) {
+ return constant;
+ }
}
}
throw new SmartherIllegalPropertyValueException(en.getSimpleName(), value);
package org.openhab.binding.bticinosmarther.internal.api.exception;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
/**
* Signals that a generic OAuth2 authorization issue with API gateway has occurred.
* @param message
* the error message returned from the API gateway
*/
- public SmartherAuthorizationException(String message) {
+ public SmartherAuthorizationException(@Nullable String message) {
super(message);
}
* @param cause
* the cause (a null value is permitted, and indicates that the cause is nonexistent or unknown)
*/
- public SmartherAuthorizationException(String message, Throwable cause) {
+ public SmartherAuthorizationException(@Nullable String message, @Nullable Throwable cause) {
super(message, cause);
}
}
import java.io.IOException;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
/**
* Signals that a generic communication issue with API gateway has occurred.
* @param message
* the error message returned from the API gateway
*/
- public SmartherGatewayException(String message) {
+ public SmartherGatewayException(@Nullable String message) {
super(message);
}
* @param cause
* the cause (a null value is permitted, and indicates that the cause is nonexistent or unknown)
*/
- public SmartherGatewayException(String message, Throwable cause) {
+ public SmartherGatewayException(@Nullable String message, @Nullable Throwable cause) {
super(message, cause);
}
* @param cause
* the cause (a null value is permitted, and indicates that the cause is nonexistent or unknown)
*/
- public SmartherGatewayException(Throwable cause) {
+ public SmartherGatewayException(@Nullable Throwable cause) {
super(cause);
}
}
package org.openhab.binding.bticinosmarther.internal.api.exception;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
/**
* Signals that an "invalid response" messaging issue with API gateway has occurred.
* @param message
* the error message returned from the API gateway
*/
- public SmartherInvalidResponseException(String message) {
+ public SmartherInvalidResponseException(@Nullable String message) {
super(message);
}
}
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
+import java.time.format.DateTimeParseException;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
* if the string cannot be parsed to a local date
*/
public static LocalDate parseDate(@Nullable String str, String pattern) {
+ if (str == null) {
+ throw new DateTimeParseException("date string is null", "<null>", 0);
+ }
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
return LocalDate.parse(str, dtf);
}
* if the string cannot be parsed to a local date and time
*/
public static LocalDateTime parseLocalTime(@Nullable String str, String pattern) {
+ if (str == null) {
+ throw new DateTimeParseException("time string is null", "<null>", 0);
+ }
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
return LocalDateTime.parse(str, dtf);
}
* if the string cannot be parsed to a date and time with timezone
*/
public static ZonedDateTime parseZonedTime(@Nullable String str, String pattern) {
+ if (str == null) {
+ throw new DateTimeParseException("zoned string is null", "<null>", 0);
+ }
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
return ZonedDateTime.parse(str, dtf);
}
package org.openhab.binding.buienradar.internal.buienradarapi;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
/**
* An exception thrown when a result from Buienradar could not be correctly parsed.
super();
}
- public BuienradarParseException(String message) {
+ public BuienradarParseException(@Nullable String message) {
super(message);
}
- public BuienradarParseException(Throwable cause) {
+ public BuienradarParseException(@Nullable Throwable cause) {
super(cause);
}
- public BuienradarParseException(String message, Throwable cause) {
+ public BuienradarParseException(@Nullable String message, @Nullable Throwable cause) {
super(message, cause);
}
- public BuienradarParseException(String message, Throwable cause, boolean enableSuppression,
+ public BuienradarParseException(@Nullable String message, @Nullable Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
actual = Optional.of(prediction.getActualDateTime());
predictions.add(prediction);
} catch (BuienradarParseException e) {
- errors.add(e.getMessage());
+ String error = e.getMessage();
+ errors.add(error != null ? error : "null");
}
}
if (!errors.isEmpty()) {
logger.debug("Message does not contain property [{}]", property);
return "";
}
- return propertyMap.get(property);
+ return propertyMap.getOrDefault(property, "");
}
public String getPropertyById(String id) {
logger.debug("Message does not contain id [{}]", id);
return "";
}
- return idMap.get(id);
+ return idMap.getOrDefault(id, "");
}
public int @Nullable [] getReplyMessageNumbers() {
package org.openhab.binding.darksky.internal.connection;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
/**
* The {@link DarkSkyCommunicationException} is a communication exception for the connections to Dark Sky API.
*
* @param message Detail message
*/
- public DarkSkyCommunicationException(String message) {
+ public DarkSkyCommunicationException(@Nullable String message) {
super(message);
}
*
* @param cause The cause
*/
- public DarkSkyCommunicationException(Throwable cause) {
+ public DarkSkyCommunicationException(@Nullable Throwable cause) {
super(cause);
}
* @param message Detail message
* @param cause The cause
*/
- public DarkSkyCommunicationException(String message, Throwable cause) {
+ public DarkSkyCommunicationException(@Nullable String message, @Nullable Throwable cause) {
super(message, cause);
}
}
package org.openhab.binding.darksky.internal.connection;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
/**
* The {@link DarkSkyConfigurationException} is a configuration exception for the connections to Dark Sky API.
*
* @param message Detail message
*/
- public DarkSkyConfigurationException(String message) {
+ public DarkSkyConfigurationException(@Nullable String message) {
super(message);
}
*
* @param cause The cause
*/
- public DarkSkyConfigurationException(Throwable cause) {
+ public DarkSkyConfigurationException(@Nullable Throwable cause) {
super(cause);
}
* @param message Detail message
* @param cause The cause
*/
- public DarkSkyConfigurationException(String message, Throwable cause) {
+ public DarkSkyConfigurationException(@Nullable String message, @Nullable Throwable cause) {
super(message, cause);
}
}
}
private String buildURL(String url, Map<String, String> requestParams) {
- return requestParams.keySet().stream().map(key -> key + "=" + encodeParam(requestParams.get(key)))
+ return requestParams.entrySet().stream().map(e -> e.getKey() + "=" + encodeParam(e.getValue()))
.collect(joining("&", url + "?", ""));
}
|| thing.getThingTypeUID().equals(THING_TYPE_EXTENDED_COLOR_LIGHT)) {
try {
Map<String, String> properties = thing.getProperties();
- ctMax = Integer.parseInt(properties.get(PROPERTY_CT_MAX));
- ctMin = Integer.parseInt(properties.get(PROPERTY_CT_MIN));
+ String ctMaxString = properties.get(PROPERTY_CT_MAX);
+ ctMax = ctMaxString == null ? ZCL_CT_MAX : Integer.parseInt(ctMaxString);
+ String ctMinString = properties.get(PROPERTY_CT_MIN);
+ ctMin = ctMinString == null ? ZCL_CT_MIN : Integer.parseInt(ctMinString);
// minimum and maximum are inverted due to mired/kelvin conversion!
StateDescription stateDescription = StateDescriptionFragmentBuilder.create()
@Override
public void handleEvent(EventItem eventItem) {
- if (EventNames.DEVICE_SENSOR_VALUE.equals(eventItem.getName())
- || EventNames.DEVICE_BINARY_INPUT_EVENT.equals(eventItem.getName())) {
- logger.debug("Detect {} eventItem = {}", eventItem.getName(), eventItem.toString());
- Device dev = getDeviceOfEvent(eventItem);
- if (dev != null) {
- if (EventNames.DEVICE_SENSOR_VALUE.equals(eventItem.getName())) {
- dev.setDeviceSensorByEvent(eventItem);
- } else {
- DeviceBinarayInputEnum binaryInputType = DeviceBinarayInputEnum.getdeviceBinarayInput(
- Short.parseShort(eventItem.getProperties().get(EventResponseEnum.INPUT_TYPE)));
- Short newState = Short.parseShort(eventItem.getProperties().get(EventResponseEnum.INPUT_STATE));
- if (binaryInputType != null) {
- dev.setBinaryInputState(binaryInputType, newState);
+ try {
+ if (EventNames.DEVICE_SENSOR_VALUE.equals(eventItem.getName())
+ || EventNames.DEVICE_BINARY_INPUT_EVENT.equals(eventItem.getName())) {
+ logger.debug("Detect {} eventItem = {}", eventItem.getName(), eventItem.toString());
+ Device dev = getDeviceOfEvent(eventItem);
+ if (dev != null) {
+ if (EventNames.DEVICE_SENSOR_VALUE.equals(eventItem.getName())) {
+ dev.setDeviceSensorByEvent(eventItem);
+ } else {
+ DeviceBinarayInputEnum binaryInputType = DeviceBinarayInputEnum.getdeviceBinarayInput(Short
+ .parseShort(eventItem.getProperties().getOrDefault(EventResponseEnum.INPUT_TYPE, "")));
+ Short newState = Short
+ .parseShort(eventItem.getProperties().getOrDefault(EventResponseEnum.INPUT_STATE, ""));
+ if (binaryInputType != null) {
+ dev.setBinaryInputState(binaryInputType, newState);
+ }
}
}
}
+ } catch (NumberFormatException e) {
+ logger.debug("Unexpected missing or invalid number while handling event", e);
}
}
@Override
public void handleEvent(EventItem eventItem) {
- logger.debug("detect event: {}", eventItem.toString());
- if (eventItem.getName().equals(EventNames.ZONE_SENSOR_VALUE)) {
- if (zoneTemperationControlListenerMap != null) {
- if (SensorEnum.ROOM_TEMPERATURE_SET_POINT.getSensorType().toString()
- .equals(eventItem.getProperties().get(EventResponseEnum.SENSOR_TYPE))) {
- Integer zoneID = Integer.parseInt(eventItem.getSource().get(EventResponseEnum.ZONEID));
- if (zoneTemperationControlListenerMap.get(zoneID) != null) {
- Float newValue = Float
- .parseFloat(eventItem.getProperties().get(EventResponseEnum.SENSOR_VALUE_FLOAT));
- if (!isEcho(zoneID, SensorEnum.ROOM_TEMPERATURE_CONTROL_VARIABLE, newValue)) {
- zoneTemperationControlListenerMap.get(zoneID).onTargetTemperatureChanged(newValue);
+ try {
+ logger.debug("detect event: {}", eventItem.toString());
+ if (eventItem.getName().equals(EventNames.ZONE_SENSOR_VALUE)) {
+ if (zoneTemperationControlListenerMap != null) {
+ if (SensorEnum.ROOM_TEMPERATURE_SET_POINT.getSensorType().toString()
+ .equals(eventItem.getProperties().get(EventResponseEnum.SENSOR_TYPE))) {
+ Integer zoneID = Integer
+ .parseInt(eventItem.getSource().getOrDefault(EventResponseEnum.ZONEID, ""));
+ if (zoneTemperationControlListenerMap.get(zoneID) != null) {
+
+ Float newValue = Float.parseFloat(
+ eventItem.getProperties().getOrDefault(EventResponseEnum.SENSOR_VALUE_FLOAT, ""));
+ if (!isEcho(zoneID, SensorEnum.ROOM_TEMPERATURE_CONTROL_VARIABLE, newValue)) {
+ zoneTemperationControlListenerMap.get(zoneID).onTargetTemperatureChanged(newValue);
+ }
}
}
- }
- if (SensorEnum.ROOM_TEMPERATURE_CONTROL_VARIABLE.getSensorType().toString()
- .equals(eventItem.getProperties().get(EventResponseEnum.SENSOR_TYPE))) {
- Integer zoneID = Integer.parseInt(eventItem.getSource().get(EventResponseEnum.ZONEID));
- if (zoneTemperationControlListenerMap.get(zoneID) != null) {
- Float newValue = Float
- .parseFloat(eventItem.getProperties().get(EventResponseEnum.SENSOR_VALUE_FLOAT));
- if (!isEcho(zoneID, SensorEnum.ROOM_TEMPERATURE_CONTROL_VARIABLE, newValue)) {
- zoneTemperationControlListenerMap.get(zoneID).onControlValueChanged(newValue.intValue());
+ if (SensorEnum.ROOM_TEMPERATURE_CONTROL_VARIABLE.getSensorType().toString()
+ .equals(eventItem.getProperties().get(EventResponseEnum.SENSOR_TYPE))) {
+ Integer zoneID = Integer
+ .parseInt(eventItem.getSource().getOrDefault(EventResponseEnum.ZONEID, ""));
+ if (zoneTemperationControlListenerMap.get(zoneID) != null) {
+ Float newValue = Float.parseFloat(
+ eventItem.getProperties().getOrDefault(EventResponseEnum.SENSOR_VALUE_FLOAT, ""));
+ if (!isEcho(zoneID, SensorEnum.ROOM_TEMPERATURE_CONTROL_VARIABLE, newValue)) {
+ zoneTemperationControlListenerMap.get(zoneID)
+ .onControlValueChanged(newValue.intValue());
+ }
}
}
}
}
- }
- if (eventItem.getName().equals(EventNames.HEATING_CONTROL_OPERATION_MODE)) {
- if (EVALUATE_REAL_ACTIVE_MODE.equals(eventItem.getProperties().get(EventResponseEnum.ACTIONS))) {
- Integer zoneID = Integer.parseInt(eventItem.getProperties().get(EventResponseEnum.ZONEID));
- TemperatureControlStatus temperationControlStatus = dSapi
- .getZoneTemperatureControlStatus(connectionMananager.getSessionToken(), zoneID, null);
- if (temperationControlStatus != null) {
- addTemperatureControlStatus(temperationControlStatus);
+ if (eventItem.getName().equals(EventNames.HEATING_CONTROL_OPERATION_MODE)) {
+ if (EVALUATE_REAL_ACTIVE_MODE.equals(eventItem.getProperties().get(EventResponseEnum.ACTIONS))) {
+ Integer zoneID = Integer
+ .parseInt(eventItem.getProperties().getOrDefault(EventResponseEnum.ZONEID, ""));
+ TemperatureControlStatus temperationControlStatus = dSapi
+ .getZoneTemperatureControlStatus(connectionMananager.getSessionToken(), zoneID, null);
+ if (temperationControlStatus != null) {
+ addTemperatureControlStatus(temperationControlStatus);
+ }
}
}
- }
- if (eventItem.getName().equals(EventNames.STATE_CHANGED)) {
- if (STATE_NAME_HEATING_WATER_SYSTEM.equals(eventItem.getProperties().get(EventResponseEnum.STATE_NAME))) {
- currentHeatingWaterSystemStage = eventItem.getProperties().get(EventResponseEnum.STATE);
- logger.debug("heating water system state changed to {}", currentHeatingWaterSystemStage);
- if (systemStateChangeListener != null) {
- systemStateChangeListener.onSystemStateChanged(STATE_NAME_HEATING_WATER_SYSTEM,
- currentHeatingWaterSystemStage);
+ if (eventItem.getName().equals(EventNames.STATE_CHANGED)) {
+ if (STATE_NAME_HEATING_WATER_SYSTEM
+ .equals(eventItem.getProperties().get(EventResponseEnum.STATE_NAME))) {
+ currentHeatingWaterSystemStage = eventItem.getProperties().get(EventResponseEnum.STATE);
+ logger.debug("heating water system state changed to {}", currentHeatingWaterSystemStage);
+ if (systemStateChangeListener != null) {
+ systemStateChangeListener.onSystemStateChanged(STATE_NAME_HEATING_WATER_SYSTEM,
+ currentHeatingWaterSystemStage);
+ }
}
}
+ } catch (NumberFormatException e) {
+ logger.debug("Unexpected missing or invalid number while handling event", e);
}
}
* Creates a new {@link DeviceSensorValue} through the properties of a digitalSTROM
* {@link EventNames#DEVICE_SENSOR_VALUE} event.
*
- * @param eventPropertie must not be null
+ * @param eventProperties must not be null
*/
- public DeviceSensorValue(Map<EventResponseEnum, String> eventPropertie) {
- if (eventPropertie.get(EventResponseEnum.SENSOR_VALUE_FLOAT) != null) {
- floatValue = Float.parseFloat(eventPropertie.get(EventResponseEnum.SENSOR_VALUE_FLOAT));
+ public DeviceSensorValue(Map<EventResponseEnum, String> eventProperties) {
+ String strVal = eventProperties.get(EventResponseEnum.SENSOR_VALUE_FLOAT);
+ if (strVal != null) {
+ floatValue = Float.parseFloat(strVal);
}
- if (eventPropertie.get(EventResponseEnum.SENSOR_TYPE) != null) {
- sensorType = SensorEnum.getSensor(Short.parseShort(eventPropertie.get(EventResponseEnum.SENSOR_TYPE)));
+ strVal = eventProperties.get(EventResponseEnum.SENSOR_TYPE);
+ if (strVal != null) {
+ sensorType = SensorEnum.getSensor(Short.parseShort(strVal));
}
- if (eventPropertie.get(EventResponseEnum.SENSOR_VALUE) != null) {
- dsValue = Integer.parseInt(eventPropertie.get(EventResponseEnum.SENSOR_VALUE));
+ strVal = eventProperties.get(EventResponseEnum.SENSOR_VALUE);
+ if (strVal != null) {
+ dsValue = Integer.parseInt(strVal);
}
- if (eventPropertie.get(EventResponseEnum.SENSOR_INDEX) != null) {
- sensorIndex = Short.parseShort(eventPropertie.get(EventResponseEnum.SENSOR_INDEX));
+ strVal = eventProperties.get(EventResponseEnum.SENSOR_INDEX);
+ if (strVal != null) {
+ sensorIndex = Short.parseShort(strVal);
}
timestamp = Date.from(Instant.ofEpochMilli(System.currentTimeMillis()));
valid = true;
package org.openhab.binding.draytonwiser.internal.api;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
/**
* Exception thrown in case of api problems.
private static final long serialVersionUID = 1L;
- public DraytonWiserApiException(final String message) {
+ public DraytonWiserApiException(final @Nullable String message) {
super(message);
}
- public DraytonWiserApiException(final String message, final Throwable cause) {
+ public DraytonWiserApiException(final @Nullable String message, final @Nullable Throwable cause) {
super(message, cause);
}
}
logger.trace("Received obisIdString {}, obisId: {}, values: {}", obisIdString, obisId, cosemStringValues);
- CosemObject cosemObject = null;
-
- if (obisLookupTableFixed.containsKey(reducedObisId)) {
- cosemObject = getCosemObjectInternal(obisLookupTableFixed.get(reducedObisId), obisId, cosemStringValues);
+ CosemObjectType objectType = obisLookupTableFixed.get(reducedObisId);
+ if (objectType != null) {
logger.trace("Found obisId {} in the fixed lookup table", reducedObisId);
- } else if (obisLookupTableMultipleFixed.containsKey(reducedObisId)) {
- for (CosemObjectType cosemObjectType : obisLookupTableMultipleFixed.get(reducedObisId)) {
- cosemObject = getCosemObjectInternal(cosemObjectType, obisId, cosemStringValues);
+ return getCosemObjectInternal(objectType, obisId, cosemStringValues);
+ }
+
+ List<CosemObjectType> objectTypeList = obisLookupTableMultipleFixed.get(reducedObisId);
+ if (objectTypeList != null) {
+ for (CosemObjectType cosemObjectType : objectTypeList) {
+ CosemObject cosemObject = getCosemObjectInternal(cosemObjectType, obisId, cosemStringValues);
if (cosemObject != null) {
logger.trace("Found obisId {} in the fixed lookup table", reducedObisId);
- break;
+ return cosemObject;
}
}
- } else if (obisLookupTableDynamic.containsKey(reducedObisId)) {
+ }
+
+ objectType = obisLookupTableDynamic.get(reducedObisId);
+ if (objectType != null) {
logger.trace("Found obisId {} in the dynamic lookup table", reducedObisId);
- cosemObject = getCosemObjectInternal(obisLookupTableDynamic.get(reducedObisId), obisId, cosemStringValues);
- } else if (obisLookupTableFixed.containsKey(reducedObisIdGroupE)) {
- cosemObject = getCosemObjectInternal(obisLookupTableFixed.get(reducedObisIdGroupE), obisId,
- cosemStringValues);
- } else {
- for (CosemObjectType obisMsgType : obisWildcardCosemTypeList) {
- if (obisMsgType.obisId.equalsWildCard(reducedObisId)) {
- cosemObject = getCosemObjectInternal(obisMsgType, obisId, cosemStringValues);
- if (cosemObject != null) {
- logger.trace("Searched reducedObisId {} in the wild card type list, result: {}", reducedObisId,
- cosemObject);
- obisLookupTableDynamic.put(reducedObisId, obisMsgType);
- break;
- }
+ return getCosemObjectInternal(objectType, obisId, cosemStringValues);
+ }
+
+ objectType = obisLookupTableFixed.get(reducedObisIdGroupE);
+ if (objectType != null) {
+ return getCosemObjectInternal(objectType, obisId, cosemStringValues);
+ }
+
+ for (CosemObjectType obisMsgType : obisWildcardCosemTypeList) {
+ if (obisMsgType.obisId.equalsWildCard(reducedObisId)) {
+ CosemObject cosemObject = getCosemObjectInternal(obisMsgType, obisId, cosemStringValues);
+ if (cosemObject != null) {
+ logger.trace("Searched reducedObisId {} in the wild card type list, result: {}", reducedObisId,
+ cosemObject);
+ obisLookupTableDynamic.put(reducedObisId, obisMsgType);
+ return cosemObject;
}
}
}
- if (cosemObject == null) {
- logger.debug("Received unknown Cosem Object(OBIS id: {})", obisId);
- }
+ logger.debug("Received unknown Cosem Object(OBIS id: {})", obisId);
- return cosemObject;
+ return null;
}
/**
.map(Thing::getHandler)
.filter(DSMRMeterHandler.class::isInstance)
.map(DSMRMeterHandler.class::cast)
- .map(DSMRMeterHandler::getMeterDescriptor)
+ .map(h -> h == null ? null : h.getMeterDescriptor())
+ .map(d -> d == null ? null : d.getMeterType())
.filter(Objects::nonNull)
- .map(h -> h.getMeterType())
.collect(Collectors.toSet());
// @formatter:on
// Create list of all configured meters that are not in the detected list. If not empty meters might not be
package org.openhab.binding.enturno.internal.connection;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
/**
* The {@link EnturCommunicationException} is a communication exception for the connections to Entur API.
private static final long serialVersionUID = 1L;
- public EnturCommunicationException(String message) {
+ public EnturCommunicationException(@Nullable String message) {
super(message);
}
- public EnturCommunicationException(String message, Throwable cause) {
+ public EnturCommunicationException(@Nullable String message, @Nullable Throwable cause) {
super(message, cause);
}
}
}
public static String getOperatingSystemName() {
- return System.getProperty("os.name");
+ String osname = System.getProperty("os.name");
+ return osname != null ? osname : "unknown";
}
}
}
private static final NamespaceContext NAMESPACE_CONTEXT = new NamespaceContext() {
@Override
- public String getNamespaceURI(@Nullable String prefix) {
+ public @Nullable String getNamespaceURI(@Nullable String prefix) {
return NAMESPACES.get(prefix);
}
package org.openhab.binding.foobot.internal;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
/**
* Exception thrown when problems occur with obtaining data for the foobot api.
private static final long serialVersionUID = 1L;
- public FoobotApiException(final int status, final String message) {
+ public FoobotApiException(final int status, final @Nullable String message) {
super(String.format("%s (code: %s)", message, status));
}
}
import static org.openhab.binding.foobot.internal.FoobotBindingConstants.*;
import java.time.Duration;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
+import java.util.*;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
private static final long serialVersionUID = -2337258558995287405L;
private static String EX_NONE = "none";
- public GreeException(Exception exception) {
+ public GreeException(@Nullable Exception exception) {
super(exception);
}
- public GreeException(String message) {
+ public GreeException(@Nullable String message) {
super(message);
}
- public GreeException(String message, Exception exception) {
+ public GreeException(@Nullable String message, @Nullable Exception exception) {
super(message, exception);
}
@Override
- public String getMessage() {
+ public @Nullable String getMessage() {
return isEmpty() ? "" : nonNullString(super.getMessage());
}
deviceTable.put(newDevice.getId(), newDevice);
}
- public GreeAirDevice getDevice(String id) {
+ public @Nullable GreeAirDevice getDevice(String id) {
return deviceTable.get(id);
}
}
private int getShadeId() throws NumberFormatException {
- return Integer.parseInt(getConfigAs(HDPowerViewShadeConfiguration.class).id);
+ String str = getConfigAs(HDPowerViewShadeConfiguration.class).id;
+ if (str == null) {
+ throw new NumberFormatException("null input string");
+ }
+ return Integer.parseInt(str);
}
private void stopShade() {
package org.openhab.binding.heliosventilation.internal;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
/**
* The {@link HeliosPropertiesFormatException} class defines an exception to describe parsing format errors
}
@Override
- public String getMessage() {
+ public @Nullable String getMessage() {
return "Cannot parse '" + fullSpec + "' for datapoint '" + channelName + "': " + reason;
}
}
private final @Nullable result data;
private final String errorMessage;
- public HPServerResult(RequestStatus status, String errorMessage) {
+ public HPServerResult(RequestStatus status, @Nullable String errorMessage) {
this.status = status;
this.data = null;
- this.errorMessage = errorMessage;
+ this.errorMessage = errorMessage != null ? errorMessage : "";
}
public HPServerResult(result data) {
ArrayList<T> lightList = new ArrayList<>();
for (String id : lightMap.keySet()) {
+ @Nullable
T light = lightMap.get(id);
- light.setId(id);
- lightList.add(light);
+ if (light != null) {
+ light.setId(id);
+ lightList.add(light);
+ }
}
return lightList;
if (getGroupId() == null) {
return getLightIds().stream().allMatch(id -> group.getLightIds().contains(id));
} else {
- return group.getId().contentEquals(getGroupId());
+ String groupId = getGroupId();
+ return groupId != null ? group.getId().contentEquals(groupId) : false;
}
}
*
* @return
*/
- public Device getBridgeDevice() {
+ public @Nullable Device getBridgeDevice() {
return getDeviceMap().get(bridgeDeviceId);
}
}
private int getRampLevel(InsteonChannelConfiguration conf, int defaultValue) {
- Map<String, @Nullable String> params = conf.getParameters();
- return params.containsKey("ramplevel") ? Integer.parseInt(params.get("ramplevel")) : defaultValue;
+ String str = conf.getParameters().get("ramplevel");
+ return str != null ? Integer.parseInt(str) : defaultValue;
}
}
}
protected double getRampTime(InsteonChannelConfiguration conf, double defaultValue) {
- Map<String, @Nullable String> params = conf.getParameters();
- return params.containsKey("ramptime") ? Double.parseDouble(params.get("ramptime")) : defaultValue;
+ String str = conf.getParameters().get("ramptime");
+ return str != null ? Double.parseDouble(str) : defaultValue;
}
}
*/
protected double getDoubleParameter(String key, double def) {
try {
- if (parameters.get(key) != null) {
- return Double.parseDouble(parameters.get(key));
- }
+ String str = parameters.get(key);
+ return str != null ? Double.parseDouble(str) : def;
} catch (NumberFormatException e) {
logger.warn("malformed int parameter in message handler: {}", key);
}
}
int b = Math.min(len, remaining());
- System.arraycopy(buf, index, bytes, off, b);
+ if (bytes != null) {
+ System.arraycopy(buf, index, bytes, off, b);
+ }
index += b;
return b;
}
* @param len the length to copy from the src byte array
*/
private void initialize(byte[] newData, int offset, int len) {
- data = new byte[len];
+ byte[] data = new byte[len];
if (offset >= 0 && offset < newData.length) {
System.arraycopy(newData, offset, data, 0, len);
} else {
logger.warn("intialize(): Offset out of bounds!");
}
+ this.data = data;
}
/**
throw new FieldException("data index out of bounds!");
}
byte[] section = new byte[numBytes];
- System.arraycopy(data, offset, section, 0, numBytes);
+ byte[] data = this.data;
+ if (data != null) {
+ System.arraycopy(data, offset, section, 0, numBytes);
+ }
return section;
}
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.thing.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
* Translates a service name to a service path (Replaces # through /)
*
*/
- public static String translatesNameToPath(String name) {
- return name.replace("#", "/");
+ public static @Nullable String translatesNameToPath(@Nullable String name) {
+ return name == null ? null : name.replace("#", "/");
}
/**
if (null != tmpSerObjekt) {
if (parent == null || parent.equals(tmpSerObjekt.getParent())) {
synchronized (sendMap) {
- if (sendMap.containsKey(actChannel)) {
- state = dataHandler.parseJSONData(sendMap.get(actChannel),
- tmpSerObjekt.getServiceType(), tmpService, actChTypes,
- KM200Utils.getChannelConfigurationStrings(actChannel));
+ JsonObject obj = sendMap.get(actChannel);
+ if (obj != null) {
+ state = dataHandler.parseJSONData(obj, tmpSerObjekt.getServiceType(), tmpService,
+ actChTypes, KM200Utils.getChannelConfigurationStrings(actChannel));
} else {
state = dataHandler.getProvidersState(tmpService, actChTypes,
KM200Utils.getChannelConfigurationStrings(actChannel));
synchronized (sendMap) {
KM200ServiceObject serObjekt = remoteDevice.getServiceObject(service);
if (null != serObjekt) {
- if (sendMap.containsKey(channel)) {
- state = dataHandler.parseJSONData(sendMap.get(channel),
- serObjekt.getServiceType(), service, chTypes,
- KM200Utils.getChannelConfigurationStrings(channel));
+ JsonObject obj = sendMap.get(channel);
+ if (obj != null) {
+ state = dataHandler.parseJSONData(obj, serObjekt.getServiceType(), service,
+ chTypes, KM200Utils.getChannelConfigurationStrings(channel));
} else {
state = dataHandler.getProvidersState(service, chTypes,
KM200Utils.getChannelConfigurationStrings(channel));
continue;
}
/* Search for new services in sub path */
- addChannels(serObj.serviceTreeMap.get(subKey), thing, subChannels, subKey + "_");
+ KM200ServiceObject obj = serObj.serviceTreeMap.get(subKey);
+ if (obj != null) {
+ addChannels(obj, thing, subChannels, subKey + "_");
+ }
break;
case DATA_TYPE_ERROR_LIST:
if ("nbrErrors".equals(subKey) || "error".equals(subKey)) {
private void disconnect(@Nullable Exception e) {
releaseConnection();
if (e != null) {
+ String message = e.getLocalizedMessage();
statusUpdateCallback.updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
- e.getLocalizedMessage());
+ message != null ? message : "");
} else {
statusUpdateCallback.updateStatus(ThingStatus.OFFLINE);
}
return new WebscrapeHandler(thing);
}
// third generation
- if (SUPPORTED_THIRD_GENERATION_THING_TYPES_UIDS.containsKey(thing.getThingTypeUID())) {
- return new ThirdGenerationHandler(thing, httpClient,
- SUPPORTED_THIRD_GENERATION_THING_TYPES_UIDS.get(thing.getThingTypeUID()));
+ ThirdGenerationInverterTypes inverterType = SUPPORTED_THIRD_GENERATION_THING_TYPES_UIDS
+ .get(thing.getThingTypeUID());
+ if (inverterType != null) {
+ return new ThirdGenerationHandler(thing, httpClient, inverterType);
}
return null;
}
public void handleConnectionFailed(@Nullable Throwable e) {
if (!(state instanceof ConnectionStateShutdown)) {
if (e != null) {
- connection.getCallback().onOffline(e.getMessage());
+ String message = e.getMessage();
+ connection.getCallback().onOffline(message != null ? message : "");
} else {
connection.getCallback().onOffline("");
}
@OnWebSocketError
public void onError(Throwable cause) {
- Optional.ofNullable(this.listener).ifPresent(l -> l.onError(cause.getMessage()));
+ String message = cause.getMessage();
+ Optional.ofNullable(this.listener).ifPresent(l -> l.onError(message != null ? message : ""));
logger.debug("Connection Error.", cause);
}
return;
}
- Optional.ofNullable(this.listener).ifPresent(l -> l.onError(cause.getMessage()));
+ String message = cause.getMessage();
+ Optional.ofNullable(this.listener).ifPresent(l -> l.onError(message != null ? message : ""));
}
@OnWebSocketClose
import java.net.URI;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
+import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
AuthData authData = gson.fromJson(result.getContentAsString(), AuthData.class);
if (authData.callbacks.size() < 2 || authData.callbacks.get(0).input.size() == 0
- || authData.callbacks.get(1).input.size() == 0
- || !config.username.contentEquals(authData.callbacks.get(0).input.get(0).valueAsString())) {
+ || authData.callbacks.get(1).input.size() == 0 || !config.username
+ .equals(Objects.requireNonNull(authData.callbacks.get(0).input.get(0)).valueAsString())) {
throw new LinkyException("Authentication error, the authentication_cookie is probably wrong");
}
import org.slf4j.LoggerFactory;
/**
- * The {@link LogReaderHandler} is responsible for handling commands, which are
+ * The {@link LogHandler} is responsible for handling commands, which are
* sent to one of the channels.
*
* @author Miika Jukka - Initial contribution
@Override
public void initialize() {
- configuration = getConfigAs(LogReaderConfiguration.class);
+ String logDir = System.getProperty("openhab.logdir");
+ if (logDir == null) {
+ updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
+ "Cannot determine system log directory.");
+ return;
+ }
- configuration.filePath = configuration.filePath.replaceFirst("\\$\\{OPENHAB_LOGDIR\\}",
- System.getProperty("openhab.logdir"));
+ configuration = getConfigAs(LogReaderConfiguration.class);
+ configuration.filePath = configuration.filePath.replaceFirst("\\$\\{OPENHAB_LOGDIR\\}", logDir);
logger.debug("Using configuration: {}", configuration);
channels.addAll(getThing().getChannels());
}
channels.sort((c1, c2) -> {
- String label = c1.getLabel();
- return label == null ? 1 : label.compareTo(c2.getLabel());
+ String label1 = c1.getLabel();
+ String label2 = c2.getLabel();
+ if (label1 == null && label2 != null) {
+ return 1;
+ } else if (label1 != null && label2 == null) {
+ return -1;
+ } else if (label1 == null && label2 == null) {
+ return 0;
+ } else {
+ return label1.compareTo(label2);
+ }
});
ThingBuilder builder = editThing();
builder.withChannels(channels);
xstream = new XStream(driver);
configureSecurity(xstream);
- setClassLoader(Project.class.getClassLoader());
+ ClassLoader classLoader = Project.class.getClassLoader();
+ if (classLoader == null) {
+ throw new UnknownError("Cannot find classloader");
+ }
+ setClassLoader(classLoader);
registerAliases(xstream);
}
+ "facet=etat_vent&facet=etat_pluie_inondation&facet=etat_orage&facet=etat_inondation&facet=etat_neige&facet=etat_canicule&"
+ "facet=etat_grand_froid&facet=etat_avalanches&refine.nom_dept=";
private static final int TIMEOUT_MS = 30000;
+ private static final String UNKNOWN_COLOR = "b3b3b3";
private static final Map<AlertLevel, String> ALERT_COLORS = Map.ofEntries(
new AbstractMap.SimpleEntry<AlertLevel, String>(AlertLevel.GREEN, "00ff00"),
new AbstractMap.SimpleEntry<AlertLevel, String>(AlertLevel.YELLOW, "ffff00"),
new AbstractMap.SimpleEntry<AlertLevel, String>(AlertLevel.ORANGE, "ff6600"),
new AbstractMap.SimpleEntry<AlertLevel, String>(AlertLevel.RED, "ff0000"),
- new AbstractMap.SimpleEntry<AlertLevel, String>(AlertLevel.UNKNOWN, "b3b3b3"));
+ new AbstractMap.SimpleEntry<AlertLevel, String>(AlertLevel.UNKNOWN, UNKNOWN_COLOR));
private final Logger logger = LoggerFactory.getLogger(MeteoAlerteHandler.class);
// Time zone provider representing time zone configured in openHAB configuration
if (isLinked(channelIcon)) {
String resource = getResource(String.format("picto/%s.svg", channelId));
if (resource != null) {
- resource = resource.replaceAll(ALERT_COLORS.get(AlertLevel.UNKNOWN), ALERT_COLORS.get(value));
+ resource = resource.replaceAll(UNKNOWN_COLOR, ALERT_COLORS.getOrDefault(value, UNKNOWN_COLOR));
}
updateState(channelIcon,
resource != null ? new RawType(resource.getBytes(), "image/svg+xml") : UnDefType.UNDEF);
package org.openhab.binding.miio.internal;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
/**
* Will be thrown instead of the many possible errors in the crypto module
super();
}
- public MiIoCryptoException(String message) {
+ public MiIoCryptoException(@Nullable String message) {
super(message);
}
- public MiIoCryptoException(String message, Exception e) {
+ public MiIoCryptoException(@Nullable String message, @Nullable Exception e) {
super(message, e);
}
}
package org.openhab.binding.miio.internal.cloud;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
/**
* Will be thrown for cloud errors
super();
}
- public MiCloudException(String message) {
+ public MiCloudException(@Nullable String message) {
super(message);
}
- public MiCloudException(String message, Exception e) {
+ public MiCloudException(@Nullable String message, @Nullable Exception e) {
super(message, e);
}
}
disconnected("No Response from device");
}
- protected void disconnected(String message) {
- updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, message);
+ protected void disconnected(@Nullable String message) {
+ updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
+ message != null ? message : "");
final MiIoAsyncCommunication miioCom = this.miioCom;
if (miioCom != null) {
lastId = miioCom.getId();
import java.util.zip.GZIPInputStream;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.miio.internal.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
return sw.toString();
}
- private void printAreaDetails(ArrayList<float[]> areas, PrintWriter pw) {
+ private void printAreaDetails(@Nullable ArrayList<float[]> areas, PrintWriter pw) {
+ if (areas == null) {
+ pw.println("null");
+ return;
+ }
areas.forEach(area -> {
pw.print("\tArea coordinates:");
for (int i = 0; i < area.length; i++) {
});
}
- private void printObstacleDetails(ArrayList<int[]> obstacle, PrintWriter pw) {
+ private void printObstacleDetails(@Nullable ArrayList<int[]> obstacle, PrintWriter pw) {
+ if (obstacle == null) {
+ pw.println("null");
+ return;
+ }
obstacle.forEach(area -> {
pw.print("\tObstacle coordinates:");
for (int i = 0; i < area.length; i++) {
public CompletableFuture<DatagramSocket> start() {
if (willbeclosed) {
CompletableFuture<DatagramSocket> f = new CompletableFuture<>();
- f.completeExceptionally(null);
+ f.completeExceptionally(new IllegalStateException("will be closed"));
return f;
}
if (sessionThread.isAlive()) {
try {
writeValue(channelId, v);
if (variableMap != null) {
- updateState(variableMap.get(channelId), v);
- updateStatus(ThingStatus.ONLINE);
+ HeliosVariable variable = variableMap.get(channelId);
+ if (variable != null) {
+ updateState(variable, v);
+ updateStatus(ThingStatus.ONLINE);
+ }
}
} catch (HeliosException e) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
import java.util.Optional;
import java.util.Set;
+import javax.measure.Unit;
+
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.modbus.handler.ModbusEndpointThingHandler;
import org.openhab.core.thing.binding.BaseThingHandler;
import org.openhab.core.thing.binding.ThingHandler;
import org.openhab.core.types.Command;
+import org.openhab.core.types.State;
import org.openhab.core.types.UnDefType;
import org.openhab.io.transport.modbus.AsyncModbusFailure;
import org.openhab.io.transport.modbus.ModbusCommunicationInterface;
Float quantity = parser.hexToFloat(hexString);
if (quantity != null) {
if (type.equals(THING_TYPE_BSP)) {
- updateState(CHANNELS_BSP.get(registerNumber),
- new QuantityType<>(quantity, UNIT_CHANNELS_BSP.get(registerNumber)));
+ Unit<?> unit = UNIT_CHANNELS_BSP.get(registerNumber);
+ if (unit != null) {
+ internalUpdateState(CHANNELS_BSP.get(registerNumber), new QuantityType<>(quantity, unit));
+ }
} else if (type.equals(THING_TYPE_XTENDER)) {
handlePolledDataXtender(registerNumber, quantity);
} else if (type.equals(THING_TYPE_VARIOTRACK)) {
case CHANNEL_PV2_OPERATING_MODE:
VSMode vsmode = StuderParser.getVSModeByCode(quantity.intValue());
if (vsmode == VSMode.UNKNOWN) {
- updateState(CHANNELS_VARIOSTRING.get(registerNumber), UnDefType.UNDEF);
+ internalUpdateState(CHANNELS_VARIOSTRING.get(registerNumber), UnDefType.UNDEF);
} else {
- updateState(CHANNELS_VARIOSTRING.get(registerNumber), new StringType(vsmode.name()));
+ internalUpdateState(CHANNELS_VARIOSTRING.get(registerNumber), new StringType(vsmode.name()));
}
break;
case CHANNEL_STATE_VARIOSTRING:
OnOffType vsstate = StuderParser.getStateByCode(quantity.intValue());
- updateState(CHANNELS_VARIOSTRING.get(registerNumber), vsstate);
+ internalUpdateState(CHANNELS_VARIOSTRING.get(registerNumber), vsstate);
break;
default:
- updateState(CHANNELS_VARIOSTRING.get(registerNumber),
- new QuantityType<>(quantity, UNIT_CHANNELS_VARIOSTRING.get(registerNumber)));
+ Unit<?> unit = UNIT_CHANNELS_VARIOSTRING.get(registerNumber);
+ if (unit != null) {
+ internalUpdateState(CHANNELS_VARIOSTRING.get(registerNumber), new QuantityType<>(quantity, unit));
+ }
}
}
case CHANNEL_MODEL_VARIOTRACK:
VTType type = StuderParser.getVTTypeByCode(quantity.intValue());
if (type == VTType.UNKNOWN) {
- updateState(CHANNELS_VARIOTRACK.get(registerNumber), UnDefType.UNDEF);
+ internalUpdateState(CHANNELS_VARIOTRACK.get(registerNumber), UnDefType.UNDEF);
} else {
- updateState(CHANNELS_VARIOTRACK.get(registerNumber), new StringType(type.name()));
+ internalUpdateState(CHANNELS_VARIOTRACK.get(registerNumber), new StringType(type.name()));
}
break;
case CHANNEL_OPERATING_MODE:
VTMode vtmode = StuderParser.getVTModeByCode(quantity.intValue());
if (vtmode == VTMode.UNKNOWN) {
- updateState(CHANNELS_VARIOTRACK.get(registerNumber), UnDefType.UNDEF);
+ internalUpdateState(CHANNELS_VARIOTRACK.get(registerNumber), UnDefType.UNDEF);
} else {
- updateState(CHANNELS_VARIOTRACK.get(registerNumber), new StringType(vtmode.name()));
+ internalUpdateState(CHANNELS_VARIOTRACK.get(registerNumber), new StringType(vtmode.name()));
}
break;
case CHANNEL_STATE_VARIOTRACK:
OnOffType vtstate = StuderParser.getStateByCode(quantity.intValue());
- updateState(CHANNELS_VARIOTRACK.get(registerNumber), vtstate);
+ internalUpdateState(CHANNELS_VARIOTRACK.get(registerNumber), vtstate);
break;
default:
- updateState(CHANNELS_VARIOTRACK.get(registerNumber),
- new QuantityType<>(quantity, UNIT_CHANNELS_VARIOTRACK.get(registerNumber)));
+ Unit<?> unit = UNIT_CHANNELS_VARIOTRACK.get(registerNumber);
+ if (unit != null) {
+ internalUpdateState(CHANNELS_VARIOTRACK.get(registerNumber), new QuantityType<>(quantity, unit));
+ }
}
}
case CHANNEL_OPERATING_STATE:
ModeXtender mode = StuderParser.getModeXtenderByCode(quantity.intValue());
if (mode == ModeXtender.UNKNOWN) {
- updateState(CHANNELS_XTENDER.get(registerNumber), UnDefType.UNDEF);
+ internalUpdateState(CHANNELS_XTENDER.get(registerNumber), UnDefType.UNDEF);
} else {
- updateState(CHANNELS_XTENDER.get(registerNumber), new StringType(mode.name()));
+ internalUpdateState(CHANNELS_XTENDER.get(registerNumber), new StringType(mode.name()));
}
break;
case CHANNEL_STATE_INVERTER:
OnOffType xtstate = StuderParser.getStateByCode(quantity.intValue());
- updateState(CHANNELS_XTENDER.get(registerNumber), xtstate);
+ internalUpdateState(CHANNELS_XTENDER.get(registerNumber), xtstate);
break;
default:
- updateState(CHANNELS_XTENDER.get(registerNumber),
- new QuantityType<>(quantity, UNIT_CHANNELS_XTENDER.get(registerNumber)));
+ Unit<?> unit = UNIT_CHANNELS_XTENDER.get(registerNumber);
+ if (unit != null) {
+ internalUpdateState(CHANNELS_XTENDER.get(registerNumber), new QuantityType<>(quantity, unit));
+ }
}
}
updateStatus(ThingStatus.ONLINE);
}
}
+
+ protected void internalUpdateState(@Nullable String channelUID, @Nullable State state) {
+ if (channelUID != null && state != null) {
+ super.updateState(channelUID, state);
+ }
+ }
}
import org.openhab.core.config.discovery.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.library.types.DecimalType;
+import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID;
import org.openhab.io.transport.modbus.AsyncModbusFailure;
import org.openhab.io.transport.modbus.ModbusBitUtilities;
return;
}
- ThingUID thingUID = new ThingUID(SUPPORTED_THING_TYPES_UIDS.get(block.moduleID), handler.getUID(),
- Integer.toString(block.address));
+ ThingTypeUID thingTypeUID = SUPPORTED_THING_TYPES_UIDS.get(block.moduleID);
+ if (thingTypeUID == null) {
+ logger.warn("Found model block but no corresponding thing type UID present: {}", block.moduleID);
+ return;
+ }
+ ThingUID thingUID = new ThingUID(thingTypeUID, handler.getUID(), Integer.toString(block.address));
Map<String, Object> properties = new HashMap<>();
properties.put(PROPERTY_VENDOR, commonBlock.manufacturer);
}
try {
ModelBlock block = new ModelBlock();
- block.address = (int) Double.parseDouble(thing.getProperties().get(PROPERTY_BLOCK_ADDRESS));
- block.length = (int) Double.parseDouble(thing.getProperties().get(PROPERTY_BLOCK_LENGTH));
+ block.address = (int) Double.parseDouble(thing.getProperties().getOrDefault(PROPERTY_BLOCK_ADDRESS, ""));
+ block.length = (int) Double.parseDouble(thing.getProperties().getOrDefault(PROPERTY_BLOCK_LENGTH, ""));
return block;
} catch (NumberFormatException ex) {
logger.debug("Could not parse address and length properties, error: {}", ex.getMessage());
}
if (command instanceof RefreshType) {
- updateChannelState(zone, channelType, zoneDataMap.get(zone.getZoneId()));
+ MonopriceAudioZoneDTO zoneDTO = zoneDataMap.get(zone.getZoneId());
+ if (zoneDTO != null) {
+ updateChannelState(zone, channelType, zoneDTO);
+ } else {
+ logger.info("Could not execute REFRESH command for zone {}: null", zone.getZoneId());
+ }
return;
}
case MonopriceAudioConnector.KEY_ZONE_UPDATE:
String zoneId = updateData.substring(0, 2);
-
- if (MonopriceAudioZone.VALID_ZONE_IDS.contains(zoneId)) {
+ MonopriceAudioZoneDTO zoneDTO = zoneDataMap.get(zoneId);
+ if (MonopriceAudioZone.VALID_ZONE_IDS.contains(zoneId) && zoneDTO != null) {
MonopriceAudioZone targetZone = MonopriceAudioZone.fromZoneId(zoneId);
- processZoneUpdate(targetZone, zoneDataMap.get(zoneId), updateData);
+ processZoneUpdate(targetZone, zoneDTO, updateData);
} else {
- logger.warn("invalid event: {} for key: {}", evt.getValue(), key);
+ logger.warn("invalid event: {} for key: {} or zone data null", evt.getValue(), key);
}
break;
default:
}
protected boolean checkConditions(BigDecimal newValue, DecimalType oldvalue) {
+ BigDecimal min = this.min;
if (min != null && newValue.compareTo(min) == -1) {
logger.trace("Number not accepted as it is below the configured minimum");
return false;
}
+ BigDecimal max = this.max;
if (max != null && newValue.compareTo(max) == 1) {
logger.trace("Number not accepted as it is above the configured maximum");
return false;
}
}
- public static boolean checkRequiredFirmware(String modelId, String currentFirmwareVersion) {
+ public static boolean checkRequiredFirmware(@Nullable String modelId, @Nullable String currentFirmwareVersion) {
+ if (modelId == null || currentFirmwareVersion == null) {
+ return false;
+ }
int[] currentVer = getFirmwareVersionNumbers(currentFirmwareVersion);
int[] requiredVer = getFirmwareVersionNumbers(
setDeviceType(config.deviceType);
try {
+ Map<String, String> properties = getThing().getProperties();
if (StringUtils.isEmpty(getAddress()) || StringUtils.isEmpty(String.valueOf(getPort()))) {
logger.warn("No IP address and port configured for the Nanoleaf controller");
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING,
"@text/error.nanoleaf.controller.noIp");
stopAllJobs();
- } else if (!StringUtils.isEmpty(getThing().getProperties().get(Thing.PROPERTY_FIRMWARE_VERSION))
- && !OpenAPIUtils.checkRequiredFirmware(getThing().getProperties().get(Thing.PROPERTY_MODEL_ID),
- getThing().getProperties().get(Thing.PROPERTY_FIRMWARE_VERSION))) {
+ } else if (!StringUtils.isEmpty(properties.get(Thing.PROPERTY_FIRMWARE_VERSION))
+ && !OpenAPIUtils.checkRequiredFirmware(properties.get(Thing.PROPERTY_MODEL_ID),
+ properties.get(Thing.PROPERTY_FIRMWARE_VERSION))) {
logger.warn("Nanoleaf controller firmware is too old: {}. Must be equal or higher than {}",
- getThing().getProperties().get(Thing.PROPERTY_FIRMWARE_VERSION), API_MIN_FW_VER_LIGHTPANELS);
+ properties.get(Thing.PROPERTY_FIRMWARE_VERSION), API_MIN_FW_VER_LIGHTPANELS);
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
"@text/error.nanoleaf.controller.incompatibleFirmware");
stopAllJobs();
* @param httpCode the http code
* @param msg the msg
*/
- HttpResponse(int httpCode, String msg) {
+ HttpResponse(int httpCode, @Nullable String msg) {
httpStatus = httpCode;
- httpReason = msg;
+ httpReason = msg != null ? msg : "";
contents = null;
}
if (bridgeStatus == ThingStatus.ONLINE) {
config = getThing().getConfiguration();
- radioHelper = thing.getProperties().containsKey(PROPERTY_SIGNAL_LEVELS)
- ? new RadioHelper(thing.getProperties().get(PROPERTY_SIGNAL_LEVELS))
- : null;
- batteryHelper = thing.getProperties().containsKey(PROPERTY_BATTERY_LEVELS)
- ? new BatteryHelper(thing.getProperties().get(PROPERTY_BATTERY_LEVELS))
- : null;
+ String signalLevel = thing.getProperties().get(PROPERTY_SIGNAL_LEVELS);
+ radioHelper = signalLevel != null ? new RadioHelper(signalLevel) : null;
+ String batteryLevel = thing.getProperties().get(PROPERTY_BATTERY_LEVELS);
+ batteryHelper = batteryLevel != null ? new BatteryHelper(batteryLevel) : null;
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, "Pending parent object initialization");
initializeThing();
public final String getMessage() {
Exception err = error;
+ String errMsg = err == null ? err.getMessage() : null;
String msg = getHttpCode().getMessage();
- if (err != null && err.getMessage() != null && !err.getMessage().isEmpty()) {
- return err.getMessage();
+ if (errMsg != null && !errMsg.isEmpty()) {
+ return errMsg;
} else if (msg != null && !msg.isEmpty()) {
return msg;
}
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
+import java.util.function.Consumer;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
}
}
+ private void setIfPresent(Map<String, String> data, String key, Consumer<String> consumer) {
+ String val = data.get(key);
+ if (val != null) {
+ consumer.accept(val);
+ }
+ }
+
private synchronized void cmdSystemInfo(Map<String, String> data) {
logger.debug("Niko Home Control: systeminfo");
- if (data.containsKey("swversion")) {
- systemInfo.setSwVersion(data.get("swversion"));
- }
- if (data.containsKey("api")) {
- systemInfo.setApi(data.get("api"));
- }
- if (data.containsKey("time")) {
- systemInfo.setTime(data.get("time"));
- }
- if (data.containsKey("language")) {
- systemInfo.setLanguage(data.get("language"));
- }
- if (data.containsKey("currency")) {
- systemInfo.setCurrency(data.get("currency"));
- }
- if (data.containsKey("units")) {
- systemInfo.setUnits(data.get("units"));
- }
- if (data.containsKey("DST")) {
- systemInfo.setDst(data.get("DST"));
- }
- if (data.containsKey("TZ")) {
- systemInfo.setTz(data.get("TZ"));
- }
- if (data.containsKey("lastenergyerase")) {
- systemInfo.setLastEnergyErase(data.get("lastenergyerase"));
- }
- if (data.containsKey("lastconfig")) {
- systemInfo.setLastConfig(data.get("lastconfig"));
- }
+ setIfPresent(data, "swversion", systemInfo::setSwVersion);
+ setIfPresent(data, "api", systemInfo::setApi);
+ setIfPresent(data, "time", systemInfo::setTime);
+ setIfPresent(data, "language", systemInfo::setLanguage);
+ setIfPresent(data, "currency", systemInfo::setCurrency);
+ setIfPresent(data, "units", systemInfo::setUnits);
+ setIfPresent(data, "DST", systemInfo::setDst);
+ setIfPresent(data, "TZ", systemInfo::setTz);
+ setIfPresent(data, "lastenergyerase", systemInfo::setLastEnergyErase);
+ setIfPresent(data, "lastconfig", systemInfo::setLastConfig);
}
/**
}
private void cmdStartEvents(Map<String, String> data) {
- int errorCode = Integer.parseInt(data.get("error"));
-
- if (errorCode == 0) {
- logger.debug("Niko Home Control: start events success");
+ String errorCodeString = data.get("error");
+ if (errorCodeString != null) {
+ int errorCode = Integer.parseInt(errorCodeString);
+ if (errorCode == 0) {
+ logger.debug("Niko Home Control: start events success");
+ } else {
+ logger.warn("Niko Home Control: error code {} returned on start events", errorCode);
+ }
} else {
- logger.warn("Niko Home Control: error code {} returned on start events", errorCode);
+ logger.warn("Niko Home Control: could not determine error code returned on start events");
}
}
for (Map<String, String> action : data) {
String id = action.get("id");
- int state = Integer.parseInt(action.get("value1"));
+ String value1 = action.get("value1");
+ int state = ((value1 == null) || value1.isEmpty() ? 0 : Integer.parseInt(value1));
String value2 = action.get("value2");
int closeTime = ((value2 == null) || value2.isEmpty() ? 0 : Integer.parseInt(value2));
String value3 = action.get("value3");
}
}
+ private int parseIntOrThrow(@Nullable String str) throws IllegalArgumentException {
+ if (str == null)
+ throw new IllegalArgumentException("String is null");
+ try {
+ return Integer.parseInt(str);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException(e);
+ }
+ }
+
private void cmdListThermostat(List<Map<String, String>> data) {
logger.debug("Niko Home Control: list thermostats");
for (Map<String, String> thermostat : data) {
-
- String id = thermostat.get("id");
- int measured = Integer.parseInt(thermostat.get("measured"));
- int setpoint = Integer.parseInt(thermostat.get("setpoint"));
- int mode = Integer.parseInt(thermostat.get("mode"));
- int overrule = Integer.parseInt(thermostat.get("overrule"));
- // overruletime received in "HH:MM" format
- String[] overruletimeStrings = thermostat.get("overruletime").split(":");
- int overruletime = 0;
- if (overruletimeStrings.length == 2) {
- overruletime = Integer.parseInt(overruletimeStrings[0]) * 60 + Integer.parseInt(overruletimeStrings[1]);
- }
- int ecosave = Integer.parseInt(thermostat.get("ecosave"));
-
- // For parity with NHC II, assume heating/cooling if thermostat is on and setpoint different from measured
- int demand = (mode != 3) ? (setpoint > measured ? 1 : (setpoint < measured ? -1 : 0)) : 0;
-
- if (!thermostats.containsKey(id)) {
- // Initial instantiation of NhcThermostat class for thermostat object
- String name = thermostat.get("name");
- String locationId = thermostat.get("location");
- String location = "";
- if (!locationId.isEmpty()) {
- location = locations.get(locationId).getName();
+ try {
+ String id = thermostat.get("id");
+ int measured = parseIntOrThrow(thermostat.get("measured"));
+ int setpoint = parseIntOrThrow(thermostat.get("setpoint"));
+ int mode = parseIntOrThrow(thermostat.get("mode"));
+ int overrule = parseIntOrThrow(thermostat.get("overrule"));
+ // overruletime received in "HH:MM" format
+ String[] overruletimeStrings = thermostat.getOrDefault("overruletime", "").split(":");
+ int overruletime = 0;
+ if (overruletimeStrings.length == 2) {
+ overruletime = Integer.parseInt(overruletimeStrings[0]) * 60
+ + Integer.parseInt(overruletimeStrings[1]);
}
- NhcThermostat nhcThermostat = new NhcThermostat1(id, name, location, this);
- nhcThermostat.updateState(measured, setpoint, mode, overrule, overruletime, ecosave, demand);
- thermostats.put(id, nhcThermostat);
- } else {
- // Thermostat object already exists, so only update state.
- // If we would re-instantiate thermostat, we would lose pointer back from thermostat to thing handler
- // that was set in thing handler initialize().
- thermostats.get(id).updateState(measured, setpoint, mode, overrule, overruletime, ecosave, demand);
+ int ecosave = parseIntOrThrow(thermostat.get("ecosave"));
+
+ // For parity with NHC II, assume heating/cooling if thermostat is on and setpoint different from
+ // measured
+ int demand = (mode != 3) ? (setpoint > measured ? 1 : (setpoint < measured ? -1 : 0)) : 0;
+
+ NhcThermostat t = thermostats.computeIfAbsent(id, i -> {
+ // Initial instantiation of NhcThermostat class for thermostat object
+ String name = thermostat.get("name");
+ String locationId = thermostat.get("location");
+ String location = "";
+ if (!locationId.isEmpty()) {
+ location = locations.get(locationId).getName();
+ }
+ if (name != null) {
+ return new NhcThermostat1(i, name, location, this);
+ }
+ throw new IllegalArgumentException();
+ });
+ if (t != null) {
+ t.updateState(measured, setpoint, mode, overrule, overruletime, ecosave, demand);
+ }
+ } catch (IllegalArgumentException e) {
+ // do nothing
}
}
}
private void cmdExecuteActions(Map<String, String> data) {
- int errorCode = Integer.parseInt(data.get("error"));
- if (errorCode == 0) {
- logger.debug("Niko Home Control: execute action success");
- } else {
- logger.warn("Niko Home Control: error code {} returned on command execution", errorCode);
+ try {
+ int errorCode = parseIntOrThrow(data.get("error"));
+ if (errorCode == 0) {
+ logger.debug("Niko Home Control: execute action success");
+ } else {
+ logger.warn("Niko Home Control: error code {} returned on command execution", errorCode);
+ }
+ } catch (IllegalArgumentException e) {
+ logger.warn("Niko Home Control: no error code returned on command execution");
}
}
private void cmdExecuteThermostat(Map<String, String> data) {
- int errorCode = Integer.parseInt(data.get("error"));
- if (errorCode == 0) {
- logger.debug("Niko Home Control: execute thermostats success");
- } else {
- logger.warn("Niko Home Control: error code {} returned on command execution", errorCode);
+ try {
+ int errorCode = parseIntOrThrow(data.get("error"));
+ if (errorCode == 0) {
+ logger.debug("Niko Home Control: execute thermostats success");
+ } else {
+ logger.warn("Niko Home Control: error code {} returned on command execution", errorCode);
+ }
+ } catch (IllegalArgumentException e) {
+ logger.warn("Niko Home Control: no error code returned on command execution");
}
}
private void eventListActions(List<Map<String, String>> data) {
for (Map<String, String> action : data) {
String id = action.get("id");
- if (!actions.containsKey(id)) {
+ if (id == null || !actions.containsKey(id)) {
logger.warn("Niko Home Control: action in controller not known {}", id);
return;
}
- int state = Integer.parseInt(action.get("value1"));
- logger.debug("Niko Home Control: event execute action {} with state {}", id, state);
- actions.get(id).setState(state);
+ String stateString = action.get("value1");
+ if (stateString != null) {
+ int state = Integer.parseInt(stateString);
+ logger.debug("Niko Home Control: event execute action {} with state {}", id, state);
+ NhcAction action1 = actions.get(id);
+ if (action1 != null) {
+ action1.setState(state);
+ }
+ }
}
}
private void eventListThermostat(List<Map<String, String>> data) {
for (Map<String, String> thermostat : data) {
- String id = thermostat.get("id");
- if (!thermostats.containsKey(id)) {
- logger.warn("Niko Home Control: thermostat in controller not known {}", id);
- return;
- }
+ try {
+ String id = thermostat.get("id");
+ if (!thermostats.containsKey(id)) {
+ logger.warn("Niko Home Control: thermostat in controller not known {}", id);
+ return;
+ }
- int measured = Integer.parseInt(thermostat.get("measured"));
- int setpoint = Integer.parseInt(thermostat.get("setpoint"));
- int mode = Integer.parseInt(thermostat.get("mode"));
- int overrule = Integer.parseInt(thermostat.get("overrule"));
- // overruletime received in "HH:MM" format
- String[] overruletimeStrings = thermostat.get("overruletime").split(":");
- int overruletime = 0;
- if (overruletimeStrings.length == 2) {
- overruletime = Integer.parseInt(overruletimeStrings[0]) * 60 + Integer.parseInt(overruletimeStrings[1]);
- }
- int ecosave = Integer.parseInt(thermostat.get("ecosave"));
+ int measured = parseIntOrThrow(thermostat.get("measured"));
+ int setpoint = parseIntOrThrow(thermostat.get("setpoint"));
+ int mode = parseIntOrThrow(thermostat.get("mode"));
+ int overrule = parseIntOrThrow(thermostat.get("overrule"));
+ // overruletime received in "HH:MM" format
+ String[] overruletimeStrings = thermostat.getOrDefault("overruletime", "").split(":");
+ int overruletime = 0;
+ if (overruletimeStrings.length == 2) {
+ overruletime = Integer.parseInt(overruletimeStrings[0]) * 60
+ + Integer.parseInt(overruletimeStrings[1]);
+ }
+ int ecosave = parseIntOrThrow(thermostat.get("ecosave"));
- int demand = (mode != 3) ? (setpoint > measured ? 1 : (setpoint < measured ? -1 : 0)) : 0;
+ int demand = (mode != 3) ? (setpoint > measured ? 1 : (setpoint < measured ? -1 : 0)) : 0;
- logger.debug(
- "Niko Home Control: event execute thermostat {} with measured {}, setpoint {}, mode {}, overrule {}, overruletime {}, ecosave {}, demand {}",
- id, measured, setpoint, mode, overrule, overruletime, ecosave, demand);
- thermostats.get(id).updateState(measured, setpoint, mode, overrule, overruletime, ecosave, demand);
+ logger.debug(
+ "Niko Home Control: event execute thermostat {} with measured {}, setpoint {}, mode {}, overrule {}, overruletime {}, ecosave {}, demand {}",
+ id, measured, setpoint, mode, overrule, overruletime, ecosave, demand);
+ NhcThermostat t = thermostats.get(id);
+ if (t != null) {
+ t.updateState(measured, setpoint, mode, overrule, overruletime, ecosave, demand);
+ }
+ } catch (IllegalArgumentException e) {
+ // do nothing
+ }
}
}
private void eventGetAlarms(Map<String, String> data) {
- int type = Integer.parseInt(data.get("type"));
String alarmText = data.get("text");
- switch (type) {
- case 0:
+ switch (data.getOrDefault("type", "")) {
+ case "0":
logger.debug("Niko Home Control: alarm - {}", alarmText);
handler.alarmEvent(alarmText);
break;
- case 1:
+ case "1":
logger.debug("Niko Home Control: notice - {}", alarmText);
handler.noticeEvent(alarmText);
break;
default:
- logger.debug("Niko Home Control: unexpected message type {}", type);
+ logger.debug("Niko Home Control: unexpected message type {}", data.get("type"));
}
}
}
if (dimmerProperty.isPresent()) {
- action.setState(Integer.parseInt(dimmerProperty.get().brightness));
- logger.debug("Niko Home Control: setting action {} internally to {}", action.getId(),
- dimmerProperty.get().brightness);
+ String brightness = dimmerProperty.get().brightness;
+ if (brightness != null) {
+ action.setState(Integer.parseInt(brightness));
+ logger.debug("Niko Home Control: setting action {} internally to {}", action.getId(),
+ dimmerProperty.get().brightness);
+ }
}
}
Optional<Boolean> overruleActiveProperty = deviceProperties.stream().map(p -> p.overruleActive)
.filter(Objects::nonNull).map(t -> Boolean.parseBoolean(t)).findFirst();
Optional<Integer> overruleSetpointProperty = deviceProperties.stream().map(p -> p.overruleSetpoint)
- .filter(s -> !((s == null) || s.isEmpty())).map(t -> Math.round(Float.parseFloat(t) * 10)).findFirst();
+ .map(s -> (!((s == null) || s.isEmpty())) ? Math.round(Float.parseFloat(s) * 10) : null)
+ .filter(Objects::nonNull).findFirst();
Optional<Integer> overruleTimeProperty = deviceProperties.stream().map(p -> p.overruleTime)
- .filter(s -> !((s == null) || s.isEmpty())).map(t -> Math.round(Float.parseFloat(t))).findFirst();
+ .map(s -> (!((s == null) || s.isEmpty())) ? Math.round(Float.parseFloat(s)) : null)
+ .filter(Objects::nonNull).findFirst();
Optional<Integer> setpointTemperatureProperty = deviceProperties.stream().map(p -> p.setpointTemperature)
- .filter(s -> !((s == null) || s.isEmpty())).map(t -> Math.round(Float.parseFloat(t) * 10)).findFirst();
- Optional<Boolean> ecoSaveProperty = deviceProperties.stream().map(p -> p.ecoSave).filter(Objects::nonNull)
- .map(t -> Boolean.parseBoolean(t)).findFirst();
+ .map(s -> (!((s == null) || s.isEmpty())) ? Math.round(Float.parseFloat(s) * 10) : null)
+ .filter(Objects::nonNull).findFirst();
+ Optional<Boolean> ecoSaveProperty = deviceProperties.stream().map(p -> p.ecoSave)
+ .map(s -> s != null ? Boolean.parseBoolean(s) : null).filter(Objects::nonNull).findFirst();
Optional<Integer> ambientTemperatureProperty = deviceProperties.stream().map(p -> p.ambientTemperature)
- .filter(s -> !(s == null || s.isEmpty())).map(t -> Math.round(Float.parseFloat(t) * 10)).findFirst();
+ .map(s -> (!((s == null) || s.isEmpty())) ? Math.round(Float.parseFloat(s) * 10) : null)
+ .filter(Objects::nonNull).findFirst();
Optional<@Nullable String> demandProperty = deviceProperties.stream().map(p -> p.demand)
.filter(Objects::nonNull).findFirst();
Optional<@Nullable String> operationModeProperty = deviceProperties.stream().map(p -> p.operationMode)
updateState(BindingConstants.CHANNEL_OWD5_GROUPNAME, StringType.valueOf(thermostat.groupName));
}
- private String getRegulationMode(int regulationMode) {
+ private @Nullable String getRegulationMode(int regulationMode) {
return REGULATION_MODES.get(regulationMode);
}
* - characters are case-insensitive
* - hubs ("1F.xxxxxxxxxxxx/aux/") may be repeated
*/
- public SensorId(String fullPath) {
+ public SensorId(@Nullable String fullPath) {
+ if (fullPath == null) {
+ throw new IllegalArgumentException();
+ }
Matcher matcher = SENSOR_ID_PATTERN.matcher(fullPath);
if (matcher.matches() && matcher.groupCount() == 2) {
path = matcher.group(1) == null ? "" : matcher.group(1);
* @return ThingTypeUID if mapping successful
*/
public ThingTypeUID getThingTypeUID() throws OwException {
- if (THING_TYPE_MAP.containsKey(sensorType)) {
- thingTypeUID = THING_TYPE_MAP.get(sensorType);
+ ThingTypeUID thingTypeUID = THING_TYPE_MAP.get(sensorType);
+ if (thingTypeUID != null) {
return thingTypeUID;
} else {
throw new OwException(sensorType + " cannot be mapped to thing type");
return;
}
- hwRevision = Integer.valueOf(properties.get(PROPERTY_HW_REVISION));
+ hwRevision = Integer.valueOf(properties.getOrDefault(PROPERTY_HW_REVISION, "0"));
- sensors.add(new DS2438(sensorId, this));
- sensors.add(new DS18x20(new SensorId(properties.get(PROPERTY_DS18B20)), this));
- if (THING_TYPE_AMS.equals(thingType)) {
- sensors.add(new DS2438(new SensorId(properties.get(PROPERTY_DS2438)), this));
- sensors.add(new DS2406_DS2413(new SensorId(properties.get(PROPERTY_DS2413)), this));
- digitalRefreshInterval = configuration.digitalRefresh * 1000;
- digitalLastRefresh = 0;
+ try {
+ sensors.add(new DS2438(sensorId, this));
+ sensors.add(new DS18x20(new SensorId(properties.get(PROPERTY_DS18B20)), this));
+ if (THING_TYPE_AMS.equals(thingType)) {
+ sensors.add(new DS2438(new SensorId(properties.get(PROPERTY_DS2438)), this));
+ sensors.add(new DS2406_DS2413(new SensorId(properties.get(PROPERTY_DS2413)), this));
+ digitalRefreshInterval = configuration.digitalRefresh * 1000;
+ digitalLastRefresh = 0;
+ }
+ } catch (IllegalArgumentException e) {
+ updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "properties invalid");
}
-
scheduler.execute(() -> {
configureThingChannels();
});
package org.openhab.binding.openweathermap.internal.connection;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
/**
* The {@link OpenWeatherMapCommunicationException} is a communication exception for the connections to OpenWeatherMap
*
* @param message Detail message
*/
- public OpenWeatherMapCommunicationException(String message) {
+ public OpenWeatherMapCommunicationException(@Nullable String message) {
super(message);
}
*
* @param cause The cause
*/
- public OpenWeatherMapCommunicationException(Throwable cause) {
+ public OpenWeatherMapCommunicationException(@Nullable Throwable cause) {
super(cause);
}
* @param message Detail message
* @param cause The cause
*/
- public OpenWeatherMapCommunicationException(String message, Throwable cause) {
+ public OpenWeatherMapCommunicationException(@Nullable String message, @Nullable Throwable cause) {
super(message, cause);
}
}
package org.openhab.binding.openweathermap.internal.connection;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
/**
* The {@link OpenWeatherMapConfigurationException} is a configuration exception for the connections to OpenWeatherMap
*
* @param message Detail message
*/
- public OpenWeatherMapConfigurationException(String message) {
+ public OpenWeatherMapConfigurationException(@Nullable String message) {
super(message);
}
*
* @param cause The cause
*/
- public OpenWeatherMapConfigurationException(Throwable cause) {
+ public OpenWeatherMapConfigurationException(@Nullable Throwable cause) {
super(cause);
}
* @param message Detail message
* @param cause The cause
*/
- public OpenWeatherMapConfigurationException(String message, Throwable cause) {
+ public OpenWeatherMapConfigurationException(@Nullable String message, @Nullable Throwable cause) {
super(message, cause);
}
}
.collect(joining("&", url + "?", ""));
}
- private String encodeParam(String value) {
+ private String encodeParam(@Nullable String value) {
+ if (value == null) {
+ return "";
+ }
try {
return URLEncoder.encode(value, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
Instant now = Instant.now();
Socket socket = this.socket;
boolean connectionTooOld = false;
- if (this.socketCreatedOn != null) {
- long millisecondsSinceLastConnect = Duration.between(this.socketCreatedOn, now).toMillis();
+ Instant socketCreatedOn = this.socketCreatedOn;
+ if (socketCreatedOn != null) {
+ long millisecondsSinceLastConnect = Duration.between(socketCreatedOn, now).toMillis();
// according to the PJLink specification, the device closes the connection after 30s idle (without notice),
// so to be on the safe side we do not reuse sockets older than 20s
connectionTooOld = millisecondsSinceLastConnect > 20 * 1000;
}
protected static String getBlockFromChannel(final @Nullable Channel channel) {
- return channel == null ? NOT_SUPPORTED : channel.getProperties().get(BLOCK_PROPERTY);
+ if (channel == null) {
+ return NOT_SUPPORTED;
+ }
+ String block = channel.getProperties().get(BLOCK_PROPERTY);
+ return block == null ? NOT_SUPPORTED : block;
}
}
}
protected boolean recentlySendConfigurationUpdate() {
+ LocalDateTime lastConfigurationUpdateSend = this.lastConfigurationUpdateSend;
return lastConfigurationUpdateSend != null
&& LocalDateTime.now().minus(Duration.ofMillis(500)).isBefore(lastConfigurationUpdateSend);
}
source.setMuted(properties.get("muted").equalsIgnoreCase("yes"));
}
if (properties.containsKey("volume")) {
- source.setVolume(Integer.valueOf(parseVolume(properties.get("volume"))));
+ source.setVolume(parseVolume(properties.get("volume")));
}
- if (properties.containsKey("monitor_of")) {
- source.setMonitorOf(client.getSink(Integer.valueOf(properties.get("monitor_of"))));
+ String monitorOf = properties.get("monitor_of");
+ if (monitorOf != null) {
+ source.setMonitorOf(client.getSink(Integer.valueOf(monitorOf)));
}
sources.add(source);
}
* @return a valid URL for the thermostat's JSON interface
*/
private String buildRequestURL(String resource) {
+ String hostName = this.hostName;
+ if (hostName == null) {
+ throw new IllegalStateException("hostname must not be null");
+ }
String urlStr = URL.replace("%hostName%", hostName);
urlStr = urlStr.replace("%resource%", resource);
package org.openhab.binding.remoteopenhab.internal.exceptions;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
/**
* Exceptions thrown by this binding.
@SuppressWarnings("serial")
public class RemoteopenhabException extends Exception {
- public RemoteopenhabException(String message) {
+ public RemoteopenhabException(@Nullable String message) {
super(message);
}
- public RemoteopenhabException(String message, Throwable cause) {
+ public RemoteopenhabException(@Nullable String message, @Nullable Throwable cause) {
super(message, cause);
}
- public RemoteopenhabException(Throwable cause) {
+ public RemoteopenhabException(@Nullable Throwable cause) {
super(cause);
}
}
values.put(now, newValue);
Optional<Long> eldestKey = values.keySet().stream().filter(key -> key < now - eldestAge).findFirst();
if (eldestKey.isPresent()) {
- agedValue = Optional.of(values.get(eldestKey.get()));
+ agedValue = Optional.ofNullable(values.get(eldestKey.get()));
values.entrySet().removeIf(map -> map.getKey() <= eldestKey.get());
}
}
try {
newValue = DataConverters.convertCommandToIntValue(command, 0, 100,
- Integer.valueOf(stateMap.get("CurrentVolume")));
+ Integer.valueOf(stateMap.getOrDefault("CurrentVolume", "")));
} catch (NumberFormatException e) {
throw new NumberFormatException("Command '" + command + "' not supported");
}
try {
newValue = DataConverters.convertCommandToIntValue(command, 0, 100,
- Integer.valueOf(stateMap.get("CurrentBrightness")));
+ Integer.valueOf(stateMap.getOrDefault("CurrentBrightness", "")));
} catch (NumberFormatException e) {
throw new NumberFormatException("Command '" + command + "' not supported");
}
try {
newValue = DataConverters.convertCommandToIntValue(command, 0, 100,
- Integer.valueOf(stateMap.get("CurrentContrast")));
+ Integer.valueOf(stateMap.getOrDefault("CurrentContrast", "")));
} catch (NumberFormatException e) {
throw new NumberFormatException("Command '" + command + "' not supported");
}
try {
newValue = DataConverters.convertCommandToIntValue(command, 0, 100,
- Integer.valueOf(stateMap.get("CurrentSharpness")));
+ Integer.valueOf(stateMap.getOrDefault("CurrentSharpness", "")));
} catch (NumberFormatException e) {
throw new NumberFormatException("Command '" + command + "' not supported");
}
try {
newValue = DataConverters.convertCommandToIntValue(command, 0, 4,
- Integer.valueOf(stateMap.get("CurrentColorTemperature")));
+ Integer.valueOf(stateMap.getOrDefault("CurrentColorTemperature", "")));
} catch (NumberFormatException e) {
throw new NumberFormatException("Command '" + command + "' not supported");
}
* @param serviceName Name of the service
* @return Class of the service
*/
- public static Class<? extends SamsungTvService> getClassByServiceName(String serviceName) {
+ public static @Nullable Class<? extends SamsungTvService> getClassByServiceName(String serviceName) {
return SERVICEMAP.get(serviceName);
}
}
logger.debug("satel.readEvent called with input: index={}", index);
Map<String, Object> result = new HashMap<>();
+ SatelEventLogHandler handler = this.handler;
if (handler != null) {
handler.readEvent(index == null ? -1 : index.intValue()).ifPresent(event -> {
result.put("index", event.getIndex());
if (bridge != null) {
final ThingHandler handler = bridge.getHandler();
if (handler != null && handler instanceof SatelBridgeHandler) {
+ ((SatelBridgeHandler) handler).addEventListener(this);
this.bridgeHandler = (SatelBridgeHandler) handler;
- this.bridgeHandler.addEventListener(this);
}
if (bridge.getStatus() == ThingStatus.ONLINE) {
updateStatus(ThingStatus.ONLINE);
private synchronized void disconnect(@Nullable String reason) {
// remove all pending commands from the queue
// notifying about send failure
- while (!this.sendQueue.isEmpty()) {
- SatelCommand cmd = this.sendQueue.poll();
+ SatelCommand cmd;
+ while ((cmd = this.sendQueue.poll()) != null) {
cmd.setState(State.FAILED);
}
final CommunicationChannel channel = this.channel;
}
private void startCommunication() {
- final Thread thread = this.thread;
+ Thread thread = this.thread;
if (thread != null && thread.isAlive()) {
logger.error("Start communication canceled: communication thread is still alive");
return;
}
// start new thread
- this.thread = new Thread(new Runnable() {
+ thread = new Thread(new Runnable() {
@Override
public void run() {
logger.debug("Communication thread started");
logger.debug("Communication thread stopped");
}
});
- this.thread.start();
+ thread.start();
+ this.thread = thread;
// if module is not initialized yet, send version command
if (!SatelModule.this.isInitialized()) {
SatelModule.this.sendCommand(new IntegraVersionCommand());
}
@Override
- public String getMessage() {
+ public @Nullable String getMessage() {
return isEmpty() ? "" : nonNullString(super.getMessage());
}
Double brightness = -1.0;
Double power = -1.0;
for (CoIotSensor update : allUpdates) {
- CoIotDescrSen d = fixDescription(sensorMap.get(update.id), blkMap);
+ CoIotDescrSen d = fixDescription(sensorMap.getOrDefault(update.id, new CoIotDescrSen()), blkMap);
if (!checkL.isEmpty() && !d.links.equals(checkL)) {
// continue until we find the correct one
continue;
}
// Check general mapping
- if (!deviceType.isEmpty() && THING_TYPE_MAPPING.containsKey(deviceType)) {
- return THING_TYPE_MAPPING.get(deviceType);
- }
- if (THING_TYPE_MAPPING.containsKey(type)) {
- return THING_TYPE_MAPPING.get(type);
+ if (!deviceType.isEmpty()) {
+ String str = THING_TYPE_MAPPING.get(deviceType);
+ if (str != null) {
+ return str;
+ }
}
- return THING_TYPE_SHELLYUNKNOWN_STR;
+
+ return THING_TYPE_MAPPING.getOrDefault(type, THING_TYPE_SHELLYUNKNOWN_STR);
}
}
}
public State getValue(String channelId) {
- if (channelData.containsKey(channelId)) {
- return channelData.get(channelId);
- }
- return UnDefType.NULL;
+ return channelData.getOrDefault(channelId, UnDefType.NULL);
}
public void resetChannel(String channelId) {
@SerializedName("presentPriority")
protected int presentPriority;
- private @Nullable String @Nullable [] enumVals;
+ private String @Nullable [] enumVals;
private boolean enumParsed = false;
protected boolean isEnum = false;
@Override
public int asInt() {
try {
- return Integer.parseInt(value);
- } catch (Exception e) {
- return UNDEFINED_VALUE;
+ String value = this.value;
+ if (value != null) {
+ return Integer.parseInt(value);
+ }
+ } catch (NumberFormatException e) {
+ // default value
}
+ return UNDEFINED_VALUE;
}
@Override
boolean shouldNegateState = NegateHandler.shouldNegateState(negateProperty, channelId -> {
Channel negateChannel = thing.getChannel(channelId);
if (negateChannel != null) {
- return device.getMeterValue(
- negateChannel.getProperties().get(SmartMeterBindingConstants.CHANNEL_PROPERTY_OBIS));
+ String property = negateChannel.getProperties().get(SmartMeterBindingConstants.CHANNEL_PROPERTY_OBIS);
+ return property != null ? device.getMeterValue(property) : null;
}
return null;
});
return UnDefType.UNDEF;
}
- if ("Number".contentEquals(acceptedChannelType)) {
+ if (acceptedChannelType != null && "Number".contentEquals(acceptedChannelType)) {
if (deviceValue instanceof String) {
double d = Double.parseDouble((String) deviceValue);
d *= 3.6;
if (refresh) {
ArgumentCaptor<PDU> pduCaptor = ArgumentCaptor.forClass(PDU.class);
- verify(snmpService, atLeast(1)).send(pduCaptor.capture(), any(), eq(null), eq(thingHandler));
+ verify(snmpService, timeout(500).atLeast(1)).send(pduCaptor.capture(), any(), eq(null), eq(thingHandler));
Vector<? extends VariableBinding> variables = pduCaptor.getValue().getVariableBindings();
assertTrue(variables.stream().filter(v -> v.getOid().toDottedString().equals(TEST_OID)).findFirst()
.isPresent());
public final String getMessage() {
Code httpCode = this.httpCode;
Exception error = this.error;
- if (error != null && error.getMessage() != null && !error.getMessage().isEmpty()) {
- return error.getMessage();
+ if (error != null) {
+ String message = error.getMessage();
+ if (message != null && !message.isEmpty()) {
+ return message;
+ }
} else if (httpCode != null && httpCode.getMessage() != null && !httpCode.getMessage().isEmpty()) {
return httpCode.getMessage();
}
@Override
public void characters(char @Nullable [] ch, int start, int length) throws SAXException {
Element elt = element;
- if (elt == null) {
+ if (elt == null || ch == null) {
return;
}
switch (elt) {
@Override
public void characters(char @Nullable [] ch, int start, int length) throws SAXException {
Element elt = element;
- if (elt == null) {
+ if (elt == null || ch == null) {
return;
}
switch (elt) {
boolean finalIncludeLinkedZones = !"0".equals(includeLinkedZones);
try {
+ String id = this.id;
+ if (id == null) {
+ throw new NumberFormatException();
+ }
finalID = Integer.parseInt(id);
+ String volume = this.volume;
+ if (volume == null) {
+ throw new NumberFormatException();
+ }
finalVolume = Integer.parseInt(volume);
- } catch (Exception e) {
+ } catch (NumberFormatException e) {
LOGGER.debug("Error parsing Integer");
}
@Override
public void characters(char @Nullable [] ch, int start, int length) throws SAXException {
CurrentElement elt = currentElement;
- if (elt == null) {
+ if (elt == null || ch == null) {
return;
}
switch (elt) {
@Override
public void characters(char @Nullable [] ch, int start, int length) throws SAXException {
- if (getPresetName) {
+ if (getPresetName && ch != null) {
presetName = new String(ch, start, length);
}
}
@Override
public void characters(char @Nullable [] ch, int start, int length) throws SAXException {
- if (roomNameTag) {
+ if (roomNameTag && ch != null) {
roomName = new String(ch, start, length);
roomNameTag = false;
}
@Override
public void characters(char @Nullable [] ch, int start, int length) throws SAXException {
- if (modelNameTag) {
+ if (modelNameTag && ch != null) {
modelName = new String(ch, start, length);
modelNameTag = false;
}
}
try {
- result = Long.valueOf(resultInput.get(requestedKey));
+ String resultString = resultInput.get(requestedKey);
+ if (resultString == null) {
+ throw new NumberFormatException("Requested key is null.");
+ }
+ result = Long.valueOf(resultString);
} catch (NumberFormatException ex) {
logger.debug("Could not fetch {} result for type: {} and filter: {}. Using default value '0': {}",
requestedKey, entriesType, entriesFilter, ex.getMessage(), ex);
package org.openhab.binding.sonyprojector.internal;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
/**
* The {@link SonyProjectorException} class is used for any exception thrown by the binding
}
// Constructor that accepts a message
- public SonyProjectorException(String message) {
+ public SonyProjectorException(@Nullable String message) {
super(message);
}
}
}
}
} catch (ExecutionException e) {
- future.completeExceptionally(e.getCause());
+ Throwable cause = e.getCause();
+ if (cause != null) {
+ future.completeExceptionally(cause);
+ } else {
+ future.completeExceptionally(e);
+ }
} catch (RuntimeException | TimeoutException e) {
future.completeExceptionally(e);
} catch (InterruptedException e) {
@Override
public String getUser() {
- return thing.getProperties().get(PROPERTY_SPOTIFY_USER);
+ return thing.getProperties().getOrDefault(PROPERTY_SPOTIFY_USER, "");
}
@Override
// Some of the code below is not designed to handle REFRESH, only reply to channels where cached values exist
if (command == RefreshType.REFRESH) {
String channelID = channelUID.getId();
- if (stateMap.containsKey(channelID)) {
- updateState(channelID, stateMap.get(channelID));
+ State newState = stateMap.get(channelID);
+ if (newState != null) {
+ updateState(channelID, newState);
}
return;
}
return channelTypesByUID.get(channelTypeUID);
}
- public ChannelType getInternalChannelType(ChannelTypeUID channelTypeUID) {
+ public @Nullable ChannelType getInternalChannelType(ChannelTypeUID channelTypeUID) {
return channelTypesByUID.get(channelTypeUID);
}
@Override
public void handleComment(final char @Nullable [] buffer, final int offset, final int len, final int line,
final int col) throws ParseException {
- logger.debug("Unexpected comment in {}:{}: {}", line, col, new String(buffer, offset, len));
+ logger.debug("Unexpected comment in {}:{}: {}", line, col,
+ buffer == null ? "<null>" : new String(buffer, offset, len));
}
@Override
public void handleCDATASection(final char @Nullable [] buffer, final int offset, final int len, final int line,
final int col) throws ParseException {
- logger.debug("Unexpected CDATA in {}:{}: {}", line, col, new String(buffer, offset, len));
+ logger.debug("Unexpected CDATA in {}:{}: {}", line, col,
+ buffer == null ? "<null>" : new String(buffer, offset, len));
}
@Override
@Override
public void handleAutoCloseElement(final @Nullable String elementName, final int line, final int col)
throws ParseException {
- logger.debug("Unexpected AutoCloseElement in {}:{}: {}", line, col, elementName);
+ logger.debug("Unexpected AutoCloseElement in {}:{}: {}", line, col,
+ elementName == null ? "<null>" : elementName);
}
@Override
public void handleUnmatchedCloseElement(final @Nullable String elementName, final int line, final int col)
throws ParseException {
- logger.debug("Unexpected UnmatchedCloseElement in {}:{}: {}", line, col, elementName);
+ logger.debug("Unexpected UnmatchedCloseElement in {}:{}: {}", line, col,
+ elementName == null ? "<null>" : elementName);
}
@Override
@Override
public void handleComment(final char @Nullable [] buffer, final int offset, final int len, final int line,
final int col) throws ParseException {
- logger.debug("Unexpected comment in {}:{}: {}", line, col, new String(buffer, offset, len));
+ logger.debug("Unexpected comment in {}:{}: {}", line, col,
+ buffer == null ? "<null>" : new String(buffer, offset, len));
}
@Override
public void handleCDATASection(final char @Nullable [] buffer, final int offset, final int len, final int line,
final int col) throws ParseException {
- logger.debug("Unexpected CDATA in {}:{}: {}", line, col, new String(buffer, offset, len));
+ logger.debug("Unexpected CDATA in {}:{}: {}", line, col,
+ buffer == null ? "<null>" : new String(buffer, offset, len));
}
@Override
return replyIdToCallbackId.get(new ReplyKey(chatId, replyId));
}
- public Integer removeMessageId(Long chatId, String replyId) {
+ public @Nullable Integer removeMessageId(Long chatId, String replyId) {
return replyIdToMessageId.remove(new ReplyKey(chatId, replyId));
}
public boolean sendTelegram(@ActionInput(name = "chatId") @Nullable Long chatId,
@ActionInput(name = "message") @Nullable String message,
@ActionInput(name = "args") @Nullable Object... args) {
+ if (message == null) {
+ return false;
+ }
return sendTelegram(chatId, String.format(message, args));
}
public static boolean sendTelegramAnswer(ThingActions actions, @Nullable String chatId, @Nullable String replyId,
@Nullable String message) {
- return ((TelegramActions) actions).sendTelegramAnswer(Long.valueOf(chatId), replyId, message);
+ if (actions instanceof TelegramActions) {
+ if (chatId == null) {
+ return false;
+ }
+ return ((TelegramActions) actions).sendTelegramAnswer(Long.valueOf(chatId), replyId, message);
+ } else {
+ throw new IllegalArgumentException("Actions is not an instance of TelegramActions");
+ }
}
@Override
@OnWebSocketError
public void onWebSocketError(Throwable e) {
- logger.debug("Error during websocket communication: {}", e.getMessage());
- onClose(0, e.getMessage());
+ String message = e.getMessage();
+ logger.debug("Error during websocket communication: {}", message);
+ onClose(0, message != null ? message : "null");
}
@OnWebSocketMessage
bridgeHandler = (TouchWandBridgeHandler) bridge.getHandler();
- unitId = getThing().getProperties().get(HANDLER_PROPERTIES_ID); // TouchWand unit id
+ String unitId = getThing().getProperties().get(HANDLER_PROPERTIES_ID); // TouchWand unit id
+ if (unitId == null) {
+ updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "unitID missing");
+ return;
+ }
+ this.unitId = unitId;
TouchWandBridgeHandler myTmpBridgeHandler = bridgeHandler;
if (myTmpBridgeHandler != null) {
@Override
public void characters(char @Nullable [] ch, int start, int length) throws SAXException {
Element el = element;
- if (el == null) {
+ if (el == null || ch == null) {
return;
}
switch (el) {
@Override
public void onValueReceived(@Nullable String variable, @Nullable String value, @Nullable String service) {
- if (variable == null) {
+ if (variable == null || value == null) {
return;
}
switch (variable) {
case "CurrentTransportState":
- if (!((value == null) || (value.isEmpty()))) {
+ if (!value.isEmpty()) {
transportState = value;
}
break;
playing = true;
updateState(CONTROL, PlayPauseType.PLAY);
scheduleTrackPositionRefresh();
- } else if ("PAUSED_PLAYBACK".contentEquals(value)) {
+ } else if ("PAUSED_PLAYBACK".equals(value)) {
updateState(CONTROL, PlayPauseType.PAUSE);
}
break;
// No parent found, so make it the root directory
browseTarget = DIRECTORY_ROOT;
}
- currentEntry = parentMap.get(browseTarget);
+ UpnpEntry entry = parentMap.get(browseTarget);
+ if (entry == null) {
+ logger.info("Browse target not found. Exiting.");
+ return;
+ }
+ currentEntry = entry;
+
}
updateState(CURRENTID, StringType.valueOf(currentEntry.getId()));
logger.debug("Browse target {}", browseTarget);
}
/**
- * Method that does a UPnP browse on a content directory. Results will be retrieved in the {@link onValueReceived}
- * method.
+ * Method that does a UPnP browse on a content directory. Results will be retrieved in the
+ * {@link #onValueReceived(String, String, String)} method.
*
* @param objectID content directory object
* @param browseFlag BrowseMetaData or BrowseDirectChildren
}
/**
- * Method that does a UPnP search on a content directory. Results will be retrieved in the {@link onValueReceived}
- * method.
+ * Method that does a UPnP search on a content directory. Results will be retrieved in the
+ * {@link #onValueReceived(String, String, String)} method.
*
* @param containerID content directory container
* @param searchCriteria search criteria, examples:
public String getSceneName(Integer level) {
logger.trace("getSceneName({}) called.", level);
logger.trace("getSceneName() returning {}.", mapDescending.get(level));
- return mapDescending.get(level);
+ return mapDescending.getOrDefault(level, "null");
}
}
public boolean isRegistered(ProductBridgeIndex bridgeProductIndex) {
logger.trace("isRegisteredProductBridgeIndex {}) called.", bridgeProductIndex.toString());
- if (!bridgeIndexToSerialNumber.containsKey(bridgeProductIndex.toInt())) {
- return false;
- }
- return isRegistered(bridgeIndexToSerialNumber.get(bridgeProductIndex.toInt()));
+ String serialNumber = bridgeIndexToSerialNumber.get(bridgeProductIndex.toInt());
+ return serialNumber != null && isRegistered(serialNumber);
}
public boolean register(VeluxProduct newProduct) {
if (!isRegistered(productUniqueIndexOrSerialNumber)) {
return VeluxProduct.UNKNOWN;
}
- return existingProductsByUniqueIndex.get(productUniqueIndexOrSerialNumber);
+ return existingProductsByUniqueIndex.getOrDefault(productUniqueIndexOrSerialNumber, VeluxProduct.UNKNOWN);
}
public VeluxProduct get(ProductBridgeIndex bridgeProductIndex) {
logger.trace("get({}) called.", bridgeProductIndex);
- if (!isRegistered(bridgeProductIndex)) {
+ String serialNumber = bridgeIndexToSerialNumber.get(bridgeProductIndex.toInt());
+ if (!isRegistered(bridgeProductIndex) || serialNumber == null) {
return VeluxProduct.UNKNOWN;
}
- return existingProductsByUniqueIndex.get(bridgeIndexToSerialNumber.get(bridgeProductIndex.toInt()));
+ return existingProductsByUniqueIndex.getOrDefault(serialNumber, VeluxProduct.UNKNOWN);
}
public VeluxProduct[] values() {
if (!isRegistered(sceneName)) {
return VeluxScene.UNKNOWN;
}
- return existingScenesBySceneName.get(sceneName.toString());
+ return existingScenesBySceneName.getOrDefault(sceneName.toString(), VeluxScene.UNKNOWN);
}
public VeluxScene[] values() {
}
public static VeluxGatewaySubState get(int stateValue) {
- if (LOOKUPTYPEID2ENUM.containsKey(stateValue)) {
- return LOOKUPTYPEID2ENUM.get(stateValue);
- } else {
- return VeluxGatewaySubState.UNDEFTYPE;
- }
+ return LOOKUPTYPEID2ENUM.getOrDefault(stateValue, VeluxGatewaySubState.UNDEFTYPE);
}
}
}
public static Command get(short thisTypeId) {
- if (LOOKUPTYPEID2ENUM.containsKey(thisTypeId)) {
- return LOOKUPTYPEID2ENUM.get(thisTypeId);
- } else {
- return Command.UNDEFTYPE;
- }
+ return LOOKUPTYPEID2ENUM.getOrDefault(thisTypeId, Command.UNDEFTYPE);
}
}
}
}
} catch (VenstarCommunicationException | JsonSyntaxException e) {
log.debug("Unable to fetch info data", e);
- goOffline(ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
+ String message = e.getMessage();
+ goOffline(ThingStatusDetail.COMMUNICATION_ERROR, message != null ? message : "");
} catch (VenstarAuthenticationException e) {
goOffline(ThingStatusDetail.CONFIGURATION_ERROR, "Authorization Failed");
}
goOnline();
} catch (VenstarCommunicationException | JsonSyntaxException e) {
log.debug("Unable to fetch info data", e);
- goOffline(ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
+ String message = e.getMessage();
+ goOffline(ThingStatusDetail.COMMUNICATION_ERROR, message != null ? message : "");
} catch (VenstarAuthenticationException e) {
goOffline(ThingStatusDetail.CONFIGURATION_ERROR, "Authorization Failed");
}
Collections.reverse(newEventList);
ArrayList<Event> events = new ArrayList<>();
for (PagedList newEvent : newEventList) {
- long eventTime = ZonedDateTime.parse(newEvent.getEventTime()).toEpochSecond();
+ String eventTimeString = newEvent.getEventTime();
+ if (eventTimeString == null) {
+ logger.debug("Event-Time is null: {}", newEvent);
+ continue;
+ }
+ long eventTime = ZonedDateTime.parse(eventTimeString).toEpochSecond();
logger.trace("Event time: {} Last Event time: {}", eventTime, lastEventTime);
if (eventTime > lastEventTime) {
logger.debug("Create event {} for event time {}", newEvent.getEventType(), eventTime);
updateState(channelUID, state);
} else {
String timestamp = communicationState.getTestDate();
- if (timestamp != null && channelUID.toString()
- .contains(communicationState.getHardwareCarrierType())) {
+ String carrierType = communicationState.getHardwareCarrierType();
+ if (timestamp != null && carrierType != null
+ && channelUID.toString().contains(carrierType)) {
updateTimeStamp(timestamp, channelUID);
}
}
import java.time.Duration;
import java.time.ZoneId;
import java.time.ZonedDateTime;
+import java.time.temporal.Temporal;
import java.util.Optional;
import org.eclipse.jdt.annotation.NonNullByDefault;
return getPositionAsState(endPosition);
}
- public long getDurationInMinutes() {
- return Duration.between(startTime, endTime).toMinutes();
+ public Optional<Long> getDurationInMinutes() {
+ Temporal start = startTime;
+ Temporal end = endTime;
+ if (start == null || end == null) {
+ return Optional.empty();
+ } else {
+ return Optional.of(Duration.between(start, end).toMinutes());
+ }
}
public Optional<Integer> getFuelConsumption() {
thing.getProperties().entrySet().stream().filter(p -> "true".equals(p.getValue()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
- if (thing.getProperties().containsKey(LAST_TRIP_ID)) {
- lastTripId = Long.parseLong(thing.getProperties().get(LAST_TRIP_ID));
+ String lastTripIdString = thing.getProperties().get(LAST_TRIP_ID);
+ if (lastTripIdString != null) {
+ lastTripId = Long.parseLong(lastTripIdString);
}
updateStatus(ThingStatus.ONLINE);
case TRIP_END_TIME:
return tripDetails.getEndTime();
case TRIP_DURATION:
- return new QuantityType<>(tripDetails.getDurationInMinutes(), MINUTE);
+ return tripDetails.getDurationInMinutes().map(value -> (State) new QuantityType<>(value, MINUTE))
+ .orElse(UnDefType.UNDEF);
case TRIP_START_ODOMETER:
return new QuantityType<>((double) tripDetails.startOdometer / 1000, KILO(METRE));
case TRIP_STOP_ODOMETER:
onConnectivityError(e);
return;
} catch (ReceivedMessageParseException e) {
- updateProperty(PROPERTY_MENU_ERROR, e.getMessage());
+ String message = e.getMessage();
+ updateProperty(PROPERTY_MENU_ERROR, message != null ? message : "");
// Some AVRs send unexpected responses. We log parser exceptions therefore.
logger.debug("Parse error!", e);
} finally {
logger.debug("State update error. Changing thing to offline", e);
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
} catch (ReceivedMessageParseException e) {
- updateProperty(PROPERTY_LAST_PARSE_ERROR, e.getMessage());
+ String message = e.getMessage();
+ updateProperty(PROPERTY_LAST_PARSE_ERROR, message != null ? message : "");
// Some AVRs send unexpected responses. We log parser exceptions therefore.
logger.debug("Parse error!", e);
}
device.setAddress(addressInfo[1].substring(2));
device.setPort(Integer.parseInt(addressInfo[2]));
device.setOnline(true);
- Color color = new Color(Integer.parseInt(bulbInfo.get("rgb")));
DeviceStatus status = device.getDeviceStatus();
- status.setR(color.getRed());
- status.setG(color.getGreen());
- status.setB(color.getBlue());
- status.setCt(Integer.parseInt(bulbInfo.get("ct")));
- status.setHue(Integer.parseInt(bulbInfo.get("hue")));
- status.setSat(Integer.parseInt(bulbInfo.get("sat")));
+ String rgb = bulbInfo.get("rgb");
+ if (rgb != null) {
+ Color color = new Color(Integer.parseInt(rgb));
+ status.setR(color.getRed());
+ status.setG(color.getGreen());
+ status.setB(color.getBlue());
+ }
+ String ct = bulbInfo.get("ct");
+ if (ct != null) {
+ status.setCt(Integer.parseInt(ct));
+ }
+ String hue = bulbInfo.get("hue");
+ if (hue != null) {
+ status.setHue(Integer.parseInt(hue));
+ }
+ String sat = bulbInfo.get("sat");
+ if (sat != null) {
+ status.setSat(Integer.parseInt(sat));
+ }
}
public static String getDefaultName(DeviceBase device) {
// Channel thermostat mode
if (channel.getUID().equals(new ChannelUID(getThing().getUID(), THERMOSTAT_MODE_CC_CHANNEL))) {
// Load physical device
- Integer nodeId = Integer.parseInt(channel.getProperties().get("nodeId"));
- ZWaveDevice physicalDevice = zwayBridgeHandler.getZWayApi().getZWaveDevice(nodeId);
-
+ String nodeIdString = channel.getProperties().get("nodeId");
+ ZWaveDevice physicalDevice = nodeIdString == null ? null
+ : zwayBridgeHandler.getZWayApi().getZWaveDevice(Integer.parseInt(nodeIdString));
if (physicalDevice != null) {
updateState(channel.getUID(), new DecimalType(physicalDevice.getInstances().get0()
.getCommandClasses().get64().getData().getMode().getValue()));
}
} else if (channel.getUID().equals(new ChannelUID(getThing().getUID(), THERMOSTAT_MODE_CC_CHANNEL))) {
// Load physical device
- Integer nodeId = Integer.parseInt(channel.getProperties().get("nodeId"));
if (command instanceof DecimalType) {
+ String nodeIdString = channel.getProperties().get("nodeId");
logger.debug("Handle command: DecimalType");
-
- zwayBridgeHandler.getZWayApi().getZWaveDeviceThermostatModeSet(nodeId,
- Integer.parseInt(command.toString()));
+ if (nodeIdString != null) {
+ zwayBridgeHandler.getZWayApi().getZWaveDeviceThermostatModeSet(Integer.parseInt(nodeIdString),
+ Integer.parseInt(command.toString()));
+ }
} else if (command instanceof RefreshType) {
logger.debug("Handle command: RefreshType");
-
refreshChannel(channel);
}
}
private void initialiseRevision() {
int revision;
try {
- revision = Integer.parseInt(storage.get(REVISION_CONFIG));
+ String revisionString = storage.get(REVISION_CONFIG);
+ if (revisionString == null) {
+ throw new NumberFormatException();
+ }
+ revision = Integer.parseInt(revisionString);
} catch (NumberFormatException e) {
revision = 1;
storage.put(REVISION_CONFIG, "" + revision);
}
try {
- lastAccessoryCount = Integer.parseInt(storage.get(ACCESSORY_COUNT));
+ String accessoryCountString = storage.get(ACCESSORY_COUNT);
+ if (accessoryCountString == null) {
+ throw new NumberFormatException();
+ }
+ lastAccessoryCount = Integer.parseInt(accessoryCountString);
} catch (NumberFormatException e) {
lastAccessoryCount = 0;
storage.put(ACCESSORY_COUNT, "" + accessoryRegistry.getAllAccessories().size());
* @return new characteristic type
*/
private static HomekitCharacteristicType legacyCheck(HomekitCharacteristicType characteristicType) {
- if (LEGACY_CHARACTERISTICS_MAPPING.containsKey(characteristicType))
- return LEGACY_CHARACTERISTICS_MAPPING.get(characteristicType);
- return characteristicType;
+ return LEGACY_CHARACTERISTICS_MAPPING.getOrDefault(characteristicType, characteristicType);
}
}
import javax.ws.rs.core.UriInfo;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
import org.openhab.io.hueemulation.internal.dto.response.HueResponse;
import org.openhab.io.hueemulation.internal.dto.response.HueResponse.HueErrorMessage;
import org.openhab.io.hueemulation.internal.dto.response.HueResponseSuccessSimple;
* @param message A message
* @return
*/
- public static Response singleError(Gson gson, UriInfo uri, int type, String message) {
- HueResponse e = new HueResponse(new HueErrorMessage(type, uri.getPath().replace("/api", ""), message));
+ public static Response singleError(Gson gson, UriInfo uri, int type, @Nullable String message) {
+ HueResponse e = new HueResponse(
+ new HueErrorMessage(type, uri.getPath().replace("/api", ""), message != null ? message : ""));
String str = gson.toJson(Collections.singleton(e), new TypeToken<List<?>>() {
}.getType());
int httpCode = 500;
return NetworkUtils.singleError(cs.gson, uri, HueResponse.ARGUMENTS_INVALID, e.getMessage());
}
+ List<String> lightsList = changeRequest.lights;
return NetworkUtils.successList(cs.gson, Arrays.asList( //
new HueSuccessGeneric(changeRequest.name, "/scenes/" + id + "/name"), //
new HueSuccessGeneric(changeRequest.description, "/scenes/" + id + "/description"), //
- new HueSuccessGeneric(changeRequest.lights != null ? String.join(",", changeRequest.lights) : null,
+ new HueSuccessGeneric(lightsList != null ? String.join(",", lightsList) : null,
"/scenes/" + id + "/lights") //
));
}
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.common.registry.RegistryChangeListener;
import org.openhab.core.items.Item;
+import org.openhab.core.items.ItemNotFoundException;
import org.openhab.core.items.ItemRegistry;
import org.openhab.core.items.RegistryHook;
}
@Override
- public Item getItem(String name) {
- return items.get(name);
+ public Item getItem(String name) throws ItemNotFoundException {
+ Item item = items.get(name);
+ if (item == null) {
+ throw new ItemNotFoundException(name);
+ }
+ return item;
}
@Override
- public Item getItemByPattern(String name) {
- return items.get(name);
+ public Item getItemByPattern(String name) throws ItemNotFoundException {
+ Item item = items.get(name);
+ if (item == null) {
+ throw new ItemNotFoundException(name);
+ }
+ return item;
}
@Override
final String manufacturer = StringUtils.isEmpty(properties.get("Manufacturer")) ? "openHAB"
: properties.get("Manufacturer");
- final Integer standbyDelay = parseInteger(properties.get("Standby Command Delay"));
- final Integer switchDelay = parseInteger(properties.get("Source Switch Delay"));
- final Integer shutDownDelay = parseInteger(properties.get("Shutdown Delay"));
+ final Integer standbyDelay = parseInteger(properties.getOrDefault("Standby Command Delay", "0"));
+ final Integer switchDelay = parseInteger(properties.getOrDefault("Source Switch Delay", "0"));
+ final Integer shutDownDelay = parseInteger(properties.getOrDefault("Shutdown Delay", "0"));
final NeeoDeviceTiming timing = new NeeoDeviceTiming(standbyDelay, switchDelay, shutDownDelay);
content.close();
}
} catch (IOException | IllegalStateException | ProcessingException e) {
- return new HttpResponse(HttpStatus.SERVICE_UNAVAILABLE_503, e.getMessage());
+ String message = e.getMessage();
+ return new HttpResponse(HttpStatus.SERVICE_UNAVAILABLE_503, message != null ? message : "");
}
}
content.close();
}
} catch (IOException | IllegalStateException | ProcessingException e) {
- return new HttpResponse(HttpStatus.SERVICE_UNAVAILABLE_503, e.getMessage());
+ String message = e.getMessage();
+ return new HttpResponse(HttpStatus.SERVICE_UNAVAILABLE_503, message != null ? message : "");
}
}
return "";
}
- return new String(contents, StandardCharsets.UTF_8);
+ return new String(localContents, StandardCharsets.UTF_8);
}
/**
package org.openhab.io.transport.modbus.exception;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
import org.openhab.io.transport.modbus.endpoint.ModbusSlaveEndpoint;
/**
}
@Override
- public String getMessage() {
+ public @Nullable String getMessage() {
return String.format("Error connecting to endpoint %s", endpoint);
}
package org.openhab.io.transport.modbus.exception;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
/**
* Exception representing situation where function code of the response does not match request
}
@Override
- public String getMessage() {
+ public @Nullable String getMessage() {
return String.format("Function code of request (%d) does not equal response (%d)", requestFunctionCode,
responseFunctionCode);
}
package org.openhab.io.transport.modbus.exception;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
/**
* Exception representing situation where data length of the response does not match request
}
@Override
- public String getMessage() {
+ public @Nullable String getMessage() {
return String.format("Data length of the request (%d) does not equal response (%d). Slave response is invalid.",
requestSize, responseSize);
}
package org.openhab.io.transport.modbus.exception;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
/**
* Exception representing situation where transaction id of the response does not match request
}
@Override
- public String getMessage() {
+ public @Nullable String getMessage() {
return String.format("Transaction id of request (%d) does not equal response (%d). Slave response is invalid.",
requestId, responseId);
}
package org.openhab.io.transport.modbus.internal;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
import org.openhab.io.transport.modbus.exception.ModbusSlaveErrorResponseException;
import net.wimpi.modbus.ModbusSlaveException;
}
@Override
- public String getMessage() {
+ public @Nullable String getMessage() {
return String.format("Slave responsed with error=%d", type);
}
import java.io.IOException;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
import org.openhab.io.transport.modbus.exception.ModbusSlaveIOException;
import net.wimpi.modbus.ModbusIOException;
}
@Override
- public String getMessage() {
+ public @Nullable String getMessage() {
return String.format("Modbus IO Error with cause=%s, EOF=%s, message='%s', cause2=%s",
error.getClass().getSimpleName(),
error instanceof ModbusIOException ? ((ModbusIOException) error).isEOF() : "?", error.getMessage(),
String tableName = tableNameResolver.fromItem(dynamoItem);
Deque<DynamoDBItem<?>> batch = batchesByTable.computeIfAbsent(tableName, new Function<>() {
@Override
- public Deque<DynamoDBItem<?>> apply(String t) {
+ public Deque<DynamoDBItem<?>> apply(@Nullable String t) {
return new ArrayDeque<>();
}
});
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
+import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Iterator;
@NonNullByDefault
public abstract class AbstractTwoItemIntegrationTest extends BaseIntegrationTest {
- protected static @Nullable ZonedDateTime beforeStore;
- protected static @Nullable ZonedDateTime afterStore1;
- protected static @Nullable ZonedDateTime afterStore2;
+ protected static ZonedDateTime beforeStore = ZonedDateTime.of(2100, 1, 1, 0, 0, 0, 0, ZoneId.systemDefault());
+ protected static ZonedDateTime afterStore1 = ZonedDateTime.of(1900, 1, 1, 0, 0, 0, 0, ZoneId.systemDefault());
+ protected static ZonedDateTime afterStore2 = ZonedDateTime.of(1900, 1, 1, 0, 0, 0, 0, ZoneId.systemDefault());
protected abstract String getItemName();
});
Map<String, Object> config = new HashMap<>();
- config.put("region", System.getProperty("DYNAMODBTEST_REGION"));
- config.put("accessKey", System.getProperty("DYNAMODBTEST_ACCESS"));
- config.put("secretKey", System.getProperty("DYNAMODBTEST_SECRET"));
+ String value = System.getProperty("DYNAMODBTEST_REGION");
+ config.put("region", value != null ? value : "");
+ value = System.getProperty("DYNAMODBTEST_ACCESS");
+ config.put("accessKey", value != null ? value : "");
+ value = System.getProperty("DYNAMODBTEST_SECRET");
+ config.put("secretKey", value != null ? value : "");
config.put("tablePrefix", "dynamodb-integration-tests-");
// Disable buffering
config.put("bufferSize", "0");
for (Entry<String, Object> entry : config.entrySet()) {
- if (entry.getValue() == null) {
+ if (((String) entry.getValue()).isEmpty()) {
LOGGER.warn(String.format(
"Expecting %s to have value for integration tests. Integration tests will be skipped",
entry.getKey()));
*/
protected CompiledScript getScript(final String filename) throws TransformationException {
synchronized (compiledScriptMap) {
- if (compiledScriptMap.containsKey(filename)) {
+ CompiledScript compiledScript = compiledScriptMap.get(filename);
+ if (compiledScript != null) {
logger.debug("Loading JavaScript {} from cache.", filename);
- return compiledScriptMap.get(filename);
+ return compiledScript;
} else {
final String path = TransformationScriptWatcher.TRANSFORM_FOLDER + File.separator + filename;
logger.debug("Loading script {} from storage ", path);
import static org.junit.jupiter.api.Assertions.*;
-import java.io.File;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
+import java.io.*;
import java.util.Locale;
import java.util.Properties;
import java.util.concurrent.Callable;
}
}, 10000, 100);
} catch (IOException e1) {
- e1.printStackTrace(System.err);
+ PrintStream err = System.err;
+ if (err != null) {
+ e1.printStackTrace(err);
+ }
}
// Checks that an unknown input in an existing file give the expected
<module>org.openhab.voice.voicerss</module>
</modules>
+ <properties>
+ <m2e.jdt.annotationpath>target/dependency</m2e.jdt.annotationpath>
+ <dep.noembedding/>
+ </properties>
+
<dependencies>
+ <dependency>
+ <groupId>org.lastnpe.eea</groupId>
+ <artifactId>eea-all</artifactId>
+ <version>2.1.0</version>
+ </dependency>
<!-- openHAB core -->
<dependency>
<groupId>org.openhab.core.bom</groupId>
</dependency>
</dependencies>
- <properties>
- <dep.noembedding/>
- </properties>
-
<build>
<pluginManagement>
<plugins>
<configuration>
<includeScope>runtime</includeScope>
<includeTypes>jar</includeTypes>
- <excludeGroupIds>javax.activation,org.apache.karaf.features</excludeGroupIds>
+ <excludeGroupIds>javax.activation,org.apache.karaf.features,org.lastnpe.eea</excludeGroupIds>
<excludeArtifactIds>${dep.noembedding}</excludeArtifactIds>
<outputDirectory>${project.build.directory}/classes</outputDirectory>
<overWriteReleases>true</overWriteReleases>
<type>jar</type>
</configuration>
</execution>
+ <execution>
+ <id>unpack-eea</id>
+ <goals>
+ <goal>unpack</goal>
+ </goals>
+ <configuration>
+ <artifactItems>
+ <artifactItem>
+ <groupId>org.lastnpe.eea</groupId>
+ <artifactId>eea-all</artifactId>
+ <version>2.1.0</version>
+ <overWrite>true</overWrite>
+ </artifactItem>
+ </artifactItems>
+ </configuration>
+ </execution>
</executions>
</plugin>
</plugins>
addedLinks.add(link);
}
- protected List<State> getStateUpdates(String itemName) {
+ protected @Nullable List<State> getStateUpdates(String itemName) {
return stateSubscriber.stateUpdates.get(itemName);
}
<module>org.openhab.persistence.mapdb.tests</module>
</modules>
+ <properties>
+ <m2e.jdt.annotationpath>target/dependency</m2e.jdt.annotationpath>
+ </properties>
+
<dependencies>
<dependency>
<groupId>org.openhab.core.bom</groupId>
<groupId>biz.aQute.bnd</groupId>
<artifactId>bnd-maven-plugin</artifactId>
</plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-dependency-plugin</artifactId>
+ <version>3.1.1</version>
+ <executions>
+ <execution>
+ <id>unpack-eea</id>
+ <goals>
+ <goal>unpack</goal>
+ </goals>
+ <configuration>
+ <artifactItems>
+ <artifactItem>
+ <groupId>org.lastnpe.eea</groupId>
+ <artifactId>eea-all</artifactId>
+ <version>2.1.0</version>
+ <overWrite>true</overWrite>
+ </artifactItem>
+ </artifactItems>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
</plugins>
</build>
<version>3.8.1</version>
<configuration>
<compilerId>eclipse</compilerId>
+ <compilerArguments>
+ <annotationpath>CLASSPATH</annotationpath>
+ <classpath>${project.build.directory}/dependency</classpath>
+ </compilerArguments>
<compilerArgs>
<arg>-err:+nullAnnot(org.eclipse.jdt.annotation.Nullable|org.eclipse.jdt.annotation.NonNull|org.eclipse.jdt.annotation.NonNullByDefault),+inheritNullAnnot,-nullUncheckedConversion</arg>
<arg>-warn:+null,+inheritNullAnnot,+nullAnnotConflict,-nullUncheckedConversion,+nullAnnotRedundant,+nullDereference</arg>