Skip to content

Commit

Permalink
chore: Address SonarLint warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
rhwood committed Sep 1, 2019
1 parent f0e4239 commit 68c09b7
Show file tree
Hide file tree
Showing 38 changed files with 598 additions and 589 deletions.
10 changes: 5 additions & 5 deletions java/src/jmri/server/json/JSON.java
Expand Up @@ -3,9 +3,9 @@
/**
* Common and utility constants used in the JMRI JSON protocol.
* <p>
* <strong>Note</strong> any documented use of a constant is not the exclusive or
* sole use of the constant. Review the JSON schemas for all uses of any given
* constant.
* <strong>Note</strong> any documented use of a constant is not the exclusive
* or sole use of the constant. Review the JSON schemas for all uses of any
* given constant.
*
* @author Randall Wood (C) 2013, 2014, 2016, 2018, 2019
*/
Expand Down Expand Up @@ -644,8 +644,8 @@ public final class JSON {
* {@value #UNKNOWN}
* <p>
* Note that this value deliberately differs from
* {@link jmri.NamedBean#UNKNOWN} so that JSON clients can treat
* all known states as true, and the unknown state as false.
* {@link jmri.NamedBean#UNKNOWN} so that JSON clients can treat all known
* states as true, and the unknown state as false.
*/
public static final int UNKNOWN = 0x00;

Expand Down
54 changes: 28 additions & 26 deletions java/src/jmri/server/json/JsonClientHandler.java
Expand Up @@ -37,7 +37,7 @@ public class JsonClientHandler {
* cause a {@value jmri.server.json.JSON#HELLO} message to be sent to the
* client.
*/
public static final String HELLO_MSG = "{\"" + JSON.TYPE + "\":\"" + JSON.HELLO + "\"}";
public static final String HELLO_MSG = "{\"" + TYPE + "\":\"" + HELLO + "\"}";
private final JsonConnection connection;
private final HashMap<String, HashSet<JsonSocketService<?>>> services = new HashMap<>();
private final JsonServerPreferences preferences = InstanceManager.getDefault(JsonServerPreferences.class);
Expand All @@ -46,7 +46,7 @@ public class JsonClientHandler {

public JsonClientHandler(JsonConnection connection) {
this.connection = connection;
ServiceLoader.load(JsonServiceFactory.class).forEach((factory) -> {
ServiceLoader.load(JsonServiceFactory.class).forEach(factory -> {
JsonSocketService<?> service = factory.getSocketService(connection);
for (String type : factory.getTypes()) {
HashSet<JsonSocketService<?>> set = this.services.get(type);
Expand All @@ -68,11 +68,8 @@ public JsonClientHandler(JsonConnection connection) {
}

public void onClose() {
services.values().stream().forEach((set) -> {
set.stream().forEach((service) -> {
service.onClose();
});
});
services.values().stream().forEach(set -> set.stream()
.forEach(service -> service.onClose()));
services.clear();
}

Expand All @@ -86,16 +83,18 @@ public void onClose() {
* @see #onMessage(JsonNode)
*/
public void onMessage(String string) throws IOException {
if (string.equals("{\"type\":\"ping\"}")) { //turn down the noise when debugging
log.trace("Received from client: '{}'", string);
if (string.equals("{\"type\":\"ping\"}")) {
// turn down the noise when debugging
log.trace("Received from client: '{}'", string);
} else {
log.debug("Received from client: '{}'", string);
}
try {
this.onMessage(this.connection.getObjectMapper().readTree(string));
} catch (JsonProcessingException pe) {
log.warn("Exception processing \"{}\"\n{}", string, pe.getMessage());
this.sendErrorMessage(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(this.connection.getLocale(), "ErrorProcessingJSON", pe.getLocalizedMessage()), 0);
this.sendErrorMessage(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
Bundle.getMessage(this.connection.getLocale(), "ErrorProcessingJSON", pe.getLocalizedMessage()), 0);
}
}

Expand All @@ -117,33 +116,32 @@ public void onMessage(JsonNode root) throws IOException {
if (preferences.getValidateClientMessages()) {
this.schemas.validateMessage(root, false, this.connection.getLocale(), id);
}
if ((root.path(TYPE).isMissingNode() || type.equals(LIST))
&& root.path(LIST).isValueNode()) {
if ((root.path(TYPE).isMissingNode() || type.equals(LIST)) && root.path(LIST).isValueNode()) {
type = root.path(LIST).asText();
method = LIST;
}
if (data.isMissingNode()) {
if ((type.equals(HELLO) || type.equals(PING) || type.equals(GOODBYE))
|| (method.equals(LIST) || method.equals(GET))) {
if ((type.equals(HELLO) || type.equals(PING) || type.equals(GOODBYE)) ||
(method.equals(LIST) || method.equals(GET))) {
// these messages are not required to have a data payload,
// so create one if the message did not contain one to avoid
// special casing later
data = this.connection.getObjectMapper().createObjectNode();
} else {
this.sendErrorMessage(HttpServletResponse.SC_BAD_REQUEST, Bundle.getMessage(this.connection.getLocale(), "ErrorMissingData"), id);
this.sendErrorMessage(HttpServletResponse.SC_BAD_REQUEST,
Bundle.getMessage(this.connection.getLocale(), "ErrorMissingData"), id);
return;
}
}
if (root.path(METHOD).isMissingNode()) { // method not explicitly set
if (data.path(METHOD).isValueNode()) {
// at one point, we used method within data, so check there also
method = data.path(METHOD).asText(JSON.GET);
}
// method not explicitly set in root, but set in data
if (root.path(METHOD).isMissingNode() && data.path(METHOD).isValueNode()) {
// at one point, we used method within data, so check there also
method = data.path(METHOD).asText(JSON.GET);
}
if (type.equals(PING)) { //turn down the noise a bit
if (type.equals(PING)) { // turn down the noise a bit
log.trace("Processing '{}' with '{}'", type, data);
} else {
log.debug("Processing '{}' with '{}'", type, data);
log.debug("Processing '{}' with '{}'", type, data);
}
if (method.equals(LIST)) {
if (this.services.get(type) != null) {
Expand All @@ -153,7 +151,8 @@ public void onMessage(JsonNode root) throws IOException {
return;
} else {
log.warn("Requested list type '{}' unknown.", type);
this.sendErrorMessage(HttpServletResponse.SC_NOT_FOUND, Bundle.getMessage(this.connection.getLocale(), "ErrorUnknownType", type), id);
this.sendErrorMessage(HttpServletResponse.SC_NOT_FOUND,
Bundle.getMessage(this.connection.getLocale(), JsonException.ERROR_UNKNOWN_TYPE, type), id);
return;
}
} else if (!data.isMissingNode()) {
Expand All @@ -169,17 +168,20 @@ public void onMessage(JsonNode root) throws IOException {
}
} else {
log.warn("Requested type '{}' unknown.", type);
this.sendErrorMessage(HttpServletResponse.SC_NOT_FOUND, Bundle.getMessage(this.connection.getLocale(), "ErrorUnknownType", type), id);
this.sendErrorMessage(HttpServletResponse.SC_NOT_FOUND,
Bundle.getMessage(this.connection.getLocale(), JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
} else {
this.sendErrorMessage(HttpServletResponse.SC_BAD_REQUEST, Bundle.getMessage(this.connection.getLocale(), "ErrorMissingData"), id);
this.sendErrorMessage(HttpServletResponse.SC_BAD_REQUEST,
Bundle.getMessage(this.connection.getLocale(), "ErrorMissingData"), id);
}
if (type.equals(GOODBYE)) {
// close the connection if GOODBYE is received.
this.connection.close();
}
} catch (JmriException je) {
this.sendErrorMessage(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(this.connection.getLocale(), "ErrorUnsupportedOperation", je.getLocalizedMessage()), id);
this.sendErrorMessage(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(
this.connection.getLocale(), "ErrorUnsupportedOperation", je.getLocalizedMessage()), id);
} catch (JsonException je) {
this.sendErrorMessage(je);
}
Expand Down
66 changes: 50 additions & 16 deletions java/src/jmri/server/json/JsonException.java
Expand Up @@ -11,6 +11,7 @@
*/
public class JsonException extends Exception {

/* JSON protocol keys */
/**
* {@value #ERROR}
*/
Expand All @@ -24,9 +25,42 @@ public class JsonException extends Exception {
*/
public static final String MESSAGE = "message"; // NOI18N

/* Error message localization keys */
/**
* {@value #ERROR_BAD_PROPERTY_VALUE}, a key for localized error messages
* indicating the value for the given property is not valid.
*/
public static final String ERROR_BAD_PROPERTY_VALUE = "ErrorBadPropertyValue"; // NOI18N
/**
* {@value #ERROR_MISSING_PROPERTY_PUT}, a key for localized error messages
* indicating a property required to complete a PUT request is missing.
*/
public static final String ERROR_MISSING_PROPERTY_PUT = "ErrorMissingPropertyPut"; // NOI18N
/**
* {@value #ERROR_NOT_FOUND}, a key for localized error messages indicating
* a resource was not found.
*/
public static final String ERROR_NOT_FOUND = "ErrorNotFound"; // NOI18N
/**
* {@value #ERROR_OBJECT}, a key for localized error messages indicating
* an inability to get a requested object.
*/
public static final String ERROR_OBJECT = "ErrorObject"; // NOI18N
/**
* {@value #ERROR_UNKNOWN_TYPE}, a key for localized error messages
* indicating the requested type cannot be handled.
*/
public static final String ERROR_UNKNOWN_TYPE = "ErrorUnknownType"; // NOI18N
/**
* {@value #LOGGED_ERROR}, a key for localized error messages indicating
* that JMRI logs contain required information to resolve the error.
*/
public static final String LOGGED_ERROR = "LoggedError"; // NOI18N

/* Internal objects */
private static final ObjectMapper MAPPER = new ObjectMapper();
private final int code;
private final ObjectNode additionalData;
private final int errorCode;
private final transient ObjectNode additionalData;
/**
* Only access through {@link #getId()}, even when used within this class
*/
Expand All @@ -37,10 +71,10 @@ public class JsonException extends Exception {
*
* @param code the error code
* @param message message, displayable to the user, in the client's
* preferred locale
* preferred locale
* @param throwable the cause of the exception
* @param id the message id passed by the client, or the additive
* inverse of that id
* inverse of that id
*/
public JsonException(int code, String message, Throwable throwable, int id) {
this(code, message, throwable, null, id);
Expand All @@ -51,15 +85,15 @@ public JsonException(int code, String message, Throwable throwable, int id) {
*
* @param code the error code
* @param message message, displayable to the user, in the client's
* preferred locale
* preferred locale
* @param throwable the cause of the exception
* @param additionalData additional data to be passed to the client
* @param id the message id passed by the client, or the
* additive inverse of that id
* additive inverse of that id
*/
public JsonException(int code, String message, Throwable throwable, ObjectNode additionalData, int id) {
super(message, throwable);
this.code = code;
this.errorCode = code;
this.additionalData = additionalData;
this.id = id;
}
Expand All @@ -70,7 +104,7 @@ public JsonException(int code, String message, Throwable throwable, ObjectNode a
* @param code the error code
* @param throwable the cause of the exception
* @param id the message id passed by the client, or the additive
* inverse of that id
* inverse of that id
*/
public JsonException(int code, Throwable throwable, int id) {
this(code, throwable, null, id);
Expand All @@ -83,11 +117,11 @@ public JsonException(int code, Throwable throwable, int id) {
* @param throwable the cause of the exception
* @param additionalData additional data to be passed to the client
* @param id the message id passed by the client, or the
* additive inverse of that id
* additive inverse of that id
*/
public JsonException(int code, Throwable throwable, ObjectNode additionalData, int id) {
super(throwable);
this.code = code;
this.errorCode = code;
this.additionalData = additionalData;
this.id = id;
}
Expand All @@ -97,9 +131,9 @@ public JsonException(int code, Throwable throwable, ObjectNode additionalData, i
*
* @param code the error code
* @param message message, displayable to the user, in the client's
* preferred locale
* preferred locale
* @param id the message id passed by the client, or the additive
* inverse of that id
* inverse of that id
*/
public JsonException(int code, String message, int id) {
this(code, message, (ObjectNode) null, id);
Expand All @@ -110,14 +144,14 @@ public JsonException(int code, String message, int id) {
*
* @param code the error code
* @param message message, displayable to the user, in the client's
* preferred locale
* preferred locale
* @param additionalData additional data to be passed to the client
* @param id the message id passed by the client, or the
* additive inverse of that id
* additive inverse of that id
*/
public JsonException(int code, String message, ObjectNode additionalData, int id) {
super(message);
this.code = code;
this.errorCode = code;
this.additionalData = additionalData;
this.id = id;
}
Expand All @@ -128,7 +162,7 @@ public JsonException(int code, String message, ObjectNode additionalData, int id
* @return the code
*/
public int getCode() {
return this.code;
return this.errorCode;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion java/src/jmri/server/json/JsonHttpService.java
Expand Up @@ -183,7 +183,7 @@ public abstract JsonNode doGetList(@Nonnull String type, @Nonnull JsonNode data,
* @throws JsonException if an error occurs preparing schema; if type is is
* not a type handled by this service, this must
* be thrown with an error code of 500 and the
* localized message "ErrorUnknownType"
* localized message ERROR_UNKNOWN_TYPE
*/
@Nonnull
public abstract JsonNode doSchema(@Nonnull String type, boolean server, @Nonnull Locale locale, int id)
Expand Down
14 changes: 6 additions & 8 deletions java/src/jmri/server/json/JsonNamedBeanHttpService.java
Expand Up @@ -41,7 +41,7 @@ public final JsonNode doGet(@Nonnull String type, @Nonnull String name, @Nonnull
@Nonnull Locale locale, int id) throws JsonException {
if (!type.equals(getType())) {
throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
Bundle.getMessage(locale, "LoggedError"), id);
Bundle.getMessage(locale, JsonException.LOGGED_ERROR), id);
}
// NOTE: although allowing a user name to be used, a system name is recommended as it is
// less likely to suffer errors in translation between the allowed name and URL conversion
Expand All @@ -56,7 +56,7 @@ public final JsonNode doGet(@Nonnull String type, @Nonnull String name, @Nonnull
public final JsonNode doPost(@Nonnull String type, @Nonnull String name, @Nonnull JsonNode data, @Nonnull Locale locale, int id) throws JsonException {
if (!type.equals(getType())) {
throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
Bundle.getMessage(locale, "LoggedError"), id);
Bundle.getMessage(locale, JsonException.LOGGED_ERROR), id);
}
// NOTE: although allowing a user name to be used, a system name is recommended as it is
// less likely to suffer errors in translation between the allowed name and URL conversion
Expand Down Expand Up @@ -102,7 +102,7 @@ public final JsonNode doGetList(String type, JsonNode data, Locale locale, int i
public void doDelete(String type, String name, JsonNode data, Locale locale, int id) throws JsonException {
if (!type.equals(getType())) {
throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
Bundle.getMessage(locale, "LoggedError"), id);
Bundle.getMessage(locale, JsonException.LOGGED_ERROR), id);
}
// NOTE: although allowing a user name to be used, a system name is recommended as it is
// less likely to suffer errors in translation between the allowed name and URL conversion
Expand Down Expand Up @@ -184,14 +184,12 @@ protected void doDelete(@CheckForNull T bean, @Nonnull String name, @Nonnull Str
protected final void deleteBean(@CheckForNull T bean, @Nonnull String name, @Nonnull String type, @Nonnull JsonNode data, @Nonnull Locale locale, int id) throws JsonException {
if (bean == null) {
throw new JsonException(HttpServletResponse.SC_NOT_FOUND,
Bundle.getMessage(locale, "ErrorNotFound", type, name), id);
Bundle.getMessage(locale, JsonException.ERROR_NOT_FOUND, type, name), id);
}
List<String> listeners = bean.getListenerRefs();
if (listeners.size() > 0 && !acceptForceDeleteToken(type, name, data.path(JSON.FORCE_DELETE).asText())) {
if (!listeners.isEmpty() && !acceptForceDeleteToken(type, name, data.path(JSON.FORCE_DELETE).asText())) {
ArrayNode conflicts = mapper.createArrayNode();
listeners.forEach((listener) -> {
conflicts.add(listener);
});
listeners.forEach(conflicts::add);
throwDeleteConflictException(type, name, conflicts, locale, id);
} else {
getManager().deregister(bean);
Expand Down

0 comments on commit 68c09b7

Please sign in to comment.