Skip to content

Commit

Permalink
Another warning hunting session, focusing on Potential null pointer a…
Browse files Browse the repository at this point in the history
…ccess

Signed-off-by: Gaël L'hopital <[email protected]>
  • Loading branch information
clinique committed Dec 9, 2024
1 parent 8e4cebd commit 33d1240
Show file tree
Hide file tree
Showing 19 changed files with 78 additions and 64 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,12 @@ public boolean equals(@Nullable Object obj) {
if (!payload.equals(other.payload)) {
return false;
}
if (source == null) {
String localSource = source;
if (localSource == null) {
if (other.source != null) {
return false;
}
} else if (!source.equals(other.source)) {
} else if (!localSource.equals(other.source)) {
return false;
}
if (!topic.equals(other.topic)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -98,13 +99,14 @@ void handleExecutionException(Method method, ExecutionException e) {
void handleException(Method method, InvocationTargetException e) {
Throwable cause = e.getCause();
logger.error(MSG_ERROR, toString(method), target, cause == null ? "" : cause.getMessage(), e.getCause());
if (exceptionHandler != null) {
exceptionHandler.accept(cause == null ? e : cause);
Consumer<Throwable> localConsumer = exceptionHandler;
if (localConsumer != null) {
localConsumer.accept(cause == null ? e : cause);
}
}

void handleDuplicate(Method method, DuplicateExecutionException e) {
Thread thread = e.getCallable().getThread();
Thread thread = Objects.requireNonNull(e.getCallable().getThread());
logger.debug(MSG_DUPLICATE, toString(method), target, toString(e.getCallable().getMethod()), thread.getName(),
thread.getId(), thread.getState().toString(), getStacktrace(thread));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,16 +101,15 @@ public MetadataStateDescriptionFragmentProvider(final @Reference MetadataRegistr
builder.withReadOnly(getBoolean(readOnly));
}

if (metadata.getConfiguration().containsKey("options")) {
List<StateOption> stateOptions = Stream
.of(metadata.getConfiguration().get("options").toString().split(",")).map(o -> {
if (o.contains("=")) {
var pair = parseValueLabelPair(o.trim());
return new StateOption(pair[0], pair[1]);
} else {
return new StateOption(o.trim(), null);
}
}).toList();
if (metadata.getConfiguration().get("options") instanceof Object options) {
List<StateOption> stateOptions = Stream.of(options.toString().split(",")).map(o -> {
if (o.contains("=")) {
var pair = parseValueLabelPair(o.trim());
return new StateOption(pair[0], pair[1]);
} else {
return new StateOption(o.trim(), null);
}
}).toList();
builder.withOptions(stateOptions);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
*
* @author Jan N. Klug - Initial contribution
*/
@SuppressWarnings("serial")
@NonNullByDefault
public class CurrencyConverter extends AbstractConverter {

Expand Down Expand Up @@ -103,7 +104,7 @@ public boolean isLinear() {
@SuppressWarnings("unchecked")
Map<Class<? extends AbstractConverter>, Integer> original = (Map<Class<? extends AbstractConverter>, Integer>) field
.get(null);
original.put(CurrencyConverter.class, 1000);
Objects.requireNonNull(original).put(CurrencyConverter.class, 1000);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new IllegalStateException("Could not add currency converter", e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import java.time.temporal.Temporal;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Objects;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
Expand Down Expand Up @@ -56,7 +57,7 @@ public Temporal adjustInto(@Nullable Temporal temporal) {
if (iterator.hasNext()) {
current = iterator.next();
}
Temporal nextTime = timeDone.plus(current);
Temporal nextTime = Objects.requireNonNull(timeDone).plus(current);
timeDone = nextTime;
return nextTime;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -206,8 +206,8 @@ public ScheduledCompletableFutureRecurring(@Nullable String identifier, ZonedDat
exceptionally(e -> {
synchronized (this) {
if (e instanceof CancellationException) {
if (scheduledPromise != null) {
scheduledPromise.cancel(true);
if (scheduledPromise instanceof ScheduledCompletableFuture promise) {
promise.cancel(true);
}
}
}
Expand All @@ -222,7 +222,7 @@ void setScheduledPromise(ScheduledCompletableFuture<T> future) {
future.cancel(true);
} else {
scheduledPromise = future;
scheduledPromise.getPromise().exceptionally(ex -> {
future.getPromise().exceptionally(ex -> {
// if an error occurs in the scheduled job propagate to parent
ScheduledCompletableFutureRecurring.this.completeExceptionally(ex);
return null;
Expand All @@ -233,12 +233,13 @@ void setScheduledPromise(ScheduledCompletableFuture<T> future) {

@Override
public long getDelay(@Nullable TimeUnit timeUnit) {
return scheduledPromise != null ? scheduledPromise.getDelay(timeUnit) : 0;
return scheduledPromise instanceof ScheduledCompletableFuture promise ? promise.getDelay(timeUnit) : 0;
}

@Override
public ZonedDateTime getScheduledTime() {
return scheduledPromise != null ? scheduledPromise.getScheduledTime() : super.getScheduledTime();
return scheduledPromise instanceof ScheduledCompletableFuture promise ? promise.getScheduledTime()
: super.getScheduledTime();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.locks.ReentrantReadWriteLock;
Expand Down Expand Up @@ -114,7 +115,7 @@ public void unregisterTracker(ReadyTracker readyTracker) {
}

private void notifyTracker(ReadyTracker readyTracker, Consumer<ReadyMarker> action) {
ReadyMarkerFilter f = trackers.get(readyTracker);
ReadyMarkerFilter f = Objects.requireNonNull(trackers.get(readyTracker));
markers.stream().filter(f::apply).forEach(action);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,11 @@ public void onEvent(@Nullable DirectoryChangeEvent directoryChangeEvent) throws
future.cancel(true);
}
future = scheduler.schedule(() -> notifyListeners(path), PROCESSING_TIME, TimeUnit.MILLISECONDS);
scheduledEventKinds.computeIfAbsent(path, k -> new CopyOnWriteArrayList<>()).add(directoryChangeEvent);
List<DirectoryChangeEvent> list = scheduledEventKinds.computeIfAbsent(path,
k -> new CopyOnWriteArrayList<>());
if (list != null) {
list.add(directoryChangeEvent);
}
scheduledEvents.put(path, future);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,8 @@ public StateDescriptionFragment merge(StateDescriptionFragment fragment) {
if (readOnly == null) {
readOnly = fragment.isReadOnly();
}
if (options == null || options.isEmpty()) {
List<StateOption> localOptions = options;
if (localOptions == null || localOptions.isEmpty()) {
options = fragment.getOptions();
}
return this;
Expand All @@ -205,12 +206,12 @@ public StateDescriptionFragment merge(StateDescriptionFragment fragment) {
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (minimum != null ? minimum.hashCode() : 0);
result = prime * result + (maximum != null ? maximum.hashCode() : 0);
result = prime * result + (step != null ? step.hashCode() : 0);
result = prime * result + (pattern != null ? pattern.hashCode() : 0);
result = prime * result + (minimum instanceof BigDecimal bigDecimal ? bigDecimal.hashCode() : 0);
result = prime * result + (maximum instanceof BigDecimal bigDecimal ? bigDecimal.hashCode() : 0);
result = prime * result + (step instanceof BigDecimal bigDecimal ? bigDecimal.hashCode() : 0);
result = prime * result + (pattern instanceof String string ? string.hashCode() : 0);
result = prime * result + (readOnly ? 1231 : 1237);
result = prime * result + (options != null ? options.hashCode() : 0);
result = prime * result + (options instanceof List<?> list ? list.hashCode() : 0);
return result;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,8 +192,8 @@ public void setItemStateConverter(@Nullable ItemStateConverter itemStateConverte

protected void internalSend(Command command) {
// try to send the command to the bus
if (eventPublisher != null) {
eventPublisher.post(ItemEventFactory.createCommandEvent(this.getName(), command));
if (eventPublisher instanceof EventPublisher publisher) {
publisher.post(ItemEventFactory.createCommandEvent(this.getName(), command));
}
}

Expand Down Expand Up @@ -456,8 +456,8 @@ public void setCategory(@Nullable String category) {

@Override
public @Nullable StateDescription getStateDescription(@Nullable Locale locale) {
if (stateDescriptionService != null) {
return stateDescriptionService.getStateDescription(this.name, locale);
if (stateDescriptionService instanceof StateDescriptionService service) {
return service.getStateDescription(this.name, locale);
}
return null;
}
Expand Down Expand Up @@ -499,8 +499,8 @@ protected void logSetTypeError(TimeSeries timeSeries) {
}

protected @Nullable CommandDescription getCommandOptions(@Nullable Locale locale) {
if (commandDescriptionService != null) {
CommandDescription commandDescription = commandDescriptionService.getCommandDescription(this.name, locale);
if (commandDescriptionService instanceof CommandDescriptionService service) {
CommandDescription commandDescription = service.getCommandDescription(this.name, locale);
if (commandDescription != null) {
return commandDescription;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -224,8 +224,8 @@ public void removeAllMembers() {
*/
@Override
public List<Class<? extends State>> getAcceptedDataTypes() {
if (baseItem != null) {
return baseItem.getAcceptedDataTypes();
if (baseItem instanceof Item item) {
return item.getAcceptedDataTypes();
} else {
List<Class<? extends State>> acceptedDataTypes = null;

Expand All @@ -249,8 +249,8 @@ public List<Class<? extends State>> getAcceptedDataTypes() {
*/
@Override
public List<Class<? extends Command>> getAcceptedCommandTypes() {
if (baseItem != null) {
return baseItem.getAcceptedCommandTypes();
if (baseItem instanceof Item item) {
return item.getAcceptedCommandTypes();
} else {
List<Class<? extends Command>> acceptedCommandTypes = null;

Expand Down Expand Up @@ -289,8 +289,8 @@ protected void internalSend(Command command) {
// if a group does not have a function it cannot have a state
@Nullable
T newState = null;
if (function != null) {
newState = function.getStateAs(getStateMembers(getMembers()), typeClass);
if (function instanceof GroupFunction groupFunction) {
newState = groupFunction.getStateAs(getStateMembers(getMembers()), typeClass);
}

Item baseItem = this.baseItem;
Expand Down Expand Up @@ -354,8 +354,8 @@ public void stateUpdated(Item item, State state) {
State oldState = this.state;
State newState = oldState;
ItemStateConverter itemStateConverter = this.itemStateConverter;
if (function != null && baseItem != null && itemStateConverter != null) {
State calculatedState = function.calculate(getStateMembers(getMembers()));
if (function instanceof GroupFunction groupFunction && baseItem != null && itemStateConverter != null) {
State calculatedState = groupFunction.calculate(getStateMembers(getMembers()));
newState = itemStateConverter.convertToAcceptedState(calculatedState, baseItem);
setState(newState);
sendGroupStateUpdatedEvent(item.getName(), newState);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -252,8 +252,8 @@ protected String keyToString(String key) {
private GroupFunction getGroupFunction(PersistedItem persistedItem, @Nullable Item baseItem) {
GroupFunctionDTO functionDTO = new GroupFunctionDTO();
functionDTO.name = persistedItem.functionName;
if (persistedItem.functionParams != null) {
functionDTO.params = persistedItem.functionParams.toArray(new String[persistedItem.functionParams.size()]);
if (persistedItem.functionParams instanceof List<?> list) {
functionDTO.params = list.toArray(new String[list.size()]);
}
return ItemDTOMapper.mapFunction(baseItem, functionDTO);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,12 +147,14 @@ public State calculate(@Nullable Set<Item> items) {
if (unit == null) {
unit = itemState.getUnit(); // set it to the first item's unit
}
values.add(itemState.toInvertibleUnit(unit).toBigDecimal());
if (itemState.toInvertibleUnit(unit) instanceof QuantityType<?> inverted) {
values.add(inverted.toBigDecimal());
}
}

if (!values.isEmpty()) {
BigDecimal median = Statistics.median(values);
if (median != null) {
if (median != null && unit != null) {
return new QuantityType<>(median, unit);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -176,8 +176,8 @@ public int compareTo(Unit<Currency> that) {
return nameCompare;
}
String thatSymbol = that.getSymbol();
if (symbol != null && thatSymbol != null) {
return symbol.compareTo(thatSymbol);
if (symbol instanceof String localSymbol && thatSymbol != null) {
return localSymbol.compareTo(thatSymbol);
} else if (symbol != null) {
return 1;
} else if (thatSymbol != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,8 @@ protected void deactivate() {
lastKnownInterfaceAddresses = List.of();
networkAddressChangeListeners = ConcurrentHashMap.newKeySet();

if (networkInterfacePollFuture != null) {
networkInterfacePollFuture.cancel(true);
if (networkInterfacePollFuture instanceof ScheduledFuture<?> future) {
future.cancel(true);
networkInterfacePollFuture = null;
}
}
Expand Down Expand Up @@ -159,13 +159,13 @@ public synchronized void modified(Map<String, Object> config) {
public @Nullable String getPrimaryIpv4HostAddress() {
String primaryIP;

if (primaryAddress != null) {
String[] addrString = primaryAddress.split("/");
if (primaryAddress instanceof String address) {
String[] addrString = address.split("/");
if (addrString.length > 1) {
String ip = getIPv4inSubnet(addrString[0], addrString[1]);
if (ip == null) {
// an error has occurred, using first interface like nothing has been configured
LOGGER.warn("Invalid address '{}', will use first interface instead.", primaryAddress);
LOGGER.warn("Invalid address '{}', will use first interface instead.", address);
primaryIP = getFirstLocalIPv4Address();
} else {
primaryIP = ip;
Expand Down Expand Up @@ -513,8 +513,8 @@ public static boolean isValidIPConfig(String ipAddress) {
}

private void scheduleToPollNetworkInterface(int intervalInSeconds) {
if (networkInterfacePollFuture != null) {
networkInterfacePollFuture.cancel(true);
if (networkInterfacePollFuture instanceof ScheduledFuture<?> future) {
future.cancel(true);
networkInterfacePollFuture = null;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -507,7 +508,7 @@ private int parseInt(final String cronExpression, final ChronoField chronoField,
public Temporal adjustInto(@Nullable final Temporal temporal) {
// Never match the actual time, so since our basic
// unit is seconds, we add one second.
Temporal ret = temporal.plus(1, ChronoUnit.SECONDS);
Temporal ret = Objects.requireNonNull(temporal).plus(1, ChronoUnit.SECONDS);

// We loop through the fields until they all match. If
// one of them does not match, its type is incremented
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + command.hashCode();
result = prime * result + (label != null ? label.hashCode() : 0);
result = prime * result + (label instanceof String string ? string.hashCode() : 0);
return result;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,10 +116,10 @@ public List<StateOption> getOptions() {
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (minimum != null ? minimum.hashCode() : 0);
result = prime * result + (maximum != null ? maximum.hashCode() : 0);
result = prime * result + (step != null ? step.hashCode() : 0);
result = prime * result + (pattern != null ? pattern.hashCode() : 0);
result = prime * result + (minimum instanceof BigDecimal bigDecimal ? bigDecimal.hashCode() : 0);
result = prime * result + (maximum instanceof BigDecimal bigDecimal ? bigDecimal.hashCode() : 0);
result = prime * result + (step instanceof BigDecimal bigDecimal ? bigDecimal.hashCode() : 0);
result = prime * result + (pattern instanceof String string ? string.hashCode() : 0);
result = prime * result + (readOnly ? 1231 : 1237);
result = prime * result + options.hashCode();
return result;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + value.hashCode();
result = prime * result + (label != null ? label.hashCode() : 0);
result = prime * result + (label instanceof String string ? string.hashCode() : 0);
return result;
}

Expand Down

0 comments on commit 33d1240

Please sign in to comment.