More code cleanups (#3975)

While cleaning up the code I found a some more code to cleanup:

* Remove unnecessary boxing
* Use `contains(..)` instead of `indexOf(..) != -1`
* Use `assertInstanceOf` in tests
* Make expensive trace logging conditional
* Remove redundant constructor
* Replace `collect(Collectors.toUnmodifiableList())` with `toList()`
* Replace `filter(..).count() == 0L` with `noneMatch(..)`
* Replace `filter(..).count() > 0` with `anyMatch(..)`

Signed-off-by: Wouter Born <github@maindrain.net>
This commit is contained in:
Wouter Born 2023-12-28 13:15:50 +01:00 committed by GitHub
parent 0e03943e48
commit ba5647b871
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
24 changed files with 62 additions and 68 deletions

View File

@ -89,7 +89,7 @@ public class AudioWaveUtils {
*/
public static void removeFMT(InputStream data) throws IOException {
DataInputStream dataInputStream = new DataInputStream(data);
Integer nextInt = dataInputStream.readInt();
int nextInt = dataInputStream.readInt();
int i = 0;
while (nextInt != DATA_MAGIC && i < 200) {
nextInt = dataInputStream.readInt();

View File

@ -328,7 +328,7 @@ public class AutomationCommandList extends AutomationCommand {
return templates;
} else {
for (String templateUID : list.keySet()) {
if (templateUID.indexOf(id) != -1) {
if (templateUID.contains(id)) {
templates.add(autoCommands.getTemplate(templateUID, locale));
}
}
@ -363,7 +363,7 @@ public class AutomationCommandList extends AutomationCommand {
return moduleTypes;
} else {
for (String typeUID : list.values()) {
if (typeUID.indexOf(id) != -1) {
if (typeUID.contains(id)) {
moduleTypes.add(autoCommands.getModuleType(typeUID, locale));
}
}

View File

@ -104,7 +104,7 @@ public class AnnotationActionModuleTypeProviderTest extends JavaTest {
assertTrue(types.contains(TEST_ACTION_TYPE_ID));
ModuleType mt = prov.getModuleType(TEST_ACTION_TYPE_ID, null);
assertTrue(mt instanceof ActionType);
assertInstanceOf(ActionType.class, mt);
ActionType at = (ActionType) mt;

View File

@ -120,7 +120,7 @@ public class AnnotatedThingActionModuleTypeProviderTest extends JavaTest {
assertTrue(types.contains(TEST_ACTION_TYPE_ID));
ModuleType mt = prov.getModuleType(TEST_ACTION_TYPE_ID, null);
assertTrue(mt instanceof ActionType);
assertInstanceOf(ActionType.class, mt);
ActionType at = (ActionType) mt;

View File

@ -249,8 +249,10 @@ public class IpAddonFinder extends BaseAddonFinder {
.configureBlocking(false);
byte[] requestArray = buildRequestArray(channel, Objects.toString(request));
logger.trace("{}: {}", candidate.getUID(),
HexFormat.of().withDelimiter(" ").formatHex(requestArray));
if (logger.isTraceEnabled()) {
logger.trace("{}: {}", candidate.getUID(),
HexFormat.of().withDelimiter(" ").formatHex(requestArray));
}
channel.send(ByteBuffer.wrap(requestArray),
new InetSocketAddress(destIp, destPort));

View File

@ -14,7 +14,6 @@ package org.openhab.core.config.discovery.addon.process;
import static org.openhab.core.config.discovery.addon.AddonFinderConstants.ADDON_SUGGESTION_FINDER;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
@ -28,7 +27,6 @@ import org.openhab.core.addon.AddonInfo;
import org.openhab.core.addon.AddonMatchProperty;
import org.openhab.core.config.discovery.addon.AddonFinder;
import org.openhab.core.config.discovery.addon.BaseAddonFinder;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -51,10 +49,6 @@ public class ProcessAddonFinder extends BaseAddonFinder {
private final Logger logger = LoggerFactory.getLogger(ProcessAddonFinder.class);
@Activate
public ProcessAddonFinder() {
}
// get list of running processes visible to openHAB,
// also tries to mitigate differences on different operating systems
String getProcessCommandProcess(ProcessHandle h) {
@ -77,7 +71,7 @@ public class ProcessAddonFinder extends BaseAddonFinder {
public Set<AddonInfo> getSuggestedAddons() {
logger.trace("ProcessAddonFinder::getSuggestedAddons");
Set<AddonInfo> result = new HashSet<>();
Set<String> processList = Collections.emptySet();
Set<String> processList;
try {
processList = ProcessHandle.allProcesses().map(this::getProcessCommandProcess)
.filter(Predicate.not(String::isEmpty)).collect(Collectors.toUnmodifiableSet());
@ -92,7 +86,7 @@ public class ProcessAddonFinder extends BaseAddonFinder {
List<AddonMatchProperty> matchProperties = method.getMatchProperties();
List<AddonMatchProperty> commands = matchProperties.stream()
.filter(amp -> COMMAND.equals(amp.getName())).collect(Collectors.toUnmodifiableList());
.filter(amp -> COMMAND.equals(amp.getName())).toList();
if (matchProperties.size() != commands.size()) {
logger.warn("Add-on '{}' addon.xml file contains unsupported 'match-property'", candidate.getUID());

View File

@ -77,7 +77,7 @@ public class UpnpAddonFinder extends BaseAddonFinder implements RegistryListener
private final Logger logger = LoggerFactory.getLogger(UpnpAddonFinder.class);
private final Map<String, RemoteDevice> devices = new ConcurrentHashMap<>();
private UpnpService upnpService;
private final UpnpService upnpService;
@Activate
public UpnpAddonFinder(@Reference UpnpService upnpService) {

View File

@ -114,12 +114,12 @@ public class PersistentInboxTest {
when(thingRegistryMock.get(eq(THING_UID))).thenReturn(thing);
when(thingProviderMock.get(eq(THING_UID))).thenReturn(thing);
assertTrue(thing.getConfiguration().get("foo") instanceof String);
assertInstanceOf(String.class, thing.getConfiguration().get("foo"));
inbox.activate();
inbox.add(DiscoveryResultBuilder.create(THING_UID).withProperty("foo", 3).build());
assertTrue(thing.getConfiguration().get("foo") instanceof String);
assertInstanceOf(String.class, thing.getConfiguration().get("foo"));
// thing updated if managed
assertEquals("3", thing.getConfiguration().get("foo"));
}
@ -131,12 +131,12 @@ public class PersistentInboxTest {
configureConfigDescriptionRegistryMock("foo", Type.TEXT);
when(thingRegistryMock.get(eq(THING_UID))).thenReturn(thing);
assertTrue(thing.getConfiguration().get("foo") instanceof String);
assertInstanceOf(String.class, thing.getConfiguration().get("foo"));
inbox.activate();
inbox.add(DiscoveryResultBuilder.create(THING_UID).withProperty("foo", 3).build());
assertTrue(thing.getConfiguration().get("foo") instanceof String);
assertInstanceOf(String.class, thing.getConfiguration().get("foo"));
// thing not updated if unmanaged
assertEquals("1", thing.getConfiguration().get("foo"));
}
@ -151,7 +151,7 @@ public class PersistentInboxTest {
inbox.approve(THING_UID, "Test", null);
assertEquals(THING_UID, lastAddedThing.getUID());
assertTrue(lastAddedThing.getConfiguration().get("foo") instanceof String);
assertInstanceOf(String.class, lastAddedThing.getConfiguration().get("foo"));
assertEquals("3", lastAddedThing.getConfiguration().get("foo"));
}
@ -165,7 +165,7 @@ public class PersistentInboxTest {
inbox.approve(THING_UID, "Test", THING_OTHER_ID);
assertEquals(THING_OTHER_UID, lastAddedThing.getUID());
assertTrue(lastAddedThing.getConfiguration().get("foo") instanceof String);
assertInstanceOf(String.class, lastAddedThing.getConfiguration().get("foo"));
assertEquals("3", lastAddedThing.getConfiguration().get("foo"));
}

View File

@ -934,7 +934,7 @@ public class ModbusManagerImpl implements ModbusManager {
private void maybeCloseConnections(ModbusSlaveEndpoint endpoint) {
boolean lastCommWithThisEndpointWasRemoved = communicationInterfaces.stream()
.filter(comm -> comm.endpoint.equals(endpoint)).count() == 0L;
.noneMatch(comm -> comm.endpoint.equals(endpoint));
if (lastCommWithThisEndpointWasRemoved) {
// Since last communication interface pointing to this endpoint was closed, we can clean up resources
// and disconnect connections.

View File

@ -169,7 +169,7 @@ public class SmokeTest extends IntegrationTestSupport {
assertThat(okCount.get(), is(equalTo(0)));
assertThat(errorCount.get(), is(equalTo(1)));
assertTrue(lastError.get() instanceof ModbusSlaveErrorResponseException, lastError.toString());
assertInstanceOf(ModbusSlaveErrorResponseException.class, lastError.get(), lastError.toString());
}
}
@ -206,7 +206,7 @@ public class SmokeTest extends IntegrationTestSupport {
assertThat(okCount.get(), is(equalTo(0)));
assertThat(errorCount.get(), is(equalTo(1)));
assertTrue(lastError.get() instanceof ModbusConnectionException, lastError.toString());
assertInstanceOf(ModbusConnectionException.class, lastError.get(), lastError.toString());
}
}
@ -239,7 +239,7 @@ public class SmokeTest extends IntegrationTestSupport {
assertTrue(callbackCalled.await(15, TimeUnit.SECONDS));
assertThat(okCount.get(), is(equalTo(0)));
assertThat(lastError.toString(), errorCount.get(), is(equalTo(1)));
assertTrue(lastError.get() instanceof ModbusSlaveIOException, lastError.toString());
assertInstanceOf(ModbusSlaveIOException.class, lastError.get(), lastError.toString());
}
}
@ -478,7 +478,7 @@ public class SmokeTest extends IntegrationTestSupport {
assertTrue(callbackCalled.await(60, TimeUnit.SECONDS));
assertThat(unexpectedCount.get(), is(equalTo(0)));
assertTrue(lastError.get() instanceof ModbusSlaveErrorResponseException, lastError.toString());
assertInstanceOf(ModbusSlaveErrorResponseException.class, lastError.get(), lastError.toString());
assertThat(modbustRequestCaptor.getAllReturnValues().size(), is(equalTo(1)));
ModbusRequest request = modbustRequestCaptor.getAllReturnValues().get(0);
@ -555,7 +555,7 @@ public class SmokeTest extends IntegrationTestSupport {
assertTrue(callbackCalled.await(60, TimeUnit.SECONDS));
assertThat(unexpectedCount.get(), is(equalTo(0)));
assertTrue(lastError.get() instanceof ModbusSlaveErrorResponseException, lastError.toString());
assertInstanceOf(ModbusSlaveErrorResponseException.class, lastError.get(), lastError.toString());
assertThat(modbustRequestCaptor.getAllReturnValues().size(), is(equalTo(1)));
ModbusRequest request = modbustRequestCaptor.getAllReturnValues().get(0);

View File

@ -173,7 +173,7 @@ public class MqttBrokerConnectionTests extends JavaTest {
"MqttBrokerConnectionTests");
// Check if the default policy is set and that the broker within the policy is set.
assertTrue(connection.getReconnectStrategy() instanceof PeriodicReconnectStrategy);
assertInstanceOf(PeriodicReconnectStrategy.class, connection.getReconnectStrategy());
AbstractReconnectStrategy p = connection.getReconnectStrategy();
assertThat(p.getBrokerConnection(), equalTo(connection));
}

View File

@ -70,12 +70,10 @@ public class SerialPortRegistry {
final Predicate<SerialPortProvider> filter;
if (scheme != null) {
// Get port providers which accept exactly the port with its scheme.
filter = provider -> provider.getAcceptedProtocols().filter(prot -> prot.getScheme().equals(scheme))
.count() > 0;
filter = provider -> provider.getAcceptedProtocols().anyMatch(prot -> prot.getScheme().equals(scheme));
} else {
// Get port providers which accept the same type (local, net)
filter = provider -> provider.getAcceptedProtocols().filter(prot -> prot.getPathType().equals(pathType))
.count() > 0;
filter = provider -> provider.getAcceptedProtocols().anyMatch(prot -> prot.getPathType().equals(pathType));
}
return portCreators.stream().filter(filter).toList();

View File

@ -195,7 +195,7 @@ public class SemanticTagRegistryImpl extends AbstractRegistry<SemanticTag, Strin
+ "': only Equipment, Location, Point and Property are allowed as root tags.");
}
type = uid;
className = newTag.getClass().getName();
className = newTag.getName();
} else {
String name = uid.substring(lastSeparator + 1);
String parentId = uid.substring(0, lastSeparator);
@ -252,7 +252,7 @@ public class SemanticTagRegistryImpl extends AbstractRegistry<SemanticTag, Strin
private void addTagSet(String tagId, Class<? extends Tag> tagSet) {
logger.trace("addTagSet {}", tagId);
String id = tagId;
while (id.indexOf("_") != -1) {
while (id.contains("_")) {
SemanticTags.addTagSet(id, tagSet);
id = id.substring(id.indexOf("_") + 1);
}
@ -266,7 +266,7 @@ public class SemanticTagRegistryImpl extends AbstractRegistry<SemanticTag, Strin
return;
}
String id = tagId;
while (id.indexOf("_") != -1) {
while (id.contains("_")) {
SemanticTags.removeTagSet(id, tagSet);
id = id.substring(id.indexOf("_") + 1);
}

View File

@ -74,14 +74,14 @@ public class JsonStorageTest extends JavaTest {
DummyObject dummy = objectStorage.get("DummyObject");
assertNotNull(dummy);
assertTrue(dummy.configuration.get("testShort") instanceof BigDecimal);
assertTrue(dummy.configuration.get("testInt") instanceof BigDecimal);
assertTrue(dummy.configuration.get("testLong") instanceof BigDecimal);
assertTrue(dummy.configuration.get("testDouble") instanceof BigDecimal);
assertTrue(dummy.configuration.get("testFloat") instanceof BigDecimal);
assertTrue(dummy.configuration.get("testBigDecimal") instanceof BigDecimal);
assertTrue(dummy.configuration.get("testBoolean") instanceof Boolean);
assertTrue(dummy.configuration.get("testString") instanceof String);
assertInstanceOf(BigDecimal.class, dummy.configuration.get("testShort"));
assertInstanceOf(BigDecimal.class, dummy.configuration.get("testInt"));
assertInstanceOf(BigDecimal.class, dummy.configuration.get("testLong"));
assertInstanceOf(BigDecimal.class, dummy.configuration.get("testDouble"));
assertInstanceOf(BigDecimal.class, dummy.configuration.get("testFloat"));
assertInstanceOf(BigDecimal.class, dummy.configuration.get("testBigDecimal"));
assertInstanceOf(Boolean.class, dummy.configuration.get("testBoolean"));
assertInstanceOf(String.class, dummy.configuration.get("testString"));
}
@Test
@ -91,14 +91,14 @@ public class JsonStorageTest extends JavaTest {
DummyObject dummy = objectStorage.get("DummyObject");
assertNotNull(dummy);
assertTrue(dummy.configuration.get("testShort") instanceof BigDecimal);
assertTrue(dummy.configuration.get("testInt") instanceof BigDecimal);
assertTrue(dummy.configuration.get("testLong") instanceof BigDecimal);
assertTrue(dummy.configuration.get("testDouble") instanceof BigDecimal);
assertTrue(dummy.configuration.get("testFloat") instanceof BigDecimal);
assertTrue(dummy.configuration.get("testBigDecimal") instanceof BigDecimal);
assertTrue(dummy.configuration.get("testBoolean") instanceof Boolean);
assertTrue(dummy.configuration.get("testString") instanceof String);
assertInstanceOf(BigDecimal.class, dummy.configuration.get("testShort"));
assertInstanceOf(BigDecimal.class, dummy.configuration.get("testInt"));
assertInstanceOf(BigDecimal.class, dummy.configuration.get("testLong"));
assertInstanceOf(BigDecimal.class, dummy.configuration.get("testDouble"));
assertInstanceOf(BigDecimal.class, dummy.configuration.get("testFloat"));
assertInstanceOf(BigDecimal.class, dummy.configuration.get("testBigDecimal"));
assertInstanceOf(Boolean.class, dummy.configuration.get("testBoolean"));
assertInstanceOf(String.class, dummy.configuration.get("testString"));
}
@Test

View File

@ -86,7 +86,7 @@ class BaseDynamicCommandDescriptionProviderTest {
verify(eventPublisherMock, times(1)).post(capture.capture());
Event event = capture.getValue();
assertTrue(event instanceof ChannelDescriptionChangedEvent);
assertInstanceOf(ChannelDescriptionChangedEvent.class, event);
ChannelDescriptionChangedEvent cdce = (ChannelDescriptionChangedEvent) event;
assertEquals(CommonChannelDescriptionField.COMMAND_OPTIONS, cdce.getField());

View File

@ -86,7 +86,7 @@ class BaseDynamicStateDescriptionProviderTest {
verify(eventPublisherMock, times(1)).post(capture.capture());
Event event = capture.getValue();
assertTrue(event instanceof ChannelDescriptionChangedEvent);
assertInstanceOf(ChannelDescriptionChangedEvent.class, event);
ChannelDescriptionChangedEvent cdce = (ChannelDescriptionChangedEvent) event;
assertEquals(CommonChannelDescriptionField.PATTERN, cdce.getField());
@ -104,7 +104,7 @@ class BaseDynamicStateDescriptionProviderTest {
verify(eventPublisherMock, times(1)).post(capture.capture());
Event event = capture.getValue();
assertTrue(event instanceof ChannelDescriptionChangedEvent);
assertInstanceOf(ChannelDescriptionChangedEvent.class, event);
ChannelDescriptionChangedEvent cdce = (ChannelDescriptionChangedEvent) event;
assertEquals(CommonChannelDescriptionField.STATE_OPTIONS, cdce.getField());

View File

@ -188,7 +188,7 @@ public abstract class AbstractFileTransformationService<T> implements Transforma
}
private void watchSubDirectory(String subDirectory, final WatchService watchService) {
if (watchedDirectories.indexOf(subDirectory) == -1) {
if (!watchedDirectories.contains(subDirectory)) {
String watchedDirectory = getSourcePath() + subDirectory;
Path transformFilePath = Paths.get(watchedDirectory);
try {

View File

@ -300,7 +300,7 @@ public class DefaultChartProvider implements ChartProvider {
} else if (state instanceof OpenClosedType) {
return state == OpenClosedType.CLOSED ? 0 : 1;
} else {
logger.debug("Unsupported item type in chart: {}", state.getClass().toString());
logger.debug("Unsupported item type in chart: {}", state.getClass());
return 0;
}
}

View File

@ -632,7 +632,7 @@ public class ItemUIRegistryImplTest {
State stateForSlider = uiRegistry.getState(sliderWidget);
assertTrue(stateForSlider instanceof PercentType);
assertInstanceOf(PercentType.class, stateForSlider);
PercentType pt = (PercentType) stateForSlider;

View File

@ -84,7 +84,7 @@ public class ManagedMetadataProviderImpl extends AbstractManagedProvider<Metadat
@Override
public Collection<Metadata> getAll() {
return super.getAll().stream().map(this::normalizeMetadata).collect(Collectors.toUnmodifiableList());
return super.getAll().stream().map(this::normalizeMetadata).toList();
}
@Override

View File

@ -708,7 +708,7 @@ public class GroupItemOSGiTest extends JavaOSGiTest {
groupItem.setState(new HSBType("200,80,80"));
groupStateAsPercent = groupItem.getStateAs(PercentType.class);
assertTrue(groupStateAsPercent instanceof PercentType);
assertInstanceOf(PercentType.class, groupStateAsPercent);
assertThat(((PercentType) groupStateAsPercent).intValue(), is(80));
}
@ -725,7 +725,7 @@ public class GroupItemOSGiTest extends JavaOSGiTest {
groupItem.setState(new PercentType(80));
groupStateAsPercent = groupItem.getStateAs(PercentType.class);
assertTrue(groupStateAsPercent instanceof PercentType);
assertInstanceOf(PercentType.class, groupStateAsPercent);
assertThat(((PercentType) groupStateAsPercent).intValue(), is(80));
}
@ -750,11 +750,11 @@ public class GroupItemOSGiTest extends JavaOSGiTest {
assertThat(change.getItemName(), is(groupItem.getName()));
State newEventState = change.getItemState();
assertTrue(newEventState instanceof PercentType);
assertInstanceOf(PercentType.class, newEventState);
assertThat(((PercentType) newEventState).intValue(), is(50));
State newGroupState = groupItem.getState();
assertTrue(newGroupState instanceof PercentType);
assertInstanceOf(PercentType.class, newGroupState);
assertThat(((PercentType) newGroupState).intValue(), is(50));
events.clear();
@ -770,11 +770,11 @@ public class GroupItemOSGiTest extends JavaOSGiTest {
assertThat(change.getItemName(), is(groupItem.getName()));
newEventState = change.getItemState();
assertTrue(newEventState instanceof PercentType);
assertInstanceOf(PercentType.class, newEventState);
assertThat(((PercentType) newEventState).intValue(), is(30));
newGroupState = groupItem.getState();
assertTrue(newGroupState instanceof PercentType);
assertInstanceOf(PercentType.class, newGroupState);
assertThat(((PercentType) newGroupState).intValue(), is(30));
}

View File

@ -43,7 +43,7 @@ public class SystemWideChannelTypesTest extends JavaOSGiTest {
@BeforeEach
public void setUp() {
ChannelTypeProvider provider = getService(ChannelTypeProvider.class, DefaultSystemChannelTypeProvider.class);
assertTrue(provider instanceof DefaultSystemChannelTypeProvider);
assertInstanceOf(DefaultSystemChannelTypeProvider.class, provider);
systemChannelTypeProvider = provider;
}

View File

@ -40,7 +40,7 @@ public class SystemProfileI18nOSGiTest extends JavaOSGiTest {
@BeforeEach
public void setUp() {
ProfileTypeProvider provider = getService(ProfileTypeProvider.class, SystemProfileFactory.class);
assertTrue(provider instanceof SystemProfileFactory);
assertInstanceOf(SystemProfileFactory.class, provider);
systemProfileTypeProvider = provider;
}

View File

@ -67,7 +67,7 @@ public class SystemWideChannelTypesTest extends JavaOSGiTest {
assertThat(channelTypeRegistry, is(notNullValue()));
ChannelTypeProvider provider = getService(ChannelTypeProvider.class, DefaultSystemChannelTypeProvider.class);
assertTrue(provider instanceof DefaultSystemChannelTypeProvider);
assertInstanceOf(DefaultSystemChannelTypeProvider.class, provider);
systemChannelTypeProvider = provider;
}