Java 17 features (N-S) (#15565)

- add missing @override
- Java style array syntax
- remove redundant modifiers
- always move String constants to left side in comparisons
- simplify lambda expressions and return statements
- use replace instead of replaceAll w/o regex
- instanceof matching and multiline strings

Signed-off-by: Holger Friedrich <mail@holger-friedrich.de>
pull/15586/head
Holger Friedrich 2023-09-13 08:03:31 +02:00 committed by GitHub
parent 641b482551
commit ab58f4ffb4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
471 changed files with 1624 additions and 1868 deletions

View File

@ -79,9 +79,7 @@ public class OpenAPIUtils {
}
try {
URI requestURI = new URI(HttpScheme.HTTP.asString(), (String) null, address, port, path, query,
(String) null);
return requestURI;
return new URI(HttpScheme.HTTP.asString(), (String) null, address, port, path, query, (String) null);
} catch (URISyntaxException var8) {
LOGGER.warn("URI could not be parsed with path {}", path);
throw new NanoleafException("Wrong URI format for API request");
@ -115,8 +113,8 @@ public class OpenAPIUtils {
}
} catch (ExecutionException ee) {
Throwable cause = ee.getCause();
if (cause != null && cause instanceof HttpResponseException
&& ((HttpResponseException) cause).getResponse().getStatus() == HttpStatus.UNAUTHORIZED_401) {
if (cause instanceof HttpResponseException httpResponseException
&& httpResponseException.getResponse().getStatus() == HttpStatus.UNAUTHORIZED_401) {
LOGGER.debug("OpenAPI request unauthorized. Invalid authorization token.");
throw new NanoleafUnauthorizedException("Invalid authorization token");
} else {

View File

@ -57,8 +57,7 @@ public class NanoleafCommandExtension extends AbstractConsoleCommandExtension {
thingRegistry.getAll().forEach(thing -> {
if (thing.getUID().getBindingId().equals(NanoleafBindingConstants.BINDING_ID)) {
ThingHandler handler = thing.getHandler();
if (handler instanceof NanoleafControllerHandler) {
NanoleafControllerHandler nanoleafControllerHandler = (NanoleafControllerHandler) handler;
if (handler instanceof NanoleafControllerHandler nanoleafControllerHandler) {
if (!handler.getThing().isEnabled()) {
console.println(
"The following Nanoleaf is NOT enabled as a Thing. Enable it first to view its layout.");
@ -76,16 +75,15 @@ public class NanoleafCommandExtension extends AbstractConsoleCommandExtension {
Thing thing = thingRegistry.get(new ThingUID(uid));
if (thing != null) {
ThingHandler handler = thing.getHandler();
if (handler instanceof NanoleafControllerHandler) {
NanoleafControllerHandler nanoleafControllerHandler = (NanoleafControllerHandler) handler;
if (handler instanceof NanoleafControllerHandler nanoleafControllerHandler) {
String layout = nanoleafControllerHandler.getLayout();
console.println(layout);
} else {
console.println("Thing with UID '" + uid.toString()
+ "' is not an initialized Nanoleaf controller.");
console.println(
"Thing with UID '" + uid + "' is not an initialized Nanoleaf controller.");
}
} else {
console.println("Thing with UID '" + uid.toString() + "' does not exist.");
console.println("Thing with UID '" + uid + "' does not exist.");
}
} else {
printUsage(console);

View File

@ -86,10 +86,8 @@ public class NanoleafMDNSDiscoveryParticipant implements MDNSDiscoveryParticipan
MODEL_ID_LIGHTPANELS.equals(modelId) ? API_MIN_FW_VER_LIGHTPANELS : API_MIN_FW_VER_CANVAS);
}
final DiscoveryResult result = DiscoveryResultBuilder.create(uid).withThingType(getThingType(service))
.withProperties(properties).withLabel(service.getName()).withRepresentationProperty(CONFIG_ADDRESS)
.build();
return result;
return DiscoveryResultBuilder.create(uid).withThingType(getThingType(service)).withProperties(properties)
.withLabel(service.getName()).withRepresentationProperty(CONFIG_ADDRESS).build();
}
@Override

View File

@ -137,8 +137,8 @@ public class NanoleafPanelHandler extends BaseThingHandler implements NanoleafPa
Bridge bridge = getBridge();
if (bridge != null) {
ThingHandler handler = bridge.getHandler();
if (handler instanceof NanoleafControllerHandler) {
((NanoleafControllerHandler) handler).getColorInformation().unregisterChangeListener(getPanelID());
if (handler instanceof NanoleafControllerHandler controllerHandler) {
controllerHandler.getColorInformation().unregisterChangeListener(getPanelID());
}
}
@ -174,8 +174,8 @@ public class NanoleafPanelHandler extends BaseThingHandler implements NanoleafPa
Bridge bridge = getBridge();
if (bridge != null) {
ThingHandler handler = bridge.getHandler();
if (handler instanceof NanoleafControllerHandler) {
((NanoleafControllerHandler) handler).getColorInformation().registerChangeListener(getPanelID(), this);
if (handler instanceof NanoleafControllerHandler controllerHandler) {
controllerHandler.getColorInformation().registerChangeListener(getPanelID(), this);
}
}
}
@ -185,8 +185,8 @@ public class NanoleafPanelHandler extends BaseThingHandler implements NanoleafPa
logger.debug("currentPanelColor: {}", currentPanelColor);
HSBType newPanelColor = new HSBType();
if (command instanceof HSBType) {
newPanelColor = (HSBType) command;
if (command instanceof HSBType hsbCommand) {
newPanelColor = hsbCommand;
} else if (command instanceof OnOffType) {
if (OnOffType.ON.equals(command)) {
newPanelColor = new HSBType(currentPanelColor.getHue(), currentPanelColor.getSaturation(),
@ -195,9 +195,8 @@ public class NanoleafPanelHandler extends BaseThingHandler implements NanoleafPa
newPanelColor = new HSBType(currentPanelColor.getHue(), currentPanelColor.getSaturation(),
MIN_PANEL_BRIGHTNESS);
}
} else if (command instanceof PercentType) {
PercentType brightness = new PercentType(
Math.max(MIN_PANEL_BRIGHTNESS.intValue(), ((PercentType) command).intValue()));
} else if (command instanceof PercentType type) {
PercentType brightness = new PercentType(Math.max(MIN_PANEL_BRIGHTNESS.intValue(), type.intValue()));
newPanelColor = new HSBType(currentPanelColor.getHue(), currentPanelColor.getSaturation(), brightness);
} else if (command instanceof IncreaseDecreaseType) {
int brightness = currentPanelColor.getBrightness().intValue();
@ -281,8 +280,8 @@ public class NanoleafPanelHandler extends BaseThingHandler implements NanoleafPa
Object panelId = getThing().getConfiguration().get(CONFIG_PANEL_ID);
if (panelId instanceof Integer) {
return (Integer) panelId;
} else if (panelId instanceof Number) {
return ((Number) panelId).intValue();
} else if (panelId instanceof Number numberValue) {
return numberValue.intValue();
} else {
// Fall back to parsing string representation of panel if it is not returning an integer
String stringPanelId = panelId.toString();
@ -300,8 +299,8 @@ public class NanoleafPanelHandler extends BaseThingHandler implements NanoleafPa
Bridge bridge = getBridge();
if (bridge != null) {
ThingHandler handler = bridge.getHandler();
if (handler instanceof NanoleafControllerHandler) {
((NanoleafControllerHandler) handler).getColorInformation().setPanelColor(panelId, color);
if (handler instanceof NanoleafControllerHandler controllerHandler) {
controllerHandler.getColorInformation().setPanelColor(panelId, color);
} else {
logger.debug("Couldn't find handler for panel {}", panelId);
}

View File

@ -26,5 +26,5 @@ public enum DrawingAlgorithm {
TRIANGLE,
HEXAGON,
CORNER,
LINE;
LINE
}

View File

@ -77,10 +77,8 @@ public class DrawingSettings {
private static ImagePoint2D toPictureLayout(Point2D original, int imageHeight, ImagePoint2D min,
double rotationRadians) {
Point2D rotated = original.rotate(rotationRadians);
ImagePoint2D translated = new ImagePoint2D(
NanoleafBindingConstants.LAYOUT_BORDER_WIDTH + rotated.getX() - min.getX(),
return new ImagePoint2D(NanoleafBindingConstants.LAYOUT_BORDER_WIDTH + rotated.getX() - min.getX(),
imageHeight - NanoleafBindingConstants.LAYOUT_BORDER_WIDTH - rotated.getY() + min.getY());
return translated;
}
private static List<ImagePoint2D> toPictureLayout(List<Point2D> originals, int imageHeight, ImagePoint2D min,

View File

@ -64,7 +64,7 @@ public class NanoleafLayout {
return new byte[] {};
}
ImagePoint2D size[] = findSize(positionDatums, rotationRadians);
ImagePoint2D[] size = findSize(positionDatums, rotationRadians);
final ImagePoint2D min = size[0];
final ImagePoint2D max = size[1];

View File

@ -90,20 +90,20 @@ public class State {
}
public void setState(IntegerState value) {
if (value instanceof Brightness) {
this.setBrightness((Brightness) value);
} else if (value instanceof Hue) {
this.setHue((Hue) value);
} else if (value instanceof Sat) {
this.setSaturation((Sat) value);
} else if (value instanceof Ct) {
this.setColorTemperature((Ct) value);
if (value instanceof Brightness brightnessState) {
this.setBrightness(brightnessState);
} else if (value instanceof Hue hueState) {
this.setHue(hueState);
} else if (value instanceof Sat satState) {
this.setSaturation(satState);
} else if (value instanceof Ct ctState) {
this.setColorTemperature(ctState);
}
}
public void setState(BooleanState value) {
if (value instanceof On) {
this.setOn((On) value);
if (value instanceof On onState) {
this.setOn(onState);
}
}
}

View File

@ -70,7 +70,7 @@ public class NanoleafLayoutTest {
}
private class TestPanelState implements PanelState {
private final HSBType testColors[] = { HSBType.fromRGB(160, 120, 40), HSBType.fromRGB(80, 60, 20),
private final HSBType[] testColors = { HSBType.fromRGB(160, 120, 40), HSBType.fromRGB(80, 60, 20),
HSBType.fromRGB(120, 90, 30), HSBType.fromRGB(200, 150, 60) };
@Override

View File

@ -49,8 +49,7 @@ public class NeatoHandlerFactory extends BaseThingHandlerFactory {
public static final Set<ThingTypeUID> SUPPORTED_THING_TYPE_UIDS = Collections
.unmodifiableSet(Stream.of(BRIDGE_TYPE_NEATOACCOUNT, THING_TYPE_VACUUMCLEANER).collect(Collectors.toSet()));
public static final Set<ThingTypeUID> DISCOVERABLE_THING_TYPE_UIDS = Collections
.singleton(THING_TYPE_VACUUMCLEANER);
public static final Set<ThingTypeUID> DISCOVERABLE_THING_TYPE_UIDS = Set.of(THING_TYPE_VACUUMCLEANER);
private Map<ThingUID, ServiceRegistration<DiscoveryService>> discoveryServiceRegistrations = new HashMap<>();

View File

@ -112,7 +112,6 @@ public class NeatoRobot {
return HttpUtil.executeUrl("POST",
"https://nucleo.neatocloud.com:4443/vendors/neato/robots/" + this.serialNumber + "/messages",
headers, stream, "text/html; charset=ISO-8859-1", 20000);
} catch (IOException | NoSuchAlgorithmException | InvalidKeyException e) {
throw new NeatoCommunicationException(e);
}

View File

@ -16,7 +16,6 @@ import static org.openhab.binding.neeo.internal.NeeoConstants.BRIDGE_TYPE_BRAIN;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
@ -50,7 +49,7 @@ public class NeeoBrainDiscovery implements MDNSDiscoveryParticipant {
@Override
public Set<@Nullable ThingTypeUID> getSupportedThingTypeUIDs() {
return Collections.singleton(BRIDGE_TYPE_BRAIN);
return Set.of(BRIDGE_TYPE_BRAIN);
}
@Override

View File

@ -13,7 +13,6 @@
package org.openhab.binding.neeo.internal.discovery;
import java.io.IOException;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;
@ -46,8 +45,7 @@ public class NeeoDeviceDiscoveryService extends AbstractDiscoveryService {
private final Logger logger = LoggerFactory.getLogger(NeeoDeviceDiscoveryService.class);
/** The device thing type we support */
private static final Set<ThingTypeUID> DISCOVERABLE_THING_TYPES_UIDS = Collections
.singleton(NeeoConstants.THING_TYPE_DEVICE);
private static final Set<ThingTypeUID> DISCOVERABLE_THING_TYPES_UIDS = Set.of(NeeoConstants.THING_TYPE_DEVICE);
/** The timeout (in seconds) for searching the room */
private static final int SEARCH_TIME = 10;

View File

@ -13,7 +13,6 @@
package org.openhab.binding.neeo.internal.discovery;
import java.io.IOException;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;
@ -44,8 +43,7 @@ public class NeeoRoomDiscoveryService extends AbstractDiscoveryService {
private final Logger logger = LoggerFactory.getLogger(NeeoRoomDiscoveryService.class);
/** The room bridge type we support */
private static final Set<ThingTypeUID> DISCOVERABLE_THING_TYPES_UIDS = Collections
.singleton(NeeoConstants.BRIDGE_TYPE_ROOM);
private static final Set<ThingTypeUID> DISCOVERABLE_THING_TYPES_UIDS = Set.of(NeeoConstants.BRIDGE_TYPE_ROOM);
/** The timeout (in seconds) for searching the brain */
private static final int SEARCH_TIME = 10;

View File

@ -339,8 +339,8 @@ public class NeeoDeviceHandler extends BaseThingHandler {
final Bridge parent = getBridge();
if (parent != null) {
final BridgeHandler handler = parent.getHandler();
if (handler instanceof NeeoRoomHandler) {
return ((NeeoRoomHandler) handler);
if (handler instanceof NeeoRoomHandler roomHandler) {
return roomHandler;
}
}
return null;

View File

@ -317,8 +317,8 @@ public class NeeoRoomHandler extends BaseBridgeHandler {
final Bridge parent = getBridge();
if (parent != null) {
final BridgeHandler handler = parent.getHandler();
if (handler instanceof NeeoBrainHandler) {
return ((NeeoBrainHandler) handler);
if (handler instanceof NeeoBrainHandler brainHandler) {
return brainHandler;
}
}
return null;

View File

@ -41,9 +41,9 @@ public class NeeoDevicesDeserializer implements JsonDeserializer<@Nullable NeeoD
Objects.requireNonNull(jsonElement, "jsonElement cannot be null");
Objects.requireNonNull(context, "context cannot be null");
if (jsonElement instanceof JsonObject) {
if (jsonElement instanceof JsonObject jsonObject) {
final List<NeeoDevice> scenarios = new ArrayList<>();
for (Map.Entry<String, JsonElement> entry : ((JsonObject) jsonElement).entrySet()) {
for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
final NeeoDevice device = context.deserialize(entry.getValue(), NeeoDevice.class);
scenarios.add(device);
}

View File

@ -41,9 +41,9 @@ public class NeeoMacrosDeserializer implements JsonDeserializer<@Nullable NeeoMa
Objects.requireNonNull(jsonElement, "jsonElement cannot be null");
Objects.requireNonNull(context, "context cannot be null");
if (jsonElement instanceof JsonObject) {
if (jsonElement instanceof JsonObject jsonObject) {
final List<NeeoMacro> scenarios = new ArrayList<>();
for (Map.Entry<String, JsonElement> entry : ((JsonObject) jsonElement).entrySet()) {
for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
final NeeoMacro macro = context.deserialize(entry.getValue(), NeeoMacro.class);
scenarios.add(macro);
}

View File

@ -41,9 +41,9 @@ public class NeeoRecipesDeserializer implements JsonDeserializer<@Nullable NeeoR
Objects.requireNonNull(jsonElement, "jsonElement cannot be null");
Objects.requireNonNull(context, "context cannot be null");
if (jsonElement instanceof JsonObject) {
if (jsonElement instanceof JsonObject jsonObject) {
final List<NeeoRecipe> recipes = new ArrayList<>();
for (Map.Entry<String, JsonElement> entry : ((JsonObject) jsonElement).entrySet()) {
for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
final NeeoRecipe recipe = context.deserialize(entry.getValue(), NeeoRecipe.class);
recipes.add(recipe);
}

View File

@ -40,9 +40,9 @@ public class NeeoRoomsDeserializer implements JsonDeserializer<@Nullable NeeoRoo
@Nullable JsonDeserializationContext context) throws JsonParseException {
Objects.requireNonNull(jsonElement, "jsonElement cannot be null");
Objects.requireNonNull(context, "context cannot be null");
if (jsonElement instanceof JsonObject) {
if (jsonElement instanceof JsonObject jsonObject) {
final List<NeeoRoom> recipes = new ArrayList<>();
for (Map.Entry<String, JsonElement> entry : ((JsonObject) jsonElement).entrySet()) {
for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
final NeeoRoom room = context.deserialize(entry.getValue(), NeeoRoom.class);
recipes.add(room);
}

View File

@ -40,9 +40,9 @@ public class NeeoScenariosDeserializer implements JsonDeserializer<@Nullable Nee
@Nullable JsonDeserializationContext context) throws JsonParseException {
Objects.requireNonNull(jsonElement, "jsonElement cannot be null");
Objects.requireNonNull(context, "context cannot be null");
if (jsonElement instanceof JsonObject) {
if (jsonElement instanceof JsonObject jsonObject) {
final List<NeeoScenario> scenarios = new ArrayList<>();
for (Map.Entry<String, JsonElement> entry : ((JsonObject) jsonElement).entrySet()) {
for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
final NeeoScenario scenario = context.deserialize(entry.getValue(), NeeoScenario.class);
scenarios.add(scenario);
}

View File

@ -29,7 +29,6 @@ import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingStatus;
import org.openhab.core.thing.ThingStatusDetail;
import org.openhab.core.thing.binding.BaseThingHandler;
import org.openhab.core.thing.binding.BridgeHandler;
import org.openhab.core.types.Command;
import org.openhab.core.types.RefreshType;
import org.openhab.core.types.State;
@ -166,8 +165,7 @@ public class NeoBaseHandler extends BaseThingHandler {
if (channel != null) {
Configuration config = channel.getConfiguration();
Object holdOnlineState = config.get(PARAM_HOLD_ONLINE_STATE);
if (holdOnlineState != null && (holdOnlineState instanceof Boolean)
&& ((Boolean) holdOnlineState).booleanValue()) {
if (holdOnlineState instanceof Boolean booleanValue && booleanValue.booleanValue()) {
/*
* the Configuration Parameter "holdOnlineState" is True so do NOT send a
* state update to OpenHAB
@ -236,11 +234,9 @@ public class NeoBaseHandler extends BaseThingHandler {
protected @Nullable NeoHubHandler getNeoHub() {
@Nullable
Bridge b;
@Nullable
BridgeHandler h;
if ((b = getBridge()) != null && (h = b.getHandler()) != null && h instanceof NeoHubHandler) {
return (NeoHubHandler) h;
if ((b = getBridge()) != null && (b.getHandler() instanceof NeoHubHandler neoHubHandler)) {
return neoHubHandler;
}
return null;

View File

@ -110,7 +110,7 @@ public class NeoHubBindingConstants {
/*
* enumerator for results of method calls
*/
public static enum NeoHubReturnResult {
public enum NeoHubReturnResult {
SUCCEEDED,
ERR_COMMUNICATION,
ERR_INITIALIZATION

View File

@ -13,7 +13,6 @@
package org.openhab.binding.neohub.internal;
import java.net.Inet4Address;
import java.util.Collections;
import java.util.Set;
import javax.jmdns.ServiceInfo;
@ -47,8 +46,7 @@ public class NeoHubDiscoveryParticipant implements MDNSDiscoveryParticipant {
private String getIpAddressIfValidNeoHub(ServiceInfo serviceInfo) {
if (serviceInfo.getName().contains(HEATMISER_NEO_HUB)) {
for (Inet4Address ipAddr : serviceInfo.getInet4Addresses()) {
String ipStr = ipAddr.getHostAddress();
return ipStr;
return ipAddr.getHostAddress();
}
}
return "";
@ -56,7 +54,7 @@ public class NeoHubDiscoveryParticipant implements MDNSDiscoveryParticipant {
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
return Collections.singleton(NeoHubBindingConstants.THING_TYPE_NEOHUB);
return Set.of(NeoHubBindingConstants.THING_TYPE_NEOHUB);
}
@Override
@ -69,11 +67,9 @@ public class NeoHubDiscoveryParticipant implements MDNSDiscoveryParticipant {
String ipStr = getIpAddressIfValidNeoHub(serviceInfo);
if (!ipStr.isEmpty()) {
ThingUID thingUID = new ThingUID(NeoHubBindingConstants.THING_TYPE_NEOHUB, ipStr.replace('.', '_'));
DiscoveryResult hub = DiscoveryResultBuilder.create(thingUID)
.withProperty(NeoHubConfiguration.HOST_NAME, ipStr)
return DiscoveryResultBuilder.create(thingUID).withProperty(NeoHubConfiguration.HOST_NAME, ipStr)
.withRepresentationProperty(NeoHubConfiguration.HOST_NAME).withLabel("NeoHub (" + ipStr + ")")
.build();
return hub;
}
return null;
}

View File

@ -111,18 +111,18 @@ public class NeoHubDiscoveryService extends AbstractDiscoveryService {
for (AbstractRecord deviceRecord : deviceRecords) {
// the record came from the legacy API (deviceType included)
if (deviceRecord instanceof InfoRecord) {
deviceType = ((InfoRecord) deviceRecord).getDeviceType();
if (deviceRecord instanceof InfoRecord infoRecord) {
deviceType = infoRecord.getDeviceType();
publishDevice(deviceRecord, deviceType);
continue;
}
// the record came from the new API (deviceType NOT included)
if (deviceRecord instanceof LiveDataRecord) {
if (deviceRecord instanceof LiveDataRecord liveDataRecord) {
if (engineerData == null) {
break;
}
String deviceName = ((LiveDataRecord) deviceRecord).getDeviceName();
String deviceName = liveDataRecord.getDeviceName();
// exclude repeater nodes from being discovered
if (MATCHER_HEATMISER_REPEATER.matcher(deviceName).matches()) {
continue;

View File

@ -314,14 +314,14 @@ public class NeoHubHandler extends BaseBridgeHandler {
// check if we also need to discard and update systemData
NeoHubReadDcbResponse systemData = this.systemData;
if (systemData != null) {
if (deviceData instanceof NeoHubLiveDeviceData) {
if (deviceData instanceof NeoHubLiveDeviceData liveDeviceData) {
/*
* note: time-stamps are measured in seconds from 1970-01-01T00:00:00Z
*
* new API: discard systemData if its time-stamp is older than the system
* time-stamp on the hub
*/
if (systemData.timeStamp < ((NeoHubLiveDeviceData) deviceData).getTimestampSystem()) {
if (systemData.timeStamp < liveDeviceData.getTimestampSystem()) {
this.systemData = null;
}
} else {
@ -416,8 +416,8 @@ public class NeoHubHandler extends BaseBridgeHandler {
List<Thing> children = getThing().getThings();
for (Thing child : children) {
ThingHandler device = child.getHandler();
if (device instanceof NeoBaseHandler) {
((NeoBaseHandler) device).toBaseSendPollResponse(deviceData);
if (device instanceof NeoBaseHandler neoBaseHandler) {
neoBaseHandler.toBaseSendPollResponse(deviceData);
}
}

View File

@ -14,10 +14,7 @@ package org.openhab.binding.neohub.internal;
import static org.openhab.binding.neohub.internal.NeoHubBindingConstants.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Map;
import java.util.Set;
@ -47,9 +44,8 @@ import org.osgi.service.component.annotations.Reference;
@Component(configurationPid = "binding.neohub", service = ThingHandlerFactory.class)
public class NeoHubHandlerFactory extends BaseThingHandlerFactory {
private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
.unmodifiableSet(new HashSet<>(Arrays.asList(THING_TYPE_NEOHUB, THING_TYPE_NEOSTAT, THING_TYPE_NEOPLUG,
THING_TYPE_NEOCONTACT, THING_TYPE_NEOTEMPERATURESENSOR)));
private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_NEOHUB, THING_TYPE_NEOSTAT,
THING_TYPE_NEOPLUG, THING_TYPE_NEOCONTACT, THING_TYPE_NEOTEMPERATURESENSOR);
private final WebSocketFactory webSocketFactory;
private final Map<ThingUID, ServiceRegistration<?>> discoServices = new HashMap<>();
@ -68,8 +64,8 @@ public class NeoHubHandlerFactory extends BaseThingHandlerFactory {
protected @Nullable ThingHandler createHandler(Thing thing) {
ThingTypeUID thingTypeUID = thing.getThingTypeUID();
if ((thingTypeUID.equals(THING_TYPE_NEOHUB)) && (thing instanceof Bridge)) {
NeoHubHandler handler = new NeoHubHandler((Bridge) thing, webSocketFactory);
if ((thingTypeUID.equals(THING_TYPE_NEOHUB)) && (thing instanceof Bridge bridge)) {
NeoHubHandler handler = new NeoHubHandler(bridge, webSocketFactory);
createDiscoveryService(handler);
return handler;
}
@ -95,8 +91,8 @@ public class NeoHubHandlerFactory extends BaseThingHandlerFactory {
@Override
protected synchronized void removeHandler(ThingHandler handler) {
if (handler instanceof NeoHubHandler) {
destroyDiscoveryService((NeoHubHandler) handler);
if (handler instanceof NeoHubHandler neoHubHandler) {
destroyDiscoveryService(neoHubHandler);
}
}

View File

@ -39,11 +39,11 @@ public class NeoPlugHandler extends NeoBaseHandler {
protected String toNeoHubBuildCommandString(String channelId, Command command) {
NeoBaseConfiguration config = this.config;
if (config != null) {
if (command instanceof OnOffType && channelId.equals(CHAN_PLUG_OUTPUT_STATE)) {
return String.format(CMD_CODE_TIMER, ((OnOffType) command).toString(), config.deviceNameInHub);
if (command instanceof OnOffType onOffCommand && channelId.equals(CHAN_PLUG_OUTPUT_STATE)) {
return String.format(CMD_CODE_TIMER, onOffCommand.toString(), config.deviceNameInHub);
}
if (command instanceof OnOffType && channelId.equals(CHAN_PLUG_AUTO_MODE)) {
return String.format(CMD_CODE_MANUAL, invert((OnOffType) command).toString(), config.deviceNameInHub);
if (command instanceof OnOffType onOffCommand && channelId.equals(CHAN_PLUG_AUTO_MODE)) {
return String.format(CMD_CODE_MANUAL, invert(onOffCommand).toString(), config.deviceNameInHub);
}
}
return "";

View File

@ -41,9 +41,9 @@ public class NeoStatHandler extends NeoBaseHandler {
protected String toNeoHubBuildCommandString(String channelId, Command command) {
NeoBaseConfiguration config = this.config;
if (config != null) {
if (command instanceof QuantityType<?> && channelId.equals(CHAN_TARGET_TEMP)) {
if (command instanceof QuantityType<?> quantityCommand && channelId.equals(CHAN_TARGET_TEMP)) {
Command doCommand = command;
QuantityType<?> temp = ((QuantityType<?>) command).toUnit(getTemperatureUnit());
QuantityType<?> temp = quantityCommand.toUnit(getTemperatureUnit());
if (temp != null) {
doCommand = temp;
}
@ -51,8 +51,8 @@ public class NeoStatHandler extends NeoBaseHandler {
config.deviceNameInHub);
}
if (command instanceof OnOffType && channelId.equals(CHAN_OCC_MODE_PRESENT)) {
return String.format(CMD_CODE_AWAY, invert((OnOffType) command).toString(), config.deviceNameInHub);
if (command instanceof OnOffType onOffCommand && channelId.equals(CHAN_OCC_MODE_PRESENT)) {
return String.format(CMD_CODE_AWAY, invert(onOffCommand).toString(), config.deviceNameInHub);
}
}
return "";

View File

@ -437,30 +437,30 @@ public class NeoHubJsonTests {
jsonElement = JsonParser.parseString(load("dcb_celsius"));
assertTrue(jsonElement.isJsonObject());
assertTrue(((JsonObject) jsonElement).keySet().size() > 0);
assertTrue(!((JsonObject) jsonElement).keySet().isEmpty());
jsonElement = JsonParser.parseString(load("live_data"));
assertTrue(jsonElement.isJsonObject());
assertTrue(((JsonObject) jsonElement).keySet().size() > 0);
assertTrue(!((JsonObject) jsonElement).keySet().isEmpty());
jsonElement = JsonParser.parseString(load("engineers"));
assertTrue(jsonElement.isJsonObject());
assertTrue(((JsonObject) jsonElement).keySet().size() > 0);
assertTrue(!((JsonObject) jsonElement).keySet().isEmpty());
jsonElement = JsonParser.parseString(load("info_new"));
assertTrue(jsonElement.isJsonObject());
assertTrue(((JsonObject) jsonElement).keySet().size() > 0);
assertTrue(!((JsonObject) jsonElement).keySet().isEmpty());
jsonElement = JsonParser.parseString(load("info_old"));
assertTrue(jsonElement.isJsonObject());
assertTrue(((JsonObject) jsonElement).keySet().size() > 0);
assertTrue(!((JsonObject) jsonElement).keySet().isEmpty());
jsonElement = JsonParser.parseString(load("system"));
assertTrue(jsonElement.isJsonObject());
assertTrue(((JsonObject) jsonElement).keySet().size() > 0);
assertTrue(!((JsonObject) jsonElement).keySet().isEmpty());
jsonElement = JsonParser.parseString(load("info_sensors_closed"));
assertTrue(jsonElement.isJsonObject());
assertTrue(((JsonObject) jsonElement).keySet().size() > 0);
assertTrue(!((JsonObject) jsonElement).keySet().isEmpty());
}
}

View File

@ -214,8 +214,8 @@ public class PubSubAPI {
listeners.remove(listener);
if (listeners.isEmpty()) {
subscriptionListeners.remove(subscriptionId);
scheduler.getQueue().removeIf(runnable -> runnable instanceof Subscriber
&& ((Subscriber) runnable).subscriptionId.equals(subscriptionId));
scheduler.getQueue().removeIf(
runnable -> runnable instanceof Subscriber s && s.subscriptionId.equals(subscriptionId));
}
}
}

View File

@ -73,8 +73,8 @@ public class SDMDiscoveryService extends AbstractDiscoveryService implements Thi
@Override
public void setThingHandler(ThingHandler handler) {
if (handler instanceof SDMAccountHandler) {
accountHandler = (SDMAccountHandler) handler;
if (handler instanceof SDMAccountHandler sdmAccountHandler) {
accountHandler = sdmAccountHandler;
}
}

View File

@ -231,7 +231,7 @@ public class SDMCommands {
*/
public SDMSetFanTimerRequest(SDMFanTimerMode timerMode, Duration duration) {
super("sdm.devices.commands.Fan.SetTimer", entry("timerMode", timerMode.name()),
entry("duration", String.valueOf(duration.toSeconds()) + "s"));
entry("duration", duration.toSeconds() + "s"));
}
}

View File

@ -211,7 +211,7 @@ public class SDMTraits {
public enum SDMTemperatureScale {
CELSIUS,
FAHRENHEIT;
FAHRENHEIT
}
/**

View File

@ -98,8 +98,8 @@ public class SDMThermostatHandler extends SDMBaseHandler {
delayedRefresh();
}
} else if (CHANNEL_FAN_TIMER_MODE.equals(channelUID.getId())) {
if (command instanceof OnOffType) {
if ((OnOffType) command == OnOffType.ON) {
if (command instanceof OnOffType onOffCommand) {
if (onOffCommand == OnOffType.ON) {
executeDeviceCommand(new SDMSetFanTimerRequest(SDMFanTimerMode.ON, getFanTimerDuration()));
} else {
executeDeviceCommand(new SDMSetFanTimerRequest(SDMFanTimerMode.OFF));
@ -107,9 +107,8 @@ public class SDMThermostatHandler extends SDMBaseHandler {
delayedRefresh();
}
} else if (CHANNEL_FAN_TIMER_TIMEOUT.equals(channelUID.getId())) {
if (command instanceof DateTimeType) {
Duration duration = Duration.between(ZonedDateTime.now(),
((DateTimeType) command).getZonedDateTime());
if (command instanceof DateTimeType dateTimeCommand) {
Duration duration = Duration.between(ZonedDateTime.now(), dateTimeCommand.getZonedDateTime());
executeDeviceCommand(new SDMSetFanTimerRequest(SDMFanTimerMode.ON, duration));
delayedRefresh();
}
@ -202,8 +201,8 @@ public class SDMThermostatHandler extends SDMBaseHandler {
if (channel != null) {
Configuration configuration = channel.getConfiguration();
Object fanTimerDuration = configuration.get(SDMBindingConstants.CONFIG_PROPERTY_FAN_TIMER_DURATION);
if (fanTimerDuration instanceof BigDecimal) {
seconds = ((BigDecimal) fanTimerDuration).longValue();
if (fanTimerDuration instanceof BigDecimal decimalValue) {
seconds = decimalValue.longValue();
}
}

View File

@ -38,7 +38,7 @@ import com.google.gson.stream.JsonWriter;
public class SDMDataUtil {
public static Reader openDataReader(String fileName) throws FileNotFoundException {
String packagePath = (SDMDataUtil.class.getPackage().getName()).replaceAll("\\.", "/");
String packagePath = (SDMDataUtil.class.getPackage().getName()).replace(".", "/");
String filePath = "src/test/resources/" + packagePath + "/" + fileName;
InputStream inputStream = new FileInputStream(filePath);

View File

@ -57,8 +57,7 @@ public class RoomActions implements ThingActions {
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
if (handler instanceof CommonInterface) {
CommonInterface commonHandler = (CommonInterface) handler;
if (handler instanceof CommonInterface commonHandler) {
this.handler = commonHandler;
}
}

View File

@ -64,7 +64,7 @@ public abstract class RestManager {
@Nullable String payload, @Nullable String contentType) throws NetatmoException {
URI uri = uriBuilder.build();
T response = apiBridge.executeUri(uri, method, clazz, payload, contentType, 3);
if (response instanceof ApiResponse.Ok && ((ApiResponse.Ok) response).failed()) {
if (response instanceof ApiResponse.Ok apiResponseOk && apiResponseOk.failed()) {
throw new NetatmoException("Command failed : %s for uri : %s", response.getStatus(), uri.toString());
}
return response;

View File

@ -58,8 +58,7 @@ public class WeatherApi extends RestManager {
throws NetatmoException {
UriBuilder uriBuilder = getApiUriBuilder(SUB_PATH_GET_STATION, PARAM_DEVICE_ID, deviceId, //
PARAM_FAVORITES, getFavorites);
StationDataResponse response = get(uriBuilder, StationDataResponse.class);
return response;
return get(uriBuilder, StationDataResponse.class);
}
/**

View File

@ -54,7 +54,7 @@ public class NetatmoConstants {
this.minValue = minValue;
this.maxValue = maxValue;
this.unit = unit;
String[] splitter = Double.valueOf(precision).toString().split("\\.");
String[] splitter = Double.toString(precision).split("\\.");
if (splitter.length > 1) {
int dec = Integer.parseInt(splitter[1]);
this.scale = dec > 0 ? Integer.toString(dec).length() : 0;
@ -169,7 +169,7 @@ public class NetatmoConstants {
public static final int THERM_MAX_SETPOINT = 30;
// Token scopes
public static enum Scope {
public enum Scope {
@SerializedName("read_station")
READ_STATION,
@SerializedName("read_thermostat")
@ -200,7 +200,7 @@ public class NetatmoConstants {
ACCESS_DOORBELL,
@SerializedName("read_carbonmonoxidedetector")
READ_CARBONMONOXIDEDETECTOR,
UNKNOWN;
UNKNOWN
}
private static final Scope[] SMOKE_SCOPES = { Scope.READ_SMOKEDETECTOR };
@ -212,7 +212,7 @@ public class NetatmoConstants {
private static final Scope[] DOORBELL_SCOPES = { Scope.READ_DOORBELL, Scope.WRITE_DOORBELL, Scope.ACCESS_DOORBELL };
private static final Scope[] PRESENCE_SCOPES = { Scope.READ_PRESENCE, Scope.WRITE_PRESENCE, Scope.ACCESS_PRESENCE };
public static enum FeatureArea {
public enum FeatureArea {
AIR_CARE(AIR_CARE_SCOPES),
WEATHER(WEATHER_SCOPES),
ENERGY(THERMOSTAT_SCOPES),
@ -234,7 +234,7 @@ public class NetatmoConstants {
static final int[] RADIO_SIGNAL_LEVELS = new int[] { 90, 80, 70, 60 }; // Resp : low, medium, high, full
// Thermostat definitions
public static enum SetpointMode {
public enum SetpointMode {
@SerializedName("program")
PROGRAM("program"),
@SerializedName("away")
@ -259,7 +259,7 @@ public class NetatmoConstants {
}
}
public static enum ThermostatZoneType {
public enum ThermostatZoneType {
@SerializedName("0")
DAY("0"),
@SerializedName("1")
@ -290,7 +290,7 @@ public class NetatmoConstants {
OFF,
@SerializedName("auto")
AUTO,
UNKNOWN;
UNKNOWN
}
public enum EventCategory {
@ -300,7 +300,7 @@ public class NetatmoConstants {
ANIMAL,
@SerializedName("vehicle")
VEHICLE,
UNKNOWN;
UNKNOWN
}
public enum TrendDescription {
@ -310,7 +310,7 @@ public class NetatmoConstants {
STABLE,
@SerializedName("down")
DOWN,
UNKNOWN;
UNKNOWN
}
public enum VideoStatus {
@ -320,7 +320,7 @@ public class NetatmoConstants {
AVAILABLE,
@SerializedName("deleted")
DELETED,
UNKNOWN;
UNKNOWN
}
public enum SdCardStatus {
@ -338,7 +338,7 @@ public class NetatmoConstants {
SD_CARD_INCOMPATIBLE_SPEED,
@SerializedName("7")
SD_CARD_INSUFFICIENT_SPACE,
UNKNOWN;
UNKNOWN
}
public enum AlimentationStatus {
@ -346,7 +346,7 @@ public class NetatmoConstants {
ALIM_INCORRECT_POWER,
@SerializedName("2")
ALIM_CORRECT_POWER,
UNKNOWN;
UNKNOWN
}
public enum SirenStatus {
@ -429,6 +429,6 @@ public class NetatmoConstants {
@SerializedName("40")
JSON_GIVEN_HAS_AN_INVALID_ENCODING,
@SerializedName("41")
DEVICE_IS_UNREACHABLE;
DEVICE_IS_UNREACHABLE
}
}

View File

@ -63,9 +63,9 @@ public class NetatmoCommandExtension extends AbstractConsoleCommandExtension imp
this.console = console;
for (Thing thing : thingRegistry.getAll()) {
ThingHandler thingHandler = thing.getHandler();
if (thingHandler instanceof ApiBridgeHandler) {
if (thingHandler instanceof ApiBridgeHandler bridgeHandler) {
console.println("Account bridge: " + thing.getLabel());
((ApiBridgeHandler) thingHandler).identifyAllModulesAndApplyAction(this::printThing);
bridgeHandler.identifyAllModulesAndApplyAction(this::printThing);
}
}
} else {

View File

@ -38,10 +38,10 @@ class NAObjectMapDeserializer implements JsonDeserializer<NAObjectMap<?>> {
throws JsonParseException {
ParameterizedType parameterized = (ParameterizedType) clazz;
Type[] typeArguments = parameterized.getActualTypeArguments();
if (typeArguments.length > 0 && json instanceof JsonArray) {
if (typeArguments.length > 0 && json instanceof JsonArray jsonArray) {
Type objectType = typeArguments[0];
NAObjectMap<NAObject> result = new NAObjectMap<>();
((JsonArray) json).forEach(item -> {
jsonArray.forEach(item -> {
result.put(context.deserialize(item, objectType));
});
return result;

View File

@ -79,8 +79,8 @@ public class NetatmoDiscoveryService extends AbstractDiscoveryService implements
@Override
public void setThingHandler(ThingHandler handler) {
if (handler instanceof ApiBridgeHandler) {
this.handler = (ApiBridgeHandler) handler;
if (handler instanceof ApiBridgeHandler bridgeHandler) {
this.handler = bridgeHandler;
}
}

View File

@ -130,8 +130,8 @@ public interface CommonInterface {
default List<CommonInterface> getActiveChildren() {
Thing thing = getThing();
if (thing instanceof Bridge) {
return ((Bridge) thing).getThings().stream().filter(Thing::isEnabled)
if (thing instanceof Bridge bridge) {
return bridge.getThings().stream().filter(Thing::isEnabled)
.filter(th -> th.getStatusInfo().getStatusDetail() != ThingStatusDetail.BRIDGE_OFFLINE)
.map(Thing::getHandler).filter(Objects::nonNull).map(CommonInterface.class::cast).toList();
}
@ -148,8 +148,7 @@ public interface CommonInterface {
}
default void setNewData(NAObject newData) {
if (newData instanceof NAThing) {
NAThing thingData = (NAThing) newData;
if (newData instanceof NAThing thingData) {
if (getId().equals(thingData.getBridge())) {
getActiveChildren().stream().filter(child -> child.getId().equals(thingData.getId())).findFirst()
.ifPresent(child -> child.setNewData(thingData));

View File

@ -82,7 +82,7 @@ public class MeasureCapability extends RestCapability<WeatherApi> {
MeasureClass.AS_SET.stream().filter(mc -> mc.apiDescriptor.equals(descriptor))
.reduce((first, second) -> second)
.ifPresent(mc -> measures.put(channel.getUID().getIdWithoutGroup(),
result instanceof ZonedDateTime ? toDateTimeType((ZonedDateTime) result)
result instanceof ZonedDateTime zonedDateTime ? toDateTimeType(zonedDateTime)
: result instanceof Double ? toQuantityType((Double) result, mc)
: UnDefType.UNDEF));
} catch (NetatmoException e) {

View File

@ -45,12 +45,12 @@ public class BatteryChannelHelper extends ChannelHelper {
protected @Nullable State internalGetProperty(String channelId, NAThing naThing, Configuration config) {
int percent = -1;
BatteryState batteryState = BatteryState.UNKNOWN;
if (naThing instanceof Module) {
percent = ((Module) naThing).getBatteryPercent();
batteryState = ((Module) naThing).getBatteryState();
} else if (naThing instanceof HomeStatusModule) {
percent = ((HomeStatusModule) naThing).getBatteryState().level;
batteryState = ((HomeStatusModule) naThing).getBatteryState();
if (naThing instanceof Module module) {
percent = module.getBatteryPercent();
batteryState = module.getBatteryState();
} else if (naThing instanceof HomeStatusModule homeStatusModule) {
percent = homeStatusModule.getBatteryState().level;
batteryState = homeStatusModule.getBatteryState();
} else {
return null;
}

View File

@ -56,8 +56,7 @@ public class CameraChannelHelper extends ChannelHelper {
@Override
protected @Nullable State internalGetProperty(String channelId, NAThing naThing, Configuration config) {
if (naThing instanceof HomeStatusModule) {
HomeStatusModule camera = (HomeStatusModule) naThing;
if (naThing instanceof HomeStatusModule camera) {
boolean isMonitoring = OnOffType.ON.equals(camera.getMonitoring());
switch (channelId) {
case CHANNEL_MONITORING:

View File

@ -48,20 +48,19 @@ public abstract class ChannelHelper {
State result = null;
if (channelGroups.isEmpty() || (groupId != null && channelGroups.contains(groupId))) {
NAObject localData = data;
if (localData instanceof HomeEvent) {
result = internalGetHomeEvent(channelId, groupId, (HomeEvent) localData);
if (localData instanceof HomeEvent homeEvent) {
result = internalGetHomeEvent(channelId, groupId, homeEvent);
if (result != null) {
return result;
}
}
if (localData instanceof Event) {
result = internalGetEvent(channelId, (Event) localData);
if (localData instanceof Event event) {
result = internalGetEvent(channelId, event);
if (result != null) {
return result;
}
}
if (localData instanceof NAThing) {
NAThing naThing = (NAThing) localData;
if (localData instanceof NAThing naThing) {
result = internalGetProperty(channelId, naThing, config);
if (result != null) {
return result;

View File

@ -40,8 +40,7 @@ public class DoorTagChannelHelper extends ChannelHelper {
@Override
protected @Nullable State internalGetProperty(String channelId, NAThing naThing, Configuration config) {
if (naThing instanceof HomeStatusModule) {
HomeStatusModule doorTag = (HomeStatusModule) naThing;
if (naThing instanceof HomeStatusModule doorTag) {
if (CHANNEL_STATUS.equalsIgnoreCase(channelId)) {
return doorTag.getStatus().map(status -> (State) OpenClosedType.valueOf(status.toUpperCase()))
.orElse(UnDefType.UNDEF);

View File

@ -56,8 +56,7 @@ public class EventChannelHelper extends ChannelHelper {
@Override
public void setNewData(@Nullable NAObject data) {
if (data instanceof Event) {
Event event = (Event) data;
if (data instanceof Event event) {
if (!event.getEventType().validFor(moduleType)) {
return;
}

View File

@ -42,10 +42,10 @@ public class LocationChannelHelper extends ChannelHelper {
protected @Nullable State internalGetProperty(String channelId, NAThing naThing, Configuration config) {
if (CHANNEL_VALUE.equals(channelId)) {
State point = UnDefType.UNDEF;
if (naThing instanceof Home) {
point = ((Home) naThing).getLocation();
} else if (naThing instanceof Device) {
point = ((Device) naThing).getPlace().map(place -> place.getLocation()).orElse(point);
if (naThing instanceof Home home) {
point = home.getLocation();
} else if (naThing instanceof Device device) {
point = device.getPlace().map(place -> place.getLocation()).orElse(point);
}
return point;
}

View File

@ -41,8 +41,7 @@ public class PersonChannelHelper extends ChannelHelper {
@Override
protected @Nullable State internalGetProperty(String channelId, NAThing naThing, Configuration config) {
if (naThing instanceof HomeDataPerson) {
HomeDataPerson person = (HomeDataPerson) naThing;
if (naThing instanceof HomeDataPerson person) {
switch (channelId) {
case CHANNEL_PERSON_AVATAR_URL:
return toStringType(person.getUrl().orElse(null));
@ -50,8 +49,7 @@ public class PersonChannelHelper extends ChannelHelper {
return toRawType(person.getUrl().orElse(null));
}
}
if (naThing instanceof HomeStatusPerson) {
HomeStatusPerson person = (HomeStatusPerson) naThing;
if (naThing instanceof HomeStatusPerson person) {
switch (channelId) {
case CHANNEL_PERSON_AT_HOME:
return OnOffType.from(person.atHome());

View File

@ -40,8 +40,7 @@ public class RoomChannelHelper extends ChannelHelper {
@Override
protected @Nullable State internalGetObject(String channelId, NAObject naObject) {
if (naObject instanceof Room) {
Room room = (Room) naObject;
if (naObject instanceof Room room) {
switch (channelId) {
case CHANNEL_ROOM_WINDOW_OPEN:
return room.hasOpenedWindows();

View File

@ -40,8 +40,7 @@ public class SetpointChannelHelper extends ChannelHelper {
@Override
protected @Nullable State internalGetObject(String channelId, NAObject naObject) {
if (naObject instanceof Room) {
Room room = (Room) naObject;
if (naObject instanceof Room room) {
switch (channelId) {
case CHANNEL_SETPOINT_MODE:
return toStringType(room.getSetpointMode().name());

View File

@ -38,8 +38,8 @@ public class Therm1ChannelHelper extends ChannelHelper {
@Override
protected @Nullable State internalGetProperty(String channelId, NAThing naThing, Configuration config) {
return (naThing instanceof HomeStatusModule && CHANNEL_THERM_RELAY.equals(channelId))
? ((HomeStatusModule) naThing).getBoilerStatus()
return (naThing instanceof HomeStatusModule homeStatusModule && CHANNEL_THERM_RELAY.equals(channelId))
? homeStatusModule.getBoilerStatus()
: null;
}
}

View File

@ -44,8 +44,8 @@ public class ChannelTypeUtils {
public static @Nullable QuantityType<?> commandToQuantity(Command command, MeasureClass measureClass) {
Measure measureDef = measureClass.measureDefinition;
if (command instanceof QuantityType<?>) {
return ((QuantityType<?>) command).toUnit(measureDef.unit);
if (command instanceof QuantityType<?> quantityCommand) {
return quantityCommand.toUnit(measureDef.unit);
}
try {
double value = Double.parseDouble(command.toString());

View File

@ -48,24 +48,34 @@ public class NAObjectTest {
@Test
public void testWebHookEvent() throws NetatmoException {
String event = "{" + " \"user_id\": \"5c810xxxxxxx45f4\"," + " \"snapshot_id\": \"5d19bxxxxxx6380342\","
+ " \"snapshot_key\": \"f0134210ff83fxxxxxxxf770090a423d9a5\","
+ " \"snapshot_url\": \"https://netatmocameraimage.blob.core.windows.net/production/5d1xxxa5\","
+ " \"event_type\": \"movement\"," + " \"camera_id\": \"70:exxxxxdd:a7\","
+ " \"device_id\": \"70:exxxxdd:a7\"," + " \"home_id\": \"5c5d79xxxx08cd594\","
+ " \"home_name\": \"Boulogne Billan.\"," + " \"event_id\": \"5d19baae369359e896380341\","
+ " \"message\": \"Boulogne Billan: Movement detected by Indoor Camera\","
+ " \"push_type\": \"NACamera-movement\"" + "}";
String event = """
{\
"user_id": "5c810xxxxxxx45f4",\
"snapshot_id": "5d19bxxxxxx6380342",\
"snapshot_key": "f0134210ff83fxxxxxxxf770090a423d9a5",\
"snapshot_url": "https://netatmocameraimage.blob.core.windows.net/production/5d1xxxa5",\
"event_type": "movement",\
"camera_id": "70:exxxxxdd:a7",\
"device_id": "70:exxxxdd:a7",\
"home_id": "5c5d79xxxx08cd594",\
"home_name": "Boulogne Billan.",\
"event_id": "5d19baae369359e896380341",\
"message": "Boulogne Billan: Movement detected by Indoor Camera",\
"push_type": "NACamera-movement"\
}\
""";
WebhookEvent object = gson.deserialize(WebhookEvent.class, event);
assertEquals(object.getEventType(), EventType.MOVEMENT);
}
@Test
public void testDashboardData() throws NetatmoException {
String dashboard = "{time_utc:1623160336,Temperature:22.1,CO2:511,"
+ "Humidity:66,Noise:36,Pressure:1026.1,AbsolutePressure:1009.3,"
+ "min_temp:20,max_temp:22.4,date_max_temp:1623147932,"
+ "Sdate_min_temp:1623125249,pressure_trend:\"nonexistent\",temp_trend:\"stable\"}";
String dashboard = """
{time_utc:1623160336,Temperature:22.1,CO2:511,\
Humidity:66,Noise:36,Pressure:1026.1,AbsolutePressure:1009.3,\
min_temp:20,max_temp:22.4,date_max_temp:1623147932,\
Sdate_min_temp:1623125249,pressure_trend:"nonexistent",temp_trend:"stable"}\
""";
Dashboard object = gson.deserialize(Dashboard.class, dashboard);
assertEquals(511, object.getCo2(), 0);
assertEquals(TrendDescription.UNKNOWN, object.getPressureTrend());

View File

@ -37,8 +37,8 @@ public class NetworkActions implements ThingActions {
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
if (handler instanceof NetworkHandler) {
this.handler = (NetworkHandler) handler;
if (handler instanceof NetworkHandler networkHandler) {
this.handler = networkHandler;
}
}

View File

@ -181,7 +181,7 @@ public class NetworkDiscoveryService extends AbstractDiscoveryService implements
public static ThingUID createServiceUID(String ip, int tcpPort) {
// uid must not contains dots
return new ThingUID(SERVICE_DEVICE, ip.replace('.', '_') + "_" + String.valueOf(tcpPort));
return new ThingUID(SERVICE_DEVICE, ip.replace('.', '_') + "_" + tcpPort);
}
/**

View File

@ -17,8 +17,9 @@ import static org.openhab.binding.network.internal.NetworkBindingConstants.*;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import org.eclipse.jdt.annotation.NonNullByDefault;
@ -181,7 +182,7 @@ public class NetworkHandler extends BaseThingHandler
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "No port configured!");
return;
}
presenceDetection.setServicePorts(Collections.singleton(port));
presenceDetection.setServicePorts(Set.of(port));
} else {
// It does not harm to send an additional UDP packet to a device,
// therefore we assume all ping devices are iOS devices. If this
@ -239,7 +240,7 @@ public class NetworkHandler extends BaseThingHandler
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
return Collections.singletonList(NetworkActions.class);
return List.of(NetworkActions.class);
}
public void sendWakeOnLanPacketViaIp() {

View File

@ -208,11 +208,11 @@ public class NetworkUtils {
return IpPingMethodEnum.JAVA_PING;
} else {
os = os.toLowerCase();
if (os.indexOf("win") >= 0) {
if (os.contains("win")) {
method = IpPingMethodEnum.WINDOWS_PING;
} else if (os.indexOf("mac") >= 0) {
} else if (os.contains("mac")) {
method = IpPingMethodEnum.MAC_OS_PING;
} else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") >= 0) {
} else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
method = IpPingMethodEnum.IPUTILS_LINUX_PING;
} else {
// We cannot estimate the command line for any other operating system and just return false

View File

@ -20,8 +20,8 @@ import static org.mockito.Mockito.*;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
@ -62,7 +62,7 @@ public class PresenceDetectionTest {
@BeforeEach
public void setUp() throws UnknownHostException {
// Mock an interface
when(networkUtils.getInterfaceNames()).thenReturn(Collections.singleton("TESTinterface"));
when(networkUtils.getInterfaceNames()).thenReturn(Set.of("TESTinterface"));
doReturn(ArpPingUtilEnum.IPUTILS_ARPING).when(networkUtils).determineNativeARPpingMethod(anyString());
doReturn(IpPingMethodEnum.WINDOWS_PING).when(networkUtils).determinePingMethod();
@ -77,7 +77,7 @@ public class PresenceDetectionTest {
subject.setTimeout(300);
subject.setUseDhcpSniffing(false);
subject.setIOSDevice(true);
subject.setServicePorts(Collections.singleton(1010));
subject.setServicePorts(Set.of(1010));
subject.setUseArpPing(true, "arping", ArpPingUtilEnum.IPUTILS_ARPING);
subject.setUseIcmpPing(true);

View File

@ -17,7 +17,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -80,7 +80,7 @@ public class DiscoveryTest {
// TCP device
when(value.isPingReachable()).thenReturn(false);
when(value.isTCPServiceReachable()).thenReturn(true);
when(value.getReachableTCPports()).thenReturn(Collections.singletonList(1010));
when(value.getReachableTCPports()).thenReturn(List.of(1010));
d.partialDetectionResult(value);
verify(listener).thingDiscovered(any(), result.capture());
DiscoveryResult dresult = result.getValue();

View File

@ -58,9 +58,9 @@ public class NUTChannelTypeProvider implements ChannelTypeProvider, ThingHandler
@Override
public void setThingHandler(@Nullable final ThingHandler handler) {
if (handler instanceof NUTHandler) {
if (handler instanceof NUTHandler nutHandler) {
this.handler = handler;
((NUTHandler) handler).setChannelTypeProvider(this);
nutHandler.setChannelTypeProvider(this);
}
}

View File

@ -15,10 +15,10 @@ package org.openhab.binding.networkupstools.internal;
import java.time.Duration;
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.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@ -112,7 +112,7 @@ public class NUTHandler extends BaseThingHandler {
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
return Collections.singleton(NUTChannelTypeProvider.class);
return Set.of(NUTChannelTypeProvider.class);
}
public void setChannelTypeProvider(final NUTChannelTypeProvider channelTypeProvider) {

View File

@ -14,7 +14,6 @@ package org.openhab.binding.networkupstools.internal;
import static org.openhab.binding.networkupstools.internal.NUTBindingConstants.THING_TYPE_UPS;
import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@ -35,7 +34,7 @@ import org.osgi.service.component.annotations.Component;
@Component(configurationPid = "binding.networkupstools", service = ThingHandlerFactory.class)
public class NUTHandlerFactory extends BaseThingHandlerFactory {
private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_UPS);
private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_UPS);
@Override
public boolean supportsThingType(final ThingTypeUID thingTypeUID) {

View File

@ -278,7 +278,7 @@ public class SerialConnector extends NibeHeatPumpBaseConnector {
int b;
// wait first byte (blocking)
if ((b = in.read()) > -1) {
byte d[] = new byte[] { (byte) b };
byte[] d = new byte[] { (byte) b };
os.write(d);
// read rest of the available bytes

View File

@ -195,7 +195,6 @@ public class SimulatorConnector extends NibeHeatPumpBaseConnector {
logger.debug("Read queue: {}, Write queue: {}", readQueue.size(), writeQueue.size());
}
Thread.sleep(800);
} catch (InterruptedException e) {
}
}

View File

@ -98,7 +98,7 @@ public class UDPConnector extends NibeHeatPumpBaseConnector {
public void sendDatagram(NibeHeatPumpMessage msg) throws NibeHeatPumpException {
logger.debug("Sending request: {}", msg.toHexString());
byte data[] = msg.decodeMessage();
byte[] data = msg.decodeMessage();
int port = -1;
if (msg instanceof ModbusWriteRequestMessage) {

View File

@ -377,10 +377,10 @@ public class NibeHeatPumpHandler extends BaseThingHandler implements NibeHeatPum
if (command instanceof DecimalType || command instanceof QuantityType || command instanceof StringType) {
BigDecimal v;
if (command instanceof DecimalType) {
v = ((DecimalType) command).toBigDecimal();
} else if (command instanceof QuantityType) {
v = ((QuantityType) command).toBigDecimal();
if (command instanceof DecimalType decimalCommand) {
v = decimalCommand.toBigDecimal();
} else if (command instanceof QuantityType quantityCommand) {
v = quantityCommand.toBigDecimal();
} else {
v = new BigDecimal(command.toString());
}
@ -491,12 +491,12 @@ public class NibeHeatPumpHandler extends BaseThingHandler implements NibeHeatPum
updateStatus(ThingStatus.ONLINE);
if (msg instanceof ModbusReadResponseMessage) {
handleReadResponseMessage((ModbusReadResponseMessage) msg);
} else if (msg instanceof ModbusWriteResponseMessage) {
handleWriteResponseMessage((ModbusWriteResponseMessage) msg);
} else if (msg instanceof ModbusDataReadOutMessage) {
handleDataReadOutMessage((ModbusDataReadOutMessage) msg);
if (msg instanceof ModbusReadResponseMessage readResponseMessage) {
handleReadResponseMessage(readResponseMessage);
} else if (msg instanceof ModbusWriteResponseMessage writeResponseMessage) {
handleWriteResponseMessage(writeResponseMessage);
} else if (msg instanceof ModbusDataReadOutMessage dataReadOutMessage) {
handleDataReadOutMessage(dataReadOutMessage);
} else {
logger.debug("Received unknown message: {}", msg.toString());
}
@ -567,7 +567,7 @@ public class NibeHeatPumpHandler extends BaseThingHandler implements NibeHeatPum
logger.trace("Value did not change, ignoring update");
} else {
final String channelPrefix = (variableInfo.type == Type.SETTING ? "setting#" : "sensor#");
final String channelId = channelPrefix + String.valueOf(coilAddress);
final String channelId = channelPrefix + coilAddress;
final String acceptedItemType = thing.getChannel(channelId).getAcceptedItemType();
logger.trace("AcceptedItemType for channel {} = {}", channelId, acceptedItemType);

View File

@ -81,37 +81,24 @@ public class NibeHeatPumpProtocolTest {
//@formatter:off
final String strTestData =
// RMU40 message, acknowledge should be send
"5C001962189600E1010200000000800000000000020914340001000005B8"
// RMU40 message, CRC failure, negative acknowledge should be send
+ "5C001962189600E1010200000000800000000000020914340001000005B9"
// MODBUS40 write request
+ "5C00206B004B"
// nonsense
+ "3EAABB"
// MODBUS40 read request
+ "5C0020690049"
// nonsense
+ "F0561939F6"
// MODBUS40 data read out, acknowledge should be send
+ "5C00206850449C9600489C88014C9C2D014E9CCF004D9CE0014F9C3200509C0400519C8201529C6B02569C3E00C9AF000001A8F600FDA77E02FAA90F0098A9DC27FFFF0000A0A93A04FFFF00009CA9FD19FFFF000081"
// nonsense
+ "F0349823"
// MODBUS40 data read out, CRC failure, negative acknowledge should be send
+ "5C00206850449C9600489C88014C9C2D014E9CCF004D9CE0014F9C3200509C0400519C8201529C6B02569C3E00C9AF000001A8F600FDA77E02FAA90F0098A9DC27FFFF0000A0A93A04FFFF00009CA9FD19FFFF000080"
// RMU40 message, acknowledge should be send
+ "5C001962189600DF01020000000080000000000002091434000100000586"
// nonsense
+ "123490"
// unknown RMU40 message, acknowledge should be send
+ "5C0019600079"
// MODBUS40 data read out, special len, acknowledge should be send
+ "5C00206851449C2500489CFC004C9CF1004E9CC7014D9C0B024F9C2500509C3300519C0B01529C5C5C01569C3100C9AF000001A80C01FDA716FAFAA9070098A91B1BFFFF0000A0A9CA02FFFF00009CA99212FFFF0000BE"
// MODBUS40 data read out, special len, acknowledge should be send
+ "5C00206852449C2500489CFE004C9CF2004E9CD4014D9CFB014F9C2500509C3700519C0D01529C5C5C01569C3200C9AF000001A80C01FDA712FAFAA9070098A95C5C1BFFFF0000A0A9D102FFFF00009CA9B412FFFF00007F"
// MODBUS40 data read out, special checksum, acknowledge should be send
+ "5C00206850449C2600489CF6004C9CF1004E9CD6014D9C0C024F9C4500509C3F00519CF100529C0401569CD500C9AF000001A80C01FDA799FAFAA9020098A91A1BFFFF0000A0A9CA02FFFF00009CA99212FFFF0000C5"
// 16-bit address (e.g. model F2120 heatpumps), acknowledge should be send
+ "5C41C9F7007F";
"""
5C001962189600E1010200000000800000000000020914340001000005B8\
5C001962189600E1010200000000800000000000020914340001000005B9\
5C00206B004B\
3EAABB\
5C0020690049\
F0561939F6\
5C00206850449C9600489C88014C9C2D014E9CCF004D9CE0014F9C3200509C0400519C8201529C6B02569C3E00C9AF000001A8F600FDA77E02FAA90F0098A9DC27FFFF0000A0A93A04FFFF00009CA9FD19FFFF000081\
F0349823\
5C00206850449C9600489C88014C9C2D014E9CCF004D9CE0014F9C3200509C0400519C8201529C6B02569C3E00C9AF000001A8F600FDA77E02FAA90F0098A9DC27FFFF0000A0A93A04FFFF00009CA9FD19FFFF000080\
5C001962189600DF01020000000080000000000002091434000100000586\
123490\
5C0019600079\
5C00206851449C2500489CFC004C9CF1004E9CC7014D9C0B024F9C2500509C3300519C0B01529C5C5C01569C3100C9AF000001A80C01FDA716FAFAA9070098A91B1BFFFF0000A0A9CA02FFFF00009CA99212FFFF0000BE\
5C00206852449C2500489CFE004C9CF2004E9CD4014D9CFB014F9C2500509C3700519C0D01529C5C5C01569C3200C9AF000001A80C01FDA712FAFAA9070098A95C5C1BFFFF0000A0A9D102FFFF00009CA9B412FFFF00007F\
5C00206850449C2600489CF6004C9CF1004E9CD6014D9C0C024F9C4500509C3F00519CF100529C0401569CD500C9AF000001A80C01FDA799FAFAA9020098A91A1BFFFF0000A0A9CA02FFFF00009CA99212FFFF0000C5\
5C41C9F7007F\
""";
//@formatter:on
// create byte data from hex string

View File

@ -56,10 +56,10 @@ public class UpdateSetting extends AbstractUplinkCommandCallback implements Nibe
private String extractValue(Command command) {
// this is necessary because we must not send the unit to the nibe backend
if (command instanceof QuantityType<?>) {
return String.valueOf(((QuantityType<?>) command).doubleValue());
} else if (command instanceof OnOffType) {
return ChannelUtil.mapValue(channel, (OnOffType) command);
if (command instanceof QuantityType<?> quantityCommand) {
return String.valueOf(quantityCommand.doubleValue());
} else if (command instanceof OnOffType onOffCommand) {
return ChannelUtil.mapValue(channel, onOffCommand);
} else {
return command.toString();
}

View File

@ -14,9 +14,9 @@ package org.openhab.binding.nikobus.internal.discovery;
import static org.openhab.binding.nikobus.internal.NikobusBindingConstants.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
@ -44,7 +44,7 @@ public class NikobusDiscoveryService extends AbstractDiscoveryService implements
private @Nullable NikobusPcLinkHandler bridgeHandler;
public NikobusDiscoveryService() throws IllegalArgumentException {
super(Collections.singleton(THING_TYPE_PUSH_BUTTON), 0);
super(Set.of(THING_TYPE_PUSH_BUTTON), 0);
}
@Override
@ -92,8 +92,8 @@ public class NikobusDiscoveryService extends AbstractDiscoveryService implements
@Override
public void setThingHandler(ThingHandler handler) {
if (handler instanceof NikobusPcLinkHandler) {
bridgeHandler = (NikobusPcLinkHandler) handler;
if (handler instanceof NikobusPcLinkHandler pcLinkHandler) {
bridgeHandler = pcLinkHandler;
}
}

View File

@ -54,8 +54,8 @@ public class NikobusDimmerModuleHandler extends NikobusSwitchModuleHandler {
@Override
protected int valueFromCommand(String channelId, Command command) {
if (command instanceof PercentType) {
return Math.round(((PercentType) command).floatValue() / 100f * 255f);
if (command instanceof PercentType percentCommand) {
return Math.round(percentCommand.floatValue() / 100f * 255f);
}
return super.valueFromCommand(channelId, command);

View File

@ -22,6 +22,7 @@ import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@ -120,7 +121,7 @@ public class NikobusPcLinkHandler extends BaseBridgeHandler {
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
return Collections.singleton(NikobusDiscoveryService.class);
return Set.of(NikobusDiscoveryService.class);
}
private void processReceivedValue(byte value) {

View File

@ -195,8 +195,8 @@ public class NikobusPushButtonHandler extends NikobusBaseThingHandler {
}
ThingHandler thingHandler = thing.getHandler();
if (thingHandler instanceof NikobusModuleHandler) {
return (NikobusModuleHandler) thingHandler;
if (thingHandler instanceof NikobusModuleHandler nikobusModuleHandler) {
return nikobusModuleHandler;
}
return null;
}
@ -256,10 +256,10 @@ public class NikobusPushButtonHandler extends NikobusBaseThingHandler {
}
SwitchModuleGroup getGroup() {
if (getSegment(2).equals("1")) {
if ("1".equals(getSegment(2))) {
return FIRST;
}
if (getSegment(2).equals("2")) {
if ("2".equals(getSegment(2))) {
return SECOND;
}
throw new IllegalArgumentException("Unexpected group found " + getSegment(2));

View File

@ -87,13 +87,12 @@ public class NikobusRollershutterModuleHandler extends NikobusModuleHandler {
@Override
protected int valueFromCommand(String channelId, Command command) {
Optional<PositionEstimator> positionEstimator = getPositionEstimator(channelId);
if (command instanceof DecimalType) {
return positionEstimator.map(estimator -> {
return estimator.processSetPosition(((DecimalType) command).intValue());
}).orElseThrow(() -> {
throw new IllegalArgumentException(
"Received position request but no estimation configured for channel " + channelId);
});
if (command instanceof DecimalType decimalCommand) {
return positionEstimator.map(estimator -> estimator.processSetPosition(decimalCommand.intValue()))
.orElseThrow(() -> {
throw new IllegalArgumentException(
"Received position request but no estimation configured for channel " + channelId);
});
}
int result = convertCommandToValue(channelId, command);
positionEstimator.ifPresent(PositionEstimator::cancelStopMovement);

View File

@ -201,8 +201,8 @@ public class NikoHomeControlDiscoveryService extends AbstractDiscoveryService im
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
if (handler instanceof NikoHomeControlBridgeHandler) {
this.handler = (NikoHomeControlBridgeHandler) handler;
if (handler instanceof NikoHomeControlBridgeHandler homeControlBridgeHandler) {
this.handler = homeControlBridgeHandler;
bridgeUID = handler.getThing().getUID();
}
}

View File

@ -125,9 +125,8 @@ public class NikoHomeControlActionHandler extends BaseThingHandler implements Nh
return;
}
if (command instanceof OnOffType) {
OnOffType s = (OnOffType) command;
if (OnOffType.OFF.equals(s)) {
if (command instanceof OnOffType onOffCommand) {
if (OnOffType.OFF.equals(onOffCommand)) {
nhcAction.execute(NHCOFF);
} else {
nhcAction.execute(NHCON);
@ -142,18 +141,16 @@ public class NikoHomeControlActionHandler extends BaseThingHandler implements Nh
return;
}
if (command instanceof OnOffType) {
OnOffType s = (OnOffType) command;
if (OnOffType.OFF.equals(s)) {
if (command instanceof OnOffType onOffCommand) {
if (OnOffType.OFF.equals(onOffCommand)) {
nhcAction.execute(NHCOFF);
} else {
nhcAction.execute(NHCON);
}
} else if (command instanceof IncreaseDecreaseType) {
IncreaseDecreaseType s = (IncreaseDecreaseType) command;
} else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
int currentValue = nhcAction.getState();
int newValue;
if (IncreaseDecreaseType.INCREASE.equals(s)) {
if (IncreaseDecreaseType.INCREASE.equals(increaseDecreaseCommand)) {
newValue = currentValue + stepValue;
// round down to step multiple
newValue = newValue - newValue % stepValue;
@ -168,12 +165,11 @@ public class NikoHomeControlActionHandler extends BaseThingHandler implements Nh
nhcAction.execute(Integer.toString(newValue));
}
}
} else if (command instanceof PercentType) {
PercentType p = (PercentType) command;
if (PercentType.ZERO.equals(p)) {
} else if (command instanceof PercentType percentCommand) {
if (PercentType.ZERO.equals(percentCommand)) {
nhcAction.execute(NHCOFF);
} else {
nhcAction.execute(Integer.toString(p.intValue()));
nhcAction.execute(Integer.toString(percentCommand.intValue()));
}
}
}
@ -185,18 +181,17 @@ public class NikoHomeControlActionHandler extends BaseThingHandler implements Nh
return;
}
if (command instanceof UpDownType) {
UpDownType s = (UpDownType) command;
if (UpDownType.UP.equals(s)) {
if (command instanceof UpDownType upDownCommand) {
if (UpDownType.UP.equals(upDownCommand)) {
nhcAction.execute(!invert ? NHCUP : NHCDOWN);
} else {
nhcAction.execute(!invert ? NHCDOWN : NHCUP);
}
} else if (command instanceof StopMoveType) {
nhcAction.execute(NHCSTOP);
} else if (command instanceof PercentType) {
PercentType p = (PercentType) command;
nhcAction.execute(!invert ? Integer.toString(100 - p.intValue()) : Integer.toString(p.intValue()));
} else if (command instanceof PercentType percentCommand) {
nhcAction.execute(!invert ? Integer.toString(100 - percentCommand.intValue())
: Integer.toString(percentCommand.intValue()));
}
}
@ -300,8 +295,7 @@ public class NikoHomeControlActionHandler extends BaseThingHandler implements Nh
properties.put("timeToClose", String.valueOf(nhcAction.getCloseTime()));
}
if (nhcAction instanceof NhcAction2) {
NhcAction2 action = (NhcAction2) nhcAction;
if (nhcAction instanceof NhcAction2 action) {
properties.put(PROPERTY_DEVICE_TYPE, action.getDeviceType());
properties.put(PROPERTY_DEVICE_TECHNOLOGY, action.getDeviceTechnology());
properties.put(PROPERTY_DEVICE_MODEL, action.getDeviceModel());

View File

@ -163,8 +163,7 @@ public class NikoHomeControlEnergyMeterHandler extends BaseThingHandler implemen
private void updateProperties(NhcEnergyMeter nhcEnergyMeter) {
Map<String, String> properties = new HashMap<>();
if (nhcEnergyMeter instanceof NhcEnergyMeter2) {
NhcEnergyMeter2 energyMeter = (NhcEnergyMeter2) nhcEnergyMeter;
if (nhcEnergyMeter instanceof NhcEnergyMeter2 energyMeter) {
properties.put(PROPERTY_DEVICE_TYPE, energyMeter.getDeviceType());
properties.put(PROPERTY_DEVICE_TECHNOLOGY, energyMeter.getDeviceTechnology());
properties.put(PROPERTY_DEVICE_MODEL, energyMeter.getDeviceModel());

View File

@ -110,8 +110,8 @@ public class NikoHomeControlThermostatHandler extends BaseThingHandler implement
updateStatus(ThingStatus.ONLINE);
break;
case CHANNEL_MODE:
if (command instanceof DecimalType) {
nhcThermostat.executeMode(((DecimalType) command).intValue());
if (command instanceof DecimalType decimalCommand) {
nhcThermostat.executeMode(decimalCommand.intValue());
}
updateStatus(ThingStatus.ONLINE);
break;
@ -128,20 +128,20 @@ public class NikoHomeControlThermostatHandler extends BaseThingHandler implement
if (time <= 0) {
time = overruleTime;
}
if (command instanceof QuantityType<?>) {
QuantityType<?> setpoint = ((QuantityType<?>) command).toUnit(CELSIUS);
if (command instanceof QuantityType<?> quantityCommand) {
QuantityType<?> setpoint = quantityCommand.toUnit(CELSIUS);
if (setpoint != null) {
nhcThermostat.executeOverrule(Math.round(setpoint.floatValue() * 10), time);
}
} else if (command instanceof DecimalType) {
BigDecimal setpoint = ((DecimalType) command).toBigDecimal();
} else if (command instanceof DecimalType decimalCommand) {
BigDecimal setpoint = decimalCommand.toBigDecimal();
nhcThermostat.executeOverrule(Math.round(setpoint.floatValue() * 10), time);
}
updateStatus(ThingStatus.ONLINE);
break;
case CHANNEL_OVERRULETIME:
if (command instanceof DecimalType) {
int overruletime = ((DecimalType) command).intValue();
if (command instanceof DecimalType decimalCommand) {
int overruletime = decimalCommand.intValue();
int overrule = nhcThermostat.getOverrule();
if (overruletime <= 0) {
overruletime = 0;
@ -244,8 +244,7 @@ public class NikoHomeControlThermostatHandler extends BaseThingHandler implement
private void updateProperties(NhcThermostat nhcThermostat) {
Map<String, String> properties = new HashMap<>();
if (nhcThermostat instanceof NhcThermostat2) {
NhcThermostat2 thermostat = (NhcThermostat2) nhcThermostat;
if (nhcThermostat instanceof NhcThermostat2 thermostat) {
properties.put(PROPERTY_DEVICE_TYPE, thermostat.getDeviceType());
properties.put(PROPERTY_DEVICE_TECHNOLOGY, thermostat.getDeviceTechnology());
properties.put(PROPERTY_DEVICE_MODEL, thermostat.getDeviceModel());

View File

@ -23,7 +23,7 @@ import org.eclipse.jdt.annotation.NonNullByDefault;
public class NikoHomeControlConstants {
// Action types abstracted from NhcI and NhcII action types
public static enum ActionType {
public enum ActionType {
TRIGGER,
RELAY,
DIMMER,

View File

@ -62,7 +62,7 @@ public class NhcMqttConnection2 implements MqttActionCallback {
private MqttMessageSubscriber messageSubscriber;
private MqttConnectionObserver connectionObserver;
private TrustManager trustManagers[];
private TrustManager[] trustManagers;
private String clientId;
private volatile String cocoAddress = "";

View File

@ -99,11 +99,10 @@ public class NoboHubBridgeHandler extends BaseBridgeHandler {
if (CHANNEL_HUB_ACTIVE_OVERRIDE_NAME.equals(channelUID.getId())) {
if (ht != null && h != null) {
if (command instanceof StringType) {
StringType strCommand = (StringType) command;
logger.debug("Changing override for hub {} to {}", channelUID, strCommand);
if (command instanceof StringType stringCommand) {
logger.debug("Changing override for hub {} to {}", channelUID, stringCommand);
try {
OverrideMode mode = OverrideMode.getByName(strCommand.toFullString());
OverrideMode mode = OverrideMode.getByName(stringCommand.toFullString());
ht.getConnection().setOverride(h, mode);
} catch (NoboCommunicationException nce) {
logger.debug("Failed setting override mode", nce);

View File

@ -92,8 +92,8 @@ public class NoboHubHandlerFactory extends BaseThingHandlerFactory {
@Override
protected void removeHandler(ThingHandler thingHandler) {
if (thingHandler instanceof NoboHubBridgeHandler) {
unregisterDiscoveryService((NoboHubBridgeHandler) thingHandler);
if (thingHandler instanceof NoboHubBridgeHandler bridgeHandler) {
unregisterDiscoveryService(bridgeHandler);
}
}

View File

@ -166,8 +166,7 @@ public class ZoneHandler extends BaseThingHandler {
if (CHANNEL_ZONE_COMFORT_TEMPERATURE.equals(channelUID.getId())) {
Zone zone = getZone();
if (zone != null) {
if (command instanceof DecimalType) {
DecimalType comfortTemp = (DecimalType) command;
if (command instanceof DecimalType comfortTemp) {
logger.debug("Set comfort temp for zone {} to {}", zone.getName(), comfortTemp.doubleValue());
zone.setComfortTemperature(comfortTemp.intValue());
sendCommand(zone.generateCommandString("U00"));
@ -180,8 +179,7 @@ public class ZoneHandler extends BaseThingHandler {
if (CHANNEL_ZONE_ECO_TEMPERATURE.equals(channelUID.getId())) {
Zone zone = getZone();
if (zone != null) {
if (command instanceof DecimalType) {
DecimalType ecoTemp = (DecimalType) command;
if (command instanceof DecimalType ecoTemp) {
logger.debug("Set eco temp for zone {} to {}", zone.getName(), ecoTemp.doubleValue());
zone.setEcoTemperature(ecoTemp.intValue());
sendCommand(zone.generateCommandString("U00"));
@ -193,8 +191,7 @@ public class ZoneHandler extends BaseThingHandler {
if (CHANNEL_ZONE_ACTIVE_WEEK_PROFILE.equals(channelUID.getId())) {
Zone zone = getZone();
if (zone != null) {
if (command instanceof DecimalType) {
DecimalType weekProfileId = (DecimalType) command;
if (command instanceof DecimalType weekProfileId) {
logger.debug("Set week profile for zone {} to {}", zone.getName(), weekProfileId);
zone.setWeekProfile(weekProfileId.intValue());
sendCommand(zone.generateCommandString("U00"));

View File

@ -82,8 +82,8 @@ public class NoboHubDiscoveryService extends AbstractDiscoveryService implements
@Override
public void setThingHandler(ThingHandler thingHandler) {
if (thingHandler instanceof NoboHubBridgeHandler) {
this.hubBridgeHandler = (NoboHubBridgeHandler) thingHandler;
if (thingHandler instanceof NoboHubBridgeHandler bridgeHandler) {
this.hubBridgeHandler = bridgeHandler;
}
}

View File

@ -51,7 +51,7 @@ public class Hub {
}
public static Hub fromH05(String h05) throws NoboDataException {
String parts[] = h05.split(" ", 8);
String[] parts = h05.split(" ", 8);
if (parts.length != 8) {
throw new NoboDataException(

View File

@ -31,7 +31,7 @@ public final class Temperature {
}
public static Temperature fromY02(String y02) throws NoboDataException {
String parts[] = y02.split(" ", 3);
String[] parts = y02.split(" ", 3);
if (parts.length != 3) {
throw new NoboDataException(
String.format("Unexpected number of parts from hub on Y02 call: %d", parts.length));

View File

@ -43,7 +43,7 @@ public final class Zone {
}
public static Zone fromH01(String h01) throws NoboDataException {
String parts[] = h01.split(" ", 8);
String[] parts = h01.split(" ", 8);
if (parts.length != 8) {
throw new NoboDataException(

View File

@ -14,7 +14,6 @@ package org.openhab.binding.novafinedust.internal;
import static org.openhab.binding.novafinedust.internal.NovaFineDustBindingConstants.THING_TYPE_SDS011;
import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@ -39,7 +38,7 @@ import org.osgi.service.component.annotations.Reference;
@Component(configurationPid = "binding.novafinedust", service = ThingHandlerFactory.class)
public class NovaFineDustHandlerFactory extends BaseThingHandlerFactory {
private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_SDS011);
private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_SDS011);
private final SerialPortManager serialPortManager;

View File

@ -80,7 +80,6 @@ public class SDS011Communicator {
*/
public void initialize(WorkMode mode, Duration interval)
throws PortInUseException, TooManyListenersException, IOException, UnsupportedCommOperationException {
logger.trace("Initializing with mode={}, interval={}", mode, interval);
SerialPort localSerialPort = portId.open(thingHandler.getThing().getUID().toString(), 2000);
@ -246,8 +245,7 @@ public class SDS011Communicator {
private boolean doRead() throws IOException {
SensorReply reply = readReply();
logger.trace("doRead(): Read reply={}", reply);
if (reply instanceof SensorMeasuredDataReply) {
SensorMeasuredDataReply sensorData = (SensorMeasuredDataReply) reply;
if (reply instanceof SensorMeasuredDataReply sensorData) {
logger.trace("We received sensor data");
if (sensorData.isValidData()) {
logger.trace("Sensor data is valid => updating channels");

View File

@ -40,8 +40,7 @@ public class SensorFirmwareReply extends SensorReply {
* @return firmware of the sensor formatted as YY-MM-DD
*/
public String getFirmware() {
String firmware = year + "-" + month + "-" + day;
return firmware;
return year + "-" + month + "-" + day;
}
@Override

View File

@ -12,7 +12,6 @@
*/
package org.openhab.binding.ntp.internal;
import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@ -46,5 +45,5 @@ public class NtpBindingConstants {
public static final String PROPERTY_DATE_TIME_FORMAT = "DateTimeFormat";
public static final String PROPERTY_NTP_SERVER_PORT = "serverPort";
public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_NTP);
public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_NTP);
}

View File

@ -101,8 +101,8 @@ public class NukiHandlerFactory extends BaseThingHandlerFactory {
public void unregisterHandler(Thing thing) {
super.unregisterHandler(thing);
ThingHandler handler = thing.getHandler();
if (handler instanceof NukiBridgeHandler) {
nukiApiServlet.remove((NukiBridgeHandler) handler);
if (handler instanceof NukiBridgeHandler bridgeHandler) {
nukiApiServlet.remove(bridgeHandler);
}
}

View File

@ -12,7 +12,6 @@
*/
package org.openhab.binding.nuki.internal.constants;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@ -38,9 +37,9 @@ public class NukiBindingConstants {
public static final ThingTypeUID THING_TYPE_SMARTLOCK = new ThingTypeUID(BINDING_ID, "smartlock");
public static final ThingTypeUID THING_TYPE_OPENER = new ThingTypeUID(BINDING_ID, "opener");
public static final Set<ThingTypeUID> THING_TYPE_BRIDGE_UIDS = Collections.singleton(THING_TYPE_BRIDGE);
public static final Set<ThingTypeUID> THING_TYPE_SMARTLOCK_UIDS = Collections.singleton(THING_TYPE_SMARTLOCK);
public static final Set<ThingTypeUID> THING_TYPE_OPENER_UIDS = Collections.singleton(THING_TYPE_OPENER);
public static final Set<ThingTypeUID> THING_TYPE_BRIDGE_UIDS = Set.of(THING_TYPE_BRIDGE);
public static final Set<ThingTypeUID> THING_TYPE_SMARTLOCK_UIDS = Set.of(THING_TYPE_SMARTLOCK);
public static final Set<ThingTypeUID> THING_TYPE_OPENER_UIDS = Set.of(THING_TYPE_OPENER);
public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Stream
.of(THING_TYPE_BRIDGE_UIDS, THING_TYPE_SMARTLOCK_UIDS, THING_TYPE_OPENER_UIDS).flatMap(Set::stream)

View File

@ -73,8 +73,7 @@ public class NukiHttpClient {
private NukiBaseResponse handleException(Exception e) {
if (e instanceof ExecutionException) {
Throwable cause = e.getCause();
if (cause instanceof HttpResponseException) {
HttpResponseException causeException = (HttpResponseException) cause;
if (cause instanceof HttpResponseException causeException) {
int status = causeException.getResponse().getStatus();
String reason = causeException.getResponse().getReason();
logger.debug("HTTP Response Exception! Status[{}] - Reason[{}]! Check your API Token!", status, reason);

View File

@ -12,7 +12,7 @@
*/
package org.openhab.binding.nuki.internal.discovery;
import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jetty.client.HttpClient;
@ -56,7 +56,7 @@ public class NukiBridgeDiscoveryService extends AbstractDiscoveryService {
@Activate
public NukiBridgeDiscoveryService(@Reference final HttpClientFactory httpClientFactory,
@Reference final ThingRegistry thingRegistry) {
super(Collections.singleton(NukiBindingConstants.THING_TYPE_BRIDGE), 30, false);
super(Set.of(NukiBindingConstants.THING_TYPE_BRIDGE), 30, false);
this.httpClient = httpClientFactory.getCommonHttpClient();
this.thingRegistry = thingRegistry;
}

View File

@ -103,8 +103,8 @@ public class NukiDeviceDiscoveryService extends AbstractDiscoveryService impleme
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
if (handler instanceof NukiBridgeHandler) {
bridge = (NukiBridgeHandler) handler;
if (handler instanceof NukiBridgeHandler bridgeHandler) {
bridge = bridgeHandler;
}
}

View File

@ -149,8 +149,7 @@ public abstract class AbstractNukiDeviceHandler<T extends NukiDeviceConfiguratio
}
private void initializeHandler(@Nullable ThingHandler handler, @Nullable ThingStatus bridgeStatus) {
if (handler instanceof NukiBridgeHandler && bridgeStatus != null) {
NukiBridgeHandler bridgeHandler = (NukiBridgeHandler) handler;
if (handler instanceof NukiBridgeHandler bridgeHandler && bridgeStatus != null) {
if (bridgeStatus == ThingStatus.ONLINE) {
this.nukiHttpClient = bridgeHandler.getNukiHttpClient();
withHttpClient(client -> {
@ -203,6 +202,7 @@ public abstract class AbstractNukiDeviceHandler<T extends NukiDeviceConfiguratio
}
}
@Override
protected void triggerChannel(String channelId, String event) {
Channel channel = thing.getChannel(channelId);
if (channel != null) {
@ -335,8 +335,8 @@ public abstract class AbstractNukiDeviceHandler<T extends NukiDeviceConfiguratio
Bridge bridge = getBridge();
if (bridge != null) {
BridgeHandler bridgeHandler = bridge.getHandler();
if (bridgeHandler instanceof NukiBridgeHandler) {
scheduler.execute(() -> handler.accept((NukiBridgeHandler) bridgeHandler));
if (bridgeHandler instanceof NukiBridgeHandler nukiBridgeHandler) {
scheduler.execute(() -> handler.accept(nukiBridgeHandler));
}
}
}

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