Skip to content
This repository has been archived by the owner on May 7, 2020. It is now read-only.

Fixed AvoidCatchingNPE and AvoidThrowingRawExceptionTypes issues found by PMD #5318

Merged
merged 1 commit into from
Apr 3, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -90,23 +90,25 @@ private Optional<ScriptEngine> createScriptEngine() {
private void loadConfig() {
Object type = module.getConfiguration().get(SCRIPT_TYPE);
Object script = module.getConfiguration().get(SCRIPT);
if (type == null || !(type instanceof String) || ((String) type).trim().isEmpty()) {
throw new RuntimeException(
String.format("Type is missing in the configuration of module '%s'.", module.getId()));
} else if (script == null || !(script instanceof String) || ((String) script).trim().isEmpty()) {
throw new RuntimeException(
String.format("Script is missing in the configuration of module '%s'.", module.getId()));
if (!isValid(type)) {
throw new IllegalStateException(String.format("Type is missing in the configuration of module '%s'.", module.getId()));
} else if (!isValid(script)) {
throw new IllegalStateException(String.format("Script is missing in the configuration of module '%s'.", module.getId()));
} else {
this.type = (String) type;
this.script = (String) script;
}
}

private boolean isValid(Object parameter) {
return parameter != null && parameter instanceof String && !((String) parameter).trim().isEmpty();
}

/**
* Adds the passed context variables of the rule engine to the context scope of the ScriptEngine, this should be
* updated each time the module is executed
*
* @param engine the scriptengine that is used
* @param engine the script engine that is used
* @param context the variables and types to put into the execution context
*/
protected void setExecutionContext(ScriptEngine engine, Map<String, ?> context) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,14 @@ public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext co
}

URI uri = null;
if (uriText == null) {
throw new ConversionException(
"No URI provided");
}

try {
uri = new URI(uriText);
} catch (NullPointerException | URISyntaxException ex) {
} catch (URISyntaxException ex) {
throw new ConversionException(
"The URI '" + uriText + "' in node '" + reader.getNodeName() + "' is invalid!", ex);
}
Expand All @@ -82,7 +87,7 @@ public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext co

// iterate through the nodes, putting the different types into their
// respective arrays
while (nodeIterator.hasNext() == true) {
while (nodeIterator.hasNext()) {
Object node = nodeIterator.next();
if (node instanceof ConfigDescriptionParameter) {
configDescriptionParams.add((ConfigDescriptionParameter) node);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ private URI readConfigDescriptionURI(NodeIterator nodeIterator) throws Conversio
if (uriText != null) {
try {
return new URI(uriText);
} catch (NullPointerException | URISyntaxException ex) {
} catch (URISyntaxException ex) {
throw new ConversionException(
"The URI '" + uriText + "' in node " + "'config-description-ref' is invalid!", ex);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ public void migrateThingType(final Thing thing, final ThingTypeUID thingTypeUID,
final Configuration configuration) {
final ThingType thingType = thingTypeRegistry.getThingType(thingTypeUID);
if (thingType == null) {
throw new RuntimeException(
throw new IllegalStateException(
MessageFormat.format("No thing type {0} registered, cannot change thing type for thing {1}",
thingTypeUID.getAsString(), thing.getUID().getAsString()));
}
Expand Down Expand Up @@ -360,7 +360,7 @@ private void waitUntilHandlerUnregistered(final Thing thing, int timeout) {
"Thing type migration failed for {0}. The handler deregistration did not complete within {1}ms.",
thing.getUID().getAsString(), timeout);
logger.error(message);
throw new RuntimeException(message);
throw new IllegalStateException(message);
}

private void waitForRunningHandlerRegistrations(ThingUID thingUID) {
Expand All @@ -379,7 +379,7 @@ private void waitForRunningHandlerRegistrations(ThingUID thingUID) {
"Thing type migration failed for {0}. Could not obtain lock for hander registration.",
thingUID.getAsString());
logger.error(message);
throw new RuntimeException(message);
throw new IllegalStateException(message);
}
}, 0, TimeUnit.MILLISECONDS);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,19 +53,18 @@ public static boolean isTransform(String pattern) {
*/
public static TransformationService getTransformationService(BundleContext context, String transformationType) {
if (context != null) {
Logger logger = LoggerFactory.getLogger(TransformationHelper.class);
String filter = "(smarthome.transform=" + transformationType + ")";
try {
Collection<ServiceReference<TransformationService>> refs = context
.getServiceReferences(TransformationService.class, filter);
if (refs != null && refs.size() > 0) {
return context.getService(refs.iterator().next());
} else {
logger.warn("Cannot get service reference for transformation service of type {}",
LOGGER.warn("Cannot get service reference for transformation service of type {}",
transformationType);
}
} catch (InvalidSyntaxException e) {
logger.warn("Cannot get service reference for transformation service of type {}", transformationType,
LOGGER.warn("Cannot get service reference for transformation service of type {}", transformationType,
e);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ public void ksEventReceived(KSEvent ksEvent) {
@Override
public synchronized void sttEventReceived(STTEvent sttEvent) {
if (sttEvent instanceof SpeechRecognitionEvent) {
if (false == this.isSTTServerAborting) {
if (!this.isSTTServerAborting) {
this.sttServiceHandle.abort();
this.isSTTServerAborting = true;
SpeechRecognitionEvent sre = (SpeechRecognitionEvent) sttEvent;
Expand All @@ -168,7 +168,7 @@ public synchronized void sttEventReceived(STTEvent sttEvent) {
} else if (sttEvent instanceof RecognitionStopEvent) {
toggleProcessing(false);
} else if (sttEvent instanceof SpeechRecognitionErrorEvent) {
if (false == this.isSTTServerAborting) {
if (!this.isSTTServerAborting) {
this.sttServiceHandle.abort();
this.isSTTServerAborting = true;
toggleProcessing(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,12 @@ List<Expression> getChildExpressions() {
boolean collectFirsts(ResourceBundle language, HashSet<String> firsts) {
boolean blocking = false;
for (Expression e : subExpressions) {
if ((blocking = e.collectFirsts(language, firsts)) == true) {
blocking = e.collectFirsts(language, firsts);
if (blocking) {
break;
}
}

return blocking;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -409,11 +409,10 @@ public void setCategory(@Nullable String category) {
* @return true if state is an acceptedDataType or subclass thereof
*/
public boolean isAcceptedState(List<Class<? extends State>> acceptedDataTypes, State state) {
if (acceptedDataTypes.stream().map(clazz -> clazz.isAssignableFrom(state.getClass()))
.filter(found -> found == true).findAny().isPresent()) {
return true;
}
return false;
return acceptedDataTypes.stream()
.map(clazz -> clazz.isAssignableFrom(state.getClass()))
.filter(found -> found)
.findAny().isPresent();
}

protected void logSetTypeError(State state) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,11 +121,11 @@ public static DateTimeType valueOf(String value) {

@Override
public String format(String pattern) {
try {
return String.format(pattern, zonedDateTime);
} catch (NullPointerException npe) {
if (pattern == null) {
return DateTimeFormatter.ofPattern(DATE_PATTERN).format(zonedDateTime);
}

return String.format(pattern, zonedDateTime);
}

public String format(Locale locale, String pattern) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ public PercentType[] toRGB() {
blue = b;
break;
default:
throw new RuntimeException();
throw new IllegalArgumentException("Could not convert to RGB.");
}
return new PercentType[] { red, green, blue };
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
*
*/
public class ExpressionThreadPoolManager extends ThreadPoolManager {

private static final Logger logger = LoggerFactory.getLogger(ExpressionThreadPoolExecutor.class);
/**
* Returns an instance of an expression-driven scheduled thread pool service. If it is the first request for the
* given pool name, the instance is newly created.
Expand All @@ -64,8 +64,7 @@ public static ExpressionThreadPoolExecutor getExpressionScheduledPool(String poo
((ThreadPoolExecutor) pool).setKeepAliveTime(THREAD_TIMEOUT, TimeUnit.SECONDS);
((ThreadPoolExecutor) pool).allowCoreThreadTimeOut(true);
pools.put(poolName, pool);
LoggerFactory.getLogger(ExpressionThreadPoolManager.class)
.debug("Created an expression-drive scheduled thread pool '{}' of size {}", poolName, cfg);
logger.debug("Created an expression-drive scheduled thread pool '{}' of size {}", poolName, cfg);
}
}
}
Expand All @@ -77,9 +76,6 @@ public static ExpressionThreadPoolExecutor getExpressionScheduledPool(String poo
}

public static class ExpressionThreadPoolExecutor extends ScheduledThreadPoolExecutor {

private final Logger logger = LoggerFactory.getLogger(ExpressionThreadPoolExecutor.class);

private Map<Expression, RunnableWrapper> scheduled = new ConcurrentHashMap<>();
private Map<RunnableWrapper, List<ScheduledFuture<?>>> futures = Collections.synchronizedMap(new HashMap<>());
private final Lock futuresLock = new ReentrantLock();
Expand All @@ -91,9 +87,6 @@ public static class ExpressionThreadPoolExecutor extends ScheduledThreadPoolExec

public ExpressionThreadPoolExecutor(final String poolName, int corePoolSize) {
this(poolName, corePoolSize, new NamedThreadFactory(poolName), new ThreadPoolExecutor.DiscardPolicy() {

private final Logger logger = LoggerFactory.getLogger(ExpressionThreadPoolExecutor.class);

// The pool is bounded and rejections will happen during shutdown
@Override
public void rejectedExecution(Runnable runnable, ThreadPoolExecutor threadPoolExecutor) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
* @author Kai Kreuzer - added exception logging
*/
public class ExecUtil {

private static Logger logger = LoggerFactory.getLogger(ExecUtil.class);
/**
* Use this to separate between command and parameter, and also between parameters.
*/
Expand All @@ -54,7 +54,6 @@ public class ExecUtil {
* @see http://www.peterfriese.de/running-applescript-from-java/
*/
public static void executeCommandLine(String commandLine) {
Logger logger = LoggerFactory.getLogger(ExecUtil.class);
try {
if (commandLine.contains(CMD_LINE_DELIMITER)) {
String[] cmdArray = commandLine.split(CMD_LINE_DELIMITER);
Expand Down Expand Up @@ -111,7 +110,6 @@ public static String executeCommandLineAndWaitResponse(String commandLine, int t
executor.setStreamHandler(streamHandler);
executor.setWatchdog(watchdog);

Logger logger = LoggerFactory.getLogger(ExecUtil.class);
try {
executor.execute(cmdLine, resultHandler);
logger.debug("executed commandLine '{}'", commandLine);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -498,9 +498,15 @@ public Response updateFirmware(

FirmwareUID firmwareUID = new FirmwareUID(thing.getThingTypeUID(), firmwareVersion);

ThingUID uid = thing.getUID();
if (uid == null || firmwareUID == null) {
return JSONResponse.createResponse(Status.BAD_REQUEST, null,
"Firmware update preconditions not satisfied.");
}

try {
firmwareUpdateService.updateFirmware(thing.getUID(), firmwareUID, LocaleUtil.getLocale(language));
} catch (IllegalArgumentException | NullPointerException | IllegalStateException ex) {
firmwareUpdateService.updateFirmware(uid, firmwareUID, LocaleUtil.getLocale(language));
} catch (IllegalArgumentException | IllegalStateException ex) {
return JSONResponse.createResponse(Status.BAD_REQUEST, null,
"Firmware update preconditions not satisfied.");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,7 @@ private PageDTO createPageBean(String sitemapName, String title, String icon, St
private WidgetDTO createWidgetBean(String sitemapName, Widget widget, boolean drillDown, URI uri, String widgetId,
Locale locale) {
// Test visibility
if (itemUIRegistry.getVisiblity(widget) == false) {
if (!itemUIRegistry.getVisiblity(widget)) {
return null;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ private Response createResponse(Status status, Object entity) {
PipedInputStream in = new PipedInputStream(out);
rp.entity(in);
} catch (IOException e) {
throw new RuntimeException(e);
throw new IllegalStateException(e);
}

Thread writerThread = new Thread(() -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ private <T> ServiceReference<T>[] getServices(final Class<T> clazz) {
.getServiceReferences(clazz.getName(), null);
return serviceReferences;
} catch (InvalidSyntaxException e) {
throw new Error("Invalid exception for a null filter");
throw new IllegalArgumentException("Invalid exception for a null filter");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,14 +128,20 @@ protected void waitForAssert(Runnable assertion, Runnable beforeLastCall, Runnab
long sleepTime) {
long waitingTime = 0;
while (waitingTime < timeout) {
if (assertion == null) {
waitingTime += sleepTime;
internalSleep(sleepTime);
continue;
}

try {
assertion.run();

if (afterLastCall != null) {
afterLastCall.run();
}
return;
} catch (final Error | NullPointerException error) {
} catch (final Error error) {
waitingTime += sleepTime;
internalSleep(sleepTime);
}
Expand Down Expand Up @@ -181,7 +187,7 @@ private void internalSleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
throw new Error("We shouldn't be interrupted while testing");
throw new IllegalStateException("We shouldn't be interrupted while testing");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1065,7 +1065,7 @@ private String processColorDefinition(State state, List<ColorArray> colorList) {
value = color.getState();
}

if (matchStateToValue(cmpState, value, color.getCondition()) == true) {
if (matchStateToValue(cmpState, value, color.getCondition())) {
// We have the color for this value - break!
colorString = color.getArg();
break;
Expand Down Expand Up @@ -1141,7 +1141,7 @@ public boolean getVisiblity(Widget w) {
value = rule.getState();
}

if (matchStateToValue(state, value, rule.getCondition()) == true) {
if (matchStateToValue(state, value, rule.getCondition())) {
// We have the name for this value!
return true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public static State getState(ChannelUID channelUID, AstroChannelConfig config, O
} else if (value instanceof String || value instanceof Enum) {
return new StringType(value.toString());
} else {
throw new RuntimeException("Unsupported value type " + value.getClass().getSimpleName());
throw new IllegalStateException("Unsupported value type " + value.getClass().getSimpleName());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ public void offlineIfWrongPIN() {
String.valueOf(DEFAULT_CONFIG_PROPERTY_PORT), DEFAULT_CONFIG_PROPERTY_REFRESH);
initializeRadioThing(config);
waitForAssert(() -> {
String exceptionMessage = "java.lang.RuntimeException: Radio does not allow connection, maybe wrong pin?";
String exceptionMessage = "Radio does not allow connection, maybe wrong pin?";
verifyCommunicationError(exceptionMessage);
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public boolean doLogin() throws IOException {
String reason = response.getReason();
logger.debug("Communication with radio failed: {} {}", statusCode, reason);
if (statusCode == HttpStatus.FORBIDDEN_403) {
throw new RuntimeException("Radio does not allow connection, maybe wrong pin?");
throw new IllegalStateException("Radio does not allow connection, maybe wrong pin?");
}
throw new IOException("Communication with radio failed, return code: " + statusCode);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -515,16 +515,19 @@ private boolean isEqual(State state1, State state2) {

boolean colorModeIsEqual = true;
boolean effectIsEqual = true;
try {
colorModeIsEqual = state1.getColorMode().equals(state2.getColorMode());
} catch (NullPointerException npe) {

if (state1.getColorMode() == null) {
logger.trace("Light does not support color mode.");
} else {
colorModeIsEqual = state1.getColorMode().equals(state2.getColorMode());
}
try {
effectIsEqual = state1.getEffect().equals(state2.getEffect());
} catch (NullPointerException npe) {

if (state1.getEffect() == null) {
logger.trace("Light does not support effect.");
} else {
effectIsEqual = state1.getEffect().equals(state2.getEffect());
}

return colorModeIsEqual && effectIsEqual;
}

Expand Down
Loading