diff --git a/bundles/org.openhab.persistence.dynamodb/src/main/java/org/openhab/persistence/dynamodb/internal/AbstractDynamoDBItem.java b/bundles/org.openhab.persistence.dynamodb/src/main/java/org/openhab/persistence/dynamodb/internal/AbstractDynamoDBItem.java index b47b5f56a..83ed2ab04 100644 --- a/bundles/org.openhab.persistence.dynamodb/src/main/java/org/openhab/persistence/dynamodb/internal/AbstractDynamoDBItem.java +++ b/bundles/org.openhab.persistence.dynamodb/src/main/java/org/openhab/persistence/dynamodb/internal/AbstractDynamoDBItem.java @@ -302,8 +302,8 @@ public abstract class AbstractDynamoDBItem implements DynamoDBItem { } else if (item instanceof NumberItem) { return new DynamoDBBigDecimalItem(name, convert(state, DecimalType.class).toBigDecimal(), time, expireDays); } else if (item instanceof PlayerItem) { - if (state instanceof PlayPauseType) { - switch ((PlayPauseType) state) { + if (state instanceof PlayPauseType pauseType) { + switch (pauseType) { case PLAY: return new DynamoDBBigDecimalItem(name, PLAY_BIGDECIMAL, time, expireDays); case PAUSE: @@ -311,8 +311,8 @@ public abstract class AbstractDynamoDBItem implements DynamoDBItem { default: throw new IllegalArgumentException("Unexpected enum with PlayPauseType: " + state.toString()); } - } else if (state instanceof RewindFastforwardType) { - switch ((RewindFastforwardType) state) { + } else if (state instanceof RewindFastforwardType rewindType) { + switch (rewindType) { case FASTFORWARD: return new DynamoDBBigDecimalItem(name, FAST_FORWARD_BIGDECIMAL, time, expireDays); case REWIND: @@ -329,12 +329,11 @@ public abstract class AbstractDynamoDBItem implements DynamoDBItem { // Normalize UP/DOWN to % return new DynamoDBBigDecimalItem(name, convert(state, PercentType.class).toBigDecimal(), time, expireDays); } else if (item instanceof StringItem) { - if (state instanceof StringType) { - return new DynamoDBStringItem(name, ((StringType) state).toString(), time, expireDays); - } else if (state instanceof DateTimeType) { + if (state instanceof StringType stringType) { + return new DynamoDBStringItem(name, stringType.toString(), time, expireDays); + } else if (state instanceof DateTimeType dateType) { return new DynamoDBStringItem(name, - ZONED_DATE_TIME_CONVERTER_STRING.toString(((DateTimeType) state).getZonedDateTime()), time, - expireDays); + ZONED_DATE_TIME_CONVERTER_STRING.toString(dateType.getZonedDateTime()), time, expireDays); } else { throw new IllegalStateException( String.format("Unexpected state type %s with StringItem", state.getClass().getSimpleName())); @@ -411,8 +410,7 @@ public abstract class AbstractDynamoDBItem implements DynamoDBItem { if (numberState == null) { return null; } - if (item instanceof NumberItem) { - NumberItem numberItem = ((NumberItem) item); + if (item instanceof NumberItem numberItem) { Unit> unit = targetUnit == null ? numberItem.getUnit() : targetUnit; if (unit != null) { return new QuantityType<>(numberState, unit); diff --git a/bundles/org.openhab.persistence.dynamodb/src/main/java/org/openhab/persistence/dynamodb/internal/DynamoDBConfig.java b/bundles/org.openhab.persistence.dynamodb/src/main/java/org/openhab/persistence/dynamodb/internal/DynamoDBConfig.java index 75f22e425..dd186e2b9 100644 --- a/bundles/org.openhab.persistence.dynamodb/src/main/java/org/openhab/persistence/dynamodb/internal/DynamoDBConfig.java +++ b/bundles/org.openhab.persistence.dynamodb/src/main/java/org/openhab/persistence/dynamodb/internal/DynamoDBConfig.java @@ -93,8 +93,10 @@ public class DynamoDBConfig { String profile = (String) config.get("profile"); if (profilesConfigFile == null || profilesConfigFile.isBlank() || profile == null || profile.isBlank()) { - LOGGER.error("Specify either 1) accessKey and secretKey; or 2) profilesConfigFile and " - + "profile for providing AWS credentials"); + LOGGER.error(""" + Specify either 1) accessKey and secretKey; or 2) profilesConfigFile and \ + profile for providing AWS credentials\ + """); return null; } ProfileFile profileFile = ProfileFile.builder().content(Path.of(profilesConfigFile)) diff --git a/bundles/org.openhab.persistence.dynamodb/src/main/java/org/openhab/persistence/dynamodb/internal/DynamoDBPersistenceService.java b/bundles/org.openhab.persistence.dynamodb/src/main/java/org/openhab/persistence/dynamodb/internal/DynamoDBPersistenceService.java index 80bdaef00..dd8355acf 100644 --- a/bundles/org.openhab.persistence.dynamodb/src/main/java/org/openhab/persistence/dynamodb/internal/DynamoDBPersistenceService.java +++ b/bundles/org.openhab.persistence.dynamodb/src/main/java/org/openhab/persistence/dynamodb/internal/DynamoDBPersistenceService.java @@ -398,8 +398,8 @@ public class DynamoDBPersistenceService implements QueryablePersistenceService { logger.warn("Could not get item {} from registry! Returning empty query results.", itemName); return Collections.emptyList(); } - if (item instanceof GroupItem) { - item = ((GroupItem) item).getBaseItem(); + if (item instanceof GroupItem groupItem) { + item = groupItem.getBaseItem(); logger.debug("Item is instanceof GroupItem '{}'", itemName); if (item == null) { logger.debug("BaseItem of GroupItem is null. Ignore and give up!"); @@ -429,7 +429,7 @@ public class DynamoDBPersistenceService implements QueryablePersistenceService { // NumberItem.getUnit() is expensive, we avoid calling it in the loop // by fetching the unit here. final Item localItem = item; - final Unit itemUnit = localItem instanceof NumberItem ? ((NumberItem) localItem).getUnit() : null; + final Unit itemUnit = localItem instanceof NumberItem ni ? ni.getUnit() : null; try { @SuppressWarnings("null") List results = itemsFuture.get().stream().map(dynamoItem -> { @@ -584,15 +584,15 @@ public class DynamoDBPersistenceService implements QueryablePersistenceService { private Item getEffectiveItem(Item item) { final Item effectiveItem; - if (item instanceof GroupItem) { - Item baseItem = ((GroupItem) item).getBaseItem(); + if (item instanceof GroupItem groupItem) { + Item baseItem = groupItem.getBaseItem(); if (baseItem == null) { // if GroupItem: is not defined in // *.items using StringType logger.debug( "Cannot detect ItemType for {} because the GroupItems' base type isn't set in *.items File.", item.getName()); - Iterator firstGroupMemberItem = ((GroupItem) item).getMembers().iterator(); + Iterator firstGroupMemberItem = groupItem.getMembers().iterator(); if (firstGroupMemberItem.hasNext()) { effectiveItem = firstGroupMemberItem.next(); } else { @@ -640,10 +640,10 @@ public class DynamoDBPersistenceService implements QueryablePersistenceService { throw new IllegalArgumentException(item.toString(), e); } State state = stateOverride == null ? item.getState() : stateOverride; - if (state instanceof QuantityType && itemTemplate instanceof NumberItem) { - Unit itemUnit = ((NumberItem) itemTemplate).getUnit(); + if (state instanceof QuantityType type && itemTemplate instanceof NumberItem numberItem) { + Unit itemUnit = numberItem.getUnit(); if (itemUnit != null) { - State convertedState = ((QuantityType) state).toUnit(itemUnit); + State convertedState = type.toUnit(itemUnit); if (convertedState == null) { logger.error("Unexpected unit conversion failure: {} to item unit {}", state, itemUnit); throw new IllegalArgumentException( @@ -657,8 +657,7 @@ public class DynamoDBPersistenceService implements QueryablePersistenceService { } private void logIfManyQueuedTasks() { - if (executor instanceof ThreadPoolExecutor) { - ThreadPoolExecutor localExecutor = (ThreadPoolExecutor) executor; + if (executor instanceof ThreadPoolExecutor localExecutor) { if (localExecutor.getQueue().size() >= 5) { logger.trace("executor queue size: {}, remaining space {}. Active threads {}", localExecutor.getQueue().size(), localExecutor.getQueue().remainingCapacity(), diff --git a/bundles/org.openhab.persistence.dynamodb/src/test/java/org/openhab/persistence/dynamodb/internal/AbstractDynamoDBItemSerializationTest.java b/bundles/org.openhab.persistence.dynamodb/src/test/java/org/openhab/persistence/dynamodb/internal/AbstractDynamoDBItemSerializationTest.java index f301554ee..56b252811 100644 --- a/bundles/org.openhab.persistence.dynamodb/src/test/java/org/openhab/persistence/dynamodb/internal/AbstractDynamoDBItemSerializationTest.java +++ b/bundles/org.openhab.persistence.dynamodb/src/test/java/org/openhab/persistence/dynamodb/internal/AbstractDynamoDBItemSerializationTest.java @@ -82,8 +82,8 @@ public class AbstractDynamoDBItemSerializationTest { Object actualState = dbItem.getState(); assertNotNull(actualState); Objects.requireNonNull(actualState); - if (expectedState instanceof BigDecimal) { - BigDecimal expectedRounded = DynamoDBBigDecimalItem.loseDigits(((BigDecimal) expectedState)); + if (expectedState instanceof BigDecimal decimal) { + BigDecimal expectedRounded = DynamoDBBigDecimalItem.loseDigits(decimal); assertEquals(0, expectedRounded.compareTo((BigDecimal) actualState), String.format("Expected state %s (%s but with some digits lost) did not match actual state %s", expectedRounded, expectedState, actualState)); diff --git a/bundles/org.openhab.persistence.dynamodb/src/test/java/org/openhab/persistence/dynamodb/internal/DynamoDBConfigTest.java b/bundles/org.openhab.persistence.dynamodb/src/test/java/org/openhab/persistence/dynamodb/internal/DynamoDBConfigTest.java index b7862180a..7923ff488 100644 --- a/bundles/org.openhab.persistence.dynamodb/src/test/java/org/openhab/persistence/dynamodb/internal/DynamoDBConfigTest.java +++ b/bundles/org.openhab.persistence.dynamodb/src/test/java/org/openhab/persistence/dynamodb/internal/DynamoDBConfigTest.java @@ -60,12 +60,12 @@ public class DynamoDBConfigTest { @Test public void testInvalidRegion() throws Exception { - assertNull(DynamoDBConfig.fromConfig(Collections.singletonMap("region", "foobie"))); + assertNull(DynamoDBConfig.fromConfig(Map.of("region", "foobie"))); } @Test public void testRegionOnly() throws Exception { - assertNull(DynamoDBConfig.fromConfig(Collections.singletonMap("region", "eu-west-1"))); + assertNull(DynamoDBConfig.fromConfig(Map.of("region", "eu-west-1"))); } @Test @@ -87,10 +87,12 @@ public class DynamoDBConfigTest { @Test public void testRegionWithProfilesConfigFile() throws Exception { Path credsFile = Files.createFile(Paths.get(folder.getPath(), "creds")); - Files.write( - credsFile, ("[fooprofile]\n" + "aws_access_key_id=testAccessKey\n" - + "aws_secret_access_key=testSecretKey\n" + "aws_session_token=testSessionToken\n").getBytes(), - StandardOpenOption.TRUNCATE_EXISTING); + Files.write(credsFile, (""" + [fooprofile] + aws_access_key_id=testAccessKey + aws_secret_access_key=testSecretKey + aws_session_token=testSessionToken + """).getBytes(), StandardOpenOption.TRUNCATE_EXISTING); DynamoDBConfig fromConfig = DynamoDBConfig.fromConfig(mapFrom("region", "eu-west-1", "profilesConfigFile", credsFile.toAbsolutePath().toString(), "profile", "fooprofile")); @@ -107,10 +109,13 @@ public class DynamoDBConfigTest { @Test public void testProfilesConfigFileRetryMode() throws Exception { Path credsFile = Files.createFile(Paths.get(folder.getPath(), "creds")); - Files.write(credsFile, - ("[fooprofile]\n" + "aws_access_key_id=testAccessKey\n" + "aws_secret_access_key=testSecretKey\n" - + "aws_session_token=testSessionToken\n" + "retry_mode=legacy").getBytes(), - StandardOpenOption.TRUNCATE_EXISTING); + Files.write(credsFile, (""" + [fooprofile] + aws_access_key_id=testAccessKey + aws_secret_access_key=testSecretKey + aws_session_token=testSessionToken + retry_mode=legacy\ + """).getBytes(), StandardOpenOption.TRUNCATE_EXISTING); DynamoDBConfig fromConfig = DynamoDBConfig.fromConfig(mapFrom("region", "eu-west-1", "profilesConfigFile", credsFile.toAbsolutePath().toString(), "profile", "fooprofile")); @@ -131,10 +136,12 @@ public class DynamoDBConfigTest { @Test public void testRegionWithInvalidProfilesConfigFile() throws Exception { Path credsFile = Files.createFile(Paths.get(folder.getPath(), "creds")); - Files.write(credsFile, - ("[fooprofile]\n" + "aws_access_key_idINVALIDKEY=testAccessKey\n" - + "aws_secret_access_key=testSecretKey\n" + "aws_session_token=testSessionToken\n").getBytes(), - StandardOpenOption.TRUNCATE_EXISTING); + Files.write(credsFile, (""" + [fooprofile] + aws_access_key_idINVALIDKEY=testAccessKey + aws_secret_access_key=testSecretKey + aws_session_token=testSessionToken + """).getBytes(), StandardOpenOption.TRUNCATE_EXISTING); assertNull(DynamoDBConfig.fromConfig(mapFrom("region", "eu-west-1", "profilesConfigFile", credsFile.toFile().getAbsolutePath(), "profile", "fooprofile"))); @@ -143,10 +150,12 @@ public class DynamoDBConfigTest { @Test public void testRegionWithProfilesConfigFileMissingProfile() throws Exception { Path credsFile = Files.createFile(Paths.get(folder.getPath(), "creds")); - Files.write( - credsFile, ("[fooprofile]\n" + "aws_access_key_id=testAccessKey\n" - + "aws_secret_access_key=testSecretKey\n" + "aws_session_token=testSessionToken\n").getBytes(), - StandardOpenOption.TRUNCATE_EXISTING); + Files.write(credsFile, (""" + [fooprofile] + aws_access_key_id=testAccessKey + aws_secret_access_key=testSecretKey + aws_session_token=testSessionToken + """).getBytes(), StandardOpenOption.TRUNCATE_EXISTING); assertNull(DynamoDBConfig.fromConfig( mapFrom("region", "eu-west-1", "profilesConfigFile", credsFile.toAbsolutePath().toString()))); diff --git a/bundles/org.openhab.persistence.influxdb/src/main/java/org/openhab/persistence/influxdb/internal/InfluxDBStateConvertUtils.java b/bundles/org.openhab.persistence.influxdb/src/main/java/org/openhab/persistence/influxdb/internal/InfluxDBStateConvertUtils.java index d9ce0749a..82d45b12e 100644 --- a/bundles/org.openhab.persistence.influxdb/src/main/java/org/openhab/persistence/influxdb/internal/InfluxDBStateConvertUtils.java +++ b/bundles/org.openhab.persistence.influxdb/src/main/java/org/openhab/persistence/influxdb/internal/InfluxDBStateConvertUtils.java @@ -70,16 +70,16 @@ public class InfluxDBStateConvertUtils { value = state.toString(); } else if (state instanceof PointType) { value = state.toString(); - } else if (state instanceof DecimalType) { - value = ((DecimalType) state).toBigDecimal(); - } else if (state instanceof QuantityType) { - value = ((QuantityType) state).toBigDecimal(); + } else if (state instanceof DecimalType type) { + value = type.toBigDecimal(); + } else if (state instanceof QuantityType type) { + value = type.toBigDecimal(); } else if (state instanceof OnOffType) { value = state == OnOffType.ON ? DIGITAL_VALUE_ON : DIGITAL_VALUE_OFF; } else if (state instanceof OpenClosedType) { value = state == OpenClosedType.OPEN ? DIGITAL_VALUE_ON : DIGITAL_VALUE_OFF; - } else if (state instanceof DateTimeType) { - value = ((DateTimeType) state).getZonedDateTime().toInstant().toEpochMilli(); + } else if (state instanceof DateTimeType type) { + value = type.getZonedDateTime().toInstant().toEpochMilli(); } else { value = state.toString(); } @@ -111,8 +111,8 @@ public class InfluxDBStateConvertUtils { @Nullable Item item = itemToSetState; - if (item instanceof GroupItem) { - item = ((GroupItem) item).getBaseItem(); + if (item instanceof GroupItem groupItem) { + item = groupItem.getBaseItem(); } if (item instanceof ColorItem) { return new HSBType(valueStr); @@ -143,8 +143,8 @@ public class InfluxDBStateConvertUtils { } private static boolean toBoolean(@Nullable Object object) { - if (object instanceof Boolean) { - return (Boolean) object; + if (object instanceof Boolean boolean1) { + return boolean1; } else if (object != null) { if ("1".equals(object) || "1.0".equals(object)) { return true; diff --git a/bundles/org.openhab.persistence.influxdb/src/main/java/org/openhab/persistence/influxdb/internal/influx1/InfluxDB1RepositoryImpl.java b/bundles/org.openhab.persistence.influxdb/src/main/java/org/openhab/persistence/influxdb/internal/influx1/InfluxDB1RepositoryImpl.java index 9449bbdac..fabae1449 100644 --- a/bundles/org.openhab.persistence.influxdb/src/main/java/org/openhab/persistence/influxdb/internal/influx1/InfluxDB1RepositoryImpl.java +++ b/bundles/org.openhab.persistence.influxdb/src/main/java/org/openhab/persistence/influxdb/internal/influx1/InfluxDB1RepositoryImpl.java @@ -148,12 +148,12 @@ public class InfluxDB1RepositoryImpl implements InfluxDBRepository { Point.Builder clientPoint = Point.measurement(point.getMeasurementName()).time(point.getTime().toEpochMilli(), TimeUnit.MILLISECONDS); Object value = point.getValue(); - if (value instanceof String) { - clientPoint.addField(FIELD_VALUE_NAME, (String) value); - } else if (value instanceof Number) { - clientPoint.addField(FIELD_VALUE_NAME, (Number) value); - } else if (value instanceof Boolean) { - clientPoint.addField(FIELD_VALUE_NAME, (Boolean) value); + if (value instanceof String string) { + clientPoint.addField(FIELD_VALUE_NAME, string); + } else if (value instanceof Number number) { + clientPoint.addField(FIELD_VALUE_NAME, number); + } else if (value instanceof Boolean boolean1) { + clientPoint.addField(FIELD_VALUE_NAME, boolean1); } else if (value == null) { clientPoint.addField(FIELD_VALUE_NAME, "null"); } else { diff --git a/bundles/org.openhab.persistence.influxdb/src/main/java/org/openhab/persistence/influxdb/internal/influx2/InfluxDB2RepositoryImpl.java b/bundles/org.openhab.persistence.influxdb/src/main/java/org/openhab/persistence/influxdb/internal/influx2/InfluxDB2RepositoryImpl.java index 0b21da6b1..862ecf4c2 100644 --- a/bundles/org.openhab.persistence.influxdb/src/main/java/org/openhab/persistence/influxdb/internal/influx2/InfluxDB2RepositoryImpl.java +++ b/bundles/org.openhab.persistence.influxdb/src/main/java/org/openhab/persistence/influxdb/internal/influx2/InfluxDB2RepositoryImpl.java @@ -186,12 +186,12 @@ public class InfluxDB2RepositoryImpl implements InfluxDBRepository { Point clientPoint = Point.measurement(point.getMeasurementName()).time(point.getTime(), WritePrecision.MS); @Nullable Object value = point.getValue(); - if (value instanceof String) { - clientPoint.addField(FIELD_VALUE_NAME, (String) value); - } else if (value instanceof Number) { - clientPoint.addField(FIELD_VALUE_NAME, (Number) value); - } else if (value instanceof Boolean) { - clientPoint.addField(FIELD_VALUE_NAME, (Boolean) value); + if (value instanceof String string) { + clientPoint.addField(FIELD_VALUE_NAME, string); + } else if (value instanceof Number number) { + clientPoint.addField(FIELD_VALUE_NAME, number); + } else if (value instanceof Boolean boolean1) { + clientPoint.addField(FIELD_VALUE_NAME, boolean1); } else if (value == null) { clientPoint.addField(FIELD_VALUE_NAME, (String) null); } else { diff --git a/bundles/org.openhab.persistence.jdbc/src/main/java/org/openhab/persistence/jdbc/internal/console/JdbcCommandExtension.java b/bundles/org.openhab.persistence.jdbc/src/main/java/org/openhab/persistence/jdbc/internal/console/JdbcCommandExtension.java index c92dbd495..4d4c6213a 100644 --- a/bundles/org.openhab.persistence.jdbc/src/main/java/org/openhab/persistence/jdbc/internal/console/JdbcCommandExtension.java +++ b/bundles/org.openhab.persistence.jdbc/src/main/java/org/openhab/persistence/jdbc/internal/console/JdbcCommandExtension.java @@ -94,8 +94,8 @@ public class JdbcCommandExtension extends AbstractConsoleCommandExtension implem private @Nullable JdbcPersistenceService getPersistenceService() { for (PersistenceService persistenceService : persistenceServiceRegistry.getAll()) { - if (persistenceService instanceof JdbcPersistenceService) { - return (JdbcPersistenceService) persistenceService; + if (persistenceService instanceof JdbcPersistenceService service) { + return service; } } return null; diff --git a/bundles/org.openhab.persistence.jdbc/src/main/java/org/openhab/persistence/jdbc/internal/db/JdbcDerbyDAO.java b/bundles/org.openhab.persistence.jdbc/src/main/java/org/openhab/persistence/jdbc/internal/db/JdbcDerbyDAO.java index 10045d1ed..3fba01c51 100644 --- a/bundles/org.openhab.persistence.jdbc/src/main/java/org/openhab/persistence/jdbc/internal/db/JdbcDerbyDAO.java +++ b/bundles/org.openhab.persistence.jdbc/src/main/java/org/openhab/persistence/jdbc/internal/db/JdbcDerbyDAO.java @@ -223,7 +223,7 @@ public class JdbcDerbyDAO extends JdbcBaseDAO { logger.debug("JDBC::doGetHistItemFilterQuery got Array length={}", m.size()); // we already retrieve the unit here once as it is a very costly operation String itemName = item.getName(); - Unit> unit = item instanceof NumberItem ? ((NumberItem) item).getUnit() : null; + Unit> unit = item instanceof NumberItem ni ? ni.getUnit() : null; return m.stream().map(o -> { logger.debug("JDBC::doGetHistItemFilterQuery 0='{}' 1='{}'", o[0], o[1]); return new JdbcHistoricItem(itemName, objectAsState(item, unit, o[1]), objectAsZonedDateTime(o[0])); diff --git a/bundles/org.openhab.persistence.jdbc/src/main/java/org/openhab/persistence/jdbc/internal/db/JdbcHsqldbDAO.java b/bundles/org.openhab.persistence.jdbc/src/main/java/org/openhab/persistence/jdbc/internal/db/JdbcHsqldbDAO.java index 01a71ec52..7be7e5c44 100644 --- a/bundles/org.openhab.persistence.jdbc/src/main/java/org/openhab/persistence/jdbc/internal/db/JdbcHsqldbDAO.java +++ b/bundles/org.openhab.persistence.jdbc/src/main/java/org/openhab/persistence/jdbc/internal/db/JdbcHsqldbDAO.java @@ -62,9 +62,11 @@ public class JdbcHsqldbDAO extends JdbcBaseDAO { // Prevent error against duplicate time value // http://hsqldb.org/doc/guide/dataaccess-chapt.html#dac_merge_statement // SQL_INSERT_ITEM_VALUE = "INSERT INTO #tableName# (TIME, VALUE) VALUES( NOW(), CAST( ? as #dbType#) )"; - sqlInsertItemValue = "MERGE INTO #tableName# " - + "USING (VALUES #tablePrimaryValue#, CAST( ? as #dbType#)) temp (TIME, VALUE) ON (#tableName#.TIME=temp.TIME) " - + "WHEN NOT MATCHED THEN INSERT (TIME, VALUE) VALUES (temp.TIME, temp.VALUE)"; + sqlInsertItemValue = """ + MERGE INTO #tableName# \ + USING (VALUES #tablePrimaryValue#, CAST( ? as #dbType#)) temp (TIME, VALUE) ON (#tableName#.TIME=temp.TIME) \ + WHEN NOT MATCHED THEN INSERT (TIME, VALUE) VALUES (temp.TIME, temp.VALUE)\ + """; } /** diff --git a/bundles/org.openhab.persistence.jdbc/src/main/java/org/openhab/persistence/jdbc/internal/db/JdbcPostgresqlDAO.java b/bundles/org.openhab.persistence.jdbc/src/main/java/org/openhab/persistence/jdbc/internal/db/JdbcPostgresqlDAO.java index 8add63026..155f7c209 100644 --- a/bundles/org.openhab.persistence.jdbc/src/main/java/org/openhab/persistence/jdbc/internal/db/JdbcPostgresqlDAO.java +++ b/bundles/org.openhab.persistence.jdbc/src/main/java/org/openhab/persistence/jdbc/internal/db/JdbcPostgresqlDAO.java @@ -63,14 +63,18 @@ public class JdbcPostgresqlDAO extends JdbcBaseDAO { sqlIfTableExists = "SELECT * FROM PG_TABLES WHERE TABLENAME='#searchTable#'"; sqlCreateItemsTableIfNot = "CREATE TABLE IF NOT EXISTS #itemsManageTable# (itemid SERIAL NOT NULL, #colname# #coltype# NOT NULL, CONSTRAINT #itemsManageTable#_pkey PRIMARY KEY (itemid))"; sqlCreateNewEntryInItemsTable = "INSERT INTO items (itemname) SELECT itemname FROM #itemsManageTable# UNION VALUES ('#itemname#') EXCEPT SELECT itemname FROM items"; - sqlGetItemTables = "SELECT table_name FROM information_schema.tables WHERE table_type='BASE TABLE' AND table_schema=(SELECT table_schema " - + "FROM information_schema.tables WHERE table_type='BASE TABLE' AND table_name='#itemsManageTable#') AND NOT table_name='#itemsManageTable#'"; + sqlGetItemTables = """ + SELECT table_name FROM information_schema.tables WHERE table_type='BASE TABLE' AND table_schema=(SELECT table_schema \ + FROM information_schema.tables WHERE table_type='BASE TABLE' AND table_name='#itemsManageTable#') AND NOT table_name='#itemsManageTable#'\ + """; // The PostgreSQL equivalent to MySQL columns.column_type is data_type (e.g. "timestamp with time zone") and // udt_name which contains a shorter alias (e.g. "timestamptz"). We alias data_type as "column_type" and // udt_name as "column_type_alias" to be compatible with the 'Column' class used in Yank.queryBeanList - sqlGetTableColumnTypes = "SELECT column_name, data_type as column_type, udt_name as column_type_alias, is_nullable FROM information_schema.columns " - + "WHERE table_name='#tableName#' AND table_catalog='#jdbcUriDatabaseName#' AND table_schema=(SELECT table_schema FROM information_schema.tables WHERE table_type='BASE TABLE' " - + "AND table_name='#itemsManageTable#')"; + sqlGetTableColumnTypes = """ + SELECT column_name, data_type as column_type, udt_name as column_type_alias, is_nullable FROM information_schema.columns \ + WHERE table_name='#tableName#' AND table_catalog='#jdbcUriDatabaseName#' AND table_schema=(SELECT table_schema FROM information_schema.tables WHERE table_type='BASE TABLE' \ + AND table_name='#itemsManageTable#')\ + """; // NOTICE: on PostgreSql >= 9.5, sqlInsertItemValue query template is modified to do an "upsert" (overwrite // existing value). The version check and query change is performed at initAfterFirstDbConnection() sqlInsertItemValue = "INSERT INTO #tableName# (TIME, VALUE) VALUES( #tablePrimaryValue#, CAST( ? as #dbType#) )"; @@ -87,8 +91,10 @@ public class JdbcPostgresqlDAO extends JdbcBaseDAO { // see: https://www.postgresql.org/docs/9.5/sql-insert.html if (dbMeta.isDbVersionGreater(9, 4)) { logger.debug("JDBC::initAfterFirstDbConnection: Values with the same time will be upserted (Pg >= 9.5)"); - sqlInsertItemValue = "INSERT INTO #tableName# (TIME, VALUE) VALUES( #tablePrimaryValue#, CAST( ? as #dbType#) )" - + " ON CONFLICT (TIME) DO UPDATE SET VALUE=EXCLUDED.VALUE"; + sqlInsertItemValue = """ + INSERT INTO #tableName# (TIME, VALUE) VALUES( #tablePrimaryValue#, CAST( ? as #dbType#) )\ + ON CONFLICT (TIME) DO UPDATE SET VALUE=EXCLUDED.VALUE\ + """; } } diff --git a/bundles/org.openhab.persistence.jpa/src/main/java/org/openhab/persistence/jpa/internal/StateHelper.java b/bundles/org.openhab.persistence.jpa/src/main/java/org/openhab/persistence/jpa/internal/StateHelper.java index dd91385d6..e10139f0e 100644 --- a/bundles/org.openhab.persistence.jpa/src/main/java/org/openhab/persistence/jpa/internal/StateHelper.java +++ b/bundles/org.openhab.persistence.jpa/src/main/java/org/openhab/persistence/jpa/internal/StateHelper.java @@ -36,14 +36,13 @@ public class StateHelper { * @return state converted as string */ public static String toString(State state) { - if (state instanceof DateTimeType) { - return String.valueOf(((DateTimeType) state).getZonedDateTime().toInstant().toEpochMilli()); + if (state instanceof DateTimeType type) { + return String.valueOf(type.getZonedDateTime().toInstant().toEpochMilli()); } - if (state instanceof DecimalType) { - return String.valueOf(((DecimalType) state).doubleValue()); + if (state instanceof DecimalType type) { + return String.valueOf(type.doubleValue()); } - if (state instanceof PointType) { - PointType pType = (PointType) state; + if (state instanceof PointType pType) { return String.format(Locale.ENGLISH, "%f;%f;%f", pType.getLatitude().doubleValue(), pType.getLongitude().doubleValue(), pType.getAltitude().doubleValue()); } diff --git a/bundles/org.openhab.persistence.mapdb/src/main/java/org/openhab/persistence/mapdb/internal/MapDbPersistenceService.java b/bundles/org.openhab.persistence.mapdb/src/main/java/org/openhab/persistence/mapdb/internal/MapDbPersistenceService.java index 336e4039c..70d3cb105 100644 --- a/bundles/org.openhab.persistence.mapdb/src/main/java/org/openhab/persistence/mapdb/internal/MapDbPersistenceService.java +++ b/bundles/org.openhab.persistence.mapdb/src/main/java/org/openhab/persistence/mapdb/internal/MapDbPersistenceService.java @@ -101,8 +101,7 @@ public class MapDbPersistenceService implements QueryablePersistenceService { map = db.createTreeMap("itemStore").makeOrGet(); } catch (RuntimeException re) { Throwable cause = re.getCause(); - if (cause instanceof ClassNotFoundException) { - ClassNotFoundException cnf = (ClassNotFoundException) cause; + if (cause instanceof ClassNotFoundException cnf) { logger.warn( "The MapDB in {} is incompatible with openHAB {}: {}. A new and empty MapDB will be used instead.", dbFile, OpenHAB.getVersion(), cnf.getMessage()); diff --git a/bundles/org.openhab.persistence.mongodb/src/main/java/org/openhab/persistence/mongodb/internal/MongoDBPersistenceService.java b/bundles/org.openhab.persistence.mongodb/src/main/java/org/openhab/persistence/mongodb/internal/MongoDBPersistenceService.java index 638e65115..f683b5e1e 100644 --- a/bundles/org.openhab.persistence.mongodb/src/main/java/org/openhab/persistence/mongodb/internal/MongoDBPersistenceService.java +++ b/bundles/org.openhab.persistence.mongodb/src/main/java/org/openhab/persistence/mongodb/internal/MongoDBPersistenceService.java @@ -199,12 +199,12 @@ public class MongoDBPersistenceService implements QueryablePersistenceService { private Object convertValue(State state) { Object value; - if (state instanceof PercentType) { - value = ((PercentType) state).toBigDecimal().doubleValue(); - } else if (state instanceof DateTimeType) { - value = Date.from(((DateTimeType) state).getZonedDateTime().toInstant()); - } else if (state instanceof DecimalType) { - value = ((DecimalType) state).toBigDecimal().doubleValue(); + if (state instanceof PercentType type) { + value = type.toBigDecimal().doubleValue(); + } else if (state instanceof DateTimeType type) { + value = Date.from(type.getZonedDateTime().toInstant()); + } else if (state instanceof DecimalType type) { + value = type.toBigDecimal().doubleValue(); } else { value = state.toString(); } diff --git a/bundles/org.openhab.persistence.rrd4j/src/main/java/org/openhab/persistence/rrd4j/internal/RRD4jPersistenceService.java b/bundles/org.openhab.persistence.rrd4j/src/main/java/org/openhab/persistence/rrd4j/internal/RRD4jPersistenceService.java index 7c1b3008f..8cc9b5688 100644 --- a/bundles/org.openhab.persistence.rrd4j/src/main/java/org/openhab/persistence/rrd4j/internal/RRD4jPersistenceService.java +++ b/bundles/org.openhab.persistence.rrd4j/src/main/java/org/openhab/persistence/rrd4j/internal/RRD4jPersistenceService.java @@ -209,8 +209,7 @@ public class RRD4jPersistenceService implements QueryablePersistenceService { } Object v = config.get(key); - if (v instanceof String) { - String value = (String) v; + if (v instanceof String value) { String name = subkeys[0].toLowerCase(); String property = subkeys[1].toLowerCase(); @@ -430,10 +429,10 @@ public class RRD4jPersistenceService implements QueryablePersistenceService { Unit unit = null; try { item = itemRegistry.getItem(itemName); - if (item instanceof NumberItem) { + if (item instanceof NumberItem numberItem) { // we already retrieve the unit here once as it is a very costly operation, // see https://github.com/openhab/openhab-addons/issues/8928 - unit = ((NumberItem) item).getUnit(); + unit = numberItem.getUnit(); } } catch (ItemNotFoundException e) { logger.debug("Could not find item '{}' in registry", itemName); @@ -566,8 +565,7 @@ public class RRD4jPersistenceService implements QueryablePersistenceService { if (!isSupportedItemType(item)) { return null; } - if (item instanceof NumberItem) { - NumberItem numberItem = (NumberItem) item; + if (item instanceof NumberItem numberItem) { useRdc = numberItem.getDimension() != null ? rrdDefs.get(DEFAULT_QUANTIFIABLE) : rrdDefs.get(DEFAULT_NUMERIC); } else { @@ -608,8 +606,8 @@ public class RRD4jPersistenceService implements QueryablePersistenceService { @SuppressWarnings({ "unchecked", "rawtypes" }) private State mapToState(double value, @Nullable Item item, @Nullable Unit unit) { - if (item instanceof GroupItem) { - item = ((GroupItem) item).getBaseItem(); + if (item instanceof GroupItem groupItem) { + item = groupItem.getBaseItem(); } if (item instanceof SwitchItem && !(item instanceof DimmerItem)) { @@ -628,8 +626,8 @@ public class RRD4jPersistenceService implements QueryablePersistenceService { } private boolean isSupportedItemType(Item item) { - if (item instanceof GroupItem) { - final Item baseItem = ((GroupItem) item).getBaseItem(); + if (item instanceof GroupItem groupItem) { + final Item baseItem = groupItem.getBaseItem(); if (baseItem != null) { item = baseItem; } diff --git a/bundles/org.openhab.persistence.rrd4j/src/main/java/org/openhab/persistence/rrd4j/internal/charts/RRD4jChartServlet.java b/bundles/org.openhab.persistence.rrd4j/src/main/java/org/openhab/persistence/rrd4j/internal/charts/RRD4jChartServlet.java index 442bd0cce..2118cff5e 100644 --- a/bundles/org.openhab.persistence.rrd4j/src/main/java/org/openhab/persistence/rrd4j/internal/charts/RRD4jChartServlet.java +++ b/bundles/org.openhab.persistence.rrd4j/src/main/java/org/openhab/persistence/rrd4j/internal/charts/RRD4jChartServlet.java @@ -267,8 +267,7 @@ public class RRD4jChartServlet implements Servlet, ChartProvider { String[] groupNames = groups.split(","); for (String groupName : groupNames) { Item item = itemUIRegistry.getItem(groupName); - if (item instanceof GroupItem) { - GroupItem groupItem = (GroupItem) item; + if (item instanceof GroupItem groupItem) { for (Item member : groupItem.getMembers()) { addLine(graphDef, member, seriesCounter++); } diff --git a/bundles/org.openhab.persistence.rrd4j/src/main/java/org/openhab/persistence/rrd4j/internal/console/RRD4jCommandExtension.java b/bundles/org.openhab.persistence.rrd4j/src/main/java/org/openhab/persistence/rrd4j/internal/console/RRD4jCommandExtension.java index 16d0c6bc3..bad9c4e07 100644 --- a/bundles/org.openhab.persistence.rrd4j/src/main/java/org/openhab/persistence/rrd4j/internal/console/RRD4jCommandExtension.java +++ b/bundles/org.openhab.persistence.rrd4j/src/main/java/org/openhab/persistence/rrd4j/internal/console/RRD4jCommandExtension.java @@ -87,8 +87,8 @@ public class RRD4jCommandExtension extends AbstractConsoleCommandExtension imple private @Nullable RRD4jPersistenceService getPersistenceService() { for (PersistenceService persistenceService : persistenceServiceRegistry.getAll()) { - if (persistenceService instanceof RRD4jPersistenceService) { - return (RRD4jPersistenceService) persistenceService; + if (persistenceService instanceof RRD4jPersistenceService service) { + return service; } } return null;