Code cleanup: Use Java17 features (#3508)

Signed-off-by: Holger Friedrich <mail@holger-friedrich.de>
This commit is contained in:
Holger Friedrich
2023-04-01 09:51:12 +02:00
committed by GitHub
parent 003635dbfa
commit 74052e7bcd
41 changed files with 168 additions and 212 deletions
@@ -231,7 +231,7 @@ public class ExpiringCacheMap<K, V> {
* Invalidates all values in the cache.
*/
public synchronized void invalidateAll() {
items.values().forEach(item -> item.invalidateValue());
items.values().forEach(ExpiringCache::invalidateValue);
}
/**
@@ -96,9 +96,9 @@ public class ThreadPoolManager {
if (config == null) {
configs.remove(poolName);
}
if (config instanceof String) {
if (config instanceof String string) {
try {
Integer poolSize = Integer.valueOf((String) config);
Integer poolSize = Integer.valueOf(string);
configs.put(poolName, poolSize);
ThreadPoolExecutor pool = (ThreadPoolExecutor) pools.get(poolName);
if (pool instanceof ScheduledThreadPoolExecutor) {
@@ -142,8 +142,8 @@ public class ThreadPoolManager {
}
}
}
if (pool instanceof ScheduledExecutorService) {
return new UnstoppableScheduledExecutorService(poolName, (ScheduledExecutorService) pool);
if (pool instanceof ScheduledExecutorService service) {
return new UnstoppableScheduledExecutorService(poolName, service);
} else {
throw new IllegalArgumentException("Pool " + poolName + " is not a scheduled pool!");
}
@@ -36,7 +36,7 @@ public abstract class AbstractProvider<@NonNull E> implements Provider<E> {
private enum EventType {
ADDED,
REMOVED,
UPDATED;
UPDATED
}
protected final Logger logger = LoggerFactory.getLogger(AbstractProvider.class);
@@ -63,7 +63,7 @@ public abstract class AbstractRegistry<@NonNull E extends Identifiable<K>, @NonN
private enum EventType {
ADDED,
REMOVED,
UPDATED;
UPDATED
}
private final Logger logger = LoggerFactory.getLogger(AbstractRegistry.class);
@@ -65,9 +65,6 @@ public class LocalizedKey {
if (!Objects.equals(key, other.key)) {
return false;
}
if (!Objects.equals(locale, other.locale)) {
return false;
}
return true;
return Objects.equals(locale, other.locale);
}
}
@@ -133,8 +133,7 @@ public class UserRegistryImpl extends AbstractRegistry<User, String, UserProvide
@Override
public Authentication authenticate(Credentials credentials) throws AuthenticationException {
if (credentials instanceof UsernamePasswordCredentials) {
UsernamePasswordCredentials usernamePasswordCreds = (UsernamePasswordCredentials) credentials;
if (credentials instanceof UsernamePasswordCredentials usernamePasswordCreds) {
User user = get(usernamePasswordCreds.getUsername());
if (user == null) {
throw new AuthenticationException("User not found: " + usernamePasswordCreds.getUsername());
@@ -148,8 +147,7 @@ public class UserRegistryImpl extends AbstractRegistry<User, String, UserProvide
}
return new Authentication(managedUser.getName(), managedUser.getRoles().stream().toArray(String[]::new));
} else if (credentials instanceof UserApiTokenCredentials) {
UserApiTokenCredentials apiTokenCreds = (UserApiTokenCredentials) credentials;
} else if (credentials instanceof UserApiTokenCredentials apiTokenCreds) {
String[] apiTokenParts = apiTokenCreds.getApiToken().split("\\.");
if (apiTokenParts.length != 3 || !APITOKEN_PREFIX.equals(apiTokenParts[0])) {
throw new AuthenticationException("Invalid API token format");
@@ -88,10 +88,10 @@ abstract class AbstractInvocationHandler<T> {
void handleExecutionException(Method method, ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof DuplicateExecutionException) {
handleDuplicate(method, (DuplicateExecutionException) cause);
} else if (cause instanceof InvocationTargetException) {
handleException(method, (InvocationTargetException) cause);
if (cause instanceof DuplicateExecutionException exception) {
handleDuplicate(method, exception);
} else if (cause instanceof InvocationTargetException exception) {
handleException(method, exception);
}
}
@@ -43,8 +43,7 @@ public class WrappedScheduledExecutorService extends ScheduledThreadPoolExecutor
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
Throwable actualThrowable = t;
if (actualThrowable == null && r instanceof Future<?>) {
Future<?> f = (Future<?>) r;
if (actualThrowable == null && r instanceof Future<?> f) {
// The Future is the wrapper task around our scheduled Runnable. This is only "done" if an Exception
// occurred, the Task was completed, or aborted. A periodic Task (scheduleWithFixedDelay etc.) is NEVER
@@ -75,11 +75,9 @@ public class EventHandler implements AutoCloseable {
Object topicObj = osgiEvent.getProperty("topic");
Object sourceObj = osgiEvent.getProperty("source");
if (typeObj instanceof String && payloadObj instanceof String && topicObj instanceof String) {
String typeStr = (String) typeObj;
String payloadStr = (String) payloadObj;
String topicStr = (String) topicObj;
String sourceStr = (sourceObj instanceof String) ? (String) sourceObj : null;
if (typeObj instanceof String typeStr && payloadObj instanceof String payloadStr
&& topicObj instanceof String topicStr) {
String sourceStr = (sourceObj instanceof String s) ? s : null;
if (!typeStr.isEmpty() && !payloadStr.isEmpty() && !topicStr.isEmpty()) {
handleEvent(typeStr, payloadStr, topicStr, sourceStr);
}
@@ -242,18 +242,15 @@ public class ExpireManager implements EventSubscriber, RegistryChangeListener<It
return;
}
if (event instanceof ItemStateEvent) {
ItemStateEvent isEvent = (ItemStateEvent) event;
if (event instanceof ItemStateEvent isEvent) {
if (!expireConfig.ignoreStateUpdates) {
processEvent(itemName, isEvent.getItemState(), expireConfig, event.getClass());
}
} else if (event instanceof ItemCommandEvent) {
ItemCommandEvent icEvent = (ItemCommandEvent) event;
} else if (event instanceof ItemCommandEvent icEvent) {
if (!expireConfig.ignoreCommands) {
processEvent(itemName, icEvent.getItemCommand(), expireConfig, event.getClass());
}
} else if (event instanceof ItemStateChangedEvent) {
ItemStateChangedEvent icEvent = (ItemStateChangedEvent) event;
} else if (event instanceof ItemStateChangedEvent icEvent) {
processEvent(itemName, icEvent.getItemState(), expireConfig, event.getClass());
}
}
@@ -386,10 +383,10 @@ public class ExpireManager implements EventSubscriber, RegistryChangeListener<It
private boolean getBooleanConfigValue(Map<String, Object> configuration, String configKey) {
boolean configValue;
Object configValueObject = configuration.get(configKey);
if (configValueObject instanceof String) {
configValue = Boolean.parseBoolean((String) configValueObject);
} else if (configValueObject instanceof Boolean) {
configValue = (Boolean) configValueObject;
if (configValueObject instanceof String string) {
configValue = Boolean.parseBoolean(string);
} else if (configValueObject instanceof Boolean boolean1) {
configValue = boolean1;
} else {
configValue = false;
}
@@ -55,9 +55,9 @@ public class ItemBuilderImpl implements ItemBuilder {
this.groups = item.getGroupNames();
this.label = item.getLabel();
this.tags = item.getTags();
if (item instanceof GroupItem) {
this.baseItem = ((GroupItem) item).getBaseItem();
this.groupFunction = ((GroupItem) item).getFunction();
if (item instanceof GroupItem groupItem) {
this.baseItem = groupItem.getBaseItem();
this.groupFunction = groupItem.getFunction();
}
}
@@ -129,8 +129,7 @@ public class ItemBuilderImpl implements ItemBuilder {
if (item == null) {
throw new IllegalStateException("No item factory could handle type " + itemType);
}
if (item instanceof ActiveItem) {
ActiveItem activeItem = (ActiveItem) item;
if (item instanceof ActiveItem activeItem) {
activeItem.setLabel(label);
activeItem.setCategory(category);
activeItem.addGroupNames(groups);
@@ -147,8 +147,8 @@ public class ItemRegistryImpl extends AbstractRegistry<Item, String, ItemProvide
if (groupName != null) {
try {
Item groupItem = getItem(groupName);
if (groupItem instanceof GroupItem) {
((GroupItem) groupItem).addMember(item);
if (groupItem instanceof GroupItem groupItem1) {
groupItem1.addMember(item);
}
} catch (ItemNotFoundException e) {
// the group might not yet be registered, let's ignore this
@@ -162,8 +162,8 @@ public class ItemRegistryImpl extends AbstractRegistry<Item, String, ItemProvide
if (groupName != null) {
try {
Item groupItem = getItem(groupName);
if (groupItem instanceof GroupItem) {
((GroupItem) groupItem).replaceMember(oldItem, newItem);
if (groupItem instanceof GroupItem item) {
item.replaceMember(oldItem, newItem);
}
} catch (ItemNotFoundException e) {
// the group might not yet be registered, let's ignore this
@@ -185,9 +185,9 @@ public class ItemRegistryImpl extends AbstractRegistry<Item, String, ItemProvide
injectServices(item);
if (item instanceof GroupItem) {
if (item instanceof GroupItem groupItem) {
// fill group with its members
addMembersToGroupItem((GroupItem) item);
addMembersToGroupItem(groupItem);
}
// add the item to all relevant groups
@@ -195,8 +195,7 @@ public class ItemRegistryImpl extends AbstractRegistry<Item, String, ItemProvide
}
private void injectServices(Item item) {
if (item instanceof GenericItem) {
GenericItem genericItem = (GenericItem) item;
if (item instanceof GenericItem genericItem) {
genericItem.setEventPublisher(getEventPublisher());
genericItem.setStateDescriptionService(stateDescriptionService);
genericItem.setCommandDescriptionService(commandDescriptionService);
@@ -218,8 +217,8 @@ public class ItemRegistryImpl extends AbstractRegistry<Item, String, ItemProvide
if (groupName != null) {
try {
Item groupItem = getItem(groupName);
if (groupItem instanceof GroupItem) {
((GroupItem) groupItem).removeMember(item);
if (groupItem instanceof GroupItem groupItem1) {
groupItem1.removeMember(item);
}
} catch (ItemNotFoundException e) {
// the group might not yet be registered, let's ignore this
@@ -235,16 +234,16 @@ public class ItemRegistryImpl extends AbstractRegistry<Item, String, ItemProvide
@Override
protected void onRemoveElement(Item element) {
if (element instanceof GenericItem) {
((GenericItem) element).dispose();
if (element instanceof GenericItem item) {
item.dispose();
}
removeFromGroupItems(element, element.getGroupNames());
}
@Override
protected void beforeUpdateElement(Item existingElement) {
if (existingElement instanceof GenericItem) {
((GenericItem) existingElement).dispose();
if (existingElement instanceof GenericItem item) {
item.dispose();
}
}
@@ -253,13 +252,13 @@ public class ItemRegistryImpl extends AbstractRegistry<Item, String, ItemProvide
// don't use #initialize and retain order of items in groups:
List<String> oldNames = oldItem.getGroupNames();
List<String> newNames = item.getGroupNames();
List<String> commonNames = oldNames.stream().filter(name -> newNames.contains(name)).collect(toList());
List<String> commonNames = oldNames.stream().filter(newNames::contains).collect(toList());
removeFromGroupItems(oldItem, oldNames.stream().filter(name -> !commonNames.contains(name)).collect(toList()));
replaceInGroupItems(oldItem, item, commonNames);
addToGroupItems(item, newNames.stream().filter(name -> !commonNames.contains(name)).collect(toList()));
if (item instanceof GroupItem) {
addMembersToGroupItem((GroupItem) item);
if (item instanceof GroupItem groupItem) {
addMembersToGroupItem(groupItem);
}
injectServices(item);
}
@@ -70,10 +70,8 @@ public class ItemStateConverterImpl implements ItemStateConverter {
}
}
if (item instanceof NumberItem && state instanceof QuantityType) {
NumberItem numberItem = (NumberItem) item;
if (item instanceof NumberItem numberItem && state instanceof QuantityType quantityState) {
if (numberItem.getDimension() != null) {
QuantityType<?> quantityState = (QuantityType<?>) state;
// in case the item does define a unit it takes precedence over all other conversions:
Unit<?> itemUnit = parseItemUnit(numberItem);
@@ -89,8 +89,7 @@ public class ItemUpdater extends AbstractItemEventSubscriber {
protected void receiveCommand(ItemCommandEvent commandEvent) {
try {
Item item = itemRegistry.getItem(commandEvent.getItemName());
if (item instanceof GroupItem) {
GroupItem groupItem = (GroupItem) item;
if (item instanceof GroupItem groupItem) {
groupItem.send(commandEvent.getItemCommand());
}
} catch (ItemNotFoundException e) {
@@ -127,14 +127,14 @@ public class MetadataStateDescriptionFragmentProvider implements StateDescriptio
private BigDecimal getBigDecimal(Object value) {
BigDecimal ret = null;
if (value != null) {
if (value instanceof BigDecimal) {
ret = (BigDecimal) value;
} else if (value instanceof String) {
ret = new BigDecimal((String) value);
} else if (value instanceof BigInteger) {
ret = new BigDecimal((BigInteger) value);
} else if (value instanceof Number) {
ret = new BigDecimal(((Number) value).doubleValue());
if (value instanceof BigDecimal decimal) {
ret = decimal;
} else if (value instanceof String string) {
ret = new BigDecimal(string);
} else if (value instanceof BigInteger integer) {
ret = new BigDecimal(integer);
} else if (value instanceof Number number) {
ret = new BigDecimal(number.doubleValue());
} else {
throw new ClassCastException("Not possible to coerce [" + value + "] from class " + value.getClass()
+ " into a BigDecimal.");
@@ -146,10 +146,10 @@ public class MetadataStateDescriptionFragmentProvider implements StateDescriptio
private Boolean getBoolean(Object value) {
Boolean ret = null;
if (value != null) {
if (value instanceof Boolean) {
ret = (Boolean) value;
} else if (value instanceof String) {
ret = Boolean.parseBoolean((String) value);
if (value instanceof Boolean boolean1) {
ret = boolean1;
} else if (value instanceof String string) {
ret = Boolean.parseBoolean(string);
} else {
throw new ClassCastException(
"Not possible to coerce [" + value + "] from class " + value.getClass() + " into a Boolean.");
@@ -80,10 +80,10 @@ public class CronSchedulerImpl implements CronScheduler {
final Object scheduleConfig = map.get(CronJob.CRON);
String[] schedules = null;
if (scheduleConfig instanceof String[]) {
schedules = (String[]) scheduleConfig;
} else if (scheduleConfig instanceof String) {
schedules = new String[] { (String) scheduleConfig };
if (scheduleConfig instanceof String[] strings) {
schedules = strings;
} else if (scheduleConfig instanceof String string) {
schedules = new String[] { string };
}
if (schedules == null || schedules.length == 0) {
logger.info("No schedules in map with key '" + CronJob.CRON + "'. Nothing scheduled");
@@ -176,8 +176,7 @@ public class SchedulerImpl implements Scheduler {
ZonedDateTime.from(newTime));
deferred.thenAccept(v -> {
if (temporalAdjuster instanceof SchedulerTemporalAdjuster) {
final SchedulerTemporalAdjuster schedulerTemporalAdjuster = (SchedulerTemporalAdjuster) temporalAdjuster;
if (temporalAdjuster instanceof SchedulerTemporalAdjuster schedulerTemporalAdjuster) {
if (!schedulerTemporalAdjuster.isDone(newTime)) {
schedule(recurringSchedule, runnable, identifier, temporalAdjuster);
@@ -72,11 +72,8 @@ public class ReadyServiceImpl implements ReadyService {
}
private void notifyTrackers(ReadyMarker readyMarker, Consumer<ReadyTracker> action) {
trackers.entrySet().stream().filter(entry -> {
return entry.getValue().apply(readyMarker);
}).map(entry -> {
return entry.getKey();
}).forEach(action);
trackers.entrySet().stream().filter(entry -> entry.getValue().apply(readyMarker)).map(Map.Entry::getKey)
.forEach(action);
}
@Override
@@ -95,7 +92,7 @@ public class ReadyServiceImpl implements ReadyService {
try {
if (!trackers.containsKey(readyTracker)) {
trackers.put(readyTracker, filter);
notifyTracker(readyTracker, marker -> readyTracker.onReadyMarkerAdded(marker));
notifyTracker(readyTracker, readyTracker::onReadyMarkerAdded);
}
} catch (RuntimeException e) {
logger.error("Registering tracker '{}' failed!", readyTracker, e);
@@ -109,7 +106,7 @@ public class ReadyServiceImpl implements ReadyService {
rwlTrackers.writeLock().lock();
try {
if (trackers.containsKey(readyTracker)) {
notifyTracker(readyTracker, marker -> readyTracker.onReadyMarkerRemoved(marker));
notifyTracker(readyTracker, readyTracker::onReadyMarkerRemoved);
}
trackers.remove(readyTracker);
} finally {
@@ -119,6 +116,6 @@ public class ReadyServiceImpl implements ReadyService {
private void notifyTracker(ReadyTracker readyTracker, Consumer<ReadyMarker> action) {
ReadyMarkerFilter f = trackers.get(readyTracker);
markers.stream().filter(marker -> f.apply(marker)).forEach(action);
markers.stream().filter(f::apply).forEach(action);
}
}
@@ -139,8 +139,8 @@ public class GroupItem extends GenericItem implements StateChangeListener {
continue;
}
allMembers.add(member);
if (member instanceof GroupItem) {
collectMembers(allMembers, ((GroupItem) member).members);
if (member instanceof GroupItem item) {
collectMembers(allMembers, item.members);
}
}
}
@@ -172,22 +172,20 @@ public class GroupItem extends GenericItem implements StateChangeListener {
// in case membership is constructed programmatically this sanitizes
// the group names on the item:
if (added && item instanceof GenericItem) {
((GenericItem) item).addGroupName(getName());
if (added && item instanceof GenericItem genericItem) {
genericItem.addGroupName(getName());
}
registerStateListener(item);
}
private void registerStateListener(Item item) {
if (item instanceof GenericItem) {
GenericItem genericItem = (GenericItem) item;
if (item instanceof GenericItem genericItem) {
genericItem.addStateChangeListener(this);
}
}
private void unregisterStateListener(Item old) {
if (old instanceof GenericItem) {
GenericItem genericItem = (GenericItem) old;
if (old instanceof GenericItem genericItem) {
genericItem.removeStateChangeListener(this);
}
}
@@ -309,9 +307,9 @@ public class GroupItem extends GenericItem implements StateChangeListener {
newState = function.getStateAs(getStateMembers(getMembers()), typeClass);
}
if (newState == null && baseItem != null && baseItem instanceof GenericItem) {
if (newState == null && baseItem != null && baseItem instanceof GenericItem item) {
// we use the transformation method from the base item
((GenericItem) baseItem).setState(state);
item.setState(state);
newState = baseItem.getStateAs(typeClass);
}
if (newState == null) {
@@ -382,8 +380,8 @@ public class GroupItem extends GenericItem implements StateChangeListener {
@Override
public void setState(State state) {
State oldState = this.state;
if (baseItem != null && baseItem instanceof GenericItem) {
((GenericItem) baseItem).setState(state);
if (baseItem != null && baseItem instanceof GenericItem item) {
item.setState(state);
this.state = baseItem.getState();
} else {
this.state = state;
@@ -394,24 +392,24 @@ public class GroupItem extends GenericItem implements StateChangeListener {
@Override
public void setStateDescriptionService(@Nullable StateDescriptionService stateDescriptionService) {
super.setStateDescriptionService(stateDescriptionService);
if (baseItem instanceof GenericItem) {
((GenericItem) baseItem).setStateDescriptionService(stateDescriptionService);
if (baseItem instanceof GenericItem item) {
item.setStateDescriptionService(stateDescriptionService);
}
}
@Override
public void setCommandDescriptionService(@Nullable CommandDescriptionService commandDescriptionService) {
super.setCommandDescriptionService(commandDescriptionService);
if (baseItem instanceof GenericItem) {
((GenericItem) baseItem).setCommandDescriptionService(commandDescriptionService);
if (baseItem instanceof GenericItem item) {
item.setCommandDescriptionService(commandDescriptionService);
}
}
@Override
public void setUnitProvider(@Nullable UnitProvider unitProvider) {
super.setUnitProvider(unitProvider);
if (baseItem instanceof GenericItem) {
((GenericItem) baseItem).setUnitProvider(unitProvider);
if (baseItem instanceof GenericItem item) {
item.setUnitProvider(unitProvider);
}
}
@@ -86,8 +86,8 @@ public class ManagedItemProvider extends AbstractManagedProvider<Item, String, P
@Override
public @Nullable Item remove(String key) {
Item item = get(key);
if (item instanceof GroupItem) {
removeGroupNameFromMembers((GroupItem) item);
if (item instanceof GroupItem groupItem) {
removeGroupNameFromMembers(groupItem);
}
return super.remove(key);
@@ -102,8 +102,8 @@ public class ManagedItemProvider extends AbstractManagedProvider<Item, String, P
*/
public @Nullable Item remove(String itemName, boolean recursive) {
Item item = get(itemName);
if (recursive && item instanceof GroupItem) {
for (String member : getMemberNamesRecursively((GroupItem) item, getAll())) {
if (recursive && item instanceof GroupItem groupItem) {
for (String member : getMemberNamesRecursively(groupItem, getAll())) {
remove(member);
}
}
@@ -128,8 +128,8 @@ public class ManagedItemProvider extends AbstractManagedProvider<Item, String, P
for (Item item : allItems) {
if (item.getGroupNames().contains(groupItem.getName())) {
memberNames.add(item.getName());
if (item instanceof GroupItem) {
memberNames.addAll(getMemberNamesRecursively((GroupItem) item, allItems));
if (item instanceof GroupItem groupItem1) {
memberNames.addAll(getMemberNamesRecursively(groupItem1, allItems));
}
}
}
@@ -148,8 +148,7 @@ public class ManagedItemProvider extends AbstractManagedProvider<Item, String, P
private @Nullable Item createItem(String itemType, String itemName) {
try {
Item item = itemBuilderFactory.newItemBuilder(itemType, itemName).build();
return item;
return itemBuilderFactory.newItemBuilder(itemType, itemName).build();
} catch (IllegalStateException e) {
logger.debug("Couldn't create item '{}' of type '{}'", itemName, itemType);
return null;
@@ -159,8 +158,8 @@ public class ManagedItemProvider extends AbstractManagedProvider<Item, String, P
private void removeGroupNameFromMembers(GroupItem groupItem) {
Set<Item> members = getMembers(groupItem, getAll());
for (Item member : members) {
if (member instanceof GenericItem) {
((GenericItem) member).removeGroupName(groupItem.getUID());
if (member instanceof GenericItem item) {
item.removeGroupName(groupItem.getUID());
update(member);
}
}
@@ -187,9 +186,9 @@ public class ManagedItemProvider extends AbstractManagedProvider<Item, String, P
String itemName = entry.getKey();
PersistedItem persistedItem = entry.getValue();
Item item = itemFactory.createItem(persistedItem.itemType, itemName);
if (item != null && item instanceof GenericItem) {
if (item != null && item instanceof GenericItem genericItem) {
iterator.remove();
configureItem(persistedItem, (GenericItem) item);
configureItem(persistedItem, genericItem);
notifyListenersAboutAddedElement(item);
} else {
logger.debug("The added item factory '{}' still could not instantiate item '{}'.", itemFactory,
@@ -237,8 +236,8 @@ public class ManagedItemProvider extends AbstractManagedProvider<Item, String, P
item = createItem(persistedItem.itemType, itemName);
}
if (item != null && item instanceof GenericItem) {
configureItem(persistedItem, (GenericItem) item);
if (item != null && item instanceof GenericItem genericItem) {
configureItem(persistedItem, genericItem);
}
if (item == null) {
@@ -283,8 +282,7 @@ public class ManagedItemProvider extends AbstractManagedProvider<Item, String, P
PersistedItem persistedItem = new PersistedItem(
item instanceof GroupItem ? GroupItem.TYPE : toItemFactoryName(item));
if (item instanceof GroupItem) {
GroupItem groupItem = (GroupItem) item;
if (item instanceof GroupItem groupItem) {
String baseItemType = null;
Item baseItem = groupItem.getBaseItem();
if (baseItem != null) {
@@ -95,10 +95,7 @@ public final class Metadata implements Identifiable<MetadataKey> {
return false;
}
Metadata other = (Metadata) obj;
if (!key.equals(other.key)) {
return false;
}
return true;
return key.equals(other.key);
}
@Override
@@ -60,8 +60,7 @@ public class ItemDTOMapper {
if (itemDTO.type != null) {
ItemBuilder builder = itemBuilderFactory.newItemBuilder(itemDTO.type, itemDTO.name);
if (itemDTO instanceof GroupItemDTO && GroupItem.TYPE.equals(itemDTO.type)) {
GroupItemDTO groupItemDTO = (GroupItemDTO) itemDTO;
if (itemDTO instanceof GroupItemDTO groupItemDTO && GroupItem.TYPE.equals(itemDTO.type)) {
Item baseItem = null;
if (groupItemDTO.groupType != null && !groupItemDTO.groupType.isEmpty()) {
baseItem = itemBuilderFactory.newItemBuilder(groupItemDTO.groupType, itemDTO.name).build();
@@ -107,8 +106,7 @@ public class ItemDTOMapper {
}
private static void fillProperties(ItemDTO itemDTO, Item item) {
if (item instanceof GroupItem) {
GroupItem groupItem = (GroupItem) item;
if (item instanceof GroupItem groupItem) {
GroupItemDTO groupItemDTO = (GroupItemDTO) itemDTO;
Item baseItem = groupItem.getBaseItem();
if (baseItem != null) {
@@ -40,10 +40,10 @@ public abstract class AbstractItemEventSubscriber implements EventSubscriber {
@Override
public void receive(Event event) {
if (event instanceof ItemStateEvent) {
receiveUpdate((ItemStateEvent) event);
} else if (event instanceof ItemCommandEvent) {
receiveCommand((ItemCommandEvent) event);
if (event instanceof ItemStateEvent stateEvent) {
receiveUpdate(stateEvent);
} else if (event instanceof ItemCommandEvent commandEvent) {
receiveCommand(commandEvent);
}
}
@@ -63,19 +63,19 @@ public class ColorItem extends DimmerItem {
if (isAcceptedState(ACCEPTED_DATA_TYPES, state)) {
State currentState = this.state;
if (currentState instanceof HSBType) {
DecimalType hue = ((HSBType) currentState).getHue();
PercentType saturation = ((HSBType) currentState).getSaturation();
if (currentState instanceof HSBType hsbType) {
DecimalType hue = hsbType.getHue();
PercentType saturation = hsbType.getSaturation();
// we map ON/OFF values to dark/bright, so that the hue and saturation values are not changed
if (state == OnOffType.OFF) {
applyState(new HSBType(hue, saturation, PercentType.ZERO));
} else if (state == OnOffType.ON) {
applyState(new HSBType(hue, saturation, PercentType.HUNDRED));
} else if (state instanceof PercentType && !(state instanceof HSBType)) {
applyState(new HSBType(hue, saturation, (PercentType) state));
} else if (state instanceof DecimalType && !(state instanceof HSBType)) {
} else if (state instanceof PercentType percentType && !(state instanceof HSBType)) {
applyState(new HSBType(hue, saturation, percentType));
} else if (state instanceof DecimalType decimalType && !(state instanceof HSBType)) {
applyState(new HSBType(hue, saturation,
new PercentType(((DecimalType) state).toBigDecimal().multiply(BigDecimal.valueOf(100)))));
new PercentType(decimalType.toBigDecimal().multiply(BigDecimal.valueOf(100)))));
} else {
applyState(state);
}
@@ -65,9 +65,8 @@ public class LocationItem extends GenericItem {
* @return distance between the two points in meters
*/
public DecimalType distanceFrom(@Nullable LocationItem awayItem) {
if (awayItem != null && awayItem.state instanceof PointType && this.state instanceof PointType) {
PointType thisPoint = (PointType) this.state;
PointType awayPoint = (PointType) awayItem.state;
if (awayItem != null && awayItem.state instanceof PointType awayPoint
&& this.state instanceof PointType thisPoint) {
return thisPoint.distanceFrom(awayPoint);
}
return new DecimalType(-1);
@@ -115,28 +115,28 @@ public class NumberItem extends GenericItem {
@Override
public void setState(State state) {
// QuantityType update to a NumberItem without, strip unit
if (state instanceof QuantityType && dimension == null) {
DecimalType plainState = new DecimalType(((QuantityType<?>) state).toBigDecimal());
if (state instanceof QuantityType quantityType && dimension == null) {
DecimalType plainState = new DecimalType(quantityType.toBigDecimal());
super.setState(plainState);
return;
}
// DecimalType update for a NumberItem with dimension, convert to QuantityType:
if (state instanceof DecimalType && dimension != null) {
if (state instanceof DecimalType decimalType && dimension != null) {
Unit<?> unit = getUnit(dimension, false);
if (unit != null) {
super.setState(new QuantityType<>(((DecimalType) state).doubleValue(), unit));
super.setState(new QuantityType<>(decimalType.doubleValue(), unit));
return;
}
}
// QuantityType update, check unit and convert if necessary:
if (state instanceof QuantityType) {
if (state instanceof QuantityType quantityType) {
Unit<?> itemUnit = getUnit(dimension, true);
Unit<?> stateUnit = ((QuantityType<?>) state).getUnit();
Unit<?> stateUnit = quantityType.getUnit();
if (itemUnit != null && (!stateUnit.getSystemUnit().equals(itemUnit.getSystemUnit())
|| UnitUtils.isDifferentMeasurementSystem(itemUnit, stateUnit))) {
QuantityType<?> convertedState = ((QuantityType<?>) state).toInvertibleUnit(itemUnit);
QuantityType<?> convertedState = quantityType.toInvertibleUnit(itemUnit);
if (convertedState != null) {
super.setState(convertedState);
return;
@@ -51,10 +51,10 @@ public class DecimalType extends Number implements PrimitiveType, State, Command
* @param value a number
*/
public DecimalType(Number value) {
if (value instanceof QuantityType) {
this.value = ((QuantityType<?>) value).toBigDecimal();
} else if (value instanceof HSBType) {
this.value = ((HSBType) value).toBigDecimal();
if (value instanceof QuantityType type) {
this.value = type.toBigDecimal();
} else if (value instanceof HSBType type) {
this.value = type.toBigDecimal();
} else {
this.value = new BigDecimal(value.toString());
}
@@ -85,7 +85,7 @@ public class HSBType extends PercentType implements ComplexType, State, Command
* @param value a stringified HSBType value in the format "hue,saturation,brightness"
*/
public HSBType(String value) {
List<String> constituents = Arrays.stream(value.split(",")).map(in -> in.trim()).collect(Collectors.toList());
List<String> constituents = Arrays.stream(value.split(",")).map(String::trim).collect(Collectors.toList());
if (constituents.size() == 3) {
this.hue = new BigDecimal(constituents.get(0));
this.saturation = new BigDecimal(constituents.get(1));
@@ -85,7 +85,7 @@ public class PointType implements ComplexType, Command, State {
public PointType(String value) {
if (!value.isEmpty()) {
List<String> elements = Arrays.stream(value.split(",")).map(in -> in.trim()).collect(Collectors.toList());
List<String> elements = Arrays.stream(value.split(",")).map(String::trim).collect(Collectors.toList());
if (elements.size() >= 2) {
canonicalize(new DecimalType(elements.get(0)), new DecimalType(elements.get(1)));
if (elements.size() == 3) {
@@ -264,10 +264,7 @@ public class PointType implements ComplexType, Command, State {
return false;
}
PointType other = (PointType) obj;
if (!getLatitude().equals(other.getLatitude()) || !getLongitude().equals(other.getLongitude())
|| !getAltitude().equals(other.getAltitude())) {
return false;
}
return true;
return !(!getLatitude().equals(other.getLatitude()) || !getLongitude().equals(other.getLongitude())
|| !getAltitude().equals(other.getAltitude()));
}
}
@@ -59,10 +59,10 @@ public interface QuantityTypeArithmeticGroupFunction extends GroupFunction {
}
protected boolean isSameDimension(@Nullable Item item) {
if (item instanceof GroupItem) {
return isSameDimension(((GroupItem) item).getBaseItem());
if (item instanceof GroupItem groupItem) {
return isSameDimension(groupItem.getBaseItem());
}
return item instanceof NumberItem && dimension.equals(((NumberItem) item).getDimension());
return item instanceof NumberItem ni && dimension.equals(ni.getDimension());
}
}
@@ -101,9 +101,6 @@ public class RawType implements PrimitiveType, State {
if (!mimeType.equals(other.mimeType)) {
return false;
}
if (!Arrays.equals(bytes, other.bytes)) {
return false;
}
return true;
return Arrays.equals(bytes, other.bytes);
}
}
@@ -287,7 +287,7 @@ public class NetUtil implements NetworkAddressService {
if (primaryIp != null) {
try {
Short prefix = getAllInterfaceAddresses().stream()
.filter(a -> a.getAddress().getHostAddress().equals(primaryIp)).map(a -> a.getPrefix())
.filter(a -> a.getAddress().getHostAddress().equals(primaryIp)).map(CidrAddress::getPrefix)
.findFirst().get().shortValue();
broadcastAddress = getIpv4NetBroadcastAddress(primaryIp, prefix);
} catch (IllegalArgumentException ex) {
@@ -467,7 +467,7 @@ public class NetUtil implements NetworkAddressService {
String ipv4AddressOnInterface = addr.getHostAddress();
String subnetStringOnInterface = getIpv4NetAddress(ipv4AddressOnInterface,
ifAddr.getNetworkPrefixLength()) + "/" + String.valueOf(ifAddr.getNetworkPrefixLength());
ifAddr.getNetworkPrefixLength()) + "/" + ifAddr.getNetworkPrefixLength();
String configuredSubnetString = getIpv4NetAddress(ipAddress, Short.parseShort(subnetMask)) + "/"
+ subnetMask;
@@ -493,7 +493,7 @@ public class NetUtil implements NetworkAddressService {
*/
public static boolean isValidIPConfig(String ipAddress) {
if (ipAddress.contains("/")) {
String parts[] = ipAddress.split("/");
String[] parts = ipAddress.split("/");
boolean ipMatches = IPV4_PATTERN.matcher(parts[0]).matches();
int netMask = Integer.parseInt(parts[1]);
@@ -518,7 +518,7 @@ public class NetUtil implements NetworkAddressService {
}
networkInterfacePollFuture = scheduledExecutorService.scheduleWithFixedDelay(
() -> this.pollAndNotifyNetworkInterfaceAddress(), 1, intervalInSeconds, TimeUnit.SECONDS);
this::pollAndNotifyNetworkInterfaceAddress, 1, intervalInSeconds, TimeUnit.SECONDS);
}
private void pollAndNotifyNetworkInterfaceAddress() {
@@ -587,11 +587,11 @@ public class NetUtil implements NetworkAddressService {
if (value == null) {
return defaultValue;
}
if (value instanceof Boolean) {
return (Boolean) value;
if (value instanceof Boolean boolean1) {
return boolean1;
}
if (value instanceof String) {
return Boolean.valueOf((String) value);
if (value instanceof String string) {
return Boolean.valueOf(string);
} else {
return defaultValue;
}
@@ -171,7 +171,7 @@ public class StartLevelService {
protected void modified(Map<String, Object> configuration) {
// clean up
slmarker.clear();
trackers.values().forEach(t -> readyService.unregisterTracker(t));
trackers.values().forEach(readyService::unregisterTracker);
trackers.clear();
// set up trackers and markers
@@ -180,7 +180,7 @@ public class StartLevelService {
.forEach(sl -> slmarker.put(sl, new ReadyMarker(STARTLEVEL_MARKER_TYPE, Integer.toString(sl))));
slmarker.put(STARTLEVEL_COMPLETE,
new ReadyMarker(STARTLEVEL_MARKER_TYPE, Integer.toString(STARTLEVEL_COMPLETE)));
startlevels.values().stream().forEach(ms -> ms.forEach(e -> registerTracker(e)));
startlevels.values().stream().forEach(ms -> ms.forEach(this::registerTracker));
}
private void registerTracker(ReadyMarker e) {
@@ -204,7 +204,7 @@ public class StartLevelService {
private Map<Integer, Set<ReadyMarker>> parseConfig(Map<String, Object> configuration) {
return configuration.entrySet().stream() //
.filter(e -> hasIntegerKey(e)) //
.filter(this::hasIntegerKey) //
.map(e -> new AbstractMap.SimpleEntry<>(Integer.valueOf(e.getKey()), markerSet(e.getValue()))) //
.sorted(Map.Entry.<Integer, Set<ReadyMarker>> comparingByKey().reversed()) //
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
@@ -212,8 +212,8 @@ public class StartLevelService {
private Set<ReadyMarker> markerSet(Object value) {
Set<ReadyMarker> markerSet = new HashSet<>();
if (value instanceof String) {
String[] segments = ((String) value).split(",");
if (value instanceof String string) {
String[] segments = string.split(",");
for (String segment : segments) {
if (segment.contains(":")) {
String[] markerParts = segment.strip().split(":");
@@ -238,7 +238,7 @@ public class StartLevelService {
@Deactivate
protected void deactivate() {
slmarker.clear();
trackers.values().forEach(t -> readyService.unregisterTracker(t));
trackers.values().forEach(readyService::unregisterTracker);
ScheduledFuture<?> job = this.job;
if (job != null) {
job.cancel(true);
@@ -48,7 +48,7 @@ public class CommandDescriptionBuilder {
*/
public CommandDescription build() {
CommandDescriptionImpl commandDescription = new CommandDescriptionImpl();
commandOptions.forEach(co -> commandDescription.addCommandOption(co));
commandOptions.forEach(commandDescription::addCommandOption);
return commandDescription;
}
@@ -116,8 +116,8 @@ public class UnitUtils {
for (Field field : system.getDeclaredFields()) {
if (field.getType().isAssignableFrom(Unit.class) && Modifier.isStatic(field.getModifiers())) {
Type genericType = field.getGenericType();
if (genericType instanceof ParameterizedType) {
Type typeParam = ((ParameterizedType) genericType).getActualTypeArguments()[0];
if (genericType instanceof ParameterizedType type) {
Type typeParam = type.getActualTypeArguments()[0];
if (typeParam instanceof WildcardType) {
continue;
}
@@ -188,14 +188,12 @@ public class UnitUtils {
|| (siUnits.contains(thatUnit) && usUnits.contains(thisUnit));
if (!differentSystems) {
if (thisUnit instanceof TransformedUnit
&& isMetricConversion(((TransformedUnit<?>) thisUnit).getConverter())) {
return isDifferentMeasurementSystem(((TransformedUnit<?>) thisUnit).getParentUnit(), thatUnit);
if (thisUnit instanceof TransformedUnit unit && isMetricConversion(unit.getConverter())) {
return isDifferentMeasurementSystem(unit.getParentUnit(), thatUnit);
}
if (thatUnit instanceof TransformedUnit
&& isMetricConversion(((TransformedUnit<?>) thatUnit).getConverter())) {
return isDifferentMeasurementSystem(thisUnit, ((TransformedUnit<?>) thatUnit).getParentUnit());
if (thatUnit instanceof TransformedUnit unit && isMetricConversion(unit.getConverter())) {
return isDifferentMeasurementSystem(thisUnit, unit.getParentUnit());
}
}
@@ -74,9 +74,8 @@ public class LRUMediaCacheEntryTest {
}
private LRUMediaCache<MetadataSample> createCache(long size) throws IOException {
LRUMediaCache<MetadataSample> voiceLRUCache = new LRUMediaCache<MetadataSample>(storageService, size,
"lrucachetest.pid", this.getClass().getClassLoader());
return voiceLRUCache;
return new LRUMediaCache<MetadataSample>(storageService, size, "lrucachetest.pid",
this.getClass().getClassLoader());
}
public static class FakeStream extends InputStream {
@@ -193,7 +192,7 @@ public class LRUMediaCacheEntryTest {
// read bytes from the two stream concurrently
List<InputStream> parallelAudioStreamList = Arrays.asList(actualAudioStream1, actualAudioStream2);
List<byte[]> bytesResultList = parallelAudioStreamList.parallelStream().map(stream -> readSafe(stream))
List<byte[]> bytesResultList = parallelAudioStreamList.parallelStream().map(this::readSafe)
.collect(Collectors.toList());
assertArrayEquals(randomData, bytesResultList.get(0));
@@ -75,9 +75,8 @@ public class LRUMediaCacheTest {
}
private LRUMediaCache<MetadataSample> createCache(long size) throws IOException {
LRUMediaCache<MetadataSample> voiceLRUCache = new LRUMediaCache<MetadataSample>(storageService, size,
"lrucachetest.pid", this.getClass().getClassLoader());
return voiceLRUCache;
return new LRUMediaCache<MetadataSample>(storageService, size, "lrucachetest.pid",
this.getClass().getClassLoader());
}
/**
@@ -118,11 +118,11 @@ public class UserRegistryImplTest {
registry.authenticate(new UserApiTokenCredentials(token2));
registry.authenticate(new UserApiTokenCredentials(token3));
registry.removeUserApiToken(user,
user.getApiTokens().stream().filter(t -> t.getName().equals("token1")).findAny().get());
user.getApiTokens().stream().filter(t -> "token1".equals(t.getName())).findAny().get());
registry.removeUserApiToken(user,
user.getApiTokens().stream().filter(t -> t.getName().equals("token2")).findAny().get());
user.getApiTokens().stream().filter(t -> "token2".equals(t.getName())).findAny().get());
registry.removeUserApiToken(user,
user.getApiTokens().stream().filter(t -> t.getName().equals("token3")).findAny().get());
user.getApiTokens().stream().filter(t -> "token3".equals(t.getName())).findAny().get());
assertEquals(user.getApiTokens().size(), 0);
}
}
@@ -77,7 +77,7 @@ public class SchedulerImplTest extends JavaTest {
assertTrue(after.isCancelled(), "Scheduled job cancelled before timeout");
Thread.sleep(200);
assertFalse(check.get(), "Callable method should not been called");
assertThrows(CancellationException.class, () -> after.get());
assertThrows(CancellationException.class, after::get);
}
@Test
@@ -144,9 +144,7 @@ public class SchedulerImplTest extends JavaTest {
ScheduledCompletableFuture<Integer> before = scheduler.before(d, Duration.ofMillis(100));
before.cancel(true);
assertTrue(before.getPromise().isCompletedExceptionally(), "Scheduled job cancelled before timeout");
assertThrows(CancellationException.class, () -> {
before.get();
});
assertThrows(CancellationException.class, before::get);
}
@Test
@@ -322,7 +320,7 @@ public class SchedulerImplTest extends JavaTest {
}
};
final AtomicReference<ScheduledCompletableFuture<Object>> reference = new AtomicReference<>();
final ScheduledCompletableFuture<Object> future = scheduler.schedule(() -> counter.incrementAndGet(),
final ScheduledCompletableFuture<Object> future = scheduler.schedule(counter::incrementAndGet,
temporalAdjuster);
reference.set(future);
future.get();
@@ -41,8 +41,7 @@ public class DimmerItemTest {
private static BigDecimal getState(final Item item, Class<? extends State> typeClass) {
final State state = item.getStateAs(typeClass);
final String str = state.toString();
final BigDecimal result = new BigDecimal(str);
return result;
return new BigDecimal(str);
}
@Test
@@ -397,8 +397,7 @@ public class UnitsTest {
@Override
public boolean matches(@Nullable Object actualValue) {
if (actualValue instanceof Quantity) {
Quantity<?> other = (Quantity<?>) actualValue;
if (actualValue instanceof Quantity other) {
if (!other.getUnit().isCompatible(quantity.getUnit())) {
return false;