Fix new SAT findings (#2291)

Signed-off-by: Wouter Born <github@maindrain.net>
This commit is contained in:
Wouter Born
2021-04-14 18:41:07 +02:00
committed by GitHub
parent 00c822816c
commit 05b7ec86f1
35 changed files with 63 additions and 113 deletions
@@ -14,7 +14,13 @@ package org.openhab.core.automation.module.script.rulesupport.internal.loader;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Implementation of {@link ScheduledExecutorService} which simply delegates to the instance supplied.
@@ -763,7 +763,7 @@ public class RuleEngineImpl implements RuleManager, RegistryChangeListener<Modul
Set<String> rules = e.getValue();
if (rules.contains(rUID)) {
rules.remove(rUID);
if (rules.size() < 1) {
if (rules.isEmpty()) {
it.remove();
}
}
@@ -116,7 +116,6 @@ final class RuleExecutionSimulator {
*/
private List<RuleExecution> simulateExecutionsForCronBasedRule(Rule rule, ZonedDateTime from, ZonedDateTime until,
SchedulerTemporalAdjuster temporalAdjuster) {
final List<RuleExecution> result = new ArrayList<>();
ZonedDateTime currentTime = ZonedDateTime.from(temporalAdjuster.adjustInto(from));
@@ -81,11 +81,7 @@ public class CompareConditionHandler extends BaseConditionModuleHandler {
case "EQUALS":
// EQUALS
if (toCompare == null) {
if ("null".equals(rightOperandString) || "".equals(rightOperandString)) {
return true;
} else {
return false;
}
return "null".equals(rightOperandString) || "".equals(rightOperandString);
} else {
return toCompare.equals(rightValue);
}
@@ -68,7 +68,7 @@ public final class ConfigStatusService implements ConfigStatusCallback {
* @throws IllegalArgumentException if given entityId is null or empty
*/
public ConfigStatusInfo getConfigStatus(String entityId, final Locale locale) {
if (entityId == null || entityId.equals("")) {
if (entityId == null || entityId.isEmpty()) {
throw new IllegalArgumentException("EntityId must not be null or empty");
}
@@ -446,10 +446,8 @@ public abstract class AbstractDiscoveryService implements DiscoveryService {
private boolean getAutoDiscoveryEnabled(Object autoDiscoveryEnabled) {
if (autoDiscoveryEnabled instanceof String) {
return Boolean.valueOf((String) autoDiscoveryEnabled);
} else if (autoDiscoveryEnabled == Boolean.TRUE) {
return true;
} else {
return false;
return autoDiscoveryEnabled == Boolean.TRUE;
}
}
@@ -507,10 +507,7 @@ public final class PersistentInbox implements Inbox, DiscoveryListener, ThingReg
}
private boolean isInRegistry(ThingUID thingUID) {
if (thingRegistry.get(thingUID) == null) {
return false;
}
return true;
return thingRegistry.get(thingUID) != null;
}
private void removeResultsForBridge(ThingUID bridgeUID) {
@@ -301,7 +301,7 @@ public class ConfigDispatcher {
// configuration file contains a PID Marker
List<String> lines = Files.readAllLines(configFile.toPath(), StandardCharsets.UTF_8);
String exclusivePID = lines.size() > 0 ? getPIDFromLine(lines.get(0)) : null;
String exclusivePID = !lines.isEmpty() ? getPIDFromLine(lines.get(0)) : null;
if (exclusivePID != null) {
if (exclusivePIDMap.contains(exclusivePID)) {
logger.warn(
@@ -54,8 +54,6 @@ public class ConfigDescriptionConverter extends GenericUnmarshaller<ConfigDescri
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
ConfigDescription configDescription = null;
// read attributes
Map<String, String> attributes = this.attributeMapValidator.readValidatedAttributes(reader);
String uriText = attributes.get("uri");
@@ -56,11 +56,7 @@ public class OpenHABHttpContext implements WrappingHttpContext {
DefaultHandlerContext handlerContext = new DefaultHandlerContext(queue);
handlerContext.execute(request, response);
if (handlerContext.hasError()) {
return false;
}
return true;
return !handlerContext.hasError();
}
@Override
@@ -28,11 +28,11 @@ import org.eclipse.jdt.annotation.Nullable;
*/
@NonNullByDefault
public class ExpiringUserSecurityContextCache {
final static private int MAX_SIZE = 10;
final static private int CLEANUP_FREQUENCY = 10;
private static final int MAX_SIZE = 10;
private static final int CLEANUP_FREQUENCY = 10;
final private long keepPeriod;
final private Map<String, Entry> entryMap;
private final long keepPeriod;
private final Map<String, Entry> entryMap;
private int calls = 0;
@@ -85,7 +85,7 @@ public class ExpiringUserSecurityContextCache {
static class Entry {
public long timestamp;
final public UserSecurityContext value;
public final UserSecurityContext value;
Entry(long timestamp, UserSecurityContext value) {
this.timestamp = timestamp;
@@ -38,7 +38,6 @@ import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
@@ -100,8 +99,6 @@ public class TokenResource implements RESTResource {
/** The default lifetime of tokens in minutes before they expire */
public static final int TOKEN_LIFETIME = 60;
private @Context @NonNullByDefault({}) UriInfo uriInfo;
private final UserRegistry userRegistry;
private final JwtHelper jwtHelper;
@@ -144,12 +144,9 @@ public class ProfileTypeResource implements RESTResource {
private boolean profileTypeMatchesItemType(ProfileType pt, String itemType) {
Collection<String> supportedItemTypesOnProfileType = pt.getSupportedItemTypes();
if (supportedItemTypesOnProfileType.isEmpty()
return supportedItemTypesOnProfileType.isEmpty()
|| supportedItemTypesOnProfileType.contains(ItemUtil.getMainItemType(itemType))
|| supportedItemTypesOnProfileType.contains(itemType)) {
return true;
}
return false;
|| supportedItemTypesOnProfileType.contains(itemType);
}
private boolean triggerProfileMatchesProfileType(ProfileType profileType, ChannelType channelType) {
@@ -157,11 +157,7 @@ public class ThingResource implements RESTResource {
private final FirmwareRegistry firmwareRegistry;
private final FirmwareUpdateService firmwareUpdateService;
private final ItemChannelLinkRegistry itemChannelLinkRegistry;
private final ItemFactory itemFactory;
private final ItemRegistry itemRegistry;
private final LocaleService localeService;
private final ManagedItemChannelLinkProvider managedItemChannelLinkProvider;
private final ManagedItemProvider managedItemProvider;
private final ManagedThingProvider managedThingProvider;
private final ThingManager thingManager;
private final ThingRegistry thingRegistry;
@@ -195,11 +191,7 @@ public class ThingResource implements RESTResource {
this.firmwareRegistry = firmwareRegistry;
this.firmwareUpdateService = firmwareUpdateService;
this.itemChannelLinkRegistry = itemChannelLinkRegistry;
this.itemFactory = itemFactory;
this.itemRegistry = itemRegistry;
this.localeService = localeService;
this.managedItemChannelLinkProvider = managedItemChannelLinkProvider;
this.managedItemProvider = managedItemProvider;
this.managedThingProvider = managedThingProvider;
this.thingManager = thingManager;
this.thingRegistry = thingRegistry;
@@ -55,25 +55,33 @@ public class ServiceDescription {
@Override
public boolean equals(Object obj) {
if (this == obj)
if (this == obj) {
return true;
if (obj == null)
}
if (obj == null) {
return false;
if (getClass() != obj.getClass())
}
if (getClass() != obj.getClass()) {
return false;
}
ServiceDescription other = (ServiceDescription) obj;
if (serviceName == null) {
if (other.serviceName != null)
if (other.serviceName != null) {
return false;
} else if (!serviceName.equals(other.serviceName))
}
} else if (!serviceName.equals(other.serviceName)) {
return false;
if (servicePort != other.servicePort)
}
if (servicePort != other.servicePort) {
return false;
}
if (serviceType == null) {
if (other.serviceType != null)
if (other.serviceType != null) {
return false;
} else if (!serviceType.equals(other.serviceType))
}
} else if (!serviceType.equals(other.serviceType)) {
return false;
}
return true;
}
@@ -942,9 +942,8 @@ public class SmokeTest extends IntegrationTestSupport {
}
private long getNumberOfOpenClients(SpyingSocketFactory socketSpy) {
final InetAddress testServerAddress;
try {
testServerAddress = localAddress();
localAddress();
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
@@ -353,11 +353,7 @@ public class UpnpIOServiceImpl implements UpnpIOService, RegistryListener {
@Override
public boolean isRegistered(UpnpIOParticipant participant) {
if (upnpService.getRegistry().getDevice(new UDN(participant.getUDN()), true) != null) {
return true;
} else {
return false;
}
return upnpService.getRegistry().getDevice(new UDN(participant.getUDN()), true) != null;
}
@Override
@@ -22,7 +22,7 @@ public class MathUtils {
/**
* calculates the greatest common divisor of two numbers
*
*
* @param m
* first number
* @param n
@@ -30,14 +30,15 @@ public class MathUtils {
* @return the gcd of m and n
*/
public static int gcd(int m, int n) {
if (m % n == 0)
if (m % n == 0) {
return n;
}
return gcd(n, m % n);
}
/**
* calculates the least common multiple of two numbers
*
*
* @param m
* first number
* @param n
@@ -50,7 +51,7 @@ public class MathUtils {
/**
* calculates the greatest common divisor of n numbers
*
*
* @param numbers
* an array of n numbers
* @return the gcd of the n numbers
@@ -65,7 +66,7 @@ public class MathUtils {
/**
* determines the least common multiple of n numbers
*
*
* @param numbers
* an array of n numbers
* @return the least common multiple of all numbers of the array
@@ -34,7 +34,7 @@ public class MappingUriExtensionsTest {
public @TempDir File folder;
private File confFolder;
private static Collection<Object[]> data() {
public static Collection<Object[]> data() {
return List.of(new Object[][] { //
{ "conf", //
"file:///q:/conf", //
@@ -75,10 +75,7 @@ public class PersistItemsJob implements SchedulerRunnable {
}
}
// if no strategies are given, check the default strategies to use
if (config.getStrategies().isEmpty() && isDefault(defaults, strategyName)) {
return true;
}
return false;
return config.getStrategies().isEmpty() && isDefault(defaults, strategyName);
}
private boolean isDefault(List<PersistenceStrategy> defaults, String strategyName) {
@@ -338,8 +338,9 @@ public class ThingManagerImpl
ChannelUID channelUID = new ChannelUID(channelGroupUID, channelDefinition.getId());
ChannelBuilder channelBuilder = ThingFactoryHelper.createChannelBuilder(channelUID,
channelDefinition, configDescriptionRegistry);
if (channelBuilder != null)
if (channelBuilder != null) {
channelBuilders.add(channelBuilder);
}
}
}
return channelBuilders;
@@ -127,13 +127,13 @@ public class LinkConsoleCommandExtension extends AbstractConsoleCommandExtension
if (!channelUIDS.contains(itemChannelLink.getLinkedUID())) {
console.println("Thing channel missing: " + itemChannelLink.toString() + " "
+ itemChannelLink.getConfiguration().toString());
if (action.equals("purge")) {
if ("purge".equals(action)) {
removeChannelLink(console, itemChannelLink.getUID());
}
} else if (!itemNames.contains(itemChannelLink.getItemName())) {
console.println("Item missing: " + itemChannelLink.toString() + " "
+ itemChannelLink.getConfiguration().toString());
if (action.equals("purge")) {
if ("purge".equals(action)) {
removeChannelLink(console, itemChannelLink.getUID());
}
}
@@ -34,7 +34,6 @@ import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.openhab.core.i18n.UnitProvider;
import org.openhab.core.items.GroupItem;
import org.openhab.core.items.Item;
import org.openhab.core.items.ItemNotFoundException;
@@ -97,7 +96,6 @@ public class ItemUIRegistryImplTest {
private @Mock ItemRegistry registry;
private @Mock Widget widget;
private @Mock Item item;
private @Mock UnitProvider unitProvider;
@BeforeEach
public void setup() throws Exception {
@@ -484,8 +484,8 @@ public abstract class AbstractRuleBasedInterpreter implements HumanLanguageInter
protected String executeSingle(ResourceBundle language, String[] labelFragments, Command command)
throws InterpretationException {
List<Item> items = getMatchingItems(language, labelFragments, command.getClass());
if (items.size() < 1) {
if (getMatchingItems(language, labelFragments, null).size() >= 1) {
if (items.isEmpty()) {
if (!getMatchingItems(language, labelFragments, null).isEmpty()) {
throw new InterpretationException(
language.getString(COMMAND_NOT_ACCEPTED).replace("<cmd>", command.toString()));
} else {
@@ -51,7 +51,7 @@ public class TokenList {
* @return the first token of the list
*/
public String head() {
return (list.size() < 1 || head < 0 || head >= list.size()) ? null : list.get(head);
return (list.isEmpty() || head < 0 || head >= list.size()) ? null : list.get(head);
}
/**
@@ -60,7 +60,7 @@ public class TokenList {
* @return the last token of the list
*/
public String tail() {
return (list.size() < 1 || tail < 0 || tail >= list.size()) ? null : list.get(tail);
return (list.isEmpty() || tail < 0 || tail >= list.size()) ? null : list.get(tail);
}
/**
@@ -38,8 +38,6 @@ import org.osgi.framework.ServiceReference;
@ExtendWith(MockitoExtension.class)
public class MetadataRegistryImplTest {
private static final String ITEM_NAME = "itemName";
@SuppressWarnings("rawtypes")
private @Mock ServiceReference managedProviderRef;
private @Mock BundleContext bundleContext;
@@ -71,7 +71,7 @@ public class VolumetricFlowRateTest {
assertThat(parsedUnit, is(equalTo(unit)));
}
private static Stream<Arguments> arguments() {
public static Stream<Arguments> arguments() {
return Stream.of(Arguments.of(Units.LITRE_PER_MINUTE, "l/min", 100.0, 6.0),
Arguments.of(Units.CUBICMETRE_PER_SECOND, "m³/s", 100.0, 360000.0),
Arguments.of(Units.CUBICMETRE_PER_MINUTE, "m³/min", 100.0, 6000.0),
@@ -80,7 +80,7 @@ public class AutomationIntegrationJsonTest extends JavaOSGiTest {
private RuleManager ruleManager;
private ManagedRuleProvider managedRuleProvider;
private ModuleTypeRegistry moduleTypeRegistry;
private Event ruleEvent;
private @SuppressWarnings("unused") Event ruleEvent;
public Event itemEvent;
// keep storage rules imported from json files
@@ -351,10 +351,12 @@ public class AutomationIntegrationJsonTest extends JavaOSGiTest {
SwitchItem myPresenceItem = (SwitchItem) itemRegistry.getItem("myPresenceItem");
myPresenceItem.setState(OnOffType.ON);
SwitchItem myLampItem = (SwitchItem) itemRegistry.getItem("myLampItem");
SwitchItem myLampItem = (SwitchItem) itemRegistry.getItem("myLampItem");
assertThat(myLampItem.getState(), is(UnDefType.NULL));
SwitchItem myMotionItem = (SwitchItem) itemRegistry.getItem("myMotionItem");
assertThat(myMotionItem.getState(), is(UnDefType.NULL));
@NonNullByDefault
EventSubscriber eventHandler = new EventSubscriber() {
@@ -362,20 +362,12 @@ public class AutomationIntegrationTest extends JavaOSGiTest {
Map<String, Object> params = new HashMap<>();
params.put("itemName", "myMotionItem3");
Configuration triggerConfig = new Configuration(params);
params = new HashMap<>();
params.put("itemName", "myMotionItem3");
params.put("state", "ON");
Configuration condition1Config = new Configuration(params);
Map<String, Object> eventInputs = Map.of("event", "ItemStateChangeTrigger3.event");
params = new HashMap<>();
params.put("operator", "=");
params.put("itemName", "myPresenceItem3");
params.put("state", "ON");
Configuration condition2Config = new Configuration(params);
params = new HashMap<>();
params.put("itemName", "myLampItem3");
params.put("command", "ON");
Configuration actionConfig = new Configuration(params);
List<Trigger> triggers = List.of(ModuleBuilder.createTrigger().withId("ItemStateChangeTrigger3")
.withTypeUID("core.ItemStateChangeTrigger").withConfiguration(triggerConfig).build());
List<Action> actions = List.of(ModuleBuilder.createAction().withId("ItemPostCommandAction3")
@@ -462,8 +454,6 @@ public class AutomationIntegrationTest extends JavaOSGiTest {
assertThat(ruleEngine.getStatusInfo(rule.getUID()).getStatus(), is(RuleStatus.IDLE));
}, 3000, 100);
Item myLampItem3 = itemRegistry.getItem("myLampItem3");
EventSubscriber itemEventHandler = new EventSubscriber() {
@Override
public Set<String> getSubscribedEventTypes() {
@@ -598,8 +588,6 @@ public class AutomationIntegrationTest extends JavaOSGiTest {
});
EventPublisher eventPublisher = getService(EventPublisher.class);
SwitchItem myPresenceItem = (SwitchItem) itemRegistry.getItem("myPresenceItem4");
// prepare the presenceItems state to be on to match the second condition of the rule
eventPublisher.post(ItemEventFactory.createStateEvent("myPresenceItem4", OnOffType.ON));
@@ -50,7 +50,6 @@ import org.openhab.core.events.EventSubscriber;
import org.openhab.core.items.Item;
import org.openhab.core.items.ItemNotFoundException;
import org.openhab.core.items.ItemProvider;
import org.openhab.core.items.ItemRegistry;
import org.openhab.core.items.events.ItemCommandEvent;
import org.openhab.core.items.events.ItemEventFactory;
import org.openhab.core.library.items.SwitchItem;
@@ -121,10 +120,6 @@ public abstract class BasicConditionHandlerTest extends JavaOSGiTest {
String testItemName1 = "TriggeredItem";
String testItemName2 = "SwitchedItem";
ItemRegistry itemRegistry = getService(ItemRegistry.class);
SwitchItem triggeredItem = (SwitchItem) itemRegistry.getItem(testItemName1);
SwitchItem switchedItem = (SwitchItem) itemRegistry.getItem(testItemName2);
/*
* Create Rule
*/
@@ -58,9 +58,7 @@ public class GenericThingProviderTest4 extends JavaOSGiTest {
private ReadyService readyService;
private Bundle bundle;
private ThingHandlerFactory hueThingHandlerFactory;
private boolean finished;
private int bridgeInitializeCounter;
private int thingInitializeCounter;
boolean slowInit;
private static final String TESTMODEL_NAME = "testModelX.things";
@@ -136,7 +134,6 @@ public class GenericThingProviderTest4 extends JavaOSGiTest {
}
};
finished = false;
bundle = FrameworkUtil.getBundle(TestHueThingHandlerFactoryX.class);
removeReadyMarker();
@@ -189,14 +186,12 @@ public class GenericThingProviderTest4 extends JavaOSGiTest {
}
private void finishLoading() {
finished = true;
assertThat(bridgeInitializeCounter, is(0));
readyService.markReady(new ReadyMarker("openhab.xmlThingTypes", bundle.getSymbolicName()));
}
private void unload() {
unregisterService(thingTypeProvider);
finished = false;
}
@SuppressWarnings("null")
@@ -73,7 +73,6 @@ public class SafeCallerImplTest extends JavaTest {
private TestInfo testInfo;
private final List<AssertingThread> threads = new LinkedList<>();
private @Mock Runnable mockRunnable;
private @Mock Runnable mockTimeoutHandler;
private @Mock Consumer<Throwable> mockErrorHandler;
@@ -78,8 +78,6 @@ public class ItemRegistryImplTest extends JavaTest {
@BeforeEach
public void beforeEach() {
ItemFactory coreItemFactory = new CoreItemFactory();
GenericItem cameraItem1 = new SwitchItem(CAMERA_ITEM_NAME1);
GenericItem cameraItem2 = new SwitchItem(CAMERA_ITEM_NAME2);
GenericItem cameraItem3 = new NumberItem(CAMERA_ITEM_NAME3);
@@ -223,7 +223,7 @@ public class AbstractWatchServiceTest extends JavaTest {
}
private void fullEventAssertionsByKind(String fileName, Kind<?> kind, boolean osSpecific) throws Exception {
waitForAssert(() -> assertThat(watchService.allFullEvents.size() >= 1, is(true)), DFL_TIMEOUT * 2,
waitForAssert(() -> assertThat(!watchService.allFullEvents.isEmpty(), is(true)), DFL_TIMEOUT * 2,
DFL_SLEEP_TIME);
if (osSpecific && ENTRY_DELETE.equals(kind)) {
@@ -117,7 +117,6 @@ public class ThingManagerOSGiJavaTest extends JavaOSGiTest {
private static final ThingUID BRIDGE_UID = new ThingUID(BRIDGE_TYPE_UID, "bridge");
private static final ChannelUID CHANNEL_UID = new ChannelUID(THING_UID, CHANNEL_ID);
private static final ChannelUID CHANNEL2_UID = new ChannelUID(THING_UID, CHANNEL2_ID);
private static final ChannelGroupUID CHANNEL_GROUP_UID = new ChannelGroupUID(THING_UID, CHANNEL_GROUP_ID);