import java.io.IOException;
import java.net.URISyntaxException;
+import java.util.Objects;
import org.apache.commons.lang.StringEscapeUtils;
import org.eclipse.jdt.annotation.NonNullByDefault;
body = e.getLocalizedMessage();
}
}
- thingHandler.startAnnouncment(device, speak, body, title, volume);
+ thingHandler.startAnnouncment(device, speak, Objects.requireNonNullElse(body, ""), title, volume);
}
refreshChannel();
}
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) {
@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;
* 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);
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;
Method m = instance.getClass().getMethod(toGetterString(propertyName), null);
Object result = m.invoke(instance, (Object[]) null);
if (nestedIndex + 1 < properties.length) {
- if (result != null) {
- return getPropertyValue(result, properties, nestedIndex + 1);
- } else {
- throw new NullPointerException();
- }
+ Objects.requireNonNull(result);
+ return getPropertyValue(result, properties, nestedIndex + 1);
}
return result;
}
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;
}
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) {
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;
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)));
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;
@Override
public BD getDevice(BluetoothAddress address) {
synchronized (devices) {
- return devices.computeIfAbsent(address, this::createDevice);
+ return Objects.requireNonNull(devices.computeIfAbsent(address, this::createDevice));
}
}
package org.openhab.binding.bluetooth;
import java.util.Map;
+import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import org.eclipse.jdt.annotation.NonNullByDefault;
@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
*/
package org.openhab.binding.bsblan.internal;
-import java.util.HashSet;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
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;
import static org.openhab.binding.bsblan.internal.BsbLanBindingConstants.*;
-import java.util.HashSet;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@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) {
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();
}
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;
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());
}
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());
// get the channel id from the map
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);
updateChannel(channelUID, logEventMessage.toString());
}
return;
}
- listener.messageReceived(changedMessage.id, gson.fromJson(message, expectedMessageType));
+ DeconzBaseMessage deconzMessage = gson.fromJson(message, expectedMessageType);
+ if (deconzMessage != null) {
+ listener.messageReceived(changedMessage.id, deconzMessage);
+ }
}
@OnWebSocketError
@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());
}
}
@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());
}
}
@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());
}
}
@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;
}
}
bridgeHandler = (DigiplexBridgeHandler) bridge.getHandler();
String areaParm = getThing().getProperties().get(DigiplexBindingConstants.PROPERTY_AREA_NO);
- areaNo = Integer.parseInt(areaParm);
+ if (areaParm != null) {
+ areaNo = Integer.parseInt(areaParm);
+ }
bridgeHandler.registerMessageHandler(visitor);
updateStatus(ThingStatus.ONLINE);
this.bridgeHandler = (DigiplexBridgeHandler) bridge.getHandler();
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);
if (areaParm != null) {
areaNo = Integer.parseInt(areaParm);
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;
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.");
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;
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.");
*/
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;
.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
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;
*/
public boolean refresh() {
String rawData = dataAccessCached.getValue();
- if (StringUtils.isEmpty(rawData)) {
+ if (rawData == null || rawData.isEmpty()) {
logger.debug("No Data from Endpoint");
return false;
}
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);
}
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) {
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.
*/
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;
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) {
@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) {
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;
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());
}
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;
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));
}
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;
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;
}
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;
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());
}
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);
}
}
super(message, exception);
}
- @Override
- public @Nullable String getMessage() {
+ public String getMessageString() {
return isEmpty() ? "" : nonNullString(super.getMessage());
}
message = MessageFormat.format("{0} ({1})", message, cause);
}
} else {
- message = getMessage();
+ message = getMessageString();
}
return message;
}
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() {
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);
}
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) {
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) {
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 {
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);
}
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;
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);
}
@Nullable
Group[] onlineGroups = getApiConnection().getGroups().payload;
- updatePlayerStatus(onlinePlayers, onlineGroups);
+ if (onlinePlayers != null && onlineGroups != null) {
+ updatePlayerStatus(onlinePlayers, onlineGroups);
+ }
} catch (ReadException | IOException e) {
logger.debug("Failed updating online state of groups/players", e);
}
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;
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) {
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;
}
/**
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;
}
/**
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;
}
/**
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;
}
/**
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
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;
try {
Gson gson = new Gson();
String json = doGetRequest(DISCOVERY_URL);
- return gson.fromJson(json, new TypeToken<List<BridgeJsonParameters>>() {
- }.getType());
+ 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) {
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;
} 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);
}
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;
if (allCommand) {
sendRunAllCommand(((DecimalType) command).intValue());
} else {
+ Objects.requireNonNull(relay);
sendRunCommand(((DecimalType) command).intValue(), relay);
}
break;
sendStopAllCommand();
}
} else {
+ Objects.requireNonNull(relay);
if (command == OnOffType.ON) {
sendRunCommand(relay);
} else {
*/
package org.openhab.binding.hydrawise.internal.api;
+import java.util.Objects;
import java.util.concurrent.TimeUnit;
import org.eclipse.jdt.annotation.NonNullByDefault;
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;
}
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
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);
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);
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;
throws HydrawiseConnectionException, HydrawiseAuthenticationException {
String json = doGet(localGetURL);
LocalScheduleResponse response = gson.fromJson(json, LocalScheduleResponse.class);
- return response;
+ return Objects.requireNonNull(response);
}
/**
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;
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);
}
* @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));
}
/**
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();
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<>();
oneTouchJson.add(oneTouchEntry.getKey(), oneTouchEntry.getValue());
});
});
- list.add(gsonInternal.fromJson(oneTouchJson, OneTouch.class));
+ list.add(Objects.requireNonNull(gsonInternal.fromJson(oneTouchJson, OneTouch.class)));
}
}
});
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<>();
auxJson.add(auxEntry.getKey(), auxEntry.getValue());
});
});
- list.add(gsonInternal.fromJson(auxJson, Auxiliary.class));
+ list.add(Objects.requireNonNull(gsonInternal.fromJson(auxJson, Auxiliary.class)));
}
}
});
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;
}
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();
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:
/**
* 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
*/
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;
static {
// read features from xml file and store them in a map
InputStream input = DeviceFeature.class.getResourceAsStream("/device_features.xml");
- if (input != null) {
- readFeatureTemplates(input);
- }
+ Objects.requireNonNull(input);
+ readFeatureTemplates(input);
}
}
* 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();
public static synchronized DeviceTypeLoader instance() {
if (deviceTypeLoader.getDeviceTypes().isEmpty()) {
InputStream input = DeviceTypeLoader.class.getResourceAsStream("/device_types.xml");
- if (input != null) {
- try {
+ try {
+ if (input != null) {
deviceTypeLoader.loadDeviceTypesXML(input);
- } catch (ParserConfigurationException e) {
- logger.warn("parser config error when reading device types xml file: ", e);
- } 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);
+ } else {
+ logger.warn("Resource stream is null, cannot read xml file.");
}
- logger.debug("loaded {} devices: ", deviceTypeLoader.getDeviceTypes().size());
- deviceTypeLoader.logDeviceTypes();
- } else {
- logger.warn("unable to get device types xml file as a resource");
+ } catch (ParserConfigurationException e) {
+ logger.warn("parser config error when reading device types xml file: ", e);
+ } 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);
}
}
return deviceTypeLoader;
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;
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);
if (channel == null) {
logger.debug("Creating a new temperature channel: {}", segmentId);
createTempChannel(segmentId, segment.getSegmentName());
+ processThermometer(segment);
+ return;
}
updateTemperatureChannel(channel, segment);
}
if (channel == null) {
logger.debug("Creating a new thermostat channel: {}", segmentId);
createThermostatChannel(segmentId, segment.getSegmentName());
+ processThermostat(segment);
+ return;
}
updateTemperatureChannel(channel, segment);
}
*/
public static String checkParameterReplacement(Channel channel, KM200Device device) {
String service = KM200Utils.translatesNameToPath(channel.getProperties().get("root"));
- if (service.contains(SWITCH_PROGRAM_REPLACEMENT)) {
- String currentService = KM200Utils
- .translatesNameToPath(channel.getProperties().get(SWITCH_PROGRAM_CURRENT_PATH_NAME));
+ 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();
- service = service.replace(SWITCH_PROGRAM_REPLACEMENT, val);
+ if (val != null) {
+ service = service.replace(SWITCH_PROGRAM_REPLACEMENT, val);
+ }
return service;
}
}
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 {
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()) {
state = StateDescriptionFragmentBuilder.create().withMinimum(BigDecimal.ZERO).withStep(BigDecimal.ONE)
.withPattern("%d minutes").build();
String posName = thing.getProperties().get(SWITCH_PROGRAM_POSITIVE);
- 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 (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");
+ }
if (null == newChannel) {
logger.warn("Creation of the channel {} was not possible", thing.getUID());
} else {
}
String negName = thing.getProperties().get(SWITCH_PROGRAM_NEGATIVE);
- 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 (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");
+ }
if (null == newChannel) {
logger.warn("Creation of the channel {} was not possible", thing.getUID());
} else {
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
+import com.google.gson.JsonSyntaxException;
/**
* KVVBridgeHandler encapsulates the communication with the KVV API.
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);
return null;
}
+ if (result == null) {
+ return null;
+ }
+
if (this.wasOffline) {
updateStatus(ThingStatus.ONLINE);
}
/**
* Creates a new @{link Cache}.
*
- * @param updateInterval the @{code updateInterval}
*/
public Cache() {
this.updateInterval = KVVBindingConstants.CACHE_DEFAULT_UPDATEINTERVAL;
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;
{
JsonElement tree = elementAdapter.read(in);
afterRead(tree);
+ if (tree == null) {
+ throw new IOException("null reader");
+ }
return delegate.fromJsonTree(tree);
}
};
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;
* @return the data
*/
public ModInfo updateModuleData(LcnAddrMod addr) {
- return modData.computeIfAbsent(addr, ModInfo::new);
+ return Objects.requireNonNull(modData.computeIfAbsent(addr, ModInfo::new));
}
/**
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;
}
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);
}
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;
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;
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;
*/
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;
.setTemperature(percentTypeToKelvin(localPowerOnTemperature, product.getTemperatureRange()));
}
+ PercentType powerOnBrightness = this.powerOnBrightness;
if (powerOnBrightness != null) {
PercentType newBrightness = onOff == OnOffType.ON ? powerOnBrightness : new PercentType(0);
getLightStateForCommand().setBrightness(newBrightness);
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)
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();
import java.time.LocalDateTime;
import java.util.List;
+import java.util.Objects;
import java.util.concurrent.TimeUnit;
import org.eclipse.jdt.annotation.NonNullByDefault;
} else {
failure = result.getFailure().getMessage();
}
- callback.onError(failure);
+ callback.onError(Objects.requireNonNullElse(failure, "Unknown error"));
} else {
callback.onResponse(getContentAsString());
}
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;
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);
}
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;
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);
});
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);
});
} else {
areaName = "Occupancy Group";
}
- logger.debug("Discovered occupancy group: {} areas: {} area name: {}", groupNum,
- oGroup.associatedAreas.length, areaName);
- notifyDiscovery(THING_TYPE_OGROUP, groupNum, areaName);
+ 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;
import java.util.LinkedList;
import java.util.List;
+import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
try {
if (messageBody.has(memberName)) {
JsonObject jsonObject = messageBody.get(memberName).getAsJsonObject();
+ @Nullable
T obj = gson.fromJson(jsonObject, type);
return obj;
} else {
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;
// direct key code
return key;
}
- if (KEY_MAP.containsKey(key)) {
- return KEY_MAP.get(key);
- }
- return "";
+ return KEY_MAP.getOrDefault(key, "");
}
/**
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;
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()));
}
logger.debug("Locating action for {} channel '{}': '{}'", getThing().getUID(), channelUID.getId(), command);
if (!actions.isEmpty()) {
- if (actions.containsKey(channelUID)) {
+ MiIoBasicChannel miIoBasicChannel = actions.get(channelUID);
+ if (miIoBasicChannel != null) {
int valuePos = 0;
- MiIoBasicChannel miIoBasicChannel = actions.get(channelUID);
for (MiIoDeviceAction action : miIoBasicChannel.getActions()) {
@Nullable
JsonElement value = null;
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;
}
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) {
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;
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()));
}
}
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jdt.annotation.NonNullByDefault;
*/
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));
}
/**
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 */
}
@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);
}
};
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);
}
};
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;
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);
}
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 {
throw resp.createException();
}
- return gson.fromJson(resp.getContent(), NeeoBrain.class);
+ return Objects.requireNonNull(gson.fromJson(resp.getContent(), NeeoBrain.class));
}
/**
throw resp.createException();
}
- return gson.fromJson(resp.getContent(), NeeoRoom.class);
+ return Objects.requireNonNull(gson.fromJson(resp.getContent(), NeeoRoom.class));
}
/**
throw resp.createException();
}
- return gson.fromJson(resp.getContent(), ExecuteResult.class);
+ return Objects.requireNonNull(gson.fromJson(resp.getContent(), ExecuteResult.class));
}
/**
throw resp.createException();
}
- return gson.fromJson(resp.getContent(), ExecuteResult.class);
+ return Objects.requireNonNull(gson.fromJson(resp.getContent(), ExecuteResult.class));
}
/**
throw resp.createException();
}
- return gson.fromJson(resp.getContent(), String[].class);
+ return Objects.requireNonNull(gson.fromJson(resp.getContent(), String[].class));
}
/**
throw resp.createException();
}
- return gson.fromJson(resp.getContent(), ExecuteResult.class);
+ return Objects.requireNonNull(gson.fromJson(resp.getContent(), ExecuteResult.class));
}
/**
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();
public class NeohubBoolDeserializer implements JsonDeserializer<NeohubBool> {
@Override
- public NeohubBool deserialize(@Nullable JsonElement json, @Nullable Type typeOfT,
- @Nullable JsonDeserializationContext context) throws JsonParseException {
- if (json != null) {
- JsonPrimitive jsonPrimitive = json.getAsJsonPrimitive();
- if (jsonPrimitive.isBoolean()) {
- return new NeohubBool(jsonPrimitive.getAsBoolean());
- } else if (jsonPrimitive.isNumber()) {
- return new NeohubBool(jsonPrimitive.getAsNumber().intValue() != 0);
- }
+ 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);
}
}
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;
}
package org.openhab.binding.netatmo.internal.webhook;
import java.io.IOException;
+import java.util.Objects;
import java.util.Scanner;
import javax.servlet.ServletException;
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);
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);
}
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");
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) {
}
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) {
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"));
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);
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;
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);
}
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);
}
}
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;
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()
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);
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));
*/
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;
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;
}
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;
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;
}
if (listener == null) {
throw new IllegalArgumentException("It makes no sense to register a null listener!");
}
- boolean added = routeDataListeners.add(listener);
- if (added) {
- String routeId = listener.getRouteId();
- List<ObaStopArrivalResponse.ArrivalAndDeparture> copiedRouteData;
- synchronized (routeData) {
- copiedRouteData = new ArrayList<>(routeData.get(routeId));
- }
- Collections.sort(copiedRouteData);
- listener.onNewRouteData(routeDataLastUpdateMs, copiedRouteData);
+ routeDataListeners.add(listener);
+ String routeId = listener.getRouteId();
+ List<ObaStopArrivalResponse.ArrivalAndDeparture> copiedRouteData;
+ synchronized (routeData) {
+ copiedRouteData = new ArrayList<>(routeData.getOrDefault(routeId, List.of()));
}
- return added;
+ Collections.sort(copiedRouteData);
+ listener.onNewRouteData(routeDataLastUpdateMs, copiedRouteData);
+
+ return true;
}
/**
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);
}
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) {
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;
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;
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;
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":
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;
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));
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;
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);
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) {
} 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;
}
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;
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;
}
}
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"));
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;
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);
- });
+ }));
}
/**
import java.io.IOException;
import java.net.MalformedURLException;
+import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
.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());
Channel channelLimitationState = getThing()
.getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_POWER_LIMITATION_STATE);
- updatePowerLimitationStatus(channelLimitationState,
- (100 - pvLimitation.intValue()) <= config.limitationTresholdValue, config.limitationDuration);
+ if (channelLimitationState != null) {
+ updatePowerLimitationStatus(channelLimitationState,
+ (100 - pvLimitation.intValue()) <= config.limitationTresholdValue, config.limitationDuration);
+ }
Channel channelConsumption = getThing()
.getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_POWER_CONSUMPTION);
- updateState(channelConsumption.getUID(),
- new QuantityType<Power>(
- getSenecValue(response.energy.homePowerConsumption).setScale(2, RoundingMode.HALF_UP),
- SmartHomeUnits.WATT));
+ if (channelConsumption != null) {
+ updateState(channelConsumption.getUID(),
+ new QuantityType<Power>(
+ getSenecValue(response.energy.homePowerConsumption).setScale(2, RoundingMode.HALF_UP),
+ SmartHomeUnits.WATT));
+ }
Channel channelEnergyProduction = getThing()
.getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_ENERGY_PRODUCTION);
- updateState(channelEnergyProduction.getUID(),
- new QuantityType<Power>(
- getSenecValue(response.energy.inverterPowerGeneration).setScale(0, RoundingMode.HALF_UP),
- SmartHomeUnits.WATT));
+ if (channelEnergyProduction != null) {
+ updateState(channelEnergyProduction.getUID(), new QuantityType<Power>(
+ getSenecValue(response.energy.inverterPowerGeneration).setScale(0, RoundingMode.HALF_UP),
+ SmartHomeUnits.WATT));
+ }
Channel channelBatteryPower = getThing().getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_BATTERY_POWER);
- updateState(channelBatteryPower.getUID(),
- new QuantityType<Power>(
- getSenecValue(response.energy.batteryPower).setScale(2, RoundingMode.HALF_UP),
- SmartHomeUnits.WATT));
+ if (channelBatteryPower != null) {
+ updateState(channelBatteryPower.getUID(),
+ new QuantityType<Power>(
+ getSenecValue(response.energy.batteryPower).setScale(2, RoundingMode.HALF_UP),
+ SmartHomeUnits.WATT));
+ }
Channel channelBatteryFuelCharge = getThing()
.getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_BATTERY_FUEL_CHARGE);
- updateState(channelBatteryFuelCharge.getUID(),
- new QuantityType<Dimensionless>(
- getSenecValue(response.energy.batteryFuelCharge).setScale(0, RoundingMode.HALF_UP),
- SmartHomeUnits.PERCENT));
+ if (channelBatteryFuelCharge != null) {
+ updateState(channelBatteryFuelCharge.getUID(),
+ new QuantityType<Dimensionless>(
+ getSenecValue(response.energy.batteryFuelCharge).setScale(0, RoundingMode.HALF_UP),
+ SmartHomeUnits.PERCENT));
+ }
Channel channelGridCurrentPhase1 = getThing()
.getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_GRID_CURRENT_PH1);
SmartHomeUnits.VOLT));
Channel channelBatteryState = getThing().getChannel(SenecHomeBindingConstants.CHANNEL_SENEC_BATTERY_STATE);
- updateBatteryState(channelBatteryState, getSenecValue(response.energy.batteryState).intValue());
+ if (channelBatteryState != null) {
+ updateBatteryState(channelBatteryState, getSenecValue(response.energy.batteryState).intValue());
+ }
updateGridPowerValues(getSenecValue(response.grid.currentGridValue));
gson = new GsonBuilder().registerTypeAdapter(ZonedDateTime.class, new TypeAdapter<ZonedDateTime>() {
@Override
- public void write(final @NonNullByDefault({}) JsonWriter out, final ZonedDateTime value)
- throws IOException {
- out.value(value.toString());
+ public void write(JsonWriter out, @Nullable ZonedDateTime value) throws IOException {
+ if (value != null) {
+ out.value(value.toString());
+ }
}
@Override
- public ZonedDateTime read(final @NonNullByDefault({}) JsonReader in) throws IOException {
+ public @Nullable ZonedDateTime read(final JsonReader in) throws IOException {
return ZonedDateTime.parse(in.nextString());
}
}).setLenient().setPrettyPrinting().create();
import java.util.HashMap;
import java.util.Map;
+import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsDimmer;
try {
initFromThingType(thingType);
settingsJson = json;
- settings = gson.fromJson(json, ShellySettingsGlobal.class);
+ settings = Objects.requireNonNull(gson.fromJson(json, ShellySettingsGlobal.class));
} catch (IllegalArgumentException | JsonSyntaxException e) {
throw new ShellyApiException(
thingName + ": Unable to transform settings JSON " + e.toString() + ", json='" + json + "'", e);
import static org.openhab.binding.shelly.internal.util.ShellyUtils.*;
import java.net.UnknownHostException;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.TreeMap;
+import java.util.*;
import org.eclipse.californium.core.CoapClient;
import org.eclipse.californium.core.coap.CoAP.Code;
continue;
}
CoIotDescrSen sen = sensorMap.get(s.id);
+ Objects.requireNonNull(sen);
// find matching sensor definition from device description, use the Link ID as index
sen = coiot.fixDescription(sen, blkMap);
if (!blkMap.containsKey(sen.links)) {
}
@Override
- public BasePoint deserialize(@Nullable JsonElement element, @Nullable Type guff,
- @Nullable JsonDeserializationContext ctxt) throws JsonParseException {
- if (element == null || ctxt == null) {
- throw new JsonParseException("method called with null argument(s)");
- }
-
+ public @Nullable BasePoint deserialize(JsonElement element, Type guff, JsonDeserializationContext ctxt)
+ throws JsonParseException {
JsonObject obj = element.getAsJsonObject();
JsonElement value = obj.get("value");
if (value == null) {
Channel channel = this.thing.getChannel(channelId.getId());
if (channel != null) {
String obis = channel.getProperties().get(SmartMeterBindingConstants.CHANNEL_PROPERTY_OBIS);
- MeterValue<?> value = this.smlDevice.getMeterValue(obis);
- if (value != null) {
- State state = getStateForObisValue(value, channel);
- updateState(channel.getUID(), state);
+ if (obis != null) {
+ MeterValue<?> value = this.smlDevice.getMeterValue(obis);
+ if (value != null) {
+ State state = getStateForObisValue(value, channel);
+ updateState(channel.getUID(), state);
+ }
}
}
}
// Negate if this channel has the unit "Watt" and the negate bit is set. Read from all other
// channels the state and check if there is a negate bit.
String channelObis = channel.getProperties().get(SmartMeterBindingConstants.CHANNEL_PROPERTY_OBIS);
- MeterValue<?> value = device.getMeterValue(channelObis);
- if (value != null && SmartHomeUnits.WATT.isCompatible(value.getUnit())) {
- for (String obis : device.getObisCodes()) {
- try {
- MeterValue<?> otherValue = device.getMeterValue(obis);
- ObisCode obisCode = ObisCode.from(obis);
- if (otherValue != null) {
- if (obisCode.matches((byte) 0x60, (byte) 0x05, (byte) 0x05)) {
- // we found status status obis 96.5.5
- if (NegateHandler.isNegateSet(otherValue.getValue(), 5)) {
- return currentState.negate();
- }
- } else if (obisCode.matches((byte) 0x01, (byte) 0x08, (byte) 0x00)) {
- // check obis 1.8.0 for status if status has negate bit set.
- String status = otherValue.getStatus();
- if (status != null && NegateHandler.isNegateSet(status, 5)) {
- return currentState.negate();
+ if (channelObis != null) {
+ MeterValue<?> value = device.getMeterValue(channelObis);
+ if (value != null && SmartHomeUnits.WATT.isCompatible(value.getUnit())) {
+ for (String obis : device.getObisCodes()) {
+ try {
+ MeterValue<?> otherValue = device.getMeterValue(obis);
+ ObisCode obisCode = ObisCode.from(obis);
+ if (otherValue != null) {
+ if (obisCode.matches((byte) 0x60, (byte) 0x05, (byte) 0x05)) {
+ // we found status status obis 96.5.5
+ if (NegateHandler.isNegateSet(otherValue.getValue(), 5)) {
+ return currentState.negate();
+ }
+ } else if (obisCode.matches((byte) 0x01, (byte) 0x08, (byte) 0x00)) {
+ // check obis 1.8.0 for status if status has negate bit set.
+ String status = otherValue.getStatus();
+ if (status != null && NegateHandler.isNegateSet(status, 5)) {
+ return currentState.negate();
+ }
}
}
+ } catch (Exception e) {
+ logger.warn("Failed to check negate status for obis {}", obis, e);
}
- } catch (Exception e) {
- logger.warn("Failed to check negate status for obis {}", obis, e);
}
}
}
private @Nullable SmartthingsBridgeHandler bridgeHandler = null;
private @Nullable ThingUID bridgeUID;
private Gson gson;
- private List<SmartthingsThingHandler> thingHandlers = Collections
- .synchronizedList(new ArrayList<SmartthingsThingHandler>());
+ private List<SmartthingsThingHandler> thingHandlers = Collections.synchronizedList(new ArrayList<>());
private @NonNullByDefault({}) HttpClient httpClient;
String data = (String) event.getProperty("data");
SmartthingsStateData stateData = new SmartthingsStateData();
stateData = gson.fromJson(data, stateData.getClass());
+ if (stateData == null) {
+ return;
+ }
SmartthingsThingHandler handler = findHandler(stateData);
if (handler != null) {
handler.handleStateMessage(stateData);
*/
package org.openhab.binding.smartthings.internal.discovery;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
// The data returned from the Smartthings hub is a list of strings where each
// element is the data for one device. That device string is another json object
- List<String> devices = new ArrayList<String>();
+ List<String> devices = new ArrayList<>();
devices = gson.fromJson(data, devices.getClass());
for (String device : devices) {
SmartthingsDeviceData deviceData = gson.fromJson(device, SmartthingsDeviceData.class);
- createDevice(deviceData);
+ createDevice(Objects.requireNonNull(deviceData));
}
}
// See https://github.com/openhab/openhab-webui/issues/212
Set<Integer> hours = new TreeSet<>();
Set<Integer> days = new TreeSet<>();
- if (config.hourlyForecasts != null) {
- hours.addAll(config.hourlyForecasts);
+ List<Integer> hourlyForecasts = config.hourlyForecasts;
+ if (hourlyForecasts != null) {
+ hours.addAll(hourlyForecasts);
}
- if (config.dailyForecasts != null) {
- days.addAll(config.dailyForecasts);
+ List<Integer> dailyForecasts = config.dailyForecasts;
+ if (dailyForecasts != null) {
+ days.addAll(dailyForecasts);
}
for (int i : hours) {
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
+import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
throw new SomfyMyLinkException("Incomplete message.");
}
- return gson.fromJson(jsonObj, responseType);
+ return Objects.requireNonNull(gson.fromJson(jsonObj, responseType));
}
private Socket getConnection() throws IOException, SomfyMyLinkException {
protected void refresh(String channel) {
SomfyTahomaBridgeHandler handler = getBridgeHandler();
- if (handler != null && stateNames.containsKey(channel)) {
- handler.refresh(url, stateNames.get(channel));
+ String stateName = stateNames.get(channel);
+ if (handler != null && stateName != null) {
+ handler.refresh(url, stateName);
}
}
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+import java.util.Objects;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Function;
import java.util.stream.Collectors;
public Me getMe() {
final ContentResponse response = request(GET, SPOTIFY_API_URL, "");
- return ModelUtil.gsonInstance().fromJson(response.getContentAsString(), Me.class);
+ return Objects.requireNonNull(ModelUtil.gsonInstance().fromJson(response.getContentAsString(), Me.class));
}
/**
import java.io.IOException;
+import org.openhab.binding.tado.internal.TadoBindingConstants;
import org.openhab.binding.tado.internal.TadoBindingConstants.FanSpeed;
import org.openhab.binding.tado.internal.TadoBindingConstants.HvacMode;
import org.openhab.binding.tado.internal.TadoBindingConstants.TemperatureUnit;
*/
public abstract class ZoneSettingsBuilder {
public static ZoneSettingsBuilder of(TadoZoneHandler zoneHandler) {
- switch (zoneHandler.getZoneType()) {
+ TadoBindingConstants.ZoneType zoneType = zoneHandler.getZoneType();
+ if (zoneType == null) {
+ throw new IllegalArgumentException("Zone type is null");
+ }
+ switch (zoneType) {
case HEATING:
return new HeatingZoneSettingsBuilder();
case AIR_CONDITIONING:
}
public TemperatureUnit getTemperatureUnit() {
- String temperatureUnitStr = this.thing.getProperties().get(TadoBindingConstants.PROPERTY_HOME_TEMPERATURE_UNIT);
+ String temperatureUnitStr = this.thing.getProperties()
+ .getOrDefault(TadoBindingConstants.PROPERTY_HOME_TEMPERATURE_UNIT, "CELSIUS");
return TemperatureUnit.valueOf(temperatureUnitStr);
}
import javax.measure.quantity.Temperature;
+import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.tado.internal.TadoBindingConstants;
import org.openhab.binding.tado.internal.TadoBindingConstants.OperationMode;
import org.openhab.binding.tado.internal.TadoBindingConstants.TemperatureUnit;
return this.configuration.fallbackTimerDuration;
}
- public ZoneType getZoneType() {
+ public @Nullable ZoneType getZoneType() {
String zoneTypeStr = this.thing.getProperties().get(TadoBindingConstants.PROPERTY_ZONE_TYPE);
- return ZoneType.valueOf(zoneTypeStr);
+ return zoneTypeStr != null ? ZoneType.valueOf(zoneTypeStr) : null;
}
public OverlayTerminationCondition getDefaultTerminationCondition() throws IOException, ApiException {
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Set;
-import java.util.UUID;
+import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
}
} else {
String currentFirmware = thing.getProperties().get(Thing.PROPERTY_FIRMWARE_VERSION);
- if (!isNullOrEmpty(currentFirmware)
- && MIN_SUPPORTED_VERSION.compareTo(new TradfriVersion(currentFirmware)) > 0) {
+ if (!isNullOrEmpty(currentFirmware) && MIN_SUPPORTED_VERSION
+ .compareTo(new TradfriVersion(Objects.requireNonNull(currentFirmware))) > 0) {
// older firmware not supported
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
String.format(
byte[] subAddresses = new byte[numberOfSubAddresses];
for (int i = 0; i < numberOfSubAddresses; i++) {
String propertyKey = SUB_ADDRESS + (i + 1);
- if (getThing().getProperties().containsKey(propertyKey)) {
- String subAddress = getThing().getProperties().get(propertyKey);
+ String subAddress = getThing().getProperties().get(propertyKey);
+ if (subAddress != null) {
subAddresses[i] = hexToByte(subAddress);
} else {
subAddresses[i] = (byte) 0xFF;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
-import java.util.ArrayList;
-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.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
if (!isFutureValid(localUpdatesTask)) {
return;
}
- infoData = gson.fromJson(response, VenstarInfoData.class);
+ infoData = Objects.requireNonNull(gson.fromJson(response, VenstarInfoData.class));
updateUnits(infoData);
updateIfChanged(CHANNEL_HEATING_SETPOINT, getHeatingSetpoint());
updateIfChanged(CHANNEL_COOLING_SETPOINT, getCoolingSetpoint());
List<QuantityType<?>> flows = new ArrayList<>();
thing.getProperties().keySet().stream().filter(key -> key.startsWith(FLOOD)).forEach(key -> {
String value = thing.getProperties().get(key);
- if (key.contains(FLOW)) {
- flows.add(new QuantityType<>(value));
- } else {
- heights.add(new QuantityType<>(value));
+ if (value != null) {
+ if (key.contains(FLOW)) {
+ flows.add(new QuantityType<>(value));
+ } else {
+ heights.add(new QuantityType<>(value));
+ }
}
});
referenceHeights = heights.stream().distinct().sorted().collect(Collectors.toList());
import java.io.IOException;
import java.nio.charset.StandardCharsets;
+import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
throw new IOException();
} else {
logger.debug("Request to `{}` answered : {}", url, jsonResponse);
- T responseDTO = gson.fromJson(jsonResponse, objectClass);
+ T responseDTO = Objects.requireNonNull(gson.fromJson(jsonResponse, objectClass));
String error = responseDTO.getErrorLabel();
if (error != null) {
throw new VolvoOnCallException(error, responseDTO.getErrorDescription());
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
+import java.util.Objects;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
}
try {
logger.trace("Handler: Parsing forecast response: {}", response);
- ForecastDTO forecast = gson.fromJson(response, ForecastDTO.class);
+ ForecastDTO forecast = Objects.requireNonNull(gson.fromJson(response, ForecastDTO.class));
logger.debug("Handler: Successfully parsed daily forecast response object");
updateStatus(ThingStatus.ONLINE);
updateDailyForecast(forecast);
import static org.openhab.binding.weathercompany.internal.WeatherCompanyBindingConstants.*;
+import java.util.Objects;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
}
try {
logger.debug("Handler: Parsing PWS observations response: {}", response);
- PwsObservationsDTO pwsObservations = gson.fromJson(response, PwsObservationsDTO.class);
+ PwsObservationsDTO pwsObservations = Objects
+ .requireNonNull(gson.fromJson(response, PwsObservationsDTO.class));
logger.debug("Handler: Successfully parsed PWS observations response object");
updateStatus(ThingStatus.ONLINE);
updatePwsObservations(pwsObservations);
package org.openhab.binding.wlanthermo.internal;
import java.net.URISyntaxException;
+import java.util.Objects;
import java.util.concurrent.*;
import org.eclipse.jdt.annotation.NonNullByDefault;
try {
// Update objects with data from device
String json = httpClient.GET(config.getUri("/app.php")).getContentAsString();
- app = gson.fromJson(json, App.class);
+ app = Objects.requireNonNull(gson.fromJson(json, App.class));
logger.debug("Received at /app.php: {}", json);
// Update channels
import java.net.URI;
import java.net.URISyntaxException;
+import java.util.Objects;
import java.util.concurrent.*;
import org.eclipse.jdt.annotation.NonNullByDefault;
try {
// Update objects with data from device
String json = httpClient.GET(config.getUri("/data")).getContentAsString();
- data = gson.fromJson(json, Data.class);
+ data = Objects.requireNonNull(gson.fromJson(json, Data.class));
logger.debug("Received at /data: {}", json);
json = httpClient.GET(config.getUri("/settings")).getContentAsString();
- settings = gson.fromJson(json, Settings.class);
+ settings = Objects.requireNonNull(gson.fromJson(json, Settings.class));
logger.debug("Received at /settings: {}", json);
// Update channels
import static org.openhab.io.homekit.internal.HomekitCharacteristicType.*;
import java.lang.reflect.InvocationTargetException;
+import java.util.*;
import java.util.AbstractMap.SimpleEntry;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
import java.util.Map.Entry;
-import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
characteristics.forEach((type, item) -> {
try {
// check whether a proxyItem already exists, if not create one.
- final HomekitOHItemProxy proxyItem = proxyItems.computeIfAbsent(item.getUID(),
- k -> new HomekitOHItemProxy(item));
+ final HomekitOHItemProxy proxyItem = Objects
+ .requireNonNull(proxyItems.computeIfAbsent(item.getUID(), k -> new HomekitOHItemProxy(item)));
final HomekitTaggedItem optionalItem = new HomekitTaggedItem(proxyItem,
accessory.getRootAccessory().getAccessoryType(), type,
accessory.getRootAccessory().getRootDeviceGroupItem(),
return NetworkUtils.singleError(cs.gson, uri, HueResponse.UNAUTHORIZED, "Not Authorized");
}
- final HueStateChange changeRequest = cs.gson.fromJson(body, HueStateChange.class);
+ final HueStateChange changeRequest = Objects.requireNonNull(cs.gson.fromJson(body, HueStateChange.class));
Rule rule = ruleRegistry.remove(id);
if (rule == null) {
*/
package org.openhab.io.hueemulation.internal.rest;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.UUID;
+import java.util.*;
import java.util.stream.Collectors;
import javax.ws.rs.Consumes;
return NetworkUtils.singleError(cs.gson, uri, HueResponse.UNAUTHORIZED, "Not Authorized");
}
- final HueChangeScheduleEntry changeRequest = cs.gson.fromJson(body, HueChangeScheduleEntry.class);
+ final HueChangeScheduleEntry changeRequest = Objects
+ .requireNonNull(cs.gson.fromJson(body, HueChangeScheduleEntry.class));
Rule rule = ruleRegistry.remove(id);
if (rule == null) {
for (RegistryChangeListener<Item> l : listeners) {
l.added(element);
}
- return put;
+ return element;
}
@Override
public @Nullable Item update(Item element) {
Item put = items.put(element.getUID(), element);
- for (RegistryChangeListener<Item> l : listeners) {
- l.updated(put, element);
+ if (put != null) {
+ for (RegistryChangeListener<Item> l : listeners) {
+ l.updated(put, element);
+ }
}
return put;
}
@Override
public @Nullable Item remove(String key) {
Item put = items.remove(key);
- for (RegistryChangeListener<Item> l : listeners) {
- l.removed(put);
+ if (put != null) {
+ for (RegistryChangeListener<Item> l : listeners) {
+ l.removed(put);
+ }
}
return put;
}
@Override
public @Nullable Item remove(String itemName, boolean recursive) {
Item put = items.remove(itemName);
- for (RegistryChangeListener<Item> l : listeners) {
- l.removed(put);
+ if (put != null) {
+ for (RegistryChangeListener<Item> l : listeners) {
+ l.removed(put);
+ }
}
return put;
}
for (RegistryChangeListener<Metadata> l : listeners) {
l.added(element);
}
- return put;
+ return element;
}
@Override
public @Nullable Metadata update(Metadata element) {
Metadata put = items.put(element.getUID(), element);
- for (RegistryChangeListener<Metadata> l : listeners) {
- l.updated(put, element);
+ if (put != null) {
+ for (RegistryChangeListener<Metadata> l : listeners) {
+ l.updated(put, element);
+ }
}
return put;
}
@Override
public @Nullable Metadata remove(MetadataKey key) {
Metadata put = items.remove(key);
- for (RegistryChangeListener<Metadata> l : listeners) {
- l.removed(put);
+ if (put != null) {
+ for (RegistryChangeListener<Metadata> l : listeners) {
+ l.removed(put);
+ }
}
return put;
}
for (RegistryChangeListener<Rule> l : listeners) {
l.added(element);
}
- return put;
+ return element;
}
@Override
public @Nullable Rule update(Rule element) {
Rule put = items.put(element.getUID(), element);
- for (RegistryChangeListener<Rule> l : listeners) {
- l.updated(put, element);
+ if (put != null) {
+ for (RegistryChangeListener<Rule> l : listeners) {
+ l.updated(put, element);
+ }
}
return put;
}
@Override
public @Nullable Rule remove(String key) {
Rule put = items.remove(key);
- for (RegistryChangeListener<Rule> l : listeners) {
- l.removed(put);
+ if (put != null) {
+ for (RegistryChangeListener<Rule> l : listeners) {
+ l.removed(put);
+ }
}
return put;
}
try (HttpRequest req = new HttpRequest()) {
final HttpResponse res = req.sendGetCommand(sysInfo);
if (res.getHttpCode() == HttpStatus.OK_200) {
- return GSON.fromJson(res.getContent(), NeeoSystemInfo.class);
+ return Objects.requireNonNull(GSON.fromJson(res.getContent(), NeeoSystemInfo.class));
} else {
throw res.createException();
}
* @param s The UTF-8 encoded String to be decoded
* @return the decoded String
*/
- public static String decodeURIComponent(String s) {
- String result = null;
+ public static String decodeURIComponent(@Nullable String s) {
+ if (s == null) {
+ return "";
+ }
+ String result = null;
try {
result = URLDecoder.decode(s, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
if (StringUtils.equalsIgnoreCase(NeeoConstants.NEEOBINDING_BINDING_ID, thing.getUID().getBindingId())) {
final Map<String, String> properties = thing.getProperties();
/** The following properties have matches in org.openhab.binding.neeo.NeeoDeviceHandler.java */
- final String neeoType = StringUtils.isEmpty(properties.get("Type")) ? NeeoDeviceType.ACCESSOIRE.toString()
- : properties.get("Type");
- final String manufacturer = StringUtils.isEmpty(properties.get("Manufacturer")) ? "openHAB"
- : properties.get("Manufacturer");
-
+ String neeoType = properties.get("Type");
+ if (neeoType == null || neeoType.isEmpty()) {
+ neeoType = NeeoDeviceType.ACCESSOIRE.toString();
+ }
+ String manufacturer = properties.get("Manufacturer");
+ if (manufacturer == null || manufacturer.isEmpty()) {
+ manufacturer = "openHAB";
+ }
final Integer standbyDelay = parseInteger(properties.getOrDefault("Standby Command Delay", "0"));
final Integer switchDelay = parseInteger(properties.getOrDefault("Source Switch Delay", "0"));
final Integer shutDownDelay = parseInteger(properties.getOrDefault("Shutdown Delay", "0"));
final Map<@NonNull String, String> properties = thing.getProperties();
final String vendor = properties.get(Thing.PROPERTY_VENDOR);
- if (StringUtils.isNotEmpty(vendor)) {
+ if (vendor != null && !vendor.isEmpty()) {
score += search(vendor, needles);
}
public class ChannelUIDSerializer implements JsonSerializer<ChannelUID>, JsonDeserializer<ChannelUID> {
@Override
- public ChannelUID deserialize(@Nullable JsonElement elm, @Nullable Type type,
- @Nullable JsonDeserializationContext context) throws JsonParseException {
- Objects.requireNonNull(elm, "elm cannot be null");
- Objects.requireNonNull(type, "type cannot be null");
- Objects.requireNonNull(context, "context cannot be null");
-
+ public @Nullable ChannelUID deserialize(JsonElement elm, Type type, JsonDeserializationContext context)
+ throws JsonParseException {
if (elm.isJsonNull()) {
throw new JsonParseException("Not a valid ChannelUID: (null)");
}
package org.openhab.io.neeo.internal.serialization;
import java.lang.reflect.Type;
-import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
@NonNullByDefault
public class ItemSubTypeSerializer implements JsonSerializer<ItemSubType>, JsonDeserializer<ItemSubType> {
@Override
- public ItemSubType deserialize(@Nullable JsonElement elm, @Nullable Type type,
- @Nullable JsonDeserializationContext jsonContext) throws JsonParseException {
- Objects.requireNonNull(elm, "elm cannot be null");
- Objects.requireNonNull(type, "type cannot be null");
- Objects.requireNonNull(jsonContext, "jsonContext cannot be null");
-
+ public @Nullable ItemSubType deserialize(JsonElement elm, Type type, JsonDeserializationContext jsonContext)
+ throws JsonParseException {
if (elm.isJsonNull()) {
throw new JsonParseException("ItemSubType could not be parsed from null");
}
}
@Override
- public JsonElement serialize(ItemSubType ist, @Nullable Type type, @Nullable JsonSerializationContext jsonContext) {
- Objects.requireNonNull(ist, "ist cannot be null");
- Objects.requireNonNull(type, "type cannot be null");
- Objects.requireNonNull(jsonContext, "jsonContext cannot be null");
-
+ public JsonElement serialize(ItemSubType ist, Type type, JsonSerializationContext jsonContext) {
return new JsonPrimitive(ist.toString());
}
}
package org.openhab.io.neeo.internal.serialization;
import java.lang.reflect.Type;
-import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
@NonNullByDefault
public class ListUiActionSerializer implements JsonSerializer<ListUiAction>, JsonDeserializer<ListUiAction> {
@Override
- public ListUiAction deserialize(@Nullable JsonElement elm, @Nullable Type type,
- @Nullable JsonDeserializationContext jsonContext) throws JsonParseException {
- Objects.requireNonNull(elm, "elm cannot be null");
- Objects.requireNonNull(type, "type cannot be null");
- Objects.requireNonNull(jsonContext, "jsonContext cannot be null");
-
+ public @Nullable ListUiAction deserialize(JsonElement elm, Type type, JsonDeserializationContext jsonContext)
+ throws JsonParseException {
if (elm.isJsonNull()) {
throw new JsonParseException("ListUiAction could not be parsed from null");
}
}
@Override
- public JsonElement serialize(ListUiAction ist, @Nullable Type type,
- @Nullable JsonSerializationContext jsonContext) {
- Objects.requireNonNull(ist, "ist cannot be null");
- Objects.requireNonNull(type, "type cannot be null");
- Objects.requireNonNull(jsonContext, "jsonContext cannot be null");
-
+ public JsonElement serialize(ListUiAction ist, Type type, JsonSerializationContext jsonContext) {
return new JsonPrimitive(ist.toString());
}
}
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
-import java.util.Objects;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jdt.annotation.NonNullByDefault;
private final Logger logger = LoggerFactory.getLogger(NeeoBrainDeviceSerializer.class);
@Override
- public JsonElement serialize(NeeoDevice device, @Nullable Type deviceType,
- @Nullable JsonSerializationContext jsonContext) {
- Objects.requireNonNull(device, "device cannot be null");
- Objects.requireNonNull(deviceType, "deviceType cannot be null");
- Objects.requireNonNull(jsonContext, "jsonContext cannot be null");
-
+ public JsonElement serialize(NeeoDevice device, Type deviceType, JsonSerializationContext jsonContext) {
final JsonObject jsonObject = new JsonObject();
final String adapterName = device.getUid().getNeeoUID();
package org.openhab.io.neeo.internal.serialization;
import java.lang.reflect.Type;
-import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
public class NeeoCapabilityTypeSerializer
implements JsonSerializer<NeeoCapabilityType>, JsonDeserializer<NeeoCapabilityType> {
@Override
- public NeeoCapabilityType deserialize(@Nullable JsonElement elm, @Nullable Type type,
- @Nullable JsonDeserializationContext jsonContext) throws JsonParseException {
- Objects.requireNonNull(elm, "elm cannot be null");
- Objects.requireNonNull(type, "type cannot be null");
- Objects.requireNonNull(jsonContext, "jsonContext cannot be null");
-
+ public @Nullable NeeoCapabilityType deserialize(JsonElement elm, Type type, JsonDeserializationContext jsonContext)
+ throws JsonParseException {
if (elm.isJsonNull()) {
throw new JsonParseException("NeeoCapabilityType could not be parsed from null");
}
}
@Override
- public JsonElement serialize(NeeoCapabilityType nct, @Nullable Type type,
- @Nullable JsonSerializationContext jsonContext) {
- Objects.requireNonNull(nct, "nct cannot be null");
- Objects.requireNonNull(type, "type cannot be null");
- Objects.requireNonNull(jsonContext, "jsonContext cannot be null");
-
+ public JsonElement serialize(NeeoCapabilityType nct, Type type, JsonSerializationContext jsonContext) {
return new JsonPrimitive(nct.toString());
}
}
package org.openhab.io.neeo.internal.serialization;
import java.lang.reflect.Type;
-import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
public class NeeoDeviceChannelKindSerializer
implements JsonSerializer<NeeoDeviceChannelKind>, JsonDeserializer<NeeoDeviceChannelKind> {
@Override
- public NeeoDeviceChannelKind deserialize(@Nullable JsonElement elm, @Nullable Type type,
- @Nullable JsonDeserializationContext jsonContext) throws JsonParseException {
- Objects.requireNonNull(elm, "elm cannot be null");
- Objects.requireNonNull(type, "type cannot be null");
- Objects.requireNonNull(jsonContext, "jsonContext cannot be null");
-
+ public @Nullable NeeoDeviceChannelKind deserialize(JsonElement elm, Type type,
+ JsonDeserializationContext jsonContext) throws JsonParseException {
if (elm.isJsonNull()) {
throw new JsonParseException("NeeoDeviceChannelKind could not be parsed from null");
}
}
@Override
- public JsonElement serialize(NeeoDeviceChannelKind ndck, @Nullable Type type,
- @Nullable JsonSerializationContext jsonContext) {
- Objects.requireNonNull(ndck, "ndck cannot be null");
- Objects.requireNonNull(type, "type cannot be null");
- Objects.requireNonNull(jsonContext, "jsonContext cannot be null");
-
+ public JsonElement serialize(NeeoDeviceChannelKind ndck, Type type, JsonSerializationContext jsonContext) {
return new JsonPrimitive(ndck.toString());
}
}
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
-import java.util.Objects;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jdt.annotation.NonNullByDefault;
}
@Override
- public JsonElement serialize(NeeoDeviceChannel chnl, @Nullable Type type,
- @Nullable JsonSerializationContext jsonContext) {
- Objects.requireNonNull(chnl, "chnl cannot be null");
- Objects.requireNonNull(type, "type cannot be null");
- Objects.requireNonNull(jsonContext, "jsonContext cannot be null");
-
+ public JsonElement serialize(NeeoDeviceChannel chnl, Type type, JsonSerializationContext jsonContext) {
final JsonObject jo = new JsonObject();
jo.add("kind", jsonContext.serialize(chnl.getKind()));
}
@Override
- public NeeoDeviceChannel deserialize(@Nullable JsonElement elm, @Nullable Type type,
- @Nullable JsonDeserializationContext context) throws JsonParseException {
- Objects.requireNonNull(elm, "elm cannot be null");
- Objects.requireNonNull(type, "type cannot be null");
- Objects.requireNonNull(context, "context cannot be null");
-
+ public @Nullable NeeoDeviceChannel deserialize(JsonElement elm, Type type, JsonDeserializationContext context)
+ throws JsonParseException {
if (!(elm instanceof JsonObject)) {
throw new JsonParseException("Element not an instance of JsonObject: " + elm);
}
}
@Override
- public NeeoDevice deserialize(@Nullable JsonElement elm, @Nullable Type type,
- @Nullable JsonDeserializationContext jsonContext) throws JsonParseException {
- Objects.requireNonNull(elm, "elm cannot be null");
- Objects.requireNonNull(type, "type cannot be null");
- Objects.requireNonNull(jsonContext, "jsonContext cannot be null");
-
+ public @Nullable NeeoDevice deserialize(JsonElement elm, Type type, JsonDeserializationContext jsonContext)
+ throws JsonParseException {
if (!(elm instanceof JsonObject)) {
throw new JsonParseException("Element not an instance of JsonObject: " + elm);
}
package org.openhab.io.neeo.internal.serialization;
import java.lang.reflect.Type;
-import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
public class NeeoDeviceTypeSerializer implements JsonSerializer<NeeoDeviceType>, JsonDeserializer<NeeoDeviceType> {
@Override
- public NeeoDeviceType deserialize(@Nullable JsonElement elm, @Nullable Type type,
- @Nullable JsonDeserializationContext jsonContext) throws JsonParseException {
- Objects.requireNonNull(elm, "elm cannot be null");
- Objects.requireNonNull(type, "type cannot be null");
- Objects.requireNonNull(jsonContext, "jsonContext cannot be null");
-
+ public @Nullable NeeoDeviceType deserialize(JsonElement elm, Type type, JsonDeserializationContext jsonContext)
+ throws JsonParseException {
if (elm.isJsonNull()) {
throw new JsonParseException("NeeoDeviceType could not be parsed from null");
}
}
@Override
- public JsonElement serialize(NeeoDeviceType ndt, @Nullable Type type,
- @Nullable JsonSerializationContext jsonContext) {
- Objects.requireNonNull(ndt, "ndt cannot be null");
- Objects.requireNonNull(type, "type cannot be null");
- Objects.requireNonNull(jsonContext, "jsonContext cannot be null");
-
+ public JsonElement serialize(NeeoDeviceType ndt, Type type, JsonSerializationContext jsonContext) {
return new JsonPrimitive(ndt.toString());
}
}
package org.openhab.io.neeo.internal.serialization;
import java.lang.reflect.Type;
-import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
public class NeeoThingUIDSerializer implements JsonSerializer<NeeoThingUID>, JsonDeserializer<NeeoThingUID> {
@Override
- public NeeoThingUID deserialize(@Nullable JsonElement elm, @Nullable Type type,
- @Nullable JsonDeserializationContext jsonContext) throws JsonParseException {
- Objects.requireNonNull(elm, "elm cannot be null");
- Objects.requireNonNull(type, "type cannot be null");
- Objects.requireNonNull(jsonContext, "jsonContext cannot be null");
-
+ public @Nullable NeeoThingUID deserialize(JsonElement elm, Type type, JsonDeserializationContext jsonContext)
+ throws JsonParseException {
if (elm.isJsonNull()) {
throw new JsonParseException("Not a valid ChannelUID: (null)");
}
}
@Override
- public JsonElement serialize(NeeoThingUID uid, @Nullable Type type,
- @Nullable JsonSerializationContext jsonContext) {
- Objects.requireNonNull(uid, "uid cannot be null");
- Objects.requireNonNull(type, "type cannot be null");
- Objects.requireNonNull(jsonContext, "jsonContext cannot be null");
-
+ public JsonElement serialize(NeeoThingUID uid, Type type, JsonSerializationContext jsonContext) {
return new JsonPrimitive(uid.getAsString());
}
}
NeeoUtil.write(resp, gson.toJson(status));
} else if (StringUtils.equalsIgnoreCase(paths[0], "blinkled")) {
final String brainId = req.getParameter("brainid");
- final NeeoBrainServlet servlet = service.getServlet(brainId);
- if (servlet == null) {
- NeeoUtil.write(resp, gson.toJson(new ReturnStatus("Unknown BraidID: " + brainId)));
+ if (brainId == null) {
+ NeeoUtil.write(resp, gson.toJson(new ReturnStatus("BrainID is null")));
} else {
- try {
- servlet.getBrainApi().blinkLed();
- NeeoUtil.write(resp, gson.toJson(new ReturnStatus(true)));
- } catch (IOException e) {
- NeeoUtil.write(resp,
- gson.toJson(new ReturnStatus("Exception occurred blinking LED: " + e.getMessage())));
+ final NeeoBrainServlet servlet = service.getServlet(brainId);
+ if (servlet == null) {
+ NeeoUtil.write(resp, gson.toJson(new ReturnStatus("Unknown BrainID: " + brainId)));
+ } else {
+ try {
+ servlet.getBrainApi().blinkLed();
+ NeeoUtil.write(resp, gson.toJson(new ReturnStatus(true)));
+ } catch (IOException e) {
+ NeeoUtil.write(resp, gson
+ .toJson(new ReturnStatus("Exception occurred blinking LED: " + e.getMessage())));
+ }
}
}
} else if (StringUtils.equalsIgnoreCase(paths[0], "getlog")) {
final String brainId = req.getParameter("brainid");
- final NeeoBrainServlet servlet = service.getServlet(brainId);
- if (servlet == null) {
- NeeoUtil.write(resp, gson.toJson(new ReturnStatus("Unknown BraidID: " + brainId)));
+ if (brainId == null) {
+ NeeoUtil.write(resp, gson.toJson(new ReturnStatus("BrainID is null")));
} else {
- try {
- final String log = servlet.getBrainApi().getLog();
- NeeoUtil.write(resp, gson.toJson(new ReturnStatus(true, log)));
- } catch (IOException e) {
- NeeoUtil.write(resp,
- gson.toJson(new ReturnStatus("Exception occurred getting log: " + e.getMessage())));
+ final NeeoBrainServlet servlet = service.getServlet(brainId);
+ if (servlet == null) {
+ NeeoUtil.write(resp, gson.toJson(new ReturnStatus("Unknown BraidID: " + brainId)));
+ } else {
+ try {
+ final String log = servlet.getBrainApi().getLog();
+ NeeoUtil.write(resp, gson.toJson(new ReturnStatus(true, log)));
+ } catch (IOException e) {
+ NeeoUtil.write(resp,
+ gson.toJson(new ReturnStatus("Exception occurred getting log: " + e.getMessage())));
+ }
}
}
-
} else {
logger.debug("Unknown get path: {}", StringUtils.join(paths, ','));
}
final String path = StringUtils.lowerCase(paths[1]);
if (StringUtils.equalsIgnoreCase(path, "search")) {
- doSearch(req.getQueryString(), resp);
+ String queryString = req.getQueryString();
+ if (queryString != null) {
+ doSearch(queryString, resp);
+ }
} else if (StringUtils.equalsIgnoreCase(path, "adapterdefinition") && paths.length >= 3) {
doAdapterDefinition(paths[2], resp);
} else {
String tableName = tableNameResolver.fromItem(dynamoItem);
Deque<DynamoDBItem<?>> batch = batchesByTable.computeIfAbsent(tableName, new Function<>() {
@Override
- public Deque<DynamoDBItem<?>> apply(@Nullable String t) {
+ public @Nullable Deque<DynamoDBItem<?>> apply(@Nullable String t) {
return new ArrayDeque<>();
}
});
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
+import java.util.Objects;
import java.util.TimeZone;
import org.eclipse.jdt.annotation.NonNullByDefault;
assertEquals("item1", dbItem.getName());
assertEquals(date, dbItem.getTime());
Object actualState = dbItem.getState();
+ assertNotNull(actualState);
+ Objects.requireNonNull(actualState);
if (expectedState instanceof BigDecimal) {
BigDecimal expectedRounded = DynamoDBBigDecimalItem.loseDigits(((BigDecimal) expectedState));
assertEquals(0, expectedRounded.compareTo((BigDecimal) actualState),
import java.math.BigDecimal;
import java.util.List;
+import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@MethodSource
public void readWriteRoundtripShouldRecreateTheWrittenState(State state) {
String json = mapper.toJson(state);
- State actual = mapper.fromJson(json, State.class);
+ State actual = Objects.requireNonNull(mapper.fromJson(json, State.class));
assertThat(actual, is(equalTo(state)));
}
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.Map;
+import java.util.*;
import javax.imageio.ImageIO;
import javax.servlet.Servlet;
int width = 480;
try {
- width = Integer.parseInt(req.getParameter("w"));
+ width = Integer.parseInt(Objects.requireNonNull(req.getParameter("w")));
} catch (Exception e) {
}
int height = 240;
try {
- height = Integer.parseInt(req.getParameter("h"));
+ height = Integer.parseInt(Objects.requireNonNull(req.getParameter("h")));
} catch (Exception e) {
}
Long period = PERIODS.get(req.getParameter("period"));
<dependency>
<groupId>org.lastnpe.eea</groupId>
<artifactId>eea-all</artifactId>
- <version>2.1.0</version>
+ <version>${eea.version}</version>
</dependency>
<!-- openHAB core -->
<dependency>
<artifactItem>
<groupId>org.lastnpe.eea</groupId>
<artifactId>eea-all</artifactId>
- <version>2.1.0</version>
+ <version>${eea.version}</version>
<overWrite>true</overWrite>
</artifactItem>
</artifactItems>
import static org.mockito.Mockito.*;
import static org.openhab.binding.modbus.internal.ModbusBindingConstantsInternal.*;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ScheduledFuture;
import java.util.function.Consumer;
assertThat(String.format("Could not determine correct item type for %s", channelId), item,
is(notNullValue()));
assertNotNull(item);
+ Objects.requireNonNull(item);
addItem(item);
toBeLinked.put(itemName, channelUID);
}
<artifactItem>
<groupId>org.lastnpe.eea</groupId>
<artifactId>eea-all</artifactId>
- <version>2.1.0</version>
+ <version>${eea.version}</version>
<overWrite>true</overWrite>
</artifactItem>
</artifactItems>
<feature.directory>src/main/feature/feature.xml</feature.directory>
<spotless.version>2.0.3</spotless.version>
+ <eea.version>2.2.1</eea.version>
</properties>
<dependencyManagement>
<classpath>${project.build.directory}/dependency</classpath>
</compilerArguments>
<compilerArgs>
- <arg>-err:+nullAnnot(org.eclipse.jdt.annotation.Nullable|org.eclipse.jdt.annotation.NonNull|org.eclipse.jdt.annotation.NonNullByDefault),+inheritNullAnnot,-nullUncheckedConversion</arg>
- <arg>-warn:+null,+inheritNullAnnot,+nullAnnotConflict,-nullUncheckedConversion,+nullAnnotRedundant,+nullDereference</arg>
+ <arg>-err:+nullAnnot(org.eclipse.jdt.annotation.Nullable|org.eclipse.jdt.annotation.NonNull|org.eclipse.jdt.annotation.NonNullByDefault),+inheritNullAnnot,+nullAnnotConflict,-nullUncheckedConversion</arg>
+ <arg>-warn:+null,+inheritNullAnnot,-nullUncheckedConversion,+nullAnnotRedundant,+nullDereference</arg>
</compilerArgs>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>