[infrastructure] move infered nullness warnings to error and update EEA (#8949)

Signed-off-by: Jan N. Klug <jan.n.klug@rub.de>
This commit is contained in:
J-N-K 2020-11-12 21:07:11 +01:00 committed by GitHub
parent 0856a0b3f2
commit ba4c96d99d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
155 changed files with 644 additions and 632 deletions

View File

@ -14,6 +14,7 @@ package org.openhab.binding.amazonechocontrol.internal.channelhandler;
import java.io.IOException; import java.io.IOException;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.Objects;
import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringEscapeUtils;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
@ -91,7 +92,7 @@ public class ChannelHandlerAnnouncement extends ChannelHandler {
body = e.getLocalizedMessage(); body = e.getLocalizedMessage();
} }
} }
thingHandler.startAnnouncment(device, speak, body, title, volume); thingHandler.startAnnouncment(device, speak, Objects.requireNonNullElse(body, ""), title, volume);
} }
refreshChannel(); refreshChannel();
} }

View File

@ -673,7 +673,7 @@ public class AccountHandler extends BaseBridgeHandler implements IWebSocketComma
public void setEnabledFlashBriefingsJson(String flashBriefingJson) { public void setEnabledFlashBriefingsJson(String flashBriefingJson) {
Connection currentConnection = connection; Connection currentConnection = connection;
JsonFeed[] feeds = gson.fromJson(flashBriefingJson, JsonFeed[].class); JsonFeed[] feeds = gson.fromJson(flashBriefingJson, JsonFeed[].class);
if (currentConnection != null) { if (currentConnection != null && feeds != null) {
try { try {
currentConnection.setEnabledFlashBriefings(feeds); currentConnection.setEnabledFlashBriefings(feeds);
} catch (IOException | URISyntaxException e) { } catch (IOException | URISyntaxException e) {

View File

@ -25,7 +25,8 @@ import com.google.gson.annotations.SerializedName;
@NonNullByDefault @NonNullByDefault
public class JsonRegisterAppRequest { public class JsonRegisterAppRequest {
public JsonRegisterAppRequest(String serial, String accessToken, String frc, JsonWebSiteCookie[] webSiteCookies) { public JsonRegisterAppRequest(String serial, @Nullable String accessToken, String frc,
JsonWebSiteCookie[] webSiteCookies) {
registrationData.deviceSerial = serial; registrationData.deviceSerial = serial;
authData.accessToken = accessToken; authData.accessToken = accessToken;
userContextMap.frc = frc; userContextMap.frc = frc;

View File

@ -73,6 +73,9 @@ public class RemoteSensor {
* there are remote sensor values * there are remote sensor values
*/ */
private void updateSensorChannels(AmbientWeatherStationHandler handler, int i, final @Nullable String jsonData) { private void updateSensorChannels(AmbientWeatherStationHandler handler, int i, final @Nullable String jsonData) {
if (jsonData == null) {
return;
}
String sensorNumber = String.valueOf(i); String sensorNumber = String.valueOf(i);
StringReader stringReader = new StringReader(jsonData); StringReader stringReader = new StringReader(jsonData);
JsonReader reader = new JsonReader(stringReader); JsonReader reader = new JsonReader(stringReader);

View File

@ -19,6 +19,7 @@ import java.time.ZoneId;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import java.util.Calendar; import java.util.Calendar;
import java.util.GregorianCalendar; import java.util.GregorianCalendar;
import java.util.Objects;
import java.util.TimeZone; import java.util.TimeZone;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
@ -91,11 +92,8 @@ public class PropertyUtils {
Method m = instance.getClass().getMethod(toGetterString(propertyName), null); Method m = instance.getClass().getMethod(toGetterString(propertyName), null);
Object result = m.invoke(instance, (Object[]) null); Object result = m.invoke(instance, (Object[]) null);
if (nestedIndex + 1 < properties.length) { if (nestedIndex + 1 < properties.length) {
if (result != null) { Objects.requireNonNull(result);
return getPropertyValue(result, properties, nestedIndex + 1); return getPropertyValue(result, properties, nestedIndex + 1);
} else {
throw new NullPointerException();
}
} }
return result; return result;
} }

View File

@ -15,6 +15,7 @@ package org.openhab.binding.bluetooth.roaming.internal;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
@ -52,7 +53,7 @@ public class RoamingBluetoothDevice extends DelegateBluetoothDevice {
} }
public void addBluetoothDevice(BluetoothDevice device) { public void addBluetoothDevice(BluetoothDevice device) {
device.addListener(devices.computeIfAbsent(device, Listener::new)); device.addListener(Objects.requireNonNull(devices.computeIfAbsent(device, Listener::new)));
} }
public void removeBluetoothDevice(BluetoothDevice device) { public void removeBluetoothDevice(BluetoothDevice device) {

View File

@ -14,6 +14,7 @@ package org.openhab.binding.bluetooth.roaming.internal;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.CopyOnWriteArraySet;
import java.util.stream.Stream; import java.util.stream.Stream;
@ -216,8 +217,8 @@ public class RoamingBridgeHandler extends BaseBridgeHandler implements RoamingBl
public RoamingBluetoothDevice getDevice(BluetoothAddress address) { public RoamingBluetoothDevice getDevice(BluetoothAddress address) {
// this will only get called by a bluetooth device handler // this will only get called by a bluetooth device handler
synchronized (devices) { synchronized (devices) {
RoamingBluetoothDevice roamingDevice = devices.computeIfAbsent(address, RoamingBluetoothDevice roamingDevice = Objects
addr -> new RoamingBluetoothDevice(this, addr)); .requireNonNull(devices.computeIfAbsent(address, addr -> new RoamingBluetoothDevice(this, addr)));
adapters.stream().filter(this::isRoamingMember) adapters.stream().filter(this::isRoamingMember)
.forEach(adapter -> roamingDevice.addBluetoothDevice(adapter.getDevice(address))); .forEach(adapter -> roamingDevice.addBluetoothDevice(adapter.getDevice(address)));

View File

@ -14,6 +14,7 @@ package org.openhab.binding.bluetooth;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.CopyOnWriteArraySet;
@ -186,7 +187,7 @@ public abstract class AbstractBluetoothBridgeHandler<BD extends BaseBluetoothDev
@Override @Override
public BD getDevice(BluetoothAddress address) { public BD getDevice(BluetoothAddress address) {
synchronized (devices) { synchronized (devices) {
return devices.computeIfAbsent(address, this::createDevice); return Objects.requireNonNull(devices.computeIfAbsent(address, this::createDevice));
} }
} }

View File

@ -13,6 +13,7 @@
package org.openhab.binding.bluetooth; package org.openhab.binding.bluetooth;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
@ -59,7 +60,7 @@ public class MockBluetoothAdapter implements BluetoothAdapter {
@Override @Override
public MockBluetoothDevice getDevice(BluetoothAddress address) { public MockBluetoothDevice getDevice(BluetoothAddress address) {
return devices.computeIfAbsent(address, addr -> new MockBluetoothDevice(this, addr)); return Objects.requireNonNull(devices.computeIfAbsent(address, addr -> new MockBluetoothDevice(this, addr)));
} }
@Override @Override

View File

@ -12,7 +12,6 @@
*/ */
package org.openhab.binding.bsblan.internal; package org.openhab.binding.bsblan.internal;
import java.util.HashSet;
import java.util.Set; import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
@ -42,15 +41,8 @@ public class BsbLanBindingConstants {
public static final String PARAMETER_CHANNEL_DESCRIPTION = "description"; public static final String PARAMETER_CHANNEL_DESCRIPTION = "description";
public static final String PARAMETER_CHANNEL_DATATYPE = "datatype"; public static final String PARAMETER_CHANNEL_DATATYPE = "datatype";
public static final Set<String> WRITEABLE_CHANNELS = new HashSet<String>() { public static final Set<String> WRITEABLE_CHANNELS = Set.of(PARAMETER_CHANNEL_NUMBER_VALUE,
PARAMETER_CHANNEL_STRING_VALUE, PARAMETER_CHANNEL_SWITCH_VALUE);
private static final long serialVersionUID = 1L;
{
add(PARAMETER_CHANNEL_NUMBER_VALUE);
add(PARAMETER_CHANNEL_STRING_VALUE);
add(PARAMETER_CHANNEL_SWITCH_VALUE);
}
};
public static final int MIN_REFRESH_INTERVAL = 5; public static final int MIN_REFRESH_INTERVAL = 5;
public static final int DEFAULT_REFRESH_INTERVAL = 60; public static final int DEFAULT_REFRESH_INTERVAL = 60;

View File

@ -14,7 +14,6 @@ package org.openhab.binding.bsblan.internal;
import static org.openhab.binding.bsblan.internal.BsbLanBindingConstants.*; import static org.openhab.binding.bsblan.internal.BsbLanBindingConstants.*;
import java.util.HashSet;
import java.util.Set; import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
@ -39,14 +38,7 @@ import org.osgi.service.component.annotations.Component;
@Component(service = ThingHandlerFactory.class, configurationPid = "binding.bsblan") @Component(service = ThingHandlerFactory.class, configurationPid = "binding.bsblan")
public class BsbLanHandlerFactory extends BaseThingHandlerFactory { public class BsbLanHandlerFactory extends BaseThingHandlerFactory {
private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = new HashSet<ThingTypeUID>() { private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_PARAMETER, THING_TYPE_BRIDGE);
private static final long serialVersionUID = 1L;
{
add(THING_TYPE_PARAMETER);
add(THING_TYPE_BRIDGE);
}
};
@Override @Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) { public boolean supportsThingType(ThingTypeUID thingTypeUID) {

View File

@ -142,9 +142,10 @@ public class SmartherAuthorizationServlet extends HttpServlet {
final StringBuffer requestURL = request.getRequestURL(); final StringBuffer requestURL = request.getRequestURL();
// Try to infer the real protocol from request headers // Try to infer the real protocol from request headers
final String realProtocol = StringUtil.defaultIfBlank(request.getHeader(X_FORWARDED_PROTO), String realProtocol = request.getHeader(X_FORWARDED_PROTO);
request.getScheme()); if (realProtocol == null || realProtocol.isBlank()) {
realProtocol = request.getScheme();
}
return requestURL.replace(0, requestURL.indexOf(":"), realProtocol).toString(); return requestURL.replace(0, requestURL.indexOf(":"), realProtocol).toString();
} }

View File

@ -21,6 +21,7 @@ import java.util.Collections;
import java.util.IdentityHashMap; import java.util.IdentityHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Function; import java.util.function.Function;
@ -177,7 +178,9 @@ public class SmartherApi {
public ModuleStatus getModuleStatus(String plantId, String moduleId) throws SmartherGatewayException { public ModuleStatus getModuleStatus(String plantId, String moduleId) throws SmartherGatewayException {
try { try {
final ContentResponse response = requestModule(GET, plantId, moduleId, null); final ContentResponse response = requestModule(GET, plantId, moduleId, null);
return ModelUtil.gsonInstance().fromJson(response.getContentAsString(), ModuleStatus.class); ModuleStatus moduleStatus = ModelUtil.gsonInstance().fromJson(response.getContentAsString(),
ModuleStatus.class);
return Objects.requireNonNull(moduleStatus);
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
throw new SmartherGatewayException(e.getMessage()); throw new SmartherGatewayException(e.getMessage());
} }
@ -280,9 +283,13 @@ public class SmartherApi {
if (response.getStatus() == HttpStatus.NO_CONTENT_204) { if (response.getStatus() == HttpStatus.NO_CONTENT_204) {
return new ArrayList<>(); return new ArrayList<>();
} else { } else {
return ModelUtil.gsonInstance().fromJson(response.getContentAsString(), List<Subscription> subscriptions = ModelUtil.gsonInstance().fromJson(response.getContentAsString(),
new TypeToken<List<Subscription>>() { new TypeToken<List<Subscription>>() {
}.getType()); }.getType());
if (subscriptions == null) {
throw new SmartherGatewayException("fromJson returned null");
}
return subscriptions;
} }
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
throw new SmartherGatewayException(e.getMessage()); throw new SmartherGatewayException(e.getMessage());

View File

@ -165,8 +165,8 @@ public class ThingHandlerPanel extends CaddxBaseThingHandler {
// get the channel id from the map // get the channel id from the map
HashMap<String, String> logMap = panelLogMessagesMap; HashMap<String, String> logMap = panelLogMessagesMap;
if (logMap != null && logMap.containsKey(eventNumberString)) { String id = logMap.get(eventNumberString);
String id = logMap.get(eventNumberString); if (logMap != null && id != null) {
ChannelUID channelUID = new ChannelUID(getThing().getUID(), id); ChannelUID channelUID = new ChannelUID(getThing().getUID(), id);
updateChannel(channelUID, logEventMessage.toString()); updateChannel(channelUID, logEventMessage.toString());
} }

View File

@ -131,7 +131,10 @@ public class WebSocketConnection {
return; return;
} }
listener.messageReceived(changedMessage.id, gson.fromJson(message, expectedMessageType)); DeconzBaseMessage deconzMessage = gson.fromJson(message, expectedMessageType);
if (deconzMessage != null) {
listener.messageReceived(changedMessage.id, deconzMessage);
}
} }
@OnWebSocketError @OnWebSocketError

View File

@ -30,9 +30,8 @@ import com.google.gson.JsonParseException;
@NonNullByDefault @NonNullByDefault
public class GroupTypeDeserializer implements JsonDeserializer<GroupType> { public class GroupTypeDeserializer implements JsonDeserializer<GroupType> {
@Override @Override
public GroupType deserialize(@Nullable JsonElement json, @Nullable Type typeOfT, public @Nullable GroupType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
@Nullable JsonDeserializationContext context) throws JsonParseException { throws JsonParseException {
String s = json != null ? json.getAsString() : null; return GroupType.fromString(json.getAsString());
return s == null ? GroupType.UNKNOWN : GroupType.fromString(s);
} }
} }

View File

@ -30,9 +30,8 @@ import com.google.gson.JsonParseException;
@NonNullByDefault @NonNullByDefault
public class LightTypeDeserializer implements JsonDeserializer<LightType> { public class LightTypeDeserializer implements JsonDeserializer<LightType> {
@Override @Override
public LightType deserialize(@Nullable JsonElement json, @Nullable Type typeOfT, public @Nullable LightType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
@Nullable JsonDeserializationContext context) throws JsonParseException { throws JsonParseException {
String s = json != null ? json.getAsString() : null; return LightType.fromString(json.getAsString());
return s == null ? LightType.UNKNOWN : LightType.fromString(s);
} }
} }

View File

@ -30,9 +30,8 @@ import com.google.gson.JsonParseException;
@NonNullByDefault @NonNullByDefault
public class ResourceTypeDeserializer implements JsonDeserializer<ResourceType> { public class ResourceTypeDeserializer implements JsonDeserializer<ResourceType> {
@Override @Override
public ResourceType deserialize(@Nullable JsonElement json, @Nullable Type typeOfT, public @Nullable ResourceType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
@Nullable JsonDeserializationContext context) throws JsonParseException { throws JsonParseException {
String s = json != null ? json.getAsString() : null; return ResourceType.fromString(json.getAsString());
return s == null ? ResourceType.UNKNOWN : ResourceType.fromString(s);
} }
} }

View File

@ -34,19 +34,14 @@ import com.google.gson.JsonSerializer;
@NonNullByDefault @NonNullByDefault
public class ThermostatModeGsonTypeAdapter implements JsonDeserializer<ThermostatMode>, JsonSerializer<ThermostatMode> { public class ThermostatModeGsonTypeAdapter implements JsonDeserializer<ThermostatMode>, JsonSerializer<ThermostatMode> {
@Override @Override
public ThermostatMode deserialize(@Nullable JsonElement json, @Nullable Type typeOfT, public @Nullable ThermostatMode deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
@Nullable JsonDeserializationContext context) throws JsonParseException { throws JsonParseException {
JsonElement jsonLocal = json; return ThermostatMode.fromString(json.getAsString());
if (jsonLocal != null) {
String s = jsonLocal.getAsString();
return s == null ? ThermostatMode.UNKNOWN : ThermostatMode.fromString(s);
}
return ThermostatMode.UNKNOWN;
} }
@Override @Override
public JsonElement serialize(ThermostatMode src, @Nullable Type typeOfSrc, public JsonElement serialize(ThermostatMode src, Type typeOfSrc, JsonSerializationContext context)
@Nullable JsonSerializationContext context) throws JsonParseException { throws JsonParseException {
return src != ThermostatMode.UNKNOWN ? new JsonPrimitive(src.getDeconzValue()) : JsonNull.INSTANCE; return src != ThermostatMode.UNKNOWN ? new JsonPrimitive(src.getDeconzValue()) : JsonNull.INSTANCE;
} }
} }

View File

@ -163,7 +163,9 @@ public class DigiplexAreaHandler extends BaseThingHandler {
bridgeHandler = (DigiplexBridgeHandler) bridge.getHandler(); bridgeHandler = (DigiplexBridgeHandler) bridge.getHandler();
String areaParm = getThing().getProperties().get(DigiplexBindingConstants.PROPERTY_AREA_NO); String areaParm = getThing().getProperties().get(DigiplexBindingConstants.PROPERTY_AREA_NO);
areaNo = Integer.parseInt(areaParm); if (areaParm != null) {
areaNo = Integer.parseInt(areaParm);
}
bridgeHandler.registerMessageHandler(visitor); bridgeHandler.registerMessageHandler(visitor);
updateStatus(ThingStatus.ONLINE); updateStatus(ThingStatus.ONLINE);

View File

@ -121,7 +121,9 @@ public class DigiplexZoneHandler extends BaseThingHandler {
this.bridgeHandler = (DigiplexBridgeHandler) bridge.getHandler(); this.bridgeHandler = (DigiplexBridgeHandler) bridge.getHandler();
String nodeParm = getThing().getProperties().get(DigiplexBindingConstants.PROPERTY_ZONE_NO); String nodeParm = getThing().getProperties().get(DigiplexBindingConstants.PROPERTY_ZONE_NO);
zoneNo = Integer.parseInt(nodeParm); if (nodeParm != null) {
zoneNo = Integer.parseInt(nodeParm);
}
String areaParm = getThing().getProperties().get(DigiplexBindingConstants.PROPERTY_AREA_NO); String areaParm = getThing().getProperties().get(DigiplexBindingConstants.PROPERTY_AREA_NO);
if (areaParm != null) { if (areaParm != null) {
areaNo = Integer.parseInt(areaParm); areaNo = Integer.parseInt(areaParm);

View File

@ -18,7 +18,6 @@ import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map; import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.openhab.binding.digitalstrom.internal.DigitalSTROMBindingConstants; import org.openhab.binding.digitalstrom.internal.DigitalSTROMBindingConstants;
import org.openhab.binding.digitalstrom.internal.lib.config.Config; import org.openhab.binding.digitalstrom.internal.lib.config.Config;
import org.openhab.binding.digitalstrom.internal.lib.serverconnection.DsAPI; import org.openhab.binding.digitalstrom.internal.lib.serverconnection.DsAPI;
@ -81,7 +80,7 @@ public class BridgeDiscoveryService extends AbstractDiscoveryService {
if (dsidMap != null) { if (dsidMap != null) {
dSID = dsidMap.get(JSONApiResponseKeysEnum.DSID.getKey()); dSID = dsidMap.get(JSONApiResponseKeysEnum.DSID.getKey());
} }
if (StringUtils.isNotBlank(dSID)) { if (dSID != null && !dSID.isBlank()) {
return new ThingUID(DigitalSTROMBindingConstants.THING_TYPE_DSS_BRIDGE, dSID); return new ThingUID(DigitalSTROMBindingConstants.THING_TYPE_DSS_BRIDGE, dSID);
} else { } else {
logger.error("Can't get server dSID to generate ThingUID. Please add the server manually."); logger.error("Can't get server dSID to generate ThingUID. Please add the server manually.");

View File

@ -19,7 +19,6 @@ import java.util.Set;
import javax.jmdns.ServiceInfo; import javax.jmdns.ServiceInfo;
import org.apache.commons.lang.StringUtils;
import org.openhab.binding.digitalstrom.internal.DigitalSTROMBindingConstants; import org.openhab.binding.digitalstrom.internal.DigitalSTROMBindingConstants;
import org.openhab.binding.digitalstrom.internal.lib.config.Config; import org.openhab.binding.digitalstrom.internal.lib.config.Config;
import org.openhab.binding.digitalstrom.internal.lib.serverconnection.DsAPI; import org.openhab.binding.digitalstrom.internal.lib.serverconnection.DsAPI;
@ -84,7 +83,7 @@ public class BridgeMDNSDiscoveryParticipant implements MDNSDiscoveryParticipant
if (dsidMap != null) { if (dsidMap != null) {
dSID = dsidMap.get(JSONApiResponseKeysEnum.DSID.getKey()); dSID = dsidMap.get(JSONApiResponseKeysEnum.DSID.getKey());
} }
if (StringUtils.isNotBlank(dSID)) { if (dSID != null && !dSID.isBlank()) {
return new ThingUID(DigitalSTROMBindingConstants.THING_TYPE_DSS_BRIDGE, dSID); return new ThingUID(DigitalSTROMBindingConstants.THING_TYPE_DSS_BRIDGE, dSID);
} else { } else {
logger.error("Can't get server dSID to generate thing UID. Please add the server manually."); logger.error("Can't get server dSID to generate thing UID. Please add the server manually.");

View File

@ -12,12 +12,8 @@
*/ */
package org.openhab.binding.dsmr.internal.discovery; package org.openhab.binding.dsmr.internal.discovery;
import java.util.Collection; import java.util.*;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
@ -148,8 +144,9 @@ public class DSMRMeterDiscoveryService extends DSMRDiscoveryService implements P
.filter(DSMRMeterHandler.class::isInstance) .filter(DSMRMeterHandler.class::isInstance)
.map(DSMRMeterHandler.class::cast) .map(DSMRMeterHandler.class::cast)
.map(h -> h == null ? null : h.getMeterDescriptor()) .map(h -> h == null ? null : h.getMeterDescriptor())
.map(d -> d == null ? null : d.getMeterType()) .map(d -> Optional.ofNullable(d == null ? null : d.getMeterType()))
.filter(Objects::nonNull) .filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toSet()); .collect(Collectors.toSet());
// @formatter:on // @formatter:on
// Create list of all configured meters that are not in the detected list. If not empty meters might not be // Create list of all configured meters that are not in the detected list. If not empty meters might not be

View File

@ -32,7 +32,6 @@ import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.XMLEvent; import javax.xml.stream.events.XMLEvent;
import org.apache.commons.lang.StringUtils;
import org.openhab.core.cache.ExpiringCache; import org.openhab.core.cache.ExpiringCache;
import org.openhab.core.library.types.DateTimeType; import org.openhab.core.library.types.DateTimeType;
import org.openhab.core.library.types.OnOffType; import org.openhab.core.library.types.OnOffType;
@ -111,7 +110,7 @@ public class DwdWarningsData {
*/ */
public boolean refresh() { public boolean refresh() {
String rawData = dataAccessCached.getValue(); String rawData = dataAccessCached.getValue();
if (StringUtils.isEmpty(rawData)) { if (rawData == null || rawData.isEmpty()) {
logger.debug("No Data from Endpoint"); logger.debug("No Data from Endpoint");
return false; return false;
} }

View File

@ -414,6 +414,10 @@ public class EcobeeActions implements ThingActions {
EventDTO event = new EventDTO(); EventDTO event = new EventDTO();
for (String key : params.keySet()) { for (String key : params.keySet()) {
Object value = params.get(key); Object value = params.get(key);
if (value == null) {
LOGGER.warn("Event field '{}' has null value, ignored.", key);
continue;
}
switch (key) { switch (key) {
case "isOccupied": case "isOccupied":
event.isOccupied = ((Boolean) value); event.isOccupied = ((Boolean) value);

View File

@ -165,9 +165,13 @@ public class SelectionDTO {
} }
public void setThermostats(Set<String> thermostatIds) { public void setThermostats(Set<String> thermostatIds) {
boolean isRegistered = thermostatIds == null || thermostatIds.isEmpty(); if (thermostatIds == null || thermostatIds.isEmpty()) {
selectionType = isRegistered ? SelectionType.REGISTERED : SelectionType.THERMOSTATS; selectionType = SelectionType.REGISTERED;
selectionMatch = isRegistered ? "" : String.join(",", thermostatIds); selectionMatch = "";
} else {
selectionType = SelectionType.THERMOSTATS;
selectionMatch = String.join(",", thermostatIds);
}
} }
public void setSelectionType(SelectionType selectionType) { public void setSelectionType(SelectionType selectionType) {

View File

@ -159,7 +159,7 @@ public class TransmitterStick {
private static final long serialVersionUID = -3216360253151368826L; private static final long serialVersionUID = -3216360253151368826L;
public DueCommandSet() { public DueCommandSet() {
super(new Comparator<Command>() { super(new Comparator<>() {
/** /**
* Due commands are sorted by priority first and then by delay. * Due commands are sorted by priority first and then by delay.
*/ */

View File

@ -23,6 +23,7 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.Objects;
import java.util.Set; import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
@ -123,7 +124,7 @@ public class AbstractFMIResponseParsingTest {
try { try {
Method parseMethod = Client.class.getDeclaredMethod("parseMultiPointCoverageXml", String.class); Method parseMethod = Client.class.getDeclaredMethod("parseMultiPointCoverageXml", String.class);
parseMethod.setAccessible(true); parseMethod.setAccessible(true);
return (FMIResponse) parseMethod.invoke(client, content); return Objects.requireNonNull((FMIResponse) parseMethod.invoke(client, content));
} catch (InvocationTargetException e) { } catch (InvocationTargetException e) {
throw e.getTargetException(); throw e.getTargetException();
} catch (Exception e) { } catch (Exception e) {
@ -137,9 +138,9 @@ public class AbstractFMIResponseParsingTest {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
protected Set<Location> parseStations(String content) { protected Set<Location> parseStations(String content) {
try { try {
Method parseMethod = Client.class.getDeclaredMethod("parseStations", String.class); Method parseMethod = Objects.requireNonNull(Client.class.getDeclaredMethod("parseStations", String.class));
parseMethod.setAccessible(true); parseMethod.setAccessible(true);
return (Set<Location>) parseMethod.invoke(client, content); return Objects.requireNonNull((Set<Location>) parseMethod.invoke(client, content));
} catch (InvocationTargetException e) { } catch (InvocationTargetException e) {
throw new RuntimeException(e.getTargetException()); throw new RuntimeException(e.getTargetException());
} catch (Exception e) { } catch (Exception e) {

View File

@ -20,6 +20,7 @@ import java.net.URLEncoder;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
@ -95,7 +96,8 @@ public class FoobotApiConnector {
URLEncoder.encode(username, StandardCharsets.UTF_8.toString())); URLEncoder.encode(username, StandardCharsets.UTF_8.toString()));
logger.debug("URL = {}", url); logger.debug("URL = {}", url);
return GSON.fromJson(request(url, apiKey), FOOTBOT_DEVICE_LIST_TYPE); List<FoobotDevice> foobotDevices = GSON.fromJson(request(url, apiKey), FOOTBOT_DEVICE_LIST_TYPE);
return Objects.requireNonNull(foobotDevices);
} catch (JsonParseException | UnsupportedEncodingException e) { } catch (JsonParseException | UnsupportedEncodingException e) {
throw new FoobotApiException(0, e.getMessage()); throw new FoobotApiException(0, e.getMessage());
} }

View File

@ -17,6 +17,7 @@ import static org.junit.jupiter.api.Assertions.*;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Objects;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.mockito.Mock; import org.mockito.Mock;
@ -53,6 +54,7 @@ public class FoobotDeviceHandlerTest {
final FoobotJsonData sensorData = connector.getSensorData("1234"); final FoobotJsonData sensorData = connector.getSensorData("1234");
assertNotNull(sensorData, "No sensor data read"); assertNotNull(sensorData, "No sensor data read");
Objects.requireNonNull(sensorData);
assertEquals(handler.sensorDataToState("temperature", sensorData), new QuantityType(12.345, SIUnits.CELSIUS)); assertEquals(handler.sensorDataToState("temperature", sensorData), new QuantityType(12.345, SIUnits.CELSIUS));
assertEquals(handler.sensorDataToState("gpi", sensorData), new DecimalType(5.6789012)); assertEquals(handler.sensorDataToState("gpi", sensorData), new DecimalType(5.6789012));
} }

View File

@ -21,10 +21,7 @@ import static org.openhab.binding.fsinternetradio.internal.FSInternetRadioBindin
import java.io.IOException; import java.io.IOException;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.NonNull;
@ -148,6 +145,7 @@ public class FSInternetRadioHandlerJavaTest extends JavaTest {
private static @NonNull Channel getChannel(final @NonNull Thing thing, final @NonNull String channelId) { private static @NonNull Channel getChannel(final @NonNull Thing thing, final @NonNull String channelId) {
final Channel channel = thing.getChannel(channelId); final Channel channel = thing.getChannel(channelId);
assertNotNull(channel); assertNotNull(channel);
Objects.requireNonNull(channel);
return channel; return channel;
} }

View File

@ -18,6 +18,7 @@ import java.nio.charset.StandardCharsets;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.ServletException; import javax.servlet.ServletException;
@ -134,7 +135,7 @@ public class RadioServiceDummy extends HttpServlet {
Collection<String> requestParameterNames = Collections.list(request.getParameterNames()); Collection<String> requestParameterNames = Collections.list(request.getParameterNames());
if (queryString != null && requestParameterNames.contains(VALUE)) { if (queryString != null && requestParameterNames.contains(VALUE)) {
StringBuffer fullUrl = request.getRequestURL().append("?").append(queryString); StringBuffer fullUrl = request.getRequestURL().append("?").append(queryString);
int value = Integer.parseInt(request.getParameter(VALUE)); int value = Integer.parseInt(Objects.requireNonNullElse(request.getParameter(VALUE), ""));
requestParameters.put(value, fullUrl.toString()); requestParameters.put(value, fullUrl.toString());
} }

View File

@ -51,7 +51,7 @@ public class MessageUtil {
public LocationMessage fromJson(String json) { public LocationMessage fromJson(String json) {
for (String pattern : PATTERNS) { for (String pattern : PATTERNS) {
Class<? extends LocationMessage> c = MESSAGE_TYPES.get(pattern); Class<? extends LocationMessage> c = MESSAGE_TYPES.get(pattern);
if (json.matches(pattern)) { if (c != null && json.matches(pattern)) {
return gson.fromJson(json, c); return gson.fromJson(json, c);
} }
} }

View File

@ -47,8 +47,7 @@ public class GreeException extends Exception {
super(message, exception); super(message, exception);
} }
@Override public String getMessageString() {
public @Nullable String getMessage() {
return isEmpty() ? "" : nonNullString(super.getMessage()); return isEmpty() ? "" : nonNullString(super.getMessage());
} }
@ -69,7 +68,7 @@ public class GreeException extends Exception {
message = MessageFormat.format("{0} ({1})", message, cause); message = MessageFormat.format("{0} ({1})", message, cause);
} }
} else { } else {
message = getMessage(); message = getMessageString();
} }
return message; return message;
} }
@ -82,7 +81,7 @@ public class GreeException extends Exception {
Class<?> extype = !isEmpty() ? getCauseClass() : null; Class<?> extype = !isEmpty() ? getCauseClass() : null;
return (extype != null) && ((extype == SocketTimeoutException.class) || (extype == TimeoutException.class) return (extype != null) && ((extype == SocketTimeoutException.class) || (extype == TimeoutException.class)
|| (extype == ExecutionException.class) || (extype == InterruptedException.class) || (extype == ExecutionException.class) || (extype == InterruptedException.class)
|| getMessage().toLowerCase().contains("timeout")); || getMessageString().toLowerCase().contains("timeout"));
} }
public boolean isUnknownHost() { public boolean isUnknownHost() {

View File

@ -97,7 +97,7 @@ public class GreeDiscoveryService extends AbstractDiscoveryService {
createResult(deviceFinder.getDevices()); createResult(deviceFinder.getDevices());
} }
} catch (GreeException e) { } catch (GreeException e) {
logger.info("Discovery: {}", messages.get("discovery.exception", e.getMessage())); logger.info("Discovery: {}", messages.get("discovery.exception", e.getMessageString()));
} catch (SocketException | RuntimeException e) { } catch (SocketException | RuntimeException e) {
logger.warn("Discovery: {}", messages.get("discovery.exception", "RuntimeException"), e); logger.warn("Discovery: {}", messages.get("discovery.exception", "RuntimeException"), e);
} }

View File

@ -122,7 +122,7 @@ public class GreeHandler extends BaseThingHandler {
message = messages.get("thinginit.failed"); message = messages.get("thinginit.failed");
logger.info("{}: {}", thingId, message); logger.info("{}: {}", thingId, message);
} catch (GreeException e) { } catch (GreeException e) {
logger.info("{}: {}", thingId, messages.get("thinginit.exception", e.getMessage())); logger.info("{}: {}", thingId, messages.get("thinginit.exception", e.getMessageString()));
} catch (IOException e) { } catch (IOException e) {
logger.warn("{}: {}", thingId, messages.get("thinginit.exception", "I/O Error"), e); logger.warn("{}: {}", thingId, messages.get("thinginit.exception", "I/O Error"), e);
} catch (RuntimeException e) { } catch (RuntimeException e) {
@ -158,7 +158,7 @@ public class GreeHandler extends BaseThingHandler {
logger.debug("{}: Command {} failed for channel {}, retry", thingId, command, channelId); logger.debug("{}: Command {} failed for channel {}, retry", thingId, command, channelId);
} else { } else {
String message = logInfo( String message = logInfo(
messages.get("command.exception", command, channelId) + ": " + e.getMessage()); messages.get("command.exception", command, channelId) + ": " + e.getMessageString());
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, message); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, message);
} }
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
@ -379,7 +379,7 @@ public class GreeHandler extends BaseThingHandler {
if (e.getCause() != null) { if (e.getCause() != null) {
subcode = " (" + e.getCause().getMessage() + ")"; subcode = " (" + e.getCause().getMessage() + ")";
} }
String message = messages.get("update.exception", e.getMessage() + subcode); String message = messages.get("update.exception", e.getMessageString() + subcode);
if (getThing().getStatus() == ThingStatus.OFFLINE) { if (getThing().getStatus() == ThingStatus.OFFLINE) {
logger.debug("{}: Thing still OFFLINE ({})", thingId, message); logger.debug("{}: Thing still OFFLINE ({})", thingId, message);
} else { } else {
@ -472,7 +472,7 @@ public class GreeHandler extends BaseThingHandler {
updateState(channelID, state); updateState(channelID, state);
} }
} catch (GreeException e) { } catch (GreeException e) {
logger.info("{}: {}", thingId, messages.get("channel.exception", channelID, e.getMessage())); logger.info("{}: {}", thingId, messages.get("channel.exception", channelID, e.getMessageString()));
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.warn("{}: {}", thingId, messages.get("channel.exception", "RuntimeException"), e); logger.warn("{}: {}", thingId, messages.get("channel.exception", "RuntimeException"), e);
} }

View File

@ -35,7 +35,6 @@ import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.harmonyhub.internal.handler.HarmonyHubHandler; import org.openhab.binding.harmonyhub.internal.handler.HarmonyHubHandler;
@ -253,8 +252,8 @@ public class HarmonyHubDiscoveryService extends AbstractDiscoveryService {
String friendlyName = properties.get("friendlyName"); String friendlyName = properties.get("friendlyName");
String hostName = properties.get("host_name"); String hostName = properties.get("host_name");
String ip = properties.get("ip"); String ip = properties.get("ip");
if (StringUtils.isNotBlank(friendlyName) && StringUtils.isNotBlank(hostName) if (friendlyName != null && !friendlyName.isBlank() && hostName != null && !hostName.isBlank()
&& StringUtils.isNotBlank(ip) && !responses.contains(hostName)) { && ip != null && !ip.isBlank() && !responses.contains(hostName)) {
responses.add(hostName); responses.add(hostName);
hubDiscovered(ip, friendlyName, hostName); hubDiscovered(ip, friendlyName, hostName);
} }

View File

@ -196,7 +196,9 @@ public class HeosBridgeHandler extends BaseBridgeHandler implements HeosEventLis
@Nullable @Nullable
Group[] onlineGroups = getApiConnection().getGroups().payload; Group[] onlineGroups = getApiConnection().getGroups().payload;
updatePlayerStatus(onlinePlayers, onlineGroups); if (onlinePlayers != null && onlineGroups != null) {
updatePlayerStatus(onlinePlayers, onlineGroups);
}
} catch (ReadException | IOException e) { } catch (ReadException | IOException e) {
logger.debug("Failed updating online state of groups/players", e); logger.debug("Failed updating online state of groups/players", e);
} }

View File

@ -18,6 +18,7 @@ import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
@ -57,7 +58,7 @@ public class HeosJsonParser {
public <T> HeosResponseObject<T> parseResponse(String jsonBody, Class<T> clazz) { public <T> HeosResponseObject<T> parseResponse(String jsonBody, Class<T> clazz) {
HeosJsonWrapper wrapper = gson.fromJson(jsonBody, HeosJsonWrapper.class); HeosJsonWrapper wrapper = gson.fromJson(jsonBody, HeosJsonWrapper.class);
return postProcess(wrapper, clazz); return postProcess(Objects.requireNonNull(wrapper), clazz);
} }
private <T> HeosResponseObject<T> postProcess(HeosJsonWrapper wrapper, Class<T> clazz) { private <T> HeosResponseObject<T> postProcess(HeosJsonWrapper wrapper, Class<T> clazz) {

View File

@ -359,7 +359,11 @@ public class HueBridge {
List<SuccessResponse> entries = safeFromJson(result.getBody(), SuccessResponse.GSON_TYPE); List<SuccessResponse> entries = safeFromJson(result.getBody(), SuccessResponse.GSON_TYPE);
SuccessResponse response = entries.get(0); SuccessResponse response = entries.get(0);
return (String) response.success.get("/lights/" + enc(light.getId()) + "/name"); String lightName = (String) response.success.get("/lights/" + enc(light.getId()) + "/name");
if (lightName == null) {
throw new ApiException("Response didn't contain light name.");
}
return lightName;
} }
/** /**
@ -560,7 +564,11 @@ public class HueBridge {
List<SuccessResponse> entries = safeFromJson(result.getBody(), SuccessResponse.GSON_TYPE); List<SuccessResponse> entries = safeFromJson(result.getBody(), SuccessResponse.GSON_TYPE);
SuccessResponse response = entries.get(0); SuccessResponse response = entries.get(0);
return (String) response.success.get("/groups/" + enc(group.getId()) + "/name"); String groupName = (String) response.success.get("/groups/" + enc(group.getId()) + "/name");
if (groupName == null) {
throw new ApiException("Response didn't contain group name.");
}
return groupName;
} }
/** /**
@ -610,7 +618,11 @@ public class HueBridge {
List<SuccessResponse> entries = safeFromJson(result.getBody(), SuccessResponse.GSON_TYPE); List<SuccessResponse> entries = safeFromJson(result.getBody(), SuccessResponse.GSON_TYPE);
SuccessResponse response = entries.get(0); SuccessResponse response = entries.get(0);
return (String) response.success.get("/groups/" + enc(group.getId()) + "/name"); String groupName = (String) response.success.get("/groups/" + enc(group.getId()) + "/name");
if (groupName == null) {
throw new ApiException("Response didn't contain group name.");
}
return groupName;
} }
/** /**
@ -955,7 +967,11 @@ public class HueBridge {
List<SuccessResponse> entries = safeFromJson(result.getBody(), SuccessResponse.GSON_TYPE); List<SuccessResponse> entries = safeFromJson(result.getBody(), SuccessResponse.GSON_TYPE);
SuccessResponse response = entries.get(0); SuccessResponse response = entries.get(0);
return (String) response.success.get("username"); String username = (String) response.success.get("username");
if (username == null) {
throw new ApiException("Response didn't contain username");
}
return username;
} }
/** /**
@ -1019,7 +1035,8 @@ public class HueBridge {
handleErrors(result); handleErrors(result);
return gson.fromJson(result.getBody(), FullConfig.class); FullConfig fullConfig = gson.fromJson(result.getBody(), FullConfig.class);
return Objects.requireNonNull(fullConfig);
} }
// Used as assert in requests that require authentication // Used as assert in requests that require authentication

View File

@ -16,12 +16,7 @@ import static org.openhab.binding.hue.internal.HueBindingConstants.*;
import static org.openhab.core.thing.Thing.PROPERTY_SERIAL_NUMBER; import static org.openhab.core.thing.Thing.PROPERTY_SERIAL_NUMBER;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
@ -162,8 +157,10 @@ public class HueBridgeNupnpDiscovery extends AbstractDiscoveryService {
try { try {
Gson gson = new Gson(); Gson gson = new Gson();
String json = doGetRequest(DISCOVERY_URL); String json = doGetRequest(DISCOVERY_URL);
return gson.fromJson(json, new TypeToken<List<BridgeJsonParameters>>() { List<BridgeJsonParameters> bridgeParameters = gson.fromJson(json,
}.getType()); new TypeToken<List<BridgeJsonParameters>>() {
}.getType());
return Objects.requireNonNull(bridgeParameters);
} catch (IOException e) { } catch (IOException e) {
logger.debug("Philips Hue NUPnP service not reachable. Can't discover bridges"); logger.debug("Philips Hue NUPnP service not reachable. Can't discover bridges");
} catch (JsonParseException je) { } catch (JsonParseException je) {

View File

@ -19,7 +19,6 @@ import java.util.Optional;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
@ -94,10 +93,9 @@ public class HydrawiseCloudHandler extends HydrawiseHandler {
} else { } else {
// try and use ID from saved property // try and use ID from saved property
String controllerId = getThing().getProperties().get(PROPERTY_CONTROLLER_ID); String controllerId = getThing().getProperties().get(PROPERTY_CONTROLLER_ID);
if (StringUtils.isNotBlank(controllerId)) { if (controllerId != null && !controllerId.isBlank()) {
try { try {
controller = getController(Integer.parseInt(controllerId), controllers); controller = getController(Integer.parseInt(controllerId), controllers);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
logger.debug("Can not parse property vaue {}", controllerId); logger.debug("Can not parse property vaue {}", controllerId);
} }

View File

@ -16,10 +16,7 @@ import static org.openhab.binding.hydrawise.internal.HydrawiseBindingConstants.*
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit; import java.time.temporal.ChronoUnit;
import java.util.Collections; import java.util.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -127,6 +124,7 @@ public abstract class HydrawiseHandler extends BaseThingHandler {
if (allCommand) { if (allCommand) {
sendRunAllCommand(((DecimalType) command).intValue()); sendRunAllCommand(((DecimalType) command).intValue());
} else { } else {
Objects.requireNonNull(relay);
sendRunCommand(((DecimalType) command).intValue(), relay); sendRunCommand(((DecimalType) command).intValue(), relay);
} }
break; break;
@ -142,6 +140,7 @@ public abstract class HydrawiseHandler extends BaseThingHandler {
sendStopAllCommand(); sendStopAllCommand();
} }
} else { } else {
Objects.requireNonNull(relay);
if (command == OnOffType.ON) { if (command == OnOffType.ON) {
sendRunCommand(relay); sendRunCommand(relay);
} else { } else {

View File

@ -12,6 +12,7 @@
*/ */
package org.openhab.binding.hydrawise.internal.api; package org.openhab.binding.hydrawise.internal.api;
import java.util.Objects;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
@ -89,7 +90,7 @@ public class HydrawiseCloudApiClient {
public StatusScheduleResponse getStatusSchedule(int controllerId) public StatusScheduleResponse getStatusSchedule(int controllerId)
throws HydrawiseConnectionException, HydrawiseAuthenticationException { throws HydrawiseConnectionException, HydrawiseAuthenticationException {
String json = doGet(String.format(STATUS_SCHEDUE_URL, apiKey, controllerId)); String json = doGet(String.format(STATUS_SCHEDUE_URL, apiKey, controllerId));
StatusScheduleResponse response = gson.fromJson(json, StatusScheduleResponse.class); StatusScheduleResponse response = Objects.requireNonNull(gson.fromJson(json, StatusScheduleResponse.class));
throwExceptionIfResponseError(response); throwExceptionIfResponseError(response);
return response; return response;
} }
@ -104,13 +105,13 @@ public class HydrawiseCloudApiClient {
public CustomerDetailsResponse getCustomerDetails() public CustomerDetailsResponse getCustomerDetails()
throws HydrawiseConnectionException, HydrawiseAuthenticationException { throws HydrawiseConnectionException, HydrawiseAuthenticationException {
String json = doGet(String.format(CUSTOMER_DETAILS_URL, apiKey)); String json = doGet(String.format(CUSTOMER_DETAILS_URL, apiKey));
CustomerDetailsResponse response = gson.fromJson(json, CustomerDetailsResponse.class); CustomerDetailsResponse response = Objects.requireNonNull(gson.fromJson(json, CustomerDetailsResponse.class));
throwExceptionIfResponseError(response); throwExceptionIfResponseError(response);
return response; return response;
} }
/*** /***
* Sets the controller with supplied {@value id} as the current controller * Sets the controller with supplied {@param id} as the current controller
* *
* @param id * @param id
* @return SetControllerResponse * @return SetControllerResponse
@ -121,7 +122,7 @@ public class HydrawiseCloudApiClient {
public SetControllerResponse setController(int id) public SetControllerResponse setController(int id)
throws HydrawiseConnectionException, HydrawiseAuthenticationException, HydrawiseCommandException { throws HydrawiseConnectionException, HydrawiseAuthenticationException, HydrawiseCommandException {
String json = doGet(String.format(SET_CONTROLLER_URL, apiKey, id)); String json = doGet(String.format(SET_CONTROLLER_URL, apiKey, id));
SetControllerResponse response = gson.fromJson(json, SetControllerResponse.class); SetControllerResponse response = Objects.requireNonNull(gson.fromJson(json, SetControllerResponse.class));
throwExceptionIfResponseError(response); throwExceptionIfResponseError(response);
if (!response.message.equals("OK")) { if (!response.message.equals("OK")) {
throw new HydrawiseCommandException(response.message); throw new HydrawiseCommandException(response.message);
@ -271,7 +272,7 @@ public class HydrawiseCloudApiClient {
private String relayCommand(String url) private String relayCommand(String url)
throws HydrawiseConnectionException, HydrawiseAuthenticationException, HydrawiseCommandException { throws HydrawiseConnectionException, HydrawiseAuthenticationException, HydrawiseCommandException {
String json = doGet(url); String json = doGet(url);
SetZoneResponse response = gson.fromJson(json, SetZoneResponse.class); SetZoneResponse response = Objects.requireNonNull(gson.fromJson(json, SetZoneResponse.class));
throwExceptionIfResponseError(response); throwExceptionIfResponseError(response);
if ("error".equals(response.messageType)) { if ("error".equals(response.messageType)) {
throw new HydrawiseCommandException(response.message); throw new HydrawiseCommandException(response.message);

View File

@ -13,6 +13,7 @@
package org.openhab.binding.hydrawise.internal.api; package org.openhab.binding.hydrawise.internal.api;
import java.net.URI; import java.net.URI;
import java.util.Objects;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
@ -95,7 +96,7 @@ public class HydrawiseLocalApiClient {
throws HydrawiseConnectionException, HydrawiseAuthenticationException { throws HydrawiseConnectionException, HydrawiseAuthenticationException {
String json = doGet(localGetURL); String json = doGet(localGetURL);
LocalScheduleResponse response = gson.fromJson(json, LocalScheduleResponse.class); LocalScheduleResponse response = gson.fromJson(json, LocalScheduleResponse.class);
return response; return Objects.requireNonNull(response);
} }
/** /**

View File

@ -17,6 +17,7 @@ import java.lang.reflect.Type;
import java.net.URI; import java.net.URI;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
@ -120,7 +121,7 @@ public class IAqualinkClient {
if (response.getStatus() != HttpStatus.OK_200) { if (response.getStatus() != HttpStatus.OK_200) {
throw new IOException(response.getReason()); throw new IOException(response.getReason());
} }
return gson.fromJson(response.getContentAsString(), AccountInfo.class); return Objects.requireNonNull(gson.fromJson(response.getContentAsString(), AccountInfo.class));
} catch (InterruptedException | TimeoutException | ExecutionException e) { } catch (InterruptedException | TimeoutException | ExecutionException e) {
throw new IOException(e); throw new IOException(e);
} }
@ -347,7 +348,7 @@ public class IAqualinkClient {
* @throws NotAuthorizedException * @throws NotAuthorizedException
*/ */
private <T> T getAqualinkObject(URI uri, Type typeOfT) throws IOException, NotAuthorizedException { private <T> T getAqualinkObject(URI uri, Type typeOfT) throws IOException, NotAuthorizedException {
return gson.fromJson(getRequest(uri), typeOfT); return Objects.requireNonNull(gson.fromJson(getRequest(uri), typeOfT));
} }
/** /**
@ -383,11 +384,8 @@ public class IAqualinkClient {
class HomeDeserializer implements JsonDeserializer<Home> { class HomeDeserializer implements JsonDeserializer<Home> {
@Override @Override
public Home deserialize(@Nullable JsonElement json, @Nullable Type typeOfT, public @Nullable Home deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
@Nullable JsonDeserializationContext context) throws JsonParseException { throws JsonParseException {
if (json == null) {
throw new JsonParseException("No JSON");
}
JsonObject jsonObject = json.getAsJsonObject(); JsonObject jsonObject = json.getAsJsonObject();
JsonArray homeScreen = jsonObject.getAsJsonArray("home_screen"); JsonArray homeScreen = jsonObject.getAsJsonArray("home_screen");
JsonObject home = new JsonObject(); JsonObject home = new JsonObject();
@ -408,11 +406,8 @@ public class IAqualinkClient {
class OneTouchDeserializer implements JsonDeserializer<OneTouch[]> { class OneTouchDeserializer implements JsonDeserializer<OneTouch[]> {
@Override @Override
public OneTouch[] deserialize(@Nullable JsonElement json, @Nullable Type typeOfT, public OneTouch @Nullable [] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
@Nullable JsonDeserializationContext context) throws JsonParseException { throws JsonParseException {
if (json == null) {
throw new JsonParseException("No JSON");
}
JsonObject jsonObject = json.getAsJsonObject(); JsonObject jsonObject = json.getAsJsonObject();
JsonArray oneTouchScreen = jsonObject.getAsJsonArray("onetouch_screen"); JsonArray oneTouchScreen = jsonObject.getAsJsonArray("onetouch_screen");
List<OneTouch> list = new ArrayList<>(); List<OneTouch> list = new ArrayList<>();
@ -429,7 +424,7 @@ public class IAqualinkClient {
oneTouchJson.add(oneTouchEntry.getKey(), oneTouchEntry.getValue()); oneTouchJson.add(oneTouchEntry.getKey(), oneTouchEntry.getValue());
}); });
}); });
list.add(gsonInternal.fromJson(oneTouchJson, OneTouch.class)); list.add(Objects.requireNonNull(gsonInternal.fromJson(oneTouchJson, OneTouch.class)));
} }
} }
}); });
@ -441,11 +436,8 @@ public class IAqualinkClient {
class AuxDeserializer implements JsonDeserializer<Auxiliary[]> { class AuxDeserializer implements JsonDeserializer<Auxiliary[]> {
@Override @Override
public Auxiliary[] deserialize(@Nullable JsonElement json, @Nullable Type typeOfT, public Auxiliary @Nullable [] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
@Nullable JsonDeserializationContext context) throws JsonParseException { throws JsonParseException {
if (json == null) {
throw new JsonParseException("No JSON");
}
JsonObject jsonObject = json.getAsJsonObject(); JsonObject jsonObject = json.getAsJsonObject();
JsonArray auxScreen = jsonObject.getAsJsonArray("devices_screen"); JsonArray auxScreen = jsonObject.getAsJsonArray("devices_screen");
List<Auxiliary> list = new ArrayList<>(); List<Auxiliary> list = new ArrayList<>();
@ -462,7 +454,7 @@ public class IAqualinkClient {
auxJson.add(auxEntry.getKey(), auxEntry.getValue()); auxJson.add(auxEntry.getKey(), auxEntry.getValue());
}); });
}); });
list.add(gsonInternal.fromJson(auxJson, Auxiliary.class)); list.add(Objects.requireNonNull(gsonInternal.fromJson(auxJson, Auxiliary.class)));
} }
} }
}); });

View File

@ -20,10 +20,7 @@ import java.net.SocketTimeoutException;
import java.net.URI; import java.net.URI;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle; import java.time.format.FormatStyle;
import java.util.Collection; import java.util.*;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.*; import java.util.concurrent.*;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
@ -238,6 +235,11 @@ public class InnogyBridgeHandler extends BaseBridgeHandler
} }
Device bridgeDevice = deviceStructMan.getBridgeDevice(); Device bridgeDevice = deviceStructMan.getBridgeDevice();
if (bridgeDevice == null) {
logger.debug("Failed to get bridge device, re-scheduling startClient.");
scheduleRestartClient(true);
return;
}
setBridgeProperties(bridgeDevice); setBridgeProperties(bridgeDevice);
bridgeId = bridgeDevice.getId(); bridgeId = bridgeDevice.getId();
startWebsocket(); startWebsocket();
@ -533,7 +535,7 @@ public class InnogyBridgeHandler extends BaseBridgeHandler
case BaseEvent.TYPE_NEW_MESSAGE_RECEIVED: case BaseEvent.TYPE_NEW_MESSAGE_RECEIVED:
case BaseEvent.TYPE_MESSAGE_CREATED: case BaseEvent.TYPE_MESSAGE_CREATED:
final MessageEvent messageEvent = gson.fromJson(msg, MessageEvent.class); final MessageEvent messageEvent = gson.fromJson(msg, MessageEvent.class);
handleNewMessageReceivedEvent(messageEvent); handleNewMessageReceivedEvent(Objects.requireNonNull(messageEvent));
break; break;
case BaseEvent.TYPE_MESSAGE_DELETED: case BaseEvent.TYPE_MESSAGE_DELETED:

View File

@ -63,7 +63,7 @@ public abstract class CommandHandler {
/** /**
* Implements what to do when an openHAB command is received * Implements what to do when an openHAB command is received
* *
* @param config the configuration for the item that generated the command * @param conf the configuration for the item that generated the command
* @param cmd the openhab command issued * @param cmd the openhab command issued
* @param device the Insteon device to which this command applies * @param device the Insteon device to which this command applies
*/ */

View File

@ -16,11 +16,7 @@ import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
@ -440,8 +436,7 @@ public class DeviceFeature {
static { static {
// read features from xml file and store them in a map // read features from xml file and store them in a map
InputStream input = DeviceFeature.class.getResourceAsStream("/device_features.xml"); InputStream input = DeviceFeature.class.getResourceAsStream("/device_features.xml");
if (input != null) { Objects.requireNonNull(input);
readFeatureTemplates(input); readFeatureTemplates(input);
}
} }
} }

View File

@ -74,7 +74,7 @@ public class DeviceTypeLoader {
* Reads the device types from input stream and stores them in memory for * Reads the device types from input stream and stores them in memory for
* later access. * later access.
* *
* @param is the input stream from which to read * @param in the input stream from which to read
*/ */
public void loadDeviceTypesXML(InputStream in) throws ParserConfigurationException, SAXException, IOException { public void loadDeviceTypesXML(InputStream in) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
@ -204,20 +204,18 @@ public class DeviceTypeLoader {
public static synchronized DeviceTypeLoader instance() { public static synchronized DeviceTypeLoader instance() {
if (deviceTypeLoader.getDeviceTypes().isEmpty()) { if (deviceTypeLoader.getDeviceTypes().isEmpty()) {
InputStream input = DeviceTypeLoader.class.getResourceAsStream("/device_types.xml"); InputStream input = DeviceTypeLoader.class.getResourceAsStream("/device_types.xml");
if (input != null) { try {
try { if (input != null) {
deviceTypeLoader.loadDeviceTypesXML(input); deviceTypeLoader.loadDeviceTypesXML(input);
} catch (ParserConfigurationException e) { } else {
logger.warn("parser config error when reading device types xml file: ", e); logger.warn("Resource stream is null, cannot read xml file.");
} catch (SAXException e) {
logger.warn("SAX exception when reading device types xml file: ", e);
} catch (IOException e) {
logger.warn("I/O exception when reading device types xml file: ", e);
} }
logger.debug("loaded {} devices: ", deviceTypeLoader.getDeviceTypes().size()); } catch (ParserConfigurationException e) {
deviceTypeLoader.logDeviceTypes(); logger.warn("parser config error when reading device types xml file: ", e);
} else { } catch (SAXException e) {
logger.warn("unable to get device types xml file as a resource"); logger.warn("SAX exception when reading device types xml file: ", e);
} catch (IOException e) {
logger.warn("I/O exception when reading device types xml file: ", e);
} }
} }
return deviceTypeLoader; return deviceTypeLoader;

View File

@ -14,13 +14,7 @@ package org.openhab.binding.insteon.internal.handler;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.ArrayList; import java.util.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
@ -185,7 +179,7 @@ public class InsteonDeviceHandler extends BaseThingHandler {
Type mapType = new TypeToken<Map<String, Object>>() { Type mapType = new TypeToken<Map<String, Object>>() {
}.getType(); }.getType();
try { try {
deviceConfigMap = new Gson().fromJson(deviceConfig, mapType); deviceConfigMap = Objects.requireNonNull(new Gson().fromJson(deviceConfig, mapType));
} catch (JsonParseException e) { } catch (JsonParseException e) {
String msg = "The device configuration parameter is not valid JSON."; String msg = "The device configuration parameter is not valid JSON.";
logger.warn("{} {}", thing.getUID().getAsString(), msg); logger.warn("{} {}", thing.getUID().getAsString(), msg);

View File

@ -177,6 +177,8 @@ public class JablotronJa100Handler extends JablotronAlarmHandler {
if (channel == null) { if (channel == null) {
logger.debug("Creating a new temperature channel: {}", segmentId); logger.debug("Creating a new temperature channel: {}", segmentId);
createTempChannel(segmentId, segment.getSegmentName()); createTempChannel(segmentId, segment.getSegmentName());
processThermometer(segment);
return;
} }
updateTemperatureChannel(channel, segment); updateTemperatureChannel(channel, segment);
} }
@ -187,6 +189,8 @@ public class JablotronJa100Handler extends JablotronAlarmHandler {
if (channel == null) { if (channel == null) {
logger.debug("Creating a new thermostat channel: {}", segmentId); logger.debug("Creating a new thermostat channel: {}", segmentId);
createThermostatChannel(segmentId, segment.getSegmentName()); createThermostatChannel(segmentId, segment.getSegmentName());
processThermostat(segment);
return;
} }
updateTemperatureChannel(channel, segment); updateTemperatureChannel(channel, segment);
} }

View File

@ -54,15 +54,21 @@ public class KM200Utils {
*/ */
public static String checkParameterReplacement(Channel channel, KM200Device device) { public static String checkParameterReplacement(Channel channel, KM200Device device) {
String service = KM200Utils.translatesNameToPath(channel.getProperties().get("root")); String service = KM200Utils.translatesNameToPath(channel.getProperties().get("root"));
if (service.contains(SWITCH_PROGRAM_REPLACEMENT)) { if (service == null) {
String currentService = KM200Utils LOGGER.warn("Root property not found in device {}", device);
.translatesNameToPath(channel.getProperties().get(SWITCH_PROGRAM_CURRENT_PATH_NAME)); throw new IllegalStateException("root property not found");
}
String currentService = KM200Utils
.translatesNameToPath(channel.getProperties().get(SWITCH_PROGRAM_CURRENT_PATH_NAME));
if (currentService != null) {
if (device.containsService(currentService)) { if (device.containsService(currentService)) {
KM200ServiceObject curSerObj = device.getServiceObject(currentService); KM200ServiceObject curSerObj = device.getServiceObject(currentService);
if (null != curSerObj) { if (null != curSerObj) {
if (DATA_TYPE_STRING_VALUE.equals(curSerObj.getServiceType())) { if (DATA_TYPE_STRING_VALUE.equals(curSerObj.getServiceType())) {
String val = (String) curSerObj.getValue(); String val = (String) curSerObj.getValue();
service = service.replace(SWITCH_PROGRAM_REPLACEMENT, val); if (val != null) {
service = service.replace(SWITCH_PROGRAM_REPLACEMENT, val);
}
return service; return service;
} }
} }

View File

@ -354,7 +354,7 @@ public class KM200SwitchProgramServiceHandler {
firstVal = (BigDecimal) setpObject.serviceTreeMap.get(key).getValue(); firstVal = (BigDecimal) setpObject.serviceTreeMap.get(key).getValue();
} else { } else {
BigDecimal nextVal = (BigDecimal) setpObject.serviceTreeMap.get(key).getValue(); BigDecimal nextVal = (BigDecimal) setpObject.serviceTreeMap.get(key).getValue();
if (null != nextVal) { if (null != nextVal && null != firstVal) {
if (nextVal.compareTo(firstVal) > 0) { if (nextVal.compareTo(firstVal) > 0) {
positiveSwitch = key; positiveSwitch = key;
} else { } else {

View File

@ -231,6 +231,10 @@ public class KM200ThingHandler extends BaseThingHandler {
return; return;
} }
String service = KM200Utils.translatesNameToPath(thing.getProperties().get("root")); String service = KM200Utils.translatesNameToPath(thing.getProperties().get("root"));
if (service == null) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "root property missing");
return;
}
synchronized (gateway.getDevice()) { synchronized (gateway.getDevice()) {
updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING); updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING);
if (!gateway.getDevice().getInited()) { if (!gateway.getDevice().getInited()) {
@ -284,10 +288,14 @@ public class KM200ThingHandler extends BaseThingHandler {
state = StateDescriptionFragmentBuilder.create().withMinimum(BigDecimal.ZERO).withStep(BigDecimal.ONE) state = StateDescriptionFragmentBuilder.create().withMinimum(BigDecimal.ZERO).withStep(BigDecimal.ONE)
.withPattern("%d minutes").build(); .withPattern("%d minutes").build();
String posName = thing.getProperties().get(SWITCH_PROGRAM_POSITIVE); String posName = thing.getProperties().get(SWITCH_PROGRAM_POSITIVE);
newChannel = createChannel(new ChannelTypeUID(thing.getUID().getAsString() + ":" + posName), if (posName == null) {
new ChannelUID(thing.getUID(), posName), service + "/" + posName, CoreItemFactory.NUMBER, newChannel = null;
currentPathName, "Positive switch of the cycle, like 'Day' 'On'", posName, true, true, state, } else {
"minutes"); newChannel = createChannel(new ChannelTypeUID(thing.getUID().getAsString() + ":" + posName),
new ChannelUID(thing.getUID(), posName), service + "/" + posName, CoreItemFactory.NUMBER,
currentPathName, "Positive switch of the cycle, like 'Day' 'On'", posName, true, true,
state, "minutes");
}
if (null == newChannel) { if (null == newChannel) {
logger.warn("Creation of the channel {} was not possible", thing.getUID()); logger.warn("Creation of the channel {} was not possible", thing.getUID());
} else { } else {
@ -295,10 +303,14 @@ public class KM200ThingHandler extends BaseThingHandler {
} }
String negName = thing.getProperties().get(SWITCH_PROGRAM_NEGATIVE); String negName = thing.getProperties().get(SWITCH_PROGRAM_NEGATIVE);
newChannel = createChannel(new ChannelTypeUID(thing.getUID().getAsString() + ":" + negName), if (negName == null) {
new ChannelUID(thing.getUID(), negName), service + "/" + negName, CoreItemFactory.NUMBER, newChannel = null;
currentPathName, "Negative switch of the cycle, like 'Night' 'Off'", negName, true, true, state, } else {
"minutes"); newChannel = createChannel(new ChannelTypeUID(thing.getUID().getAsString() + ":" + negName),
new ChannelUID(thing.getUID(), negName), service + "/" + negName, CoreItemFactory.NUMBER,
currentPathName, "Negative switch of the cycle, like 'Night' 'Off'", negName, true, true,
state, "minutes");
}
if (null == newChannel) { if (null == newChannel) {
logger.warn("Creation of the channel {} was not possible", thing.getUID()); logger.warn("Creation of the channel {} was not possible", thing.getUID());
} else { } else {

View File

@ -30,6 +30,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
/** /**
* KVVBridgeHandler encapsulates the communication with the KVV API. * KVVBridgeHandler encapsulates the communication with the KVV API.
@ -106,7 +107,7 @@ public class KVVBridgeHandler extends BaseBridgeHandler {
DepartureResult result; DepartureResult result;
try { try {
result = new Gson().fromJson(data, DepartureResult.class); result = new Gson().fromJson(data, DepartureResult.class);
} catch (Exception e) { } catch (JsonSyntaxException e) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Failed to connect to KVV API"); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Failed to connect to KVV API");
logger.debug("Failed to parse departure data", e); logger.debug("Failed to parse departure data", e);
logger.debug("Server returned '{}'", data); logger.debug("Server returned '{}'", data);
@ -114,6 +115,10 @@ public class KVVBridgeHandler extends BaseBridgeHandler {
return null; return null;
} }
if (result == null) {
return null;
}
if (this.wasOffline) { if (this.wasOffline) {
updateStatus(ThingStatus.ONLINE); updateStatus(ThingStatus.ONLINE);
} }
@ -132,7 +137,6 @@ public class KVVBridgeHandler extends BaseBridgeHandler {
/** /**
* Creates a new @{link Cache}. * Creates a new @{link Cache}.
* *
* @param updateInterval the @{code updateInterval}
*/ */
public Cache() { public Cache() {
this.updateInterval = KVVBindingConstants.CACHE_DEFAULT_UPDATEINTERVAL; this.updateInterval = KVVBindingConstants.CACHE_DEFAULT_UPDATEINTERVAL;

View File

@ -5,6 +5,7 @@
package org.openhab.binding.lametrictime.api.common.impl.typeadapters.imported; package org.openhab.binding.lametrictime.api.common.impl.typeadapters.imported;
import java.io.IOException; import java.io.IOException;
import java.io.ObjectStreamException;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
@ -51,6 +52,9 @@ public abstract class CustomizedTypeAdapterFactory<C> implements TypeAdapterFact
{ {
JsonElement tree = elementAdapter.read(in); JsonElement tree = elementAdapter.read(in);
afterRead(tree); afterRead(tree);
if (tree == null) {
throw new IOException("null reader");
}
return delegate.fromJsonTree(tree); return delegate.fromJsonTree(tree);
} }
}; };

View File

@ -21,12 +21,7 @@ import java.nio.channels.Channel;
import java.nio.channels.CompletionHandler; import java.nio.channels.CompletionHandler;
import java.time.Instant; import java.time.Instant;
import java.time.temporal.ChronoUnit; import java.time.temporal.ChronoUnit;
import java.util.ArrayList; import java.util.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.BlockingQueue; import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
@ -150,7 +145,7 @@ public class Connection {
* @return the data * @return the data
*/ */
public ModInfo updateModuleData(LcnAddrMod addr) { public ModInfo updateModuleData(LcnAddrMod addr) {
return modData.computeIfAbsent(addr, ModInfo::new); return Objects.requireNonNull(modData.computeIfAbsent(addr, ModInfo::new));
} }
/** /**

View File

@ -17,6 +17,7 @@ import java.net.InetSocketAddress;
import java.net.StandardSocketOptions; import java.net.StandardSocketOptions;
import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler; import java.nio.channels.CompletionHandler;
import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
@ -78,15 +79,13 @@ public class ConnectionStateConnecting extends AbstractConnectionState {
} }
private void handleConnectionFailure(@Nullable Throwable e) { private void handleConnectionFailure(@Nullable Throwable e) {
String message; String message = null;
if (e != null) { if (e != null) {
logger.warn("Could not connect to {}:{}: {}", connection.getSettings().getAddress(), logger.warn("Could not connect to {}:{}: {}", connection.getSettings().getAddress(),
connection.getSettings().getPort(), e.getMessage()); connection.getSettings().getPort(), e.getMessage());
message = e.getMessage(); message = e.getMessage();
} else {
message = "";
} }
connection.getCallback().onOffline(message); connection.getCallback().onOffline(Objects.requireNonNullElse(message, ""));
context.handleConnectionFailed(e); context.handleConnectionFailed(e);
} }

View File

@ -36,6 +36,7 @@ package org.openhab.binding.lgwebos.internal.handler.command;
import java.util.function.Function; import java.util.function.Function;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.lgwebos.internal.handler.core.ResponseListener; import org.openhab.binding.lgwebos.internal.handler.core.ResponseListener;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
@ -57,11 +58,11 @@ public class ServiceCommand<T> {
protected Type type; protected Type type;
protected JsonObject payload; protected JsonObject payload;
protected String target; protected String target;
protected Function<JsonObject, T> converter; protected Function<JsonObject, @Nullable T> converter;
ResponseListener<T> responseListener; ResponseListener<T> responseListener;
public ServiceCommand(String targetURL, JsonObject payload, Function<JsonObject, T> converter, public ServiceCommand(String targetURL, JsonObject payload, Function<JsonObject, @Nullable T> converter,
ResponseListener<T> listener) { ResponseListener<T> listener) {
this.target = targetURL; this.target = targetURL;
this.payload = payload; this.payload = payload;

View File

@ -35,6 +35,7 @@ package org.openhab.binding.lgwebos.internal.handler.command;
import java.util.function.Function; import java.util.function.Function;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.lgwebos.internal.handler.core.ResponseListener; import org.openhab.binding.lgwebos.internal.handler.core.ResponseListener;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
@ -48,7 +49,7 @@ import com.google.gson.JsonObject;
*/ */
public class ServiceSubscription<T> extends ServiceCommand<T> { public class ServiceSubscription<T> extends ServiceCommand<T> {
public ServiceSubscription(String uri, JsonObject payload, Function<JsonObject, T> converter, public ServiceSubscription(String uri, JsonObject payload, Function<JsonObject, @Nullable T> converter,
ResponseListener<T> listener) { ResponseListener<T> listener) {
super(uri, payload, converter, listener); super(uri, payload, converter, listener);
type = Type.subscribe; type = Type.subscribe;

View File

@ -636,6 +636,7 @@ public class LifxLightHandler extends BaseThingHandler {
.setTemperature(percentTypeToKelvin(localPowerOnTemperature, product.getTemperatureRange())); .setTemperature(percentTypeToKelvin(localPowerOnTemperature, product.getTemperatureRange()));
} }
PercentType powerOnBrightness = this.powerOnBrightness;
if (powerOnBrightness != null) { if (powerOnBrightness != null) {
PercentType newBrightness = onOff == OnOffType.ON ? powerOnBrightness : new PercentType(0); PercentType newBrightness = onOff == OnOffType.ON ? powerOnBrightness : new PercentType(0);
getLightStateForCommand().setBrightness(newBrightness); getLightStateForCommand().setBrightness(newBrightness);

View File

@ -213,7 +213,7 @@ public class EnedisHttpApi {
public UserInfo getUserInfo() throws LinkyException { public UserInfo getUserInfo() throws LinkyException {
final String user_info_url = URL_APPS_LINCS + "/userinfos"; final String user_info_url = URL_APPS_LINCS + "/userinfos";
String data = getData(user_info_url); String data = getData(user_info_url);
return gson.fromJson(data, UserInfo.class); return Objects.requireNonNull(gson.fromJson(data, UserInfo.class));
} }
private Consumption getMeasures(String userId, String prmId, LocalDate from, LocalDate to, String request) private Consumption getMeasures(String userId, String prmId, LocalDate from, LocalDate to, String request)

View File

@ -533,14 +533,14 @@ public class LxServerHandler extends BaseThingHandler implements LxServerHandler
channels.sort((c1, c2) -> { channels.sort((c1, c2) -> {
String label1 = c1.getLabel(); String label1 = c1.getLabel();
String label2 = c2.getLabel(); String label2 = c2.getLabel();
if (label1 == null && label2 != null) { if (label1 != null && label2 != null) {
return label1.compareTo(label2);
} else if (label1 == null && label2 != null) {
return 1; return 1;
} else if (label1 != null && label2 == null) { } else if (label1 != null && label2 == null) {
return -1; return -1;
} else if (label1 == null && label2 == null) {
return 0;
} else { } else {
return label1.compareTo(label2); return 0;
} }
}); });
ThingBuilder builder = editThing(); ThingBuilder builder = editThing();

View File

@ -14,6 +14,7 @@ package org.openhab.binding.luftdateninfo.internal.handler;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
@ -82,7 +83,7 @@ public class HTTPHandler {
} else { } else {
failure = result.getFailure().getMessage(); failure = result.getFailure().getMessage();
} }
callback.onError(failure); callback.onError(Objects.requireNonNullElse(failure, "Unknown error"));
} else { } else {
callback.onResponse(getContentAsString()); callback.onResponse(getContentAsString());
} }

View File

@ -15,6 +15,7 @@ package org.openhab.binding.luftdateninfo.internal;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
import java.util.List; import java.util.List;
import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
@ -41,14 +42,17 @@ public class HTTPHandlerEvalTest {
public void setUp() { public void setUp() {
String conditionsStr = FileReader.readFileInString("src/test/resources/condition-result-no-pressure.json"); String conditionsStr = FileReader.readFileInString("src/test/resources/condition-result-no-pressure.json");
assertNotNull(conditionsStr); assertNotNull(conditionsStr);
Objects.requireNonNull(conditionsStr);
conditions = http.getLatestValues(conditionsStr); conditions = http.getLatestValues(conditionsStr);
String particulateStr = FileReader.readFileInString("src/test/resources/pm-result.json"); String particulateStr = FileReader.readFileInString("src/test/resources/pm-result.json");
assertNotNull(particulateStr); assertNotNull(particulateStr);
Objects.requireNonNull(particulateStr);
particulate = http.getLatestValues(particulateStr); particulate = http.getLatestValues(particulateStr);
String noiseStr = FileReader.readFileInString("src/test/resources/noise-result.json"); String noiseStr = FileReader.readFileInString("src/test/resources/noise-result.json");
assertNotNull(noiseStr); assertNotNull(noiseStr);
Objects.requireNonNull(noiseStr);
noise = http.getLatestValues(noiseStr); noise = http.getLatestValues(noiseStr);
} }

View File

@ -15,6 +15,7 @@ package org.openhab.binding.luftdateninfo.internal;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
import java.util.List; import java.util.List;
import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -39,8 +40,10 @@ public class HTTPHandlerValueTest {
public void testValueDecoding() { public void testValueDecoding() {
String resource1 = FileReader.readFileInString("src/test/resources/condition-result-no-pressure.json"); String resource1 = FileReader.readFileInString("src/test/resources/condition-result-no-pressure.json");
assertNotNull(resource1); assertNotNull(resource1);
Objects.requireNonNull(resource1);
List<SensorDataValue> l = http.getLatestValues(resource1); List<SensorDataValue> l = http.getLatestValues(resource1);
assertNotNull(l); assertNotNull(l);
Objects.requireNonNull(l);
l.forEach(sd -> { l.forEach(sd -> {
testSensorValue(sd); testSensorValue(sd);
}); });
@ -48,8 +51,10 @@ public class HTTPHandlerValueTest {
String resource2 = FileReader String resource2 = FileReader
.readFileInString("src/test/resources/condition-result-no-pressure-flipped-values.json"); .readFileInString("src/test/resources/condition-result-no-pressure-flipped-values.json");
assertNotNull(resource2); assertNotNull(resource2);
Objects.requireNonNull(resource2);
l = http.getLatestValues(resource2); l = http.getLatestValues(resource2);
assertNotNull(l); assertNotNull(l);
Objects.requireNonNull(l);
l.forEach(sd -> { l.forEach(sd -> {
testSensorValue(sd); testSensorValue(sd);
}); });

View File

@ -150,9 +150,11 @@ public class LeapDeviceDiscoveryService extends AbstractDiscoveryService
} else { } else {
areaName = "Occupancy Group"; areaName = "Occupancy Group";
} }
logger.debug("Discovered occupancy group: {} areas: {} area name: {}", groupNum, if (areaName != null) {
oGroup.associatedAreas.length, areaName); logger.debug("Discovered occupancy group: {} areas: {} area name: {}", groupNum,
notifyDiscovery(THING_TYPE_OGROUP, groupNum, areaName); oGroup.associatedAreas.length, areaName);
notifyDiscovery(THING_TYPE_OGROUP, groupNum, areaName);
}
} }
} }
this.areaMap = null; this.areaMap = null;

View File

@ -14,6 +14,7 @@ package org.openhab.binding.lutron.internal.protocol.leap;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
@ -212,6 +213,7 @@ public class LeapMessageParser {
try { try {
if (messageBody.has(memberName)) { if (messageBody.has(memberName)) {
JsonObject jsonObject = messageBody.get(memberName).getAsJsonObject(); JsonObject jsonObject = messageBody.get(memberName).getAsJsonObject();
@Nullable
T obj = gson.fromJson(jsonObject, type); T obj = gson.fromJson(jsonObject, type);
return obj; return obj;
} else { } else {
@ -233,7 +235,7 @@ public class LeapMessageParser {
for (JsonElement element : jsonArray) { for (JsonElement element : jsonArray) {
JsonObject jsonObject = element.getAsJsonObject(); JsonObject jsonObject = element.getAsJsonObject();
T obj = gson.fromJson(jsonObject, type); T obj = Objects.requireNonNull(gson.fromJson(jsonObject, type));
objList.add(obj); objList.add(obj);
} }
return objList; return objList;

View File

@ -391,10 +391,7 @@ public class MagentaTVControl {
// direct key code // direct key code
return key; return key;
} }
if (KEY_MAP.containsKey(key)) { return KEY_MAP.getOrDefault(key, "");
return KEY_MAP.get(key);
}
return "";
} }
/** /**

View File

@ -21,6 +21,7 @@ import java.nio.charset.StandardCharsets;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import java.util.AbstractMap; import java.util.AbstractMap;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -115,9 +116,13 @@ public class MeteoAlerteHandler extends BaseThingHandler {
throw new MalformedURLException("queryUrl not initialized"); throw new MalformedURLException("queryUrl not initialized");
} }
String response = HttpUtil.executeUrl("GET", queryUrl, TIMEOUT_MS); String response = HttpUtil.executeUrl("GET", queryUrl, TIMEOUT_MS);
if (response == null) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "empty response");
return;
}
updateStatus(ThingStatus.ONLINE); updateStatus(ThingStatus.ONLINE);
ApiResponse apiResponse = gson.fromJson(response, ApiResponse.class); ApiResponse apiResponse = gson.fromJson(response, ApiResponse.class);
updateChannels(apiResponse); updateChannels(Objects.requireNonNull(apiResponse));
} catch (MalformedURLException e) { } catch (MalformedURLException e) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
String.format("Querying '%s' raised : %s", queryUrl, e.getMessage())); String.format("Querying '%s' raised : %s", queryUrl, e.getMessage()));

View File

@ -129,9 +129,9 @@ public class MiIoBasicHandler extends MiIoAbstractHandler {
} }
logger.debug("Locating action for {} channel '{}': '{}'", getThing().getUID(), channelUID.getId(), command); logger.debug("Locating action for {} channel '{}': '{}'", getThing().getUID(), channelUID.getId(), command);
if (!actions.isEmpty()) { if (!actions.isEmpty()) {
if (actions.containsKey(channelUID)) { MiIoBasicChannel miIoBasicChannel = actions.get(channelUID);
if (miIoBasicChannel != null) {
int valuePos = 0; int valuePos = 0;
MiIoBasicChannel miIoBasicChannel = actions.get(channelUID);
for (MiIoDeviceAction action : miIoBasicChannel.getActions()) { for (MiIoDeviceAction action : miIoBasicChannel.getActions()) {
@Nullable @Nullable
JsonElement value = null; JsonElement value = null;

View File

@ -17,12 +17,7 @@ import static org.openhab.binding.modbus.internal.ModbusBindingConstantsInternal
import java.math.BigDecimal; import java.math.BigDecimal;
import java.time.Duration; import java.time.Duration;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.Collection; import java.util.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.NotImplementedException; import org.apache.commons.lang.NotImplementedException;
@ -922,7 +917,8 @@ public class ModbusDataThingHandler extends BaseThingHandler {
} }
private ChannelUID getChannelUID(String channelID) { private ChannelUID getChannelUID(String channelID) {
return channelCache.computeIfAbsent(channelID, id -> new ChannelUID(getThing().getUID(), id)); return Objects
.requireNonNull(channelCache.computeIfAbsent(channelID, id -> new ChannelUID(getThing().getUID(), id)));
} }
private void updateStatusIfChanged(ThingStatus status) { private void updateStatusIfChanged(ThingStatus status) {

View File

@ -24,6 +24,7 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import java.lang.annotation.Target;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.Objects;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.stream.Stream; import java.util.stream.Stream;
@ -201,8 +202,10 @@ public class MqttTopicClassMapperTests {
String suffix = mapToField != null ? mapToField.suffix() : ""; String suffix = mapToField != null ? mapToField.suffix() : "";
assertThat(f.field.get(attributes).toString(), is(prefix + annotation.value() + suffix)); assertThat(f.field.get(attributes).toString(), is(prefix + annotation.value() + suffix));
} else { } else {
assertThat(Stream.of((String[]) f.field.get(attributes)).reduce((v, i) -> v + "," + i).orElse(""), String[] attributeArray = (String[]) f.field.get(attributes);
is(annotation.value())); assertNotNull(attributeArray);
Objects.requireNonNull(attributeArray);
assertThat(Stream.of(attributeArray).reduce((v, i) -> v + "," + i).orElse(""), is(annotation.value()));
} }
} }

View File

@ -14,6 +14,7 @@ package org.openhab.binding.mqtt.homeassistant.internal;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
@ -54,7 +55,7 @@ public abstract class BaseChannelConfiguration {
*/ */
public static <C extends BaseChannelConfiguration> C fromString(final String configJSON, final Gson gson, public static <C extends BaseChannelConfiguration> C fromString(final String configJSON, final Gson gson,
final Class<C> clazz) { final Class<C> clazz) {
return gson.fromJson(configJSON, clazz); return Objects.requireNonNull(gson.fromJson(configJSON, clazz));
} }
/** /**

View File

@ -69,10 +69,7 @@ public class ChannelConfigurationTypeAdapterFactory implements TypeAdapterFactor
return new TypeAdapter<T>() { return new TypeAdapter<T>() {
@Override @Override
public T read(@Nullable JsonReader in) throws IOException { public @Nullable T read(JsonReader in) throws IOException {
if (in == null) {
return null;
}
/* read the object using the default adapter, but translate the names in the reader */ /* read the object using the default adapter, but translate the names in the reader */
T result = delegate.read(MappingJsonReader.getConfigMapper(in)); T result = delegate.read(MappingJsonReader.getConfigMapper(in));
/* do the '~' expansion afterwards */ /* do the '~' expansion afterwards */
@ -81,7 +78,7 @@ public class ChannelConfigurationTypeAdapterFactory implements TypeAdapterFactor
} }
@Override @Override
public void write(@Nullable JsonWriter out, T value) throws IOException { public void write(JsonWriter out, @Nullable T value) throws IOException {
delegate.write(out, value); delegate.write(out, value);
} }
}; };
@ -93,17 +90,14 @@ public class ChannelConfigurationTypeAdapterFactory implements TypeAdapterFactor
return new TypeAdapter<T>() { return new TypeAdapter<T>() {
@Override @Override
public T read(@Nullable JsonReader in) throws IOException { public @Nullable T read(JsonReader in) throws IOException {
if (in == null) {
return null;
}
/* read the object using the default adapter, but translate the names in the reader */ /* read the object using the default adapter, but translate the names in the reader */
T result = delegate.read(MappingJsonReader.getDeviceMapper(in)); T result = delegate.read(MappingJsonReader.getDeviceMapper(in));
return result; return result;
} }
@Override @Override
public void write(@Nullable JsonWriter out, T value) throws IOException { public void write(JsonWriter out, @Nullable T value) throws IOException {
delegate.write(out, value); delegate.write(out, value);
} }
}; };

View File

@ -19,6 +19,7 @@ import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.Scanner; import java.util.Scanner;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
@ -493,9 +494,8 @@ public class NanoleafControllerHandler extends BaseBridgeHandler {
if (line.startsWith("data:")) { if (line.startsWith("data:")) {
String json = line.substring(5).trim(); // supposed to be JSON String json = line.substring(5).trim(); // supposed to be JSON
try { try {
@Nullable
TouchEvents touchEvents = gson.fromJson(json, TouchEvents.class); TouchEvents touchEvents = gson.fromJson(json, TouchEvents.class);
handleTouchEvents(touchEvents); handleTouchEvents(Objects.requireNonNull(touchEvents));
} catch (JsonSyntaxException jse) { } catch (JsonSyntaxException jse) {
logger.error("couldn't parse touch event json {}", json); logger.error("couldn't parse touch event json {}", json);
} }
@ -645,9 +645,8 @@ public class NanoleafControllerHandler extends BaseBridgeHandler {
private ControllerInfo receiveControllerInfo() throws NanoleafException, NanoleafUnauthorizedException { private ControllerInfo receiveControllerInfo() throws NanoleafException, NanoleafUnauthorizedException {
ContentResponse controllerlInfoJSON = OpenAPIUtils.sendOpenAPIRequest(OpenAPIUtils.requestBuilder(httpClient, ContentResponse controllerlInfoJSON = OpenAPIUtils.sendOpenAPIRequest(OpenAPIUtils.requestBuilder(httpClient,
getControllerConfig(), API_GET_CONTROLLER_INFO, HttpMethod.GET)); getControllerConfig(), API_GET_CONTROLLER_INFO, HttpMethod.GET));
@Nullable
ControllerInfo controllerInfo = gson.fromJson(controllerlInfoJSON.getContentAsString(), ControllerInfo.class); ControllerInfo controllerInfo = gson.fromJson(controllerlInfoJSON.getContentAsString(), ControllerInfo.class);
return controllerInfo; return Objects.requireNonNull(controllerInfo);
} }
private void sendStateCommand(String channel, Command command) throws NanoleafException { private void sendStateCommand(String channel, Command command) throws NanoleafException {

View File

@ -76,7 +76,7 @@ public class NeeoBrainApi implements AutoCloseable {
throw resp.createException(); throw resp.createException();
} }
return gson.fromJson(resp.getContent(), NeeoBrain.class); return Objects.requireNonNull(gson.fromJson(resp.getContent(), NeeoBrain.class));
} }
/** /**
@ -97,7 +97,7 @@ public class NeeoBrainApi implements AutoCloseable {
throw resp.createException(); throw resp.createException();
} }
return gson.fromJson(resp.getContent(), NeeoRoom.class); return Objects.requireNonNull(gson.fromJson(resp.getContent(), NeeoRoom.class));
} }
/** /**
@ -121,7 +121,7 @@ public class NeeoBrainApi implements AutoCloseable {
throw resp.createException(); throw resp.createException();
} }
return gson.fromJson(resp.getContent(), ExecuteResult.class); return Objects.requireNonNull(gson.fromJson(resp.getContent(), ExecuteResult.class));
} }
/** /**
@ -145,7 +145,7 @@ public class NeeoBrainApi implements AutoCloseable {
throw resp.createException(); throw resp.createException();
} }
return gson.fromJson(resp.getContent(), ExecuteResult.class); return Objects.requireNonNull(gson.fromJson(resp.getContent(), ExecuteResult.class));
} }
/** /**
@ -163,7 +163,7 @@ public class NeeoBrainApi implements AutoCloseable {
throw resp.createException(); throw resp.createException();
} }
return gson.fromJson(resp.getContent(), String[].class); return Objects.requireNonNull(gson.fromJson(resp.getContent(), String[].class));
} }
/** /**
@ -189,7 +189,7 @@ public class NeeoBrainApi implements AutoCloseable {
throw resp.createException(); throw resp.createException();
} }
return gson.fromJson(resp.getContent(), ExecuteResult.class); return Objects.requireNonNull(gson.fromJson(resp.getContent(), ExecuteResult.class));
} }
/** /**

View File

@ -190,7 +190,7 @@ public class NeeoBrainHandler extends BaseBridgeHandler {
public void post(String json) { public void post(String json) {
triggerChannel(NeeoConstants.CHANNEL_BRAIN_FOWARDACTIONS, json); triggerChannel(NeeoConstants.CHANNEL_BRAIN_FOWARDACTIONS, json);
final NeeoAction action = gson.fromJson(json, NeeoAction.class); final NeeoAction action = Objects.requireNonNull(gson.fromJson(json, NeeoAction.class));
for (final Thing child : getThing().getThings()) { for (final Thing child : getThing().getThings()) {
final ThingHandler th = child.getHandler(); final ThingHandler th = child.getHandler();

View File

@ -35,16 +35,15 @@ import com.google.gson.JsonPrimitive;
public class NeohubBoolDeserializer implements JsonDeserializer<NeohubBool> { public class NeohubBoolDeserializer implements JsonDeserializer<NeohubBool> {
@Override @Override
public NeohubBool deserialize(@Nullable JsonElement json, @Nullable Type typeOfT, public @Nullable NeohubBool deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
@Nullable JsonDeserializationContext context) throws JsonParseException { throws JsonParseException {
if (json != null) { JsonPrimitive jsonPrimitive = json.getAsJsonPrimitive();
JsonPrimitive jsonPrimitive = json.getAsJsonPrimitive(); if (jsonPrimitive.isBoolean()) {
if (jsonPrimitive.isBoolean()) { return new NeohubBool(jsonPrimitive.getAsBoolean());
return new NeohubBool(jsonPrimitive.getAsBoolean()); } else if (jsonPrimitive.isNumber()) {
} else if (jsonPrimitive.isNumber()) { return new NeohubBool(jsonPrimitive.getAsNumber().intValue() != 0);
return new NeohubBool(jsonPrimitive.getAsNumber().intValue() != 0);
}
} }
return new NeohubBool(false); return new NeohubBool(false);
} }
} }

View File

@ -60,11 +60,13 @@ public class NestUpdateHandler<T> {
private Set<NestThingDataListener<T>> getListeners(String nestId) { private Set<NestThingDataListener<T>> getListeners(String nestId) {
Set<NestThingDataListener<T>> listeners = new HashSet<>(); Set<NestThingDataListener<T>> listeners = new HashSet<>();
if (listenersMap.get(nestId) != null) { Set<NestThingDataListener<T>> idListeners = listenersMap.get(nestId);
listeners.addAll(listenersMap.get(nestId)); if (idListeners != null) {
listeners.addAll(idListeners);
} }
if (listenersMap.get(ANY_ID) != null) { Set<NestThingDataListener<T>> anyListeners = listenersMap.get(ANY_ID);
listeners.addAll(listenersMap.get(ANY_ID)); if (anyListeners != null) {
listeners.addAll(anyListeners);
} }
return listeners; return listeners;
} }

View File

@ -13,6 +13,7 @@
package org.openhab.binding.netatmo.internal.webhook; package org.openhab.binding.netatmo.internal.webhook;
import java.io.IOException; import java.io.IOException;
import java.util.Objects;
import java.util.Scanner; import java.util.Scanner;
import javax.servlet.ServletException; import javax.servlet.ServletException;
@ -91,7 +92,7 @@ public class WelcomeWebHookServlet extends HttpServlet {
if (!data.isEmpty() && handler != null) { if (!data.isEmpty() && handler != null) {
NAWebhookCameraEvent event = gson.fromJson(data, NAWebhookCameraEvent.class); NAWebhookCameraEvent event = gson.fromJson(data, NAWebhookCameraEvent.class);
logger.debug("Event transmitted from restService"); logger.debug("Event transmitted from restService");
handler.webHookEvent(event); handler.webHookEvent(Objects.requireNonNull(event));
} }
setHeaders(resp); setHeaders(resp);

View File

@ -328,6 +328,10 @@ public class NikoHomeControlCommunication1 extends NikoHomeControlCommunication
for (Map<String, String> location : data) { for (Map<String, String> location : data) {
String id = location.get("id"); String id = location.get("id");
String name = location.get("name"); String name = location.get("name");
if (id == null || name == null) {
logger.debug("id or name null, ignoring entry");
continue;
}
NhcLocation1 nhcLocation1 = new NhcLocation1(name); NhcLocation1 nhcLocation1 = new NhcLocation1(name);
locations.put(id, nhcLocation1); locations.put(id, nhcLocation1);
} }
@ -337,8 +341,11 @@ public class NikoHomeControlCommunication1 extends NikoHomeControlCommunication
logger.debug("Niko Home Control: list actions"); logger.debug("Niko Home Control: list actions");
for (Map<String, String> action : data) { for (Map<String, String> action : data) {
String id = action.get("id"); String id = action.get("id");
if (id == null) {
logger.debug("id not found in action {}", action);
continue;
}
String value1 = action.get("value1"); String value1 = action.get("value1");
int state = ((value1 == null) || value1.isEmpty() ? 0 : Integer.parseInt(value1)); int state = ((value1 == null) || value1.isEmpty() ? 0 : Integer.parseInt(value1));
String value2 = action.get("value2"); String value2 = action.get("value2");
@ -349,6 +356,10 @@ public class NikoHomeControlCommunication1 extends NikoHomeControlCommunication
if (!actions.containsKey(id)) { if (!actions.containsKey(id)) {
// Initial instantiation of NhcAction class for action object // Initial instantiation of NhcAction class for action object
String name = action.get("name"); String name = action.get("name");
if (name == null) {
logger.debug("name not found in action {}", action);
continue;
}
String type = action.get("type"); String type = action.get("type");
ActionType actionType = ActionType.GENERIC; ActionType actionType = ActionType.GENERIC;
switch (type) { switch (type) {
@ -371,8 +382,8 @@ public class NikoHomeControlCommunication1 extends NikoHomeControlCommunication
} }
String locationId = action.get("location"); String locationId = action.get("location");
String location = ""; String location = "";
if (!locationId.isEmpty()) { if (locationId != null && !locationId.isEmpty()) {
location = locations.get(locationId).getName(); location = locations.getOrDefault(locationId, new NhcLocation1("")).getName();
} }
NhcAction nhcAction = new NhcAction1(id, name, actionType, location, this, scheduler); NhcAction nhcAction = new NhcAction1(id, name, actionType, location, this, scheduler);
if (actionType == ActionType.ROLLERSHUTTER) { if (actionType == ActionType.ROLLERSHUTTER) {
@ -405,6 +416,10 @@ public class NikoHomeControlCommunication1 extends NikoHomeControlCommunication
for (Map<String, String> thermostat : data) { for (Map<String, String> thermostat : data) {
try { try {
String id = thermostat.get("id"); String id = thermostat.get("id");
if (id == null) {
logger.debug("skipping thermostat {}, id not found", thermostat);
continue;
}
int measured = parseIntOrThrow(thermostat.get("measured")); int measured = parseIntOrThrow(thermostat.get("measured"));
int setpoint = parseIntOrThrow(thermostat.get("setpoint")); int setpoint = parseIntOrThrow(thermostat.get("setpoint"));
int mode = parseIntOrThrow(thermostat.get("mode")); int mode = parseIntOrThrow(thermostat.get("mode"));
@ -528,6 +543,10 @@ public class NikoHomeControlCommunication1 extends NikoHomeControlCommunication
private void eventGetAlarms(Map<String, String> data) { private void eventGetAlarms(Map<String, String> data) {
String alarmText = data.get("text"); String alarmText = data.get("text");
if (alarmText == null) {
logger.debug("message does not contain alarmtext: {}", data);
return;
}
switch (data.getOrDefault("type", "")) { switch (data.getOrDefault("type", "")) {
case "0": case "0":
logger.debug("Niko Home Control: alarm - {}", alarmText); logger.debug("Niko Home Control: alarm - {}", alarmText);

View File

@ -33,8 +33,7 @@ import java.util.stream.IntStream;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.nikohomecontrol.internal.protocol.NhcControllerEvent; import org.openhab.binding.nikohomecontrol.internal.protocol.*;
import org.openhab.binding.nikohomecontrol.internal.protocol.NikoHomeControlCommunication;
import org.openhab.binding.nikohomecontrol.internal.protocol.NikoHomeControlConstants.ActionType; import org.openhab.binding.nikohomecontrol.internal.protocol.NikoHomeControlConstants.ActionType;
import org.openhab.binding.nikohomecontrol.internal.protocol.nhc2.NhcDevice2.NhcProperty; import org.openhab.binding.nikohomecontrol.internal.protocol.nhc2.NhcDevice2.NhcProperty;
import org.openhab.binding.nikohomecontrol.internal.protocol.nhc2.NhcMessage2.NhcMessageParam; import org.openhab.binding.nikohomecontrol.internal.protocol.nhc2.NhcMessage2.NhcMessageParam;
@ -309,7 +308,7 @@ public class NikoHomeControlCommunication2 extends NikoHomeControlCommunication
return; return;
} else if ("devices.added".equals(method)) { } else if ("devices.added".equals(method)) {
deviceList.forEach(this::addDevice); deviceList.forEach(this::addDevice);
} else if ("devices.changed".contentEquals(method)) { } else if ("devices.changed".equals(method)) {
deviceList.forEach(this::removeDevice); deviceList.forEach(this::removeDevice);
deviceList.forEach(this::addDevice); deviceList.forEach(this::addDevice);
} }
@ -444,12 +443,16 @@ public class NikoHomeControlCommunication2 extends NikoHomeControlCommunication
return; return;
} }
if (actions.containsKey(device.uuid)) { NhcAction action = actions.get(device.uuid);
updateActionState((NhcAction2) actions.get(device.uuid), deviceProperties); NhcThermostat thermostat = thermostats.get(device.uuid);
} else if (thermostats.containsKey(device.uuid)) { NhcEnergyMeter energyMeter = energyMeters.get(device.uuid);
updateThermostatState((NhcThermostat2) thermostats.get(device.uuid), deviceProperties);
} else if (energyMeters.containsKey(device.uuid)) { if (action != null) {
updateEnergyMeterState((NhcEnergyMeter2) energyMeters.get(device.uuid), deviceProperties); updateActionState((NhcAction2) action, deviceProperties);
} else if (thermostat != null) {
updateThermostatState((NhcThermostat2) thermostat, deviceProperties);
} else if (energyMeter != null) {
updateEnergyMeterState((NhcEnergyMeter2) energyMeter, deviceProperties);
} }
} }

View File

@ -22,6 +22,7 @@ import java.time.Instant;
import java.time.ZoneId; import java.time.ZoneId;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -122,8 +123,7 @@ public class NtpHandler extends BaseThingHandler {
logger.debug("{} using default timezone '{}', because configuration setting '{}' is null.", logger.debug("{} using default timezone '{}', because configuration setting '{}' is null.",
getThing().getUID(), timeZoneProvider.getTimeZone(), PROPERTY_TIMEZONE); getThing().getUID(), timeZoneProvider.getTimeZone(), PROPERTY_TIMEZONE);
} }
ZoneId zoneId = timeZoneId != null ? timeZoneId : timeZoneProvider.getTimeZone(); ZoneId zoneId = Objects.requireNonNullElse(timeZoneId, timeZoneProvider.getTimeZone());
Channel stringChannel = getThing().getChannel(CHANNEL_STRING); Channel stringChannel = getThing().getChannel(CHANNEL_STRING);
if (stringChannel != null) { if (stringChannel != null) {
String dateTimeFormatString = stringChannel.getConfiguration() String dateTimeFormatString = stringChannel.getConfiguration()
@ -183,7 +183,7 @@ public class NtpHandler extends BaseThingHandler {
refreshNtpCount--; refreshNtpCount--;
} }
ZoneId zoneId = timeZoneId != null ? timeZoneId : timeZoneProvider.getTimeZone(); ZoneId zoneId = Objects.requireNonNullElse(timeZoneId, timeZoneProvider.getTimeZone());
ZonedDateTime zoned = ZonedDateTime.ofInstant(Instant.ofEpochMilli(networkTimeInMillis), zoneId); ZonedDateTime zoned = ZonedDateTime.ofInstant(Instant.ofEpochMilli(networkTimeInMillis), zoneId);
updateState(CHANNEL_DATE_TIME, new DateTimeType(zoned)); updateState(CHANNEL_DATE_TIME, new DateTimeType(zoned));
dateTimeFormat.withZone(zoneId); dateTimeFormat.withZone(zoneId);
@ -208,7 +208,7 @@ public class NtpHandler extends BaseThingHandler {
timeInfo.computeDetails(); timeInfo.computeDetails();
long serverMillis = timeInfo.getReturnTime() + timeInfo.getOffset(); long serverMillis = timeInfo.getReturnTime() + timeInfo.getOffset();
ZoneId zoneId = timeZoneId != null ? timeZoneId : timeZoneProvider.getTimeZone(); ZoneId zoneId = Objects.requireNonNullElse(timeZoneId, timeZoneProvider.getTimeZone());
ZonedDateTime zoned = ZonedDateTime.ofInstant(Instant.ofEpochMilli(serverMillis), zoneId); ZonedDateTime zoned = ZonedDateTime.ofInstant(Instant.ofEpochMilli(serverMillis), zoneId);
logger.debug("{} Got time update from host '{}': {}.", getThing().getUID(), hostname, logger.debug("{} Got time update from host '{}': {}.", getThing().getUID(), hostname,
zoned.format(DATE_FORMATTER_WITH_TZ)); zoned.format(DATE_FORMATTER_WITH_TZ));

View File

@ -12,8 +12,6 @@
*/ */
package org.openhab.binding.nuki.internal; package org.openhab.binding.nuki.internal;
import java.util.ArrayList;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpClient;
@ -118,9 +116,7 @@ public class NukiHandlerFactory extends BaseThingHandlerFactory {
logger.warn("Cannot find port of the http service."); logger.warn("Cannot find port of the http service.");
return null; return null;
} }
ArrayList<String> parameters = new ArrayList<>(); String callbackUrl = String.format(NukiBindingConstants.CALLBACK_URL, ipAddress + ":" + port);
parameters.add(ipAddress + ":" + port);
String callbackUrl = String.format(NukiBindingConstants.CALLBACK_URL, parameters.toArray());
logger.trace("callbackUrl[{}]", callbackUrl); logger.trace("callbackUrl[{}]", callbackUrl);
return callbackUrl; return callbackUrl;
} }

View File

@ -17,7 +17,6 @@ import java.math.BigDecimal;
import java.net.SocketException; import java.net.SocketException;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.time.Instant; import java.time.Instant;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
@ -64,16 +63,12 @@ public class NukiHttpClient {
String configIp = (String) configuration.get(NukiBindingConstants.CONFIG_IP); String configIp = (String) configuration.get(NukiBindingConstants.CONFIG_IP);
BigDecimal configPort = (BigDecimal) configuration.get(NukiBindingConstants.CONFIG_PORT); BigDecimal configPort = (BigDecimal) configuration.get(NukiBindingConstants.CONFIG_PORT);
String configApiToken = (String) configuration.get(NukiBindingConstants.CONFIG_API_TOKEN); String configApiToken = (String) configuration.get(NukiBindingConstants.CONFIG_API_TOKEN);
ArrayList<String> parameters = new ArrayList<>(); String[] parameters = new String[additionalArguments.length + 3];
parameters.add(configIp); parameters[0] = configIp;
parameters.add(configPort.toString()); parameters[1] = configPort.toString();
parameters.add(configApiToken); parameters[2] = configApiToken;
if (additionalArguments != null) { System.arraycopy(additionalArguments, 0, parameters, 3, additionalArguments.length);
for (String argument : additionalArguments) { String uri = String.format(uriTemplate, parameters);
parameters.add(argument);
}
}
String uri = String.format(uriTemplate, parameters.toArray());
logger.trace("prepareUri(...):URI[{}]", uri); logger.trace("prepareUri(...):URI[{}]", uri);
return uri; return uri;
} }

View File

@ -119,17 +119,16 @@ public class StopHandler extends BaseBridgeHandler {
if (listener == null) { if (listener == null) {
throw new IllegalArgumentException("It makes no sense to register a null listener!"); throw new IllegalArgumentException("It makes no sense to register a null listener!");
} }
boolean added = routeDataListeners.add(listener); routeDataListeners.add(listener);
if (added) { String routeId = listener.getRouteId();
String routeId = listener.getRouteId(); List<ObaStopArrivalResponse.ArrivalAndDeparture> copiedRouteData;
List<ObaStopArrivalResponse.ArrivalAndDeparture> copiedRouteData; synchronized (routeData) {
synchronized (routeData) { copiedRouteData = new ArrayList<>(routeData.getOrDefault(routeId, List.of()));
copiedRouteData = new ArrayList<>(routeData.get(routeId));
}
Collections.sort(copiedRouteData);
listener.onNewRouteData(routeDataLastUpdateMs, copiedRouteData);
} }
return added; Collections.sort(copiedRouteData);
listener.onNewRouteData(routeDataLastUpdateMs, copiedRouteData);
return true;
} }
/** /**
@ -212,7 +211,8 @@ public class StopHandler extends BaseBridgeHandler {
routeData.put(d.routeId, Arrays.asList(d)); routeData.put(d.routeId, Arrays.asList(d));
} }
for (String key : routeData.keySet()) { for (String key : routeData.keySet()) {
List<ObaStopArrivalResponse.ArrivalAndDeparture> copy = new ArrayList<>(routeData.get(key)); List<ObaStopArrivalResponse.ArrivalAndDeparture> copy = new ArrayList<>(
routeData.getOrDefault(key, List.of()));
Collections.sort(copy); Collections.sort(copy);
copiedRouteData.put(key, copy); copiedRouteData.put(key, copy);
} }

View File

@ -102,7 +102,7 @@ public class BAE091xSensorThingHandler extends OwBaseThingHandler {
BAE091xHandlerConfiguration configuration = getConfig().as(BAE091xHandlerConfiguration.class); BAE091xHandlerConfiguration configuration = getConfig().as(BAE091xHandlerConfiguration.class);
Set<OwChannelConfig> wantedChannel = new HashSet<>(); Set<OwChannelConfig> wantedChannel = new HashSet<>();
wantedChannel.addAll(SENSOR_TYPE_CHANNEL_MAP.get(sensorType)); wantedChannel.addAll(SENSOR_TYPE_CHANNEL_MAP.getOrDefault(sensorType, Set.of()));
// Pin1: // Pin1:
switch (configuration.pin1) { switch (configuration.pin1) {

View File

@ -16,6 +16,7 @@ import static org.openhab.binding.pixometer.internal.PixometerBindingConstants.*
import java.io.IOException; import java.io.IOException;
import java.time.Duration; import java.time.Duration;
import java.util.Objects;
import java.util.Properties; import java.util.Properties;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -253,7 +254,7 @@ public class MeterHandler extends BaseThingHandler {
ReadingInstance latestReading = gson.fromJson(new JsonParser().parse(urlResponse), ReadingInstance.class); ReadingInstance latestReading = gson.fromJson(new JsonParser().parse(urlResponse), ReadingInstance.class);
return new MeterState(latestReading); return new MeterState(Objects.requireNonNull(latestReading));
} catch (IOException e) { } catch (IOException e) {
logger.debug("Exception while refreshing cache for Meter {}: {}", getThing().getUID(), e.getMessage(), e); logger.debug("Exception while refreshing cache for Meter {}: {}", getThing().getUID(), e.getMessage(), e);
return null; return null;

View File

@ -18,6 +18,7 @@ import java.io.InputStream;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.Properties; import java.util.Properties;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -286,12 +287,12 @@ public class RemoteopenhabRestClient {
break; break;
case "ItemAddedEvent": case "ItemAddedEvent":
itemName = extractItemNameFromTopic(event.topic, event.type, "added"); itemName = extractItemNameFromTopic(event.topic, event.type, "added");
item = jsonParser.fromJson(event.payload, Item.class); item = Objects.requireNonNull(jsonParser.fromJson(event.payload, Item.class));
listeners.forEach(listener -> listener.onItemAdded(item)); listeners.forEach(listener -> listener.onItemAdded(item));
break; break;
case "ItemRemovedEvent": case "ItemRemovedEvent":
itemName = extractItemNameFromTopic(event.topic, event.type, "removed"); itemName = extractItemNameFromTopic(event.topic, event.type, "removed");
item = jsonParser.fromJson(event.payload, Item.class); item = Objects.requireNonNull(jsonParser.fromJson(event.payload, Item.class));
listeners.forEach(listener -> listener.onItemRemoved(item)); listeners.forEach(listener -> listener.onItemRemoved(item));
break; break;
case "ItemUpdatedEvent": case "ItemUpdatedEvent":

View File

@ -13,6 +13,7 @@
package org.openhab.binding.revogi.internal.api; package org.openhab.binding.revogi.internal.api;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
@ -69,7 +70,7 @@ public class StatusService {
private StatusRawDTO deserializeString(String response) { private StatusRawDTO deserializeString(String response) {
String extractedJsonResponse = response.substring(response.lastIndexOf(VERSION_STRING) + 2); String extractedJsonResponse = response.substring(response.lastIndexOf(VERSION_STRING) + 2);
try { try {
return gson.fromJson(extractedJsonResponse, StatusRawDTO.class); return Objects.requireNonNull(gson.fromJson(extractedJsonResponse, StatusRawDTO.class));
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
logger.warn("Could not parse string \"{}\" to StatusRaw", response, e); logger.warn("Could not parse string \"{}\" to StatusRaw", response, e);
return new StatusRawDTO(503, 0, new StatusDTO(false, 503, null, null, null)); return new StatusRawDTO(503, 0, new StatusDTO(false, 503, null, null, null));

View File

@ -13,6 +13,7 @@
package org.openhab.binding.revogi.internal.api; package org.openhab.binding.revogi.internal.api;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
@ -76,7 +77,7 @@ public class SwitchService {
private SwitchResponseDTO deserializeString(String response) { private SwitchResponseDTO deserializeString(String response) {
String extractedJsonResponse = response.substring(response.lastIndexOf(VERSION_STRING) + 2); String extractedJsonResponse = response.substring(response.lastIndexOf(VERSION_STRING) + 2);
try { try {
return gson.fromJson(extractedJsonResponse, SwitchResponseDTO.class); return Objects.requireNonNull(gson.fromJson(extractedJsonResponse, SwitchResponseDTO.class));
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
logger.warn("Could not parse string \"{}\" to SwitchResponse", response); logger.warn("Could not parse string \"{}\" to SwitchResponse", response);
return new SwitchResponseDTO(0, 503); return new SwitchResponseDTO(0, 503);

View File

@ -70,6 +70,10 @@ public class RFXComDeviceDiscoveryService extends AbstractDiscoveryService imple
String id = message.getDeviceId(); String id = message.getDeviceId();
ThingTypeUID uid = RFXComBindingConstants.PACKET_TYPE_THING_TYPE_UID_MAP.get(message.getPacketType()); ThingTypeUID uid = RFXComBindingConstants.PACKET_TYPE_THING_TYPE_UID_MAP.get(message.getPacketType());
if (uid == null) {
logger.debug("cannot find uid for message {}", message);
return;
}
ThingUID thingUID = new ThingUID(uid, bridge, id.replace(ID_DELIMITER, "_")); ThingUID thingUID = new ThingUID(uid, bridge, id.replace(ID_DELIMITER, "_"));
if (!bridgeHandler.getConfiguration().disableDiscovery) { if (!bridgeHandler.getConfiguration().disableDiscovery) {

View File

@ -984,7 +984,7 @@ public abstract class RotelConnector {
} else { } else {
for (RotelSource src : sourcesLabels.keySet()) { for (RotelSource src : sourcesLabels.keySet()) {
String label = sourcesLabels.get(src); String label = sourcesLabels.get(src);
if (value.startsWith(label)) { if (label != null && value.startsWith(label)) {
if (source == null || sourcesLabels.get(source).length() < label.length()) { if (source == null || sourcesLabels.get(source).length() < label.length()) {
source = src; source = src;
} }

View File

@ -16,6 +16,7 @@ import java.io.InterruptedIOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
@ -1145,11 +1146,10 @@ public class RotelSimuConnector extends RotelConnector {
String label; String label;
if (considerFollowMain && source.getName().equals(RotelSource.CAT1_FOLLOW_MAIN.getName())) { if (considerFollowMain && source.getName().equals(RotelSource.CAT1_FOLLOW_MAIN.getName())) {
label = "SOURCE"; label = "SOURCE";
} else if (sourcesLabels.get(source) != null) {
label = sourcesLabels.get(source);
} else { } else {
label = source.getLabel(); label = Objects.requireNonNullElse(sourcesLabels.get(source), source.getLabel());
} }
return label; return label;
} }
} }

View File

@ -231,10 +231,8 @@ public class MainTVServerService implements UpnpIOParticipant, SamsungTvService
if (result.get("Result").equals("OK")) { if (result.get("Result").equals("OK")) {
String xml = result.get("SourceList"); String xml = result.get("SourceList");
if (xml != null) {
Map<String, String> list = parseSourceList(xml); id = parseSourceList(xml).get(source);
if (list != null) {
id = list.get(source);
} }
} else { } else {
logger.warn("Source list query failed, result='{}'", result.get("Result")); logger.warn("Source list query failed, result='{}'", result.get("Result"));

View File

@ -15,6 +15,7 @@ package org.openhab.binding.satel.internal.event;
import java.util.BitSet; import java.util.BitSet;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.binding.satel.internal.types.StateType; import org.openhab.binding.satel.internal.types.StateType;
@ -71,10 +72,10 @@ public class IntegraStateEvent implements SatelEvent {
if (stateType.getStartByte() == 0 && bitsCount == stateBits.size()) { if (stateType.getStartByte() == 0 && bitsCount == stateBits.size()) {
return stateBits; return stateBits;
} }
return stateBitsMap.computeIfAbsent(stateType, k -> { return Objects.requireNonNull(stateBitsMap.computeIfAbsent(stateType, k -> {
int startBit = k.getStartByte() * 8; int startBit = k.getStartByte() * 8;
return stateBits.get(startBit, startBit + bitsCount); return stateBits.get(startBit, startBit + bitsCount);
}); }));
} }
/** /**

View File

@ -14,6 +14,7 @@ package org.openhab.binding.senechome.internal;
import java.io.IOException; import java.io.IOException;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.util.Objects;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
@ -78,7 +79,7 @@ public class SenecHomeApi {
.content(new StringContentProvider(gson.toJson(new SenecHomeResponse()))).send(); .content(new StringContentProvider(gson.toJson(new SenecHomeResponse()))).send();
if (response.getStatus() == HttpStatus.OK_200) { if (response.getStatus() == HttpStatus.OK_200) {
return gson.fromJson(response.getContentAsString(), SenecHomeResponse.class); return Objects.requireNonNull(gson.fromJson(response.getContentAsString(), SenecHomeResponse.class));
} else { } else {
logger.trace("Got unexpected response code {}", response.getStatus()); logger.trace("Got unexpected response code {}", response.getStatus());
throw new IOException("Got unexpected response code " + response.getStatus()); throw new IOException("Got unexpected response code " + response.getStatus());

Some files were not shown because too many files have changed in this diff Show More