Skip to content

Commit

Permalink
[infrastructure] improve null-analysis (#46)
Browse files Browse the repository at this point in the history
* improve null-analysis

- upgrade EEA
- make null-analysis more strict
- fix null errors

Signed-off-by: Jan N. Klug <jan.n.klug@rub.de>
  • Loading branch information
J-N-K authored Mar 25, 2021
1 parent b3bd101 commit f6bd3a6
Show file tree
Hide file tree
Showing 40 changed files with 306 additions and 117 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1592,7 +1592,6 @@ private void executeSequenceNode(List<Device> devices, JsonObject nodeToExecute)
logger.debug("added {} device {}", queueObject.hashCode(), serialNumbers);
}

@SuppressWarnings("null") // peek can return null
private void handleExecuteSequenceNode() {
Lock lock = Objects.requireNonNull(locks.computeIfAbsent(TimerType.DEVICES, k -> new ReentrantLock()));
if (lock.tryLock()) {
Expand All @@ -1612,12 +1611,16 @@ private void handleExecuteSequenceNode() {
.get(tmpDevice.serialNumber);
if (tmpQueueObjects != null) {
QueueObject tmpQueueObject = tmpQueueObjects.peek();
Future<?> tmpFuture = tmpQueueObject.future;
Future<?> tmpFuture = null;
if (tmpQueueObject != null) {
tmpFuture = tmpQueueObject.future;
}
if (!queueObject.equals(tmpQueueObject)
|| (tmpFuture != null && !tmpFuture.isDone())) {
execute = false;
break;
}

serial = serial + tmpDevice.serialNumber + " ";
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import java.util.Base64;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
Expand Down Expand Up @@ -135,7 +136,7 @@ public void openURL(String url)
public String getCurrentPackage() throws AndroidDebugBridgeDeviceException, InterruptedException,
AndroidDebugBridgeDeviceReadException, TimeoutException, ExecutionException {
String result = runAdbShell("dumpsys", "window", "windows", "|", "grep", "mFocusedApp");
String targetLine = Arrays.stream(result.split("\n")).findFirst().orElse("");
String targetLine = Objects.requireNonNull(Arrays.stream(result.split("\n")).findFirst().orElse(""));
String[] lineParts = targetLine.split(" ");
if (lineParts.length >= 2) {
String packageActivityName = lineParts[lineParts.length - 2];
Expand Down Expand Up @@ -333,7 +334,8 @@ private String runAdbShell(String... args)
}
lock.lock();
try {
commandFuture = scheduler.submit(() -> {
stopCommandFuture(); // make sure there is not future
Future<String> commandFuture = scheduler.submit(() -> {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
String cmd = String.join(" ", args);
logger.debug("{} - shell:{}", ip, cmd);
Expand All @@ -350,6 +352,7 @@ private String runAdbShell(String... args)
}
return byteArrayOutputStream.toString(StandardCharsets.US_ASCII);
});
this.commandFuture = commandFuture;
return commandFuture.get(timeoutSec, TimeUnit.SECONDS).trim();
} finally {
stopCommandFuture();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,15 +102,16 @@ private CompletableFuture<Result> doNetwork(HttpMethod method, String address, @
}

request.method(method).timeout(timeout, TimeUnit.MILLISECONDS).send(new BufferingResponseListener() {
@NonNullByDefault({})

@Override
public void onComplete(org.eclipse.jetty.client.api.Result result) {
final HttpResponse response = (HttpResponse) result.getResponse();
if (result.getFailure() != null) {
f.completeExceptionally(result.getFailure());
return;
}
f.complete(new Result(getContentAsString(), response.getStatus()));
String content = getContentAsString();
f.complete(new Result(content != null ? content : "", response.getStatus()));
}
});
return f;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import org.eclipse.jdt.annotation.NonNull;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.thing.Bridge;
import org.openhab.core.thing.ChannelUID;
Expand Down Expand Up @@ -284,7 +285,7 @@ public void immediateFade(String channelString, String fadeString, Boolean resum
}

@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
public @NonNull Collection<@NonNull Class<? extends @NonNull ThingHandlerService>> getServices() {
return Collections.singletonList(DmxActions.class);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,14 @@
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.jdt.annotation.NonNull;
import org.openhab.core.library.types.PercentType;

/**
* The {@link ValueSet} holds a set of values and fade times
*
* @author Jan N. Klug - Initial contribution
*/

public class ValueSet {
protected static final Pattern VALUESET_PATTERN = Pattern.compile("^(\\d*):([\\d,]*):([\\d-]*)$");

Expand Down Expand Up @@ -189,7 +189,7 @@ public static List<ValueSet> parseChaseConfig(String chaseConfigString) {
}

@Override
public String toString() {
public @NonNull String toString() {
String str = "fade/hold:" + String.valueOf(fadeTime) + "/" + String.valueOf(holdTime) + ": ";
for (Integer value : values) {
str += String.valueOf(value) + " ";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
*/
package org.smarthomej.binding.dmx.internal.action;

import org.eclipse.jdt.annotation.NonNull;
import org.openhab.core.library.types.PercentType;
import org.smarthomej.binding.dmx.internal.Util;
import org.smarthomej.binding.dmx.internal.multiverse.DmxChannel;
Expand Down Expand Up @@ -139,7 +140,7 @@ public int getNewValue(DmxChannel channel, long currentTime) {
}

@Override
public String toString() {
public @NonNull String toString() {
return "FadeAction: " + String.valueOf(targetValue) + ", fade time " + String.valueOf(fadeTime)
+ "ms, hold time " + String.valueOf(holdTime) + "ms";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.jdt.annotation.NonNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand Down Expand Up @@ -132,7 +133,7 @@ public String getAddressString() {
* @return string representation of this node (address:port)
*/
@Override
public String toString() {
public @NonNull String toString() {
if (this.address == null) {
return "(null):" + String.valueOf(this.port);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ protected void sendDmxData() {
universe.calculateBuffer(now);
for (IpNode receiverNode : receiverNodes.keySet()) {
Socket socket = receiverNodes.get(receiverNode);
if (socket.isConnected()) {
if (socket != null && socket.isConnected()) {
try {
socket.getOutputStream().write(universe.getBuffer());
} catch (IOException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
import java.util.stream.IntStream;
import java.util.stream.Stream;

import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smarthomej.binding.dmx.internal.Util;
Expand Down Expand Up @@ -92,20 +94,20 @@ public void setUniverseId(int universeId) {
}

@Override
public int compareTo(BaseDmxChannel otherDmxChannel) {
public int compareTo(@Nullable BaseDmxChannel otherDmxChannel) {
if (otherDmxChannel == null) {
return -1;
}
int universeCompare = new Integer(getUniverseId()).compareTo(new Integer(otherDmxChannel.getUniverseId()));
int universeCompare = Integer.valueOf(getUniverseId()).compareTo(otherDmxChannel.getUniverseId());
if (universeCompare == 0) {
return new Integer(getChannelId()).compareTo(new Integer(otherDmxChannel.getChannelId()));
return Integer.valueOf(getChannelId()).compareTo(otherDmxChannel.getChannelId());
} else {
return universeCompare;
}
}

@Override
public String toString() {
public @NonNull String toString() {
return universeId + ":" + dmxChannelId;
}

Expand All @@ -125,9 +127,9 @@ public static List<BaseDmxChannel> fromString(String dmxChannelString, int defau
Matcher channelMatch = CHANNEL_PATTERN.matcher(singleDmxChannelString);
if (channelMatch.matches()) {
final int universeId = (channelMatch.group(1) == null) ? defaultUniverseId
: Integer.valueOf(channelMatch.group(1));
dmxChannelWidth = channelMatch.group(3).equals("") ? 1 : Integer.valueOf(channelMatch.group(3));
dmxChannelId = Integer.valueOf(channelMatch.group(2));
: Integer.parseInt(channelMatch.group(1));
dmxChannelWidth = channelMatch.group(3).equals("") ? 1 : Integer.parseInt(channelMatch.group(3));
dmxChannelId = Integer.parseInt(channelMatch.group(2));
LOGGER.trace("parsed channel string {} to universe {}, id {}, width {}", singleDmxChannelString,
universeId, dmxChannelId, dmxChannelWidth);
IntStream.range(dmxChannelId, dmxChannelId + dmxChannelWidth)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;

import org.mockito.ArgumentCaptor;
Expand Down Expand Up @@ -93,6 +94,7 @@ protected void assertThingStatus(Thing thing) {
// check that thing properly follows bridge status
ThingHandler handler = thing.getHandler();
assertNotNull(handler);
Objects.requireNonNull(handler);
handler.bridgeStatusChanged(ThingStatusInfoBuilder.create(ThingStatus.OFFLINE).build());
waitForAssert(() -> assertEquals(ThingStatus.OFFLINE, thing.getStatusInfo().getStatus()));
handler.bridgeStatusChanged(ThingStatusInfoBuilder.create(ThingStatus.ONLINE).build());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -287,8 +287,9 @@ private void createChannel(Channel channel) {
// we need a key consisting of stateContent and URL, only if both are equal, we can use the same cache
String key = channelConfig.stateContent + "$" + stateUrl;
channelUrls.put(channelUID, key);
urlHandlers.computeIfAbsent(key, k -> new RefreshingUrlCache(scheduler, rateLimitedHttpClient, stateUrl,
config, channelConfig.stateContent)).addConsumer(itemValueConverter::process);
Objects.requireNonNull(urlHandlers.computeIfAbsent(key, k -> new RefreshingUrlCache(scheduler,
rateLimitedHttpClient, stateUrl, config, channelConfig.stateContent)))
.addConsumer(itemValueConverter::process);
}

StateDescription stateDescription = StateDescriptionFragmentBuilder.create()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public HttpResponseListener(CompletableFuture<@Nullable ContentWrapper> future,
}

@Override
public void onComplete(@NonNullByDefault({}) Result result) {
public void onComplete(Result result) {
Response response = result.getResponse();
if (logger.isTraceEnabled()) {
logger.trace("Received from '{}': {}", result.getRequest().getURI(), responseToLogString(response));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Objects;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.TestInstance;
Expand Down Expand Up @@ -76,46 +77,46 @@ void testInit() throws InterruptedException, IOException {
handler.initialize();
Mockito.verify(myThing, Mockito.times(1)).getConfiguration();

System.in.read();
Objects.requireNonNull(System.in).read();
handler.dispose();
}

// @Test
void testCleanRegion() throws IOException, InterruptedException {
handler.initialize();

System.in.read();
Objects.requireNonNull(System.in).read();

ChannelUID cmd = new ChannelUID("my:thi:blabla:command");
handler.handleCommand(cmd, new StringType("cleanRegions:AABBCCDDEEFFGGHH;2,3"));

System.in.read();
Objects.requireNonNull(System.in).read();
handler.dispose();
}

// @Test
void testDock() throws IOException, InterruptedException {
handler.initialize();

System.in.read();
Objects.requireNonNull(System.in).read();

ChannelUID cmd = new ChannelUID("my:thi:blabla:command");
handler.handleCommand(cmd, new StringType("dock"));

System.in.read();
Objects.requireNonNull(System.in).read();
handler.dispose();
}

// @Test
void testStop() throws IOException, InterruptedException {
handler.initialize();

System.in.read();
Objects.requireNonNull(System.in).read();

ChannelUID cmd = new ChannelUID("my:thi:blabla:command");
handler.handleCommand(cmd, new StringType("stop"));

System.in.read();
Objects.requireNonNull(System.in).read();
handler.dispose();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.thing.ThingStatus;
Expand Down Expand Up @@ -222,7 +223,6 @@ private void disconnect(@Nullable Exception e) {
}
}

@SuppressWarnings("null")
private void releaseConnection() {
logger.debug("Bridge {} is disconnecting from the KNX bus", thingUID);
readDatapoints.clear();
Expand All @@ -241,7 +241,7 @@ private void releaseConnection() {
});
}

private <@Nullable T> T nullify(T target, @Nullable Consumer<T> lastWill) {
private <T> @Nullable T nullify(@Nullable T target, @Nullable Consumer<@NonNull T> lastWill) {
if (target != null && lastWill != null) {
lastWill.accept(target);
}
Expand Down Expand Up @@ -272,7 +272,6 @@ private String toDPTValue(Type type, String dpt) {
return typeHelper.toDPTValue(type, dpt);
}

@SuppressWarnings("null")
private void readNextQueuedDatapoint() {
if (!connectIfNotAutomatic()) {
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,12 +143,20 @@ private Map<String, String> readDeviceDescription(IndividualAddress address) {
if (data != null) {
final DD0 dd = DeviceDescriptor.DD0.from(data);

ret.put(FIRMWARE_TYPE, Firmware.getName(dd.firmwareType()));
ret.put(FIRMWARE_VERSION, Firmware.getName(dd.firmwareVersion()));
ret.put(FIRMWARE_SUBVERSION, Firmware.getName(dd.firmwareSubcode()));
logger.debug("The device with address {} is of type {}, version {}, subversion {}", address,
Firmware.getName(dd.firmwareType()), Firmware.getName(dd.firmwareVersion()),
Firmware.getName(dd.firmwareSubcode()));
String type = Firmware.getName(dd.firmwareType());
if (type != null) {
ret.put(FIRMWARE_TYPE, type);
}
String version = Firmware.getName(dd.firmwareVersion());
if (version != null) {
ret.put(FIRMWARE_VERSION, version);
}
String subVersion = Firmware.getName(dd.firmwareSubcode());
if (subVersion != null) {
ret.put(FIRMWARE_SUBVERSION, subVersion);
}
logger.debug("The device with address {} is of type {}, version {}, subversion {}", address, type, version,
subVersion);
} else {
logger.debug("The KNX device with address {} does not expose a Device Descriptor", address);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
*/
package org.smarthomej.binding.knx.internal.client;

import org.eclipse.jdt.annotation.Nullable;

import tuwien.auto.calimero.datapoint.Datapoint;

/**
Expand Down Expand Up @@ -57,7 +59,7 @@ public int hashCode() {
}

@Override
public boolean equals(Object obj) {
public boolean equals(@Nullable Object obj) {
if (this == obj) {
return true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,8 @@ protected void attachToClient() {
}
DeviceConfig config = getConfigAs(DeviceConfig.class);
try {
if (config.getAddress() != null && !config.getAddress().isEmpty()) {
String configAddress = config.getAddress();
if (configAddress != null && !configAddress.isEmpty()) {
updateStatus(ThingStatus.UNKNOWN);
address = new IndividualAddress(config.getAddress());

Expand Down
Loading

0 comments on commit f6bd3a6

Please sign in to comment.