[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.net.URISyntaxException;
import java.util.Objects;
import org.apache.commons.lang.StringEscapeUtils;
import org.eclipse.jdt.annotation.NonNullByDefault;
@ -91,7 +92,7 @@ public class ChannelHandlerAnnouncement extends ChannelHandler {
body = e.getLocalizedMessage();
}
}
thingHandler.startAnnouncment(device, speak, body, title, volume);
thingHandler.startAnnouncment(device, speak, Objects.requireNonNullElse(body, ""), title, volume);
}
refreshChannel();
}

View File

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

View File

@ -25,7 +25,8 @@ import com.google.gson.annotations.SerializedName;
@NonNullByDefault
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;
authData.accessToken = accessToken;
userContextMap.frc = frc;

View File

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

View File

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

View File

@ -15,6 +15,7 @@ package org.openhab.binding.bluetooth.roaming.internal;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicReference;
@ -52,7 +53,7 @@ public class RoamingBluetoothDevice extends DelegateBluetoothDevice {
}
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) {

View File

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

View File

@ -14,6 +14,7 @@ package org.openhab.binding.bluetooth;
import java.time.ZonedDateTime;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
@ -186,7 +187,7 @@ public abstract class AbstractBluetoothBridgeHandler<BD extends BaseBluetoothDev
@Override
public BD getDevice(BluetoothAddress address) {
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;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import org.eclipse.jdt.annotation.NonNullByDefault;
@ -59,7 +60,7 @@ public class MockBluetoothAdapter implements BluetoothAdapter {
@Override
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

View File

@ -12,7 +12,6 @@
*/
package org.openhab.binding.bsblan.internal;
import java.util.HashSet;
import java.util.Set;
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_DATATYPE = "datatype";
public static final Set<String> WRITEABLE_CHANNELS = new HashSet<String>() {
private static final long serialVersionUID = 1L;
{
add(PARAMETER_CHANNEL_NUMBER_VALUE);
add(PARAMETER_CHANNEL_STRING_VALUE);
add(PARAMETER_CHANNEL_SWITCH_VALUE);
}
};
public static final Set<String> WRITEABLE_CHANNELS = Set.of(PARAMETER_CHANNEL_NUMBER_VALUE,
PARAMETER_CHANNEL_STRING_VALUE, PARAMETER_CHANNEL_SWITCH_VALUE);
public static final int MIN_REFRESH_INTERVAL = 5;
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 java.util.HashSet;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@ -39,14 +38,7 @@ import org.osgi.service.component.annotations.Component;
@Component(service = ThingHandlerFactory.class, configurationPid = "binding.bsblan")
public class BsbLanHandlerFactory extends BaseThingHandlerFactory {
private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = new HashSet<ThingTypeUID>() {
private static final long serialVersionUID = 1L;
{
add(THING_TYPE_PARAMETER);
add(THING_TYPE_BRIDGE);
}
};
private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_PARAMETER, THING_TYPE_BRIDGE);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {

View File

@ -142,9 +142,10 @@ public class SmartherAuthorizationServlet extends HttpServlet {
final StringBuffer requestURL = request.getRequestURL();
// Try to infer the real protocol from request headers
final String realProtocol = StringUtil.defaultIfBlank(request.getHeader(X_FORWARDED_PROTO),
request.getScheme());
String realProtocol = request.getHeader(X_FORWARDED_PROTO);
if (realProtocol == null || realProtocol.isBlank()) {
realProtocol = request.getScheme();
}
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.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Function;
@ -177,7 +178,9 @@ public class SmartherApi {
public ModuleStatus getModuleStatus(String plantId, String moduleId) throws SmartherGatewayException {
try {
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) {
throw new SmartherGatewayException(e.getMessage());
}
@ -280,9 +283,13 @@ public class SmartherApi {
if (response.getStatus() == HttpStatus.NO_CONTENT_204) {
return new ArrayList<>();
} else {
return ModelUtil.gsonInstance().fromJson(response.getContentAsString(),
List<Subscription> subscriptions = ModelUtil.gsonInstance().fromJson(response.getContentAsString(),
new TypeToken<List<Subscription>>() {
}.getType());
if (subscriptions == null) {
throw new SmartherGatewayException("fromJson returned null");
}
return subscriptions;
}
} catch (JsonSyntaxException e) {
throw new SmartherGatewayException(e.getMessage());

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -34,19 +34,14 @@ import com.google.gson.JsonSerializer;
@NonNullByDefault
public class ThermostatModeGsonTypeAdapter implements JsonDeserializer<ThermostatMode>, JsonSerializer<ThermostatMode> {
@Override
public ThermostatMode deserialize(@Nullable JsonElement json, @Nullable Type typeOfT,
@Nullable JsonDeserializationContext context) throws JsonParseException {
JsonElement jsonLocal = json;
if (jsonLocal != null) {
String s = jsonLocal.getAsString();
return s == null ? ThermostatMode.UNKNOWN : ThermostatMode.fromString(s);
}
return ThermostatMode.UNKNOWN;
public @Nullable ThermostatMode deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return ThermostatMode.fromString(json.getAsString());
}
@Override
public JsonElement serialize(ThermostatMode src, @Nullable Type typeOfSrc,
@Nullable JsonSerializationContext context) throws JsonParseException {
public JsonElement serialize(ThermostatMode src, Type typeOfSrc, JsonSerializationContext context)
throws JsonParseException {
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();
String areaParm = getThing().getProperties().get(DigiplexBindingConstants.PROPERTY_AREA_NO);
if (areaParm != null) {
areaNo = Integer.parseInt(areaParm);
}
bridgeHandler.registerMessageHandler(visitor);
updateStatus(ThingStatus.ONLINE);

View File

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

View File

@ -18,7 +18,6 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.openhab.binding.digitalstrom.internal.DigitalSTROMBindingConstants;
import org.openhab.binding.digitalstrom.internal.lib.config.Config;
import org.openhab.binding.digitalstrom.internal.lib.serverconnection.DsAPI;
@ -81,7 +80,7 @@ public class BridgeDiscoveryService extends AbstractDiscoveryService {
if (dsidMap != null) {
dSID = dsidMap.get(JSONApiResponseKeysEnum.DSID.getKey());
}
if (StringUtils.isNotBlank(dSID)) {
if (dSID != null && !dSID.isBlank()) {
return new ThingUID(DigitalSTROMBindingConstants.THING_TYPE_DSS_BRIDGE, dSID);
} else {
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 org.apache.commons.lang.StringUtils;
import org.openhab.binding.digitalstrom.internal.DigitalSTROMBindingConstants;
import org.openhab.binding.digitalstrom.internal.lib.config.Config;
import org.openhab.binding.digitalstrom.internal.lib.serverconnection.DsAPI;
@ -84,7 +83,7 @@ public class BridgeMDNSDiscoveryParticipant implements MDNSDiscoveryParticipant
if (dsidMap != null) {
dSID = dsidMap.get(JSONApiResponseKeysEnum.DSID.getKey());
}
if (StringUtils.isNotBlank(dSID)) {
if (dSID != null && !dSID.isBlank()) {
return new ThingUID(DigitalSTROMBindingConstants.THING_TYPE_DSS_BRIDGE, dSID);
} else {
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;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import org.eclipse.jdt.annotation.NonNullByDefault;
@ -148,8 +144,9 @@ public class DSMRMeterDiscoveryService extends DSMRDiscoveryService implements P
.filter(DSMRMeterHandler.class::isInstance)
.map(DSMRMeterHandler.class::cast)
.map(h -> h == null ? null : h.getMeterDescriptor())
.map(d -> d == null ? null : d.getMeterType())
.filter(Objects::nonNull)
.map(d -> Optional.ofNullable(d == null ? null : d.getMeterType()))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toSet());
// @formatter:on
// Create list of all configured meters that are not in the detected list. If not empty meters might not be

View File

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

View File

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

View File

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

View File

@ -159,7 +159,7 @@ public class TransmitterStick {
private static final long serialVersionUID = -3216360253151368826L;
public DueCommandSet() {
super(new Comparator<Command>() {
super(new Comparator<>() {
/**
* 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.Path;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@ -123,7 +124,7 @@ public class AbstractFMIResponseParsingTest {
try {
Method parseMethod = Client.class.getDeclaredMethod("parseMultiPointCoverageXml", String.class);
parseMethod.setAccessible(true);
return (FMIResponse) parseMethod.invoke(client, content);
return Objects.requireNonNull((FMIResponse) parseMethod.invoke(client, content));
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
@ -137,9 +138,9 @@ public class AbstractFMIResponseParsingTest {
@SuppressWarnings("unchecked")
protected Set<Location> parseStations(String content) {
try {
Method parseMethod = Client.class.getDeclaredMethod("parseStations", String.class);
Method parseMethod = Objects.requireNonNull(Client.class.getDeclaredMethod("parseStations", String.class));
parseMethod.setAccessible(true);
return (Set<Location>) parseMethod.invoke(client, content);
return Objects.requireNonNull((Set<Location>) parseMethod.invoke(client, content));
} catch (InvocationTargetException e) {
throw new RuntimeException(e.getTargetException());
} catch (Exception e) {

View File

@ -20,6 +20,7 @@ import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@ -95,7 +96,8 @@ public class FoobotApiConnector {
URLEncoder.encode(username, StandardCharsets.UTF_8.toString()));
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) {
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.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
@ -53,6 +54,7 @@ public class FoobotDeviceHandlerTest {
final FoobotJsonData sensorData = connector.getSensorData("1234");
assertNotNull(sensorData, "No sensor data read");
Objects.requireNonNull(sensorData);
assertEquals(handler.sensorDataToState("temperature", sensorData), new QuantityType(12.345, SIUnits.CELSIUS));
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.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import org.apache.commons.lang.StringUtils;
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) {
final Channel channel = thing.getChannel(channelId);
assertNotNull(channel);
Objects.requireNonNull(channel);
return channel;
}

View File

@ -18,6 +18,7 @@ import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.ServletException;
@ -134,7 +135,7 @@ public class RadioServiceDummy extends HttpServlet {
Collection<String> requestParameterNames = Collections.list(request.getParameterNames());
if (queryString != null && requestParameterNames.contains(VALUE)) {
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());
}

View File

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

View File

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

View File

@ -97,7 +97,7 @@ public class GreeDiscoveryService extends AbstractDiscoveryService {
createResult(deviceFinder.getDevices());
}
} 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) {
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");
logger.info("{}: {}", thingId, message);
} catch (GreeException e) {
logger.info("{}: {}", thingId, messages.get("thinginit.exception", e.getMessage()));
logger.info("{}: {}", thingId, messages.get("thinginit.exception", e.getMessageString()));
} catch (IOException e) {
logger.warn("{}: {}", thingId, messages.get("thinginit.exception", "I/O Error"), e);
} catch (RuntimeException e) {
@ -158,7 +158,7 @@ public class GreeHandler extends BaseThingHandler {
logger.debug("{}: Command {} failed for channel {}, retry", thingId, command, channelId);
} else {
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);
}
} catch (IllegalArgumentException e) {
@ -379,7 +379,7 @@ public class GreeHandler extends BaseThingHandler {
if (e.getCause() != null) {
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) {
logger.debug("{}: Thing still OFFLINE ({})", thingId, message);
} else {
@ -472,7 +472,7 @@ public class GreeHandler extends BaseThingHandler {
updateState(channelID, state);
}
} 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) {
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.Stream;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.harmonyhub.internal.handler.HarmonyHubHandler;
@ -253,8 +252,8 @@ public class HarmonyHubDiscoveryService extends AbstractDiscoveryService {
String friendlyName = properties.get("friendlyName");
String hostName = properties.get("host_name");
String ip = properties.get("ip");
if (StringUtils.isNotBlank(friendlyName) && StringUtils.isNotBlank(hostName)
&& StringUtils.isNotBlank(ip) && !responses.contains(hostName)) {
if (friendlyName != null && !friendlyName.isBlank() && hostName != null && !hostName.isBlank()
&& ip != null && !ip.isBlank() && !responses.contains(hostName)) {
responses.add(hostName);
hubDiscovered(ip, friendlyName, hostName);
}

View File

@ -196,7 +196,9 @@ public class HeosBridgeHandler extends BaseBridgeHandler implements HeosEventLis
@Nullable
Group[] onlineGroups = getApiConnection().getGroups().payload;
if (onlinePlayers != null && onlineGroups != null) {
updatePlayerStatus(onlinePlayers, onlineGroups);
}
} catch (ReadException | IOException 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.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import org.eclipse.jdt.annotation.NonNullByDefault;
@ -57,7 +58,7 @@ public class HeosJsonParser {
public <T> HeosResponseObject<T> parseResponse(String jsonBody, Class<T> clazz) {
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) {

View File

@ -359,7 +359,11 @@ public class HueBridge {
List<SuccessResponse> entries = safeFromJson(result.getBody(), SuccessResponse.GSON_TYPE);
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);
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);
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);
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);
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

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

View File

@ -19,7 +19,6 @@ import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
@ -94,10 +93,9 @@ public class HydrawiseCloudHandler extends HydrawiseHandler {
} else {
// try and use ID from saved property
String controllerId = getThing().getProperties().get(PROPERTY_CONTROLLER_ID);
if (StringUtils.isNotBlank(controllerId)) {
if (controllerId != null && !controllerId.isBlank()) {
try {
controller = getController(Integer.parseInt(controllerId), controllers);
} catch (NumberFormatException e) {
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.temporal.ChronoUnit;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.*;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@ -127,6 +124,7 @@ public abstract class HydrawiseHandler extends BaseThingHandler {
if (allCommand) {
sendRunAllCommand(((DecimalType) command).intValue());
} else {
Objects.requireNonNull(relay);
sendRunCommand(((DecimalType) command).intValue(), relay);
}
break;
@ -142,6 +140,7 @@ public abstract class HydrawiseHandler extends BaseThingHandler {
sendStopAllCommand();
}
} else {
Objects.requireNonNull(relay);
if (command == OnOffType.ON) {
sendRunCommand(relay);
} else {

View File

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

View File

@ -13,6 +13,7 @@
package org.openhab.binding.hydrawise.internal.api;
import java.net.URI;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@ -95,7 +96,7 @@ public class HydrawiseLocalApiClient {
throws HydrawiseConnectionException, HydrawiseAuthenticationException {
String json = doGet(localGetURL);
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.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
@ -120,7 +121,7 @@ public class IAqualinkClient {
if (response.getStatus() != HttpStatus.OK_200) {
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) {
throw new IOException(e);
}
@ -347,7 +348,7 @@ public class IAqualinkClient {
* @throws 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> {
@Override
public Home deserialize(@Nullable JsonElement json, @Nullable Type typeOfT,
@Nullable JsonDeserializationContext context) throws JsonParseException {
if (json == null) {
throw new JsonParseException("No JSON");
}
public @Nullable Home deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
JsonArray homeScreen = jsonObject.getAsJsonArray("home_screen");
JsonObject home = new JsonObject();
@ -408,11 +406,8 @@ public class IAqualinkClient {
class OneTouchDeserializer implements JsonDeserializer<OneTouch[]> {
@Override
public OneTouch[] deserialize(@Nullable JsonElement json, @Nullable Type typeOfT,
@Nullable JsonDeserializationContext context) throws JsonParseException {
if (json == null) {
throw new JsonParseException("No JSON");
}
public OneTouch @Nullable [] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
JsonArray oneTouchScreen = jsonObject.getAsJsonArray("onetouch_screen");
List<OneTouch> list = new ArrayList<>();
@ -429,7 +424,7 @@ public class IAqualinkClient {
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[]> {
@Override
public Auxiliary[] deserialize(@Nullable JsonElement json, @Nullable Type typeOfT,
@Nullable JsonDeserializationContext context) throws JsonParseException {
if (json == null) {
throw new JsonParseException("No JSON");
}
public Auxiliary @Nullable [] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
JsonArray auxScreen = jsonObject.getAsJsonArray("devices_screen");
List<Auxiliary> list = new ArrayList<>();
@ -462,7 +454,7 @@ public class IAqualinkClient {
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.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.*;
import java.util.concurrent.*;
import org.apache.commons.lang.StringUtils;
@ -238,6 +235,11 @@ public class InnogyBridgeHandler extends BaseBridgeHandler
}
Device bridgeDevice = deviceStructMan.getBridgeDevice();
if (bridgeDevice == null) {
logger.debug("Failed to get bridge device, re-scheduling startClient.");
scheduleRestartClient(true);
return;
}
setBridgeProperties(bridgeDevice);
bridgeId = bridgeDevice.getId();
startWebsocket();
@ -533,7 +535,7 @@ public class InnogyBridgeHandler extends BaseBridgeHandler
case BaseEvent.TYPE_NEW_MESSAGE_RECEIVED:
case BaseEvent.TYPE_MESSAGE_CREATED:
final MessageEvent messageEvent = gson.fromJson(msg, MessageEvent.class);
handleNewMessageReceivedEvent(messageEvent);
handleNewMessageReceivedEvent(Objects.requireNonNull(messageEvent));
break;
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
*
* @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 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.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.*;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
@ -440,8 +436,7 @@ public class DeviceFeature {
static {
// read features from xml file and store them in a map
InputStream input = DeviceFeature.class.getResourceAsStream("/device_features.xml");
if (input != null) {
Objects.requireNonNull(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
* 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 {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
@ -204,9 +204,12 @@ public class DeviceTypeLoader {
public static synchronized DeviceTypeLoader instance() {
if (deviceTypeLoader.getDeviceTypes().isEmpty()) {
InputStream input = DeviceTypeLoader.class.getResourceAsStream("/device_types.xml");
if (input != null) {
try {
if (input != null) {
deviceTypeLoader.loadDeviceTypesXML(input);
} else {
logger.warn("Resource stream is null, cannot read xml file.");
}
} catch (ParserConfigurationException e) {
logger.warn("parser config error when reading device types xml file: ", e);
} catch (SAXException e) {
@ -214,11 +217,6 @@ public class DeviceTypeLoader {
} catch (IOException e) {
logger.warn("I/O exception when reading device types xml file: ", e);
}
logger.debug("loaded {} devices: ", deviceTypeLoader.getDeviceTypes().size());
deviceTypeLoader.logDeviceTypes();
} else {
logger.warn("unable to get device types xml file as a resource");
}
}
return deviceTypeLoader;
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -21,12 +21,7 @@ import java.nio.channels.Channel;
import java.nio.channels.CompletionHandler;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
@ -150,7 +145,7 @@ public class Connection {
* @return the data
*/
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.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
@ -78,15 +79,13 @@ public class ConnectionStateConnecting extends AbstractConnectionState {
}
private void handleConnectionFailure(@Nullable Throwable e) {
String message;
String message = null;
if (e != null) {
logger.warn("Could not connect to {}:{}: {}", connection.getSettings().getAddress(),
connection.getSettings().getPort(), e.getMessage());
message = e.getMessage();
} else {
message = "";
}
connection.getCallback().onOffline(message);
connection.getCallback().onOffline(Objects.requireNonNullElse(message, ""));
context.handleConnectionFailed(e);
}

View File

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

View File

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

View File

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

View File

@ -213,7 +213,7 @@ public class EnedisHttpApi {
public UserInfo getUserInfo() throws LinkyException {
final String user_info_url = URL_APPS_LINCS + "/userinfos";
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)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -21,6 +21,7 @@ import java.nio.charset.StandardCharsets;
import java.time.ZonedDateTime;
import java.util.AbstractMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@ -115,9 +116,13 @@ public class MeteoAlerteHandler extends BaseThingHandler {
throw new MalformedURLException("queryUrl not initialized");
}
String response = HttpUtil.executeUrl("GET", queryUrl, TIMEOUT_MS);
if (response == null) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "empty response");
return;
}
updateStatus(ThingStatus.ONLINE);
ApiResponse apiResponse = gson.fromJson(response, ApiResponse.class);
updateChannels(apiResponse);
updateChannels(Objects.requireNonNull(apiResponse));
} catch (MalformedURLException e) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
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);
if (!actions.isEmpty()) {
if (actions.containsKey(channelUID)) {
int valuePos = 0;
MiIoBasicChannel miIoBasicChannel = actions.get(channelUID);
if (miIoBasicChannel != null) {
int valuePos = 0;
for (MiIoDeviceAction action : miIoBasicChannel.getActions()) {
@Nullable
JsonElement value = null;

View File

@ -17,12 +17,7 @@ import static org.openhab.binding.modbus.internal.ModbusBindingConstantsInternal
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.*;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.NotImplementedException;
@ -922,7 +917,8 @@ public class ModbusDataThingHandler extends BaseThingHandler {
}
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) {

View File

@ -24,6 +24,7 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.stream.Stream;
@ -201,8 +202,10 @@ public class MqttTopicClassMapperTests {
String suffix = mapToField != null ? mapToField.suffix() : "";
assertThat(f.field.get(attributes).toString(), is(prefix + annotation.value() + suffix));
} else {
assertThat(Stream.of((String[]) f.field.get(attributes)).reduce((v, i) -> v + "," + i).orElse(""),
is(annotation.value()));
String[] attributeArray = (String[]) f.field.get(attributes);
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.Map;
import java.util.Objects;
import org.apache.commons.lang.StringUtils;
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,
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>() {
@Override
public T read(@Nullable JsonReader in) throws IOException {
if (in == null) {
return null;
}
public @Nullable T read(JsonReader in) throws IOException {
/* read the object using the default adapter, but translate the names in the reader */
T result = delegate.read(MappingJsonReader.getConfigMapper(in));
/* do the '~' expansion afterwards */
@ -81,7 +78,7 @@ public class ChannelConfigurationTypeAdapterFactory implements TypeAdapterFactor
}
@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);
}
};
@ -93,17 +90,14 @@ public class ChannelConfigurationTypeAdapterFactory implements TypeAdapterFactor
return new TypeAdapter<T>() {
@Override
public T read(@Nullable JsonReader in) throws IOException {
if (in == null) {
return null;
}
public @Nullable T read(JsonReader in) throws IOException {
/* read the object using the default adapter, but translate the names in the reader */
T result = delegate.read(MappingJsonReader.getDeviceMapper(in));
return result;
}
@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);
}
};

View File

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

View File

@ -76,7 +76,7 @@ public class NeeoBrainApi implements AutoCloseable {
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();
}
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();
}
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();
}
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();
}
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();
}
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) {
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()) {
final ThingHandler th = child.getHandler();

View File

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

View File

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

View File

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

View File

@ -328,6 +328,10 @@ public class NikoHomeControlCommunication1 extends NikoHomeControlCommunication
for (Map<String, String> location : data) {
String id = location.get("id");
String name = location.get("name");
if (id == null || name == null) {
logger.debug("id or name null, ignoring entry");
continue;
}
NhcLocation1 nhcLocation1 = new NhcLocation1(name);
locations.put(id, nhcLocation1);
}
@ -337,8 +341,11 @@ public class NikoHomeControlCommunication1 extends NikoHomeControlCommunication
logger.debug("Niko Home Control: list actions");
for (Map<String, String> action : data) {
String id = action.get("id");
if (id == null) {
logger.debug("id not found in action {}", action);
continue;
}
String value1 = action.get("value1");
int state = ((value1 == null) || value1.isEmpty() ? 0 : Integer.parseInt(value1));
String value2 = action.get("value2");
@ -349,6 +356,10 @@ public class NikoHomeControlCommunication1 extends NikoHomeControlCommunication
if (!actions.containsKey(id)) {
// Initial instantiation of NhcAction class for action object
String name = action.get("name");
if (name == null) {
logger.debug("name not found in action {}", action);
continue;
}
String type = action.get("type");
ActionType actionType = ActionType.GENERIC;
switch (type) {
@ -371,8 +382,8 @@ public class NikoHomeControlCommunication1 extends NikoHomeControlCommunication
}
String locationId = action.get("location");
String location = "";
if (!locationId.isEmpty()) {
location = locations.get(locationId).getName();
if (locationId != null && !locationId.isEmpty()) {
location = locations.getOrDefault(locationId, new NhcLocation1("")).getName();
}
NhcAction nhcAction = new NhcAction1(id, name, actionType, location, this, scheduler);
if (actionType == ActionType.ROLLERSHUTTER) {
@ -405,6 +416,10 @@ public class NikoHomeControlCommunication1 extends NikoHomeControlCommunication
for (Map<String, String> thermostat : data) {
try {
String id = thermostat.get("id");
if (id == null) {
logger.debug("skipping thermostat {}, id not found", thermostat);
continue;
}
int measured = parseIntOrThrow(thermostat.get("measured"));
int setpoint = parseIntOrThrow(thermostat.get("setpoint"));
int mode = parseIntOrThrow(thermostat.get("mode"));
@ -528,6 +543,10 @@ public class NikoHomeControlCommunication1 extends NikoHomeControlCommunication
private void eventGetAlarms(Map<String, String> data) {
String alarmText = data.get("text");
if (alarmText == null) {
logger.debug("message does not contain alarmtext: {}", data);
return;
}
switch (data.getOrDefault("type", "")) {
case "0":
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.Nullable;
import org.openhab.binding.nikohomecontrol.internal.protocol.NhcControllerEvent;
import org.openhab.binding.nikohomecontrol.internal.protocol.NikoHomeControlCommunication;
import org.openhab.binding.nikohomecontrol.internal.protocol.*;
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.NhcMessage2.NhcMessageParam;
@ -309,7 +308,7 @@ public class NikoHomeControlCommunication2 extends NikoHomeControlCommunication
return;
} else if ("devices.added".equals(method)) {
deviceList.forEach(this::addDevice);
} else if ("devices.changed".contentEquals(method)) {
} else if ("devices.changed".equals(method)) {
deviceList.forEach(this::removeDevice);
deviceList.forEach(this::addDevice);
}
@ -444,12 +443,16 @@ public class NikoHomeControlCommunication2 extends NikoHomeControlCommunication
return;
}
if (actions.containsKey(device.uuid)) {
updateActionState((NhcAction2) actions.get(device.uuid), deviceProperties);
} else if (thermostats.containsKey(device.uuid)) {
updateThermostatState((NhcThermostat2) thermostats.get(device.uuid), deviceProperties);
} else if (energyMeters.containsKey(device.uuid)) {
updateEnergyMeterState((NhcEnergyMeter2) energyMeters.get(device.uuid), deviceProperties);
NhcAction action = actions.get(device.uuid);
NhcThermostat thermostat = thermostats.get(device.uuid);
NhcEnergyMeter energyMeter = energyMeters.get(device.uuid);
if (action != null) {
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.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@ -122,8 +123,7 @@ public class NtpHandler extends BaseThingHandler {
logger.debug("{} using default timezone '{}', because configuration setting '{}' is null.",
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);
if (stringChannel != null) {
String dateTimeFormatString = stringChannel.getConfiguration()
@ -183,7 +183,7 @@ public class NtpHandler extends BaseThingHandler {
refreshNtpCount--;
}
ZoneId zoneId = timeZoneId != null ? timeZoneId : timeZoneProvider.getTimeZone();
ZoneId zoneId = Objects.requireNonNullElse(timeZoneId, timeZoneProvider.getTimeZone());
ZonedDateTime zoned = ZonedDateTime.ofInstant(Instant.ofEpochMilli(networkTimeInMillis), zoneId);
updateState(CHANNEL_DATE_TIME, new DateTimeType(zoned));
dateTimeFormat.withZone(zoneId);
@ -208,7 +208,7 @@ public class NtpHandler extends BaseThingHandler {
timeInfo.computeDetails();
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);
logger.debug("{} Got time update from host '{}': {}.", getThing().getUID(), hostname,
zoned.format(DATE_FORMATTER_WITH_TZ));

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -18,6 +18,7 @@ import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
@ -286,12 +287,12 @@ public class RemoteopenhabRestClient {
break;
case "ItemAddedEvent":
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));
break;
case "ItemRemovedEvent":
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));
break;
case "ItemUpdatedEvent":

View File

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

View File

@ -70,6 +70,10 @@ public class RFXComDeviceDiscoveryService extends AbstractDiscoveryService imple
String id = message.getDeviceId();
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, "_"));
if (!bridgeHandler.getConfiguration().disableDiscovery) {

View File

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

View File

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

View File

@ -231,10 +231,8 @@ public class MainTVServerService implements UpnpIOParticipant, SamsungTvService
if (result.get("Result").equals("OK")) {
String xml = result.get("SourceList");
Map<String, String> list = parseSourceList(xml);
if (list != null) {
id = list.get(source);
if (xml != null) {
id = parseSourceList(xml).get(source);
}
} else {
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.HashMap;
import java.util.Map;
import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.binding.satel.internal.types.StateType;
@ -71,10 +72,10 @@ public class IntegraStateEvent implements SatelEvent {
if (stateType.getStartByte() == 0 && bitsCount == stateBits.size()) {
return stateBits;
}
return stateBitsMap.computeIfAbsent(stateType, k -> {
return Objects.requireNonNull(stateBitsMap.computeIfAbsent(stateType, k -> {
int startBit = k.getStartByte() * 8;
return stateBits.get(startBit, startBit + bitsCount);
});
}));
}
/**

View File

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