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 27, 2018
1 parent 6852de6 commit f8c8ee6
Show file tree
Hide file tree
Showing 17 changed files with 406 additions and 267 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,20 +29,28 @@
import org.slf4j.LoggerFactory;

/**
* This is an abstract class that can be used when implementing any module handler that handles scripts.
* This is an abstract class that can be used when implementing any module
* handler that handles scripts.
*
* @author Kai Kreuzer - Initial contribution
* @author Simon Merschjohann
*
* @param <T> the type of module the concrete handler can handle
* @param <T>
* the type of module the concrete handler can handle
*/
public abstract class AbstractScriptModuleHandler<T extends Module> extends BaseModuleHandler<T> {
private final Logger logger = LoggerFactory.getLogger(this.getClass());

/** Constant defining the configuration parameter of modules that specifies the mime type of a script */
/**
* Constant defining the configuration parameter of modules that specifies the
* mime type of a script
*/
protected static final String SCRIPT_TYPE = "type";

/** Constant defining the configuration parameter of modules that specifies the script itself */
/**
* Constant defining the configuration parameter of modules that specifies the
* script itself
*/
protected static final String SCRIPT = "script";

protected ScriptEngineManager scriptEngineManager;
Expand Down Expand Up @@ -90,24 +98,27 @@ 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(
if (isNotValid(type) || isNotValid(script)) {
throw new IllegalStateException(
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()));
} else {
this.type = (String) type;
this.script = (String) script;
}
}

private boolean isNotValid(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
* 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 context the variables and types to put into the execution context
* @param engine
* the scriptengine that is used
* @param context
* the variables and types to put into the execution context
*/
protected void setExecutionContext(ScriptEngine engine, Map<String, ?> context) {
ScriptContext executionContext = engine.getContext();
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 @@ -55,10 +55,12 @@ public class DateTimeType implements PrimitiveType, State, Command {
private final DateTimeFormatter formatterTzIso = DateTimeFormatter.ofPattern(DATE_PARSE_PATTERN_WITH_TZ_ISO);

/**
* @deprecated The constructor uses Calendar object hence it doesn't store time zone. A new constructor is
* available. Use {@link #DateTimeType(ZonedDateTime)} instead.
* @deprecated The constructor uses Calendar object hence it doesn't store time
* zone. A new constructor is available. Use
* {@link #DateTimeType(ZonedDateTime)} instead.
*
* @param calendar The Calendar object containing the time stamp.
* @param calendar
* The Calendar object containing the time stamp.
*/
@Deprecated
public DateTimeType(Calendar calendar) {
Expand Down Expand Up @@ -104,7 +106,8 @@ public DateTimeType(String zonedValue) {
}

/**
* @deprecated The method is deprecated. You can use {@link #getZonedDateTime()} instead.
* @deprecated The method is deprecated. You can use {@link #getZonedDateTime()}
* instead.
*/
@Deprecated
public Calendar getCalendar() {
Expand All @@ -121,11 +124,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 @@ -174,7 +174,7 @@ public Void run() {
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else {
throw new RuntimeException(cause);
throw new IllegalStateException(cause);
}
}
}
Expand All @@ -200,7 +200,7 @@ public HttpClient run() {
sslContext.init(null, trustManagers, null);
sslContextFactory.setSslContext(sslContext);
} catch (Exception ex) {
throw new RuntimeException(
throw new IllegalStateException(
"Cannot create an TLS context for the endpoint '" + endpoint + "'!", ex);
}
}
Expand All @@ -220,7 +220,7 @@ public HttpClient run() {
httpClient.start();
} catch (Exception e) {
logger.error("Could not start jetty client", e);
throw new RuntimeException("Could not start jetty client", e);
throw new IllegalStateException("Could not start jetty client", e);
}
}

Expand All @@ -232,7 +232,7 @@ public HttpClient run() {
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else {
throw new RuntimeException(cause);
throw new IllegalStateException(cause);
}
}
}
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("I/O error occurred"+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
Loading

0 comments on commit f8c8ee6

Please sign in to comment.