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>
This commit is contained in:
Holger Friedrich
2023-09-13 08:03:31 +02:00
committed by GitHub
parent 641b482551
commit ab58f4ffb4
471 changed files with 1624 additions and 1868 deletions

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());