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

Commit

Permalink
Fixed pmd issues found is smarthome - AvoidCatchingNPE and AvoidThrow…
Browse files Browse the repository at this point in the history
…ingRawExceptionTypes

Signed-off-by: VelinYordanov <[email protected]>
  • Loading branch information
VelinYordanov committed Mar 29, 2018
1 parent 6852de6 commit 934dafc
Show file tree
Hide file tree
Showing 16 changed files with 44 additions and 32 deletions.
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 @@ -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 @@ -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 @@ -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 @@ -181,7 +181,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 @@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -873,6 +873,10 @@ private void handleErrors(Result result) throws IOException, ApiException {
}

for (ErrorResponse error : errors) {
if (error == null) {
continue;
}

switch (error.getType()) {
case 1:
username = null;
Expand All @@ -893,8 +897,6 @@ private void handleErrors(Result result) throws IOException, ApiException {
}
} catch (JsonParseException e) {
// Not an error
} catch (NullPointerException e) {
// Object that looks like error
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ public void handleCommand(ChannelUID channelUID, Command command) {
}
}
} catch (Exception e) {
throw new RuntimeException("Could not send command to WeMo Bridge", e);
throw new IllegalStateException("Could not send command to WeMo Bridge", e);
}
}
}
Expand Down Expand Up @@ -339,7 +339,7 @@ public void getDeviceState() {
}
}
} catch (Exception e) {
throw new RuntimeException("Could not retrieve new Wemo light state", e);
throw new IllegalStateException("Could not retrieve new Wemo light state", e);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public static String executeCall(String wemoURL, String soapHeader, String conte
String wemoCallResponse = HttpUtil.executeUrl("POST", wemoURL, wemoHeaders, wemoContent, null, 2000);
return wemoCallResponse;
} catch (Exception e) {
throw new RuntimeException("Could not call WeMo", e);
throw new IllegalStateException("Could not call WeMo", e);
}
}

Expand Down
5 changes: 5 additions & 0 deletions tools/static-code-analysis/pmd/suppressions.properties
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,8 @@ org.eclipse.smarthome.io.console.karaf.internal.OSGiConsole=SystemPrintln
org.eclipse.smarthome.io.console.rfc147.internal.CommandWrapper=SystemPrintln
org.eclipse.smarthome.io.console.rfc147.internal.OSGiConsole=SystemPrintln
org.eclipse.smarthome.core.internal.events.ThreadedEventHandler=EmptyIfStmt
org.eclipse.smarthome.config.xml.ConfigDescriptionConverter=AvoidCatchingNPE
org.eclipse.smarthome.io.rest.core.internal.thing.ThingResource=AvoidCatchingNPE
org.eclipse.smarthome.test.java.JavaTest=AvoidCatchingNPE
org.eclipse.smarthome.model.core.internal.ModelRepositoryImpl=AvoidCatchingNPE
org.eclipse.smarthome.io.net.http.internal.SecureHttpClientFactory=AvoidThrowingRawExceptionTypes

0 comments on commit 934dafc

Please sign in to comment.