[persistence] Use Java 17 features (#15486)

Signed-off-by: Holger Friedrich <mail@holger-friedrich.de>
This commit is contained in:
Holger Friedrich
2023-08-26 08:56:27 +02:00
committed by GitHub
parent 5b42c4b071
commit 1cf57e7dfe
18 changed files with 118 additions and 107 deletions

View File

@@ -302,8 +302,8 @@ public abstract class AbstractDynamoDBItem<T> implements DynamoDBItem<T> {
} 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<T> implements DynamoDBItem<T> {
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<T> implements DynamoDBItem<T> {
// 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<T> implements DynamoDBItem<T> {
if (numberState == null) {
return null;
}
if (item instanceof NumberItem) {
NumberItem numberItem = ((NumberItem) item);
if (item instanceof NumberItem numberItem) {
Unit<? extends Quantity<?>> unit = targetUnit == null ? numberItem.getUnit() : targetUnit;
if (unit != null) {
return new QuantityType<>(numberState, unit);

View File

@@ -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))

View File

@@ -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<HistoricItem> 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:<ItemType> 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<Item> firstGroupMemberItem = ((GroupItem) item).getMembers().iterator();
Iterator<Item> 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(),

View File

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

View File

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