diff --git a/java/src/jmri/server/json/JSON.java b/java/src/jmri/server/json/JSON.java
index aa083ab7c51..13267896a7d 100644
--- a/java/src/jmri/server/json/JSON.java
+++ b/java/src/jmri/server/json/JSON.java
@@ -3,9 +3,9 @@
/**
* Common and utility constants used in the JMRI JSON protocol.
*
- * Note 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.
+ * Note 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
*/
@@ -644,8 +644,8 @@ public final class JSON {
* {@value #UNKNOWN}
*
* 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;
diff --git a/java/src/jmri/server/json/JsonClientHandler.java b/java/src/jmri/server/json/JsonClientHandler.java
index c137b2cd30f..21e729818b3 100644
--- a/java/src/jmri/server/json/JsonClientHandler.java
+++ b/java/src/jmri/server/json/JsonClientHandler.java
@@ -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>> services = new HashMap<>();
private final JsonServerPreferences preferences = InstanceManager.getDefault(JsonServerPreferences.class);
@@ -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> set = this.services.get(type);
@@ -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();
}
@@ -86,8 +83,9 @@ 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);
}
@@ -95,7 +93,8 @@ public void onMessage(String string) throws IOException {
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);
}
}
@@ -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) {
@@ -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()) {
@@ -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);
}
diff --git a/java/src/jmri/server/json/JsonException.java b/java/src/jmri/server/json/JsonException.java
index 971d9443e92..e7b3990f99f 100644
--- a/java/src/jmri/server/json/JsonException.java
+++ b/java/src/jmri/server/json/JsonException.java
@@ -11,6 +11,7 @@
*/
public class JsonException extends Exception {
+ /* JSON protocol keys */
/**
* {@value #ERROR}
*/
@@ -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
*/
@@ -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);
@@ -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;
}
@@ -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);
@@ -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;
}
@@ -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);
@@ -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;
}
@@ -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;
}
/**
diff --git a/java/src/jmri/server/json/JsonHttpService.java b/java/src/jmri/server/json/JsonHttpService.java
index 9b064c7cd0d..9cda2feed34 100644
--- a/java/src/jmri/server/json/JsonHttpService.java
+++ b/java/src/jmri/server/json/JsonHttpService.java
@@ -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)
diff --git a/java/src/jmri/server/json/JsonNamedBeanHttpService.java b/java/src/jmri/server/json/JsonNamedBeanHttpService.java
index 689c7afd71a..5022655adcf 100644
--- a/java/src/jmri/server/json/JsonNamedBeanHttpService.java
+++ b/java/src/jmri/server/json/JsonNamedBeanHttpService.java
@@ -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
@@ -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
@@ -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
@@ -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 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);
diff --git a/java/src/jmri/server/json/JsonNonProvidedNamedBeanHttpService.java b/java/src/jmri/server/json/JsonNonProvidedNamedBeanHttpService.java
index c3eddee6567..d2e56b54b01 100644
--- a/java/src/jmri/server/json/JsonNonProvidedNamedBeanHttpService.java
+++ b/java/src/jmri/server/json/JsonNonProvidedNamedBeanHttpService.java
@@ -92,14 +92,14 @@ protected abstract ObjectNode doGet(T bean, @Nonnull String name, @Nonnull Strin
protected ObjectNode getNamedBean(T bean, @Nonnull String name, @Nonnull String type, @Nonnull Locale locale, int id)
throws JsonException {
if (bean == null) {
- throw new JsonException(404, Bundle.getMessage(locale, "ErrorNotFound", type, name), id);
+ throw new JsonException(404, Bundle.getMessage(locale, JsonException.ERROR_NOT_FOUND, type, name), id);
}
ObjectNode data = mapper.createObjectNode();
data.put(JSON.NAME, bean.getSystemName());
data.put(JSON.USERNAME, bean.getUserName());
data.put(JSON.COMMENT, bean.getComment());
ArrayNode properties = data.putArray(JSON.PROPERTIES);
- bean.getPropertyKeys().stream().forEach((key) -> {
+ bean.getPropertyKeys().stream().forEach(key -> {
Object value = bean.getProperty(key);
if (value != null) {
properties.add(mapper.createObjectNode().put(key, value.toString()));
@@ -130,7 +130,7 @@ protected ObjectNode getNamedBean(T bean, @Nonnull String name, @Nonnull String
protected T postNamedBean(T bean, @Nonnull JsonNode data, @Nonnull String name, @Nonnull String type,
@Nonnull Locale locale, int id) throws JsonException {
if (bean == null) {
- throw new JsonException(404, Bundle.getMessage(locale, "ErrorNotFound", type, name), id);
+ throw new JsonException(404, Bundle.getMessage(locale, JsonException.ERROR_NOT_FOUND, type, name), id);
}
if (data.path(JSON.USERNAME).isTextual()) {
bean.setUserName(data.path(JSON.USERNAME).asText());
diff --git a/java/src/jmri/server/json/block/JsonBlockHttpService.java b/java/src/jmri/server/json/block/JsonBlockHttpService.java
index 69385e8612b..010f964d527 100644
--- a/java/src/jmri/server/json/block/JsonBlockHttpService.java
+++ b/java/src/jmri/server/json/block/JsonBlockHttpService.java
@@ -57,9 +57,7 @@ public ObjectNode doGet(Block block, String name, String type, Locale locale, in
data.put(JsonBlock.PERMISSIVE, block.getPermissiveWorking());
data.put(JsonBlock.SPEED_LIMIT, block.getSpeedLimit());
ArrayNode array = data.putArray(JsonBlock.DENIED);
- block.getDeniedBlocks().forEach((denied) -> {
- array.add(denied);
- });
+ block.getDeniedBlocks().forEach(array::add);
return root;
}
@@ -97,7 +95,7 @@ public ObjectNode doPost(Block block, String name, String type, JsonNode data, L
block.setSensor(sensor.getSystemName());
} else {
throw new JsonException(404,
- Bundle.getMessage(locale, "ErrorNotFound", JsonSensor.SENSOR, node.asText()), id);
+ Bundle.getMessage(locale, JsonException.ERROR_NOT_FOUND, JsonSensor.SENSOR, node.asText()), id);
}
}
}
@@ -111,7 +109,7 @@ public ObjectNode doPost(Block block, String name, String type, JsonNode data, L
block.setReporter(reporter);
} else {
throw new JsonException(404,
- Bundle.getMessage(locale, "ErrorNotFound", JsonReporter.REPORTER, node.asText()), id);
+ Bundle.getMessage(locale, JsonException.ERROR_NOT_FOUND, JsonReporter.REPORTER, node.asText()), id);
}
}
}
@@ -119,11 +117,13 @@ public ObjectNode doPost(Block block, String name, String type, JsonNode data, L
try {
block.setBlockSpeed(text);
} catch (JmriException ex) {
- throw new JsonException(HttpServletResponse.SC_BAD_REQUEST, Bundle.getMessage(locale, "ErrorBadPropertyValue", text, JSON.SPEED, type), id);
+ throw new JsonException(HttpServletResponse.SC_BAD_REQUEST, Bundle.getMessage(locale, JsonException.ERROR_BAD_PROPERTY_VALUE, text, JSON.SPEED, type), id);
}
block.setCurvature(data.path(JsonBlock.CURVATURE).asInt(block.getCurvature()));
block.setDirection(data.path(JSON.DIRECTION).asInt(block.getDirection()));
- block.setLength(Double.valueOf(data.path(JSON.LENGTH).asDouble(block.getLengthMm())).floatValue());
+ if (data.path(JSON.LENGTH).isNumber()) {
+ block.setLength(data.path(JSON.LENGTH).floatValue());
+ }
block.setPermissiveWorking(data.path(JsonBlock.PERMISSIVE).asBoolean(block.getPermissiveWorking()));
return this.doGet(block, name, type, locale, id);
}
@@ -145,7 +145,7 @@ public JsonNode doSchema(String type, boolean server, Locale locale, int id) thr
"jmri/server/json/block/block-client.json",
id);
default:
- throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, "ErrorUnknownType", type), id);
+ throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
}
@@ -155,7 +155,7 @@ protected String getType() {
}
@Override
- protected ProvidingManager getManager() throws UnsupportedOperationException {
+ protected ProvidingManager getManager() {
return InstanceManager.getDefault(BlockManager.class);
}
}
diff --git a/java/src/jmri/server/json/consist/JsonConsist.java b/java/src/jmri/server/json/consist/JsonConsist.java
index ab2407cfb50..f6e1c211ad9 100644
--- a/java/src/jmri/server/json/consist/JsonConsist.java
+++ b/java/src/jmri/server/json/consist/JsonConsist.java
@@ -15,6 +15,12 @@ public class JsonConsist {
* {@value #CONSISTS}
*/
public static final String CONSISTS = "consists"; // NOI18N
+ /**
+ * {@value #ERROR_NO_CONSIST_MANAGER}, a key for localized error messages
+ * indicating that no consist manager is available.
+ */
+ public static final String ERROR_NO_CONSIST_MANAGER = "ErrorNoConsistManager"; // NOI18N
+
/**
* Prevent instantiation, since this class only contains static values
*/
diff --git a/java/src/jmri/server/json/consist/JsonConsistHttpService.java b/java/src/jmri/server/json/consist/JsonConsistHttpService.java
index 345dffdbabb..d9e70ee37a1 100644
--- a/java/src/jmri/server/json/consist/JsonConsistHttpService.java
+++ b/java/src/jmri/server/json/consist/JsonConsistHttpService.java
@@ -29,7 +29,6 @@
import jmri.server.json.util.JsonUtilHttpService;
/**
- *
* @author Randall Wood Copyright 2016, 2018
*/
public class JsonConsistHttpService extends JsonHttpService {
@@ -38,27 +37,23 @@ public class JsonConsistHttpService extends JsonHttpService {
public JsonConsistHttpService(ObjectMapper mapper) {
super(mapper);
- this.manager = InstanceManager.getOptionalDefault(JsonConsistManager.class).orElseGet(() -> {
- return InstanceManager.setDefault(JsonConsistManager.class, new JsonConsistManager());
- });
+ this.manager = InstanceManager.getOptionalDefault(JsonConsistManager.class)
+ .orElseGet(() -> InstanceManager.setDefault(JsonConsistManager.class, new JsonConsistManager()));
}
@Override
public JsonNode doGet(String type, String name, JsonNode data, Locale locale, int id) throws JsonException {
if (!this.manager.isConsistManager()) {
- throw new JsonException(503, Bundle.getMessage(locale, "ErrorNoConsistManager"), id); // NOI18N
+ throw new JsonException(503, Bundle.getMessage(locale, JsonConsist.ERROR_NO_CONSIST_MANAGER), id); // NOI18N
}
return this.getConsist(locale, JsonUtilHttpService.addressForString(name), id);
}
/**
- * Change the properties and locomotives of a consist.
- *
- * This method takes as input the JSON representation of a consist as
- * provided by {@link #getConsist(Locale, jmri.LocoAddress, int) }.
- *
- * If present in the JSON, this method sets the following consist
- * properties:
+ * Change the properties and locomotives of a consist. This method takes as
+ * input the JSON representation of a consist as provided by
+ * {@link #getConsist(Locale, jmri.LocoAddress, int) }. If present in the
+ * JSON, this method sets the following consist properties:
*
* - consistID
* - consistType
@@ -85,7 +80,7 @@ public JsonNode doGet(String type, String name, JsonNode data, Locale locale, in
@Override
public JsonNode doPost(String type, String name, JsonNode data, Locale locale, int id) throws JsonException {
if (!this.manager.isConsistManager()) {
- throw new JsonException(503, Bundle.getMessage(locale, "ErrorNoConsistManager"), id); // NOI18N
+ throw new JsonException(503, Bundle.getMessage(locale, JsonConsist.ERROR_NO_CONSIST_MANAGER), id); // NOI18N
}
LocoAddress address;
if (data.path(ADDRESS).canConvertToInt()) {
@@ -94,7 +89,7 @@ public JsonNode doPost(String type, String name, JsonNode data, Locale locale, i
address = JsonUtilHttpService.addressForString(data.path(ADDRESS).asText());
}
if (!this.manager.getConsistList().contains(address)) {
- throw new JsonException(404, Bundle.getMessage(locale, "ErrorObject", CONSIST, name), id);
+ throw new JsonException(404, Bundle.getMessage(locale, JsonException.ERROR_OBJECT, CONSIST, name), id);
}
Consist consist = this.manager.getConsist(address);
if (data.path(NAME).isTextual()) {
@@ -107,7 +102,8 @@ public JsonNode doPost(String type, String name, JsonNode data, Locale locale, i
ArrayList engines = new ArrayList<>();
// add every engine
for (JsonNode engine : data.path(ENGINES)) {
- DccLocoAddress engineAddress = new DccLocoAddress(engine.path(ADDRESS).asInt(), engine.path(IS_LONG_ADDRESS).asBoolean());
+ DccLocoAddress engineAddress =
+ new DccLocoAddress(engine.path(ADDRESS).asInt(), engine.path(IS_LONG_ADDRESS).asBoolean());
if (!consist.contains(engineAddress)) {
consist.add(engineAddress, engine.path(FORWARD).asBoolean());
}
@@ -116,9 +112,9 @@ public JsonNode doPost(String type, String name, JsonNode data, Locale locale, i
}
// remove engines if needed
ArrayList consistEngines = new ArrayList<>(consist.getConsistList());
- consistEngines.stream().filter((engineAddress) -> (!engines.contains(engineAddress))).forEach((engineAddress) -> {
- consist.remove(engineAddress);
- });
+ consistEngines.stream()
+ .filter(engineAddress -> (!engines.contains(engineAddress)))
+ .forEach(consist::remove);
}
try {
(new ConsistFile()).writeFile(this.manager.getConsistList());
@@ -131,7 +127,7 @@ public JsonNode doPost(String type, String name, JsonNode data, Locale locale, i
@Override
public JsonNode doPut(String type, String name, JsonNode data, Locale locale, int id) throws JsonException {
if (!this.manager.isConsistManager()) {
- throw new JsonException(503, Bundle.getMessage(locale, "ErrorNoConsistManager"), id); // NOI18N
+ throw new JsonException(503, Bundle.getMessage(locale, JsonConsist.ERROR_NO_CONSIST_MANAGER), id); // NOI18N
}
LocoAddress address;
if (data.path(ADDRESS).canConvertToInt()) {
@@ -146,10 +142,10 @@ public JsonNode doPut(String type, String name, JsonNode data, Locale locale, in
@Override
public void doDelete(String type, String name, JsonNode data, Locale locale, int id) throws JsonException {
if (!this.manager.isConsistManager()) {
- throw new JsonException(503, Bundle.getMessage(locale, "ErrorNoConsistManager"), id); // NOI18N
+ throw new JsonException(503, Bundle.getMessage(locale, JsonConsist.ERROR_NO_CONSIST_MANAGER), id); // NOI18N
}
if (!this.manager.getConsistList().contains(JsonUtilHttpService.addressForString(name))) {
- throw new JsonException(404, Bundle.getMessage(locale, "ErrorObject", CONSIST, name), id); // NOI18N
+ throw new JsonException(404, Bundle.getMessage(locale, JsonException.ERROR_OBJECT, CONSIST, name), id); // NOI18N
}
this.manager.delConsist(JsonUtilHttpService.addressForString(name));
}
@@ -157,7 +153,7 @@ public void doDelete(String type, String name, JsonNode data, Locale locale, int
@Override
public JsonNode doGetList(String type, JsonNode data, Locale locale, int id) throws JsonException {
if (!this.manager.isConsistManager()) {
- throw new JsonException(503, Bundle.getMessage(locale, "ErrorNoConsistManager"), id); // NOI18N
+ throw new JsonException(503, Bundle.getMessage(locale, JsonConsist.ERROR_NO_CONSIST_MANAGER), id); // NOI18N
}
ArrayNode array = mapper.createArrayNode();
for (LocoAddress address : this.manager.getConsistList()) {
@@ -167,9 +163,8 @@ public JsonNode doGetList(String type, JsonNode data, Locale locale, int id) thr
}
/**
- * Get the JSON representation of a consist.
- *
- * The JSON representation is an object with the following data attributes:
+ * Get the JSON representation of a consist. The JSON representation is an
+ * object with the following data attributes:
*
* - address - integer address
* - isLongAddress - boolean true if address is long, false if short
@@ -203,7 +198,7 @@ public JsonNode getConsist(Locale locale, LocoAddress address, int id) throws Js
data.put(IS_LONG_ADDRESS, consist.getConsistAddress().isLongAddress());
data.put(TYPE, consist.getConsistType());
ArrayNode engines = data.putArray(ENGINES);
- consist.getConsistList().stream().forEach((locomotive) -> {
+ consist.getConsistList().stream().forEach(locomotive -> {
ObjectNode engine = mapper.createObjectNode();
engine.put(ADDRESS, locomotive.getNumber());
engine.put(IS_LONG_ADDRESS, locomotive.isLongAddress());
@@ -215,7 +210,7 @@ public JsonNode getConsist(Locale locale, LocoAddress address, int id) throws Js
data.put(SIZE_LIMIT, consist.sizeLimit());
return message(CONSIST, data, id);
} else {
- throw new JsonException(404, Bundle.getMessage(locale, "ErrorObject", CONSIST, address.toString()), id); // NOI18N
+ throw new JsonException(404, Bundle.getMessage(locale, JsonException.ERROR_OBJECT, CONSIST, address.toString()), id); // NOI18N
}
}
@@ -230,7 +225,8 @@ public JsonNode doSchema(String type, boolean server, Locale locale, int id) thr
"jmri/server/json/consist/consist-client.json",
id);
default:
- throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, "ErrorUnknownType", type), id);
+ throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
+ Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
}
}
diff --git a/java/src/jmri/server/json/idTag/JsonIdTagHttpService.java b/java/src/jmri/server/json/idTag/JsonIdTagHttpService.java
index 0cb5fda1c66..80d33018820 100644
--- a/java/src/jmri/server/json/idTag/JsonIdTagHttpService.java
+++ b/java/src/jmri/server/json/idTag/JsonIdTagHttpService.java
@@ -36,12 +36,11 @@ public ObjectNode doGet(IdTag idTag, String name, String type, Locale locale, in
ObjectNode root = this.getNamedBean(idTag, name, type, locale, id); // throws JsonException if idTag == null
ObjectNode data = root.with(JSON.DATA);
if (idTag != null) {
- switch (idTag.getState()) {
- case IdTag.UNKNOWN:
- data.put(JSON.STATE, JSON.UNKNOWN);
- break;
- default:
- data.put(JSON.STATE, idTag.getState());
+ int state = idTag.getState();
+ if (state == IdTag.UNKNOWN) {
+ data.put(JSON.STATE, JSON.UNKNOWN);
+ } else {
+ data.put(JSON.STATE, state);
}
Reporter reporter = idTag.getWhereLastSeen();
data.put(JsonReporter.REPORTER, reporter != null ? reporter.getSystemName() : null);
@@ -61,7 +60,7 @@ public ObjectNode doPost(IdTag idTag, String name, String type, JsonNode data, L
if (reporter != null) {
idTag.setWhereLastSeen(reporter);
} else {
- throw new JsonException(HttpServletResponse.SC_NOT_FOUND, Bundle.getMessage(locale, "ErrorNotFound", JsonReporter.REPORTER, node.asText()), id);
+ throw new JsonException(HttpServletResponse.SC_NOT_FOUND, Bundle.getMessage(locale, JsonException.ERROR_NOT_FOUND, JsonReporter.REPORTER, node.asText()), id);
}
}
return doGet(idTag, name, type, locale, id);
@@ -74,15 +73,14 @@ public void doDelete(IdTag bean, String name, String type, JsonNode data, Locale
@Override
public JsonNode doSchema(String type, boolean server, Locale locale, int id) throws JsonException {
- switch (type) {
- case IDTAG:
- return doSchema(type,
- server,
- "jmri/server/json/idTag/idTag-server.json",
- "jmri/server/json/idTag/idTag-client.json",
- id);
- default:
- throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, "ErrorUnknownType", type), id);
+ if (IDTAG.equals(type)) {
+ return doSchema(type,
+ server,
+ "jmri/server/json/idTag/idTag-server.json",
+ "jmri/server/json/idTag/idTag-client.json",
+ id);
+ } else {
+ throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
}
@@ -92,7 +90,7 @@ protected String getType() {
}
@Override
- protected ProvidingManager getManager() throws UnsupportedOperationException {
+ protected ProvidingManager getManager() {
return InstanceManager.getDefault(IdTagManager.class);
}
}
diff --git a/java/src/jmri/server/json/layoutblock/JsonLayoutBlockHttpService.java b/java/src/jmri/server/json/layoutblock/JsonLayoutBlockHttpService.java
index 468bad29454..7d9c5c5ad6f 100644
--- a/java/src/jmri/server/json/layoutblock/JsonLayoutBlockHttpService.java
+++ b/java/src/jmri/server/json/layoutblock/JsonLayoutBlockHttpService.java
@@ -87,7 +87,6 @@ protected ObjectNode doGet(LayoutBlock layoutBlock, String name, String type, Lo
@Override
public JsonNode doPost(String type, String name, JsonNode data, Locale locale, int id) throws JsonException {
return doPost(InstanceManager.getDefault(LayoutBlockManager.class).getBeanBySystemName(name), data, name, type, locale, id);
-
}
public JsonNode doPost(LayoutBlock layoutBlock, JsonNode data, String name, String type, Locale locale, int id) throws JsonException {
@@ -101,7 +100,7 @@ public JsonNode doPost(LayoutBlock layoutBlock, JsonNode data, String name, Stri
layoutBlock.setBlockTrackColor(color);
}
} catch (IllegalArgumentException ex) {
- throw new JsonException(HttpServletResponse.SC_BAD_REQUEST, Bundle.getMessage(locale, "ErrorBadPropertyValue", string, TRACK_COLOR, type), id);
+ throw new JsonException(HttpServletResponse.SC_BAD_REQUEST, Bundle.getMessage(locale, JsonException.ERROR_BAD_PROPERTY_VALUE, string, TRACK_COLOR, type), id);
}
try {
string = data.path(OCCUPIED_COLOR).asText();
@@ -110,7 +109,7 @@ public JsonNode doPost(LayoutBlock layoutBlock, JsonNode data, String name, Stri
layoutBlock.setBlockTrackColor(color);
}
} catch (IllegalArgumentException ex) {
- throw new JsonException(HttpServletResponse.SC_BAD_REQUEST, Bundle.getMessage(locale, "ErrorBadPropertyValue", string, OCCUPIED_COLOR, type), id);
+ throw new JsonException(HttpServletResponse.SC_BAD_REQUEST, Bundle.getMessage(locale, JsonException.ERROR_BAD_PROPERTY_VALUE, string, OCCUPIED_COLOR, type), id);
}
try {
string = data.path(EXTRA_COLOR).asText();
@@ -119,14 +118,14 @@ public JsonNode doPost(LayoutBlock layoutBlock, JsonNode data, String name, Stri
layoutBlock.setBlockTrackColor(color);
}
} catch (IllegalArgumentException ex) {
- throw new JsonException(HttpServletResponse.SC_BAD_REQUEST, Bundle.getMessage(locale, "ErrorBadPropertyValue", string, EXTRA_COLOR, type), id);
+ throw new JsonException(HttpServletResponse.SC_BAD_REQUEST, Bundle.getMessage(locale, JsonException.ERROR_BAD_PROPERTY_VALUE, string, EXTRA_COLOR, type), id);
}
if (!data.path(MEMORY).isMissingNode()) {
string = !data.path(MEMORY).isNull() ? data.path(MEMORY).asText() : null;
if (string != null) {
Memory memory = InstanceManager.getDefault(MemoryManager.class).getBeanBySystemName(string);
if (memory == null) {
- throw new JsonException(HttpServletResponse.SC_NOT_FOUND, Bundle.getMessage(locale, "ErrorNotFound", MEMORY, string), id);
+ throw new JsonException(HttpServletResponse.SC_NOT_FOUND, Bundle.getMessage(locale, JsonException.ERROR_NOT_FOUND, MEMORY, string), id);
}
layoutBlock.setMemoryName(memory.getUserName());
} else {
@@ -138,7 +137,7 @@ public JsonNode doPost(LayoutBlock layoutBlock, JsonNode data, String name, Stri
if (string != null) {
Sensor sensor = InstanceManager.getDefault(SensorManager.class).getBeanBySystemName(string);
if (sensor == null) {
- throw new JsonException(HttpServletResponse.SC_NOT_FOUND, Bundle.getMessage(locale, "ErrorNotFound", SENSOR, string), id);
+ throw new JsonException(HttpServletResponse.SC_NOT_FOUND, Bundle.getMessage(locale, JsonException.ERROR_NOT_FOUND, SENSOR, string), id);
}
layoutBlock.setOccupancySensorName(sensor.getUserName());
} else {
@@ -181,14 +180,12 @@ public JsonNode doPut(String type, String name, JsonNode data, Locale locale, in
public void doDelete(String type, String name, JsonNode data, Locale locale, int id) throws JsonException {
LayoutBlock layoutBlock = InstanceManager.getDefault(LayoutBlockManager.class).getBeanBySystemName(name);
if (layoutBlock == null) {
- throw new JsonException(HttpServletResponse.SC_NOT_FOUND, Bundle.getMessage(locale, "ErrorNotFound", type, name), id);
+ throw new JsonException(HttpServletResponse.SC_NOT_FOUND, Bundle.getMessage(locale, JsonException.ERROR_NOT_FOUND, type, name), id);
}
List listeners = layoutBlock.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 {
InstanceManager.getDefault(LayoutBlockManager.class).deregister(layoutBlock);
@@ -211,7 +208,7 @@ public JsonNode doSchema(String type, boolean server, Locale locale, int id) thr
"jmri/server/json/layoutblock/layoutBlock-client.json",
id);
default:
- throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, "ErrorUnknownType", type), id);
+ throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
}
}
diff --git a/java/src/jmri/server/json/light/JsonLightHttpService.java b/java/src/jmri/server/json/light/JsonLightHttpService.java
index 5849feb2ca6..ee05e029bb4 100644
--- a/java/src/jmri/server/json/light/JsonLightHttpService.java
+++ b/java/src/jmri/server/json/light/JsonLightHttpService.java
@@ -85,7 +85,7 @@ public JsonNode doSchema(String type, boolean server, Locale locale, int id) thr
"jmri/server/json/light/light-client.json",
id);
default:
- throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, "ErrorUnknownType", type), id);
+ throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
}
@@ -95,7 +95,7 @@ protected String getType() {
}
@Override
- protected ProvidingManager getManager() throws UnsupportedOperationException {
+ protected ProvidingManager getManager() {
return InstanceManager.getDefault(LightManager.class);
}
}
diff --git a/java/src/jmri/server/json/memory/JsonMemoryHttpService.java b/java/src/jmri/server/json/memory/JsonMemoryHttpService.java
index 3a9de7a88b3..8965b157c02 100644
--- a/java/src/jmri/server/json/memory/JsonMemoryHttpService.java
+++ b/java/src/jmri/server/json/memory/JsonMemoryHttpService.java
@@ -64,7 +64,7 @@ public JsonNode doSchema(String type, boolean server, Locale locale, int id) thr
"jmri/server/json/memory/memory-client.json",
id);
default:
- throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, "ErrorUnknownType", type), id);
+ throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
}
@@ -74,7 +74,7 @@ protected String getType() {
}
@Override
- protected ProvidingManager getManager() throws UnsupportedOperationException {
+ protected ProvidingManager getManager() {
return InstanceManager.getDefault(MemoryManager.class);
}
}
diff --git a/java/src/jmri/server/json/message/JsonMessageClientManager.java b/java/src/jmri/server/json/message/JsonMessageClientManager.java
index c43c7e260ea..a92ab21ee59 100644
--- a/java/src/jmri/server/json/message/JsonMessageClientManager.java
+++ b/java/src/jmri/server/json/message/JsonMessageClientManager.java
@@ -12,7 +12,6 @@
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
-import javax.annotation.CheckForNull;
import jmri.InstanceManagerAutoDefault;
import jmri.server.json.JsonConnection;
@@ -35,11 +34,11 @@ public class JsonMessageClientManager implements InstanceManagerAutoDefault {
* @throws IllegalArgumentException if client is already in use for a
* different connection
*/
- public void subscribe(@Nonnull String client, @Nonnull JsonConnection connection) throws IllegalArgumentException {
- if (this.clients.containsKey(client) && !connection.equals(this.clients.get(client))) {
+ public void subscribe(@Nonnull String client, @Nonnull JsonConnection connection) {
+ if (clients.containsKey(client) && !connection.equals(clients.get(client))) {
throw new IllegalArgumentException("client in use with different connection");
}
- this.clients.putIfAbsent(client, connection);
+ clients.putIfAbsent(client, connection);
}
/**
@@ -48,7 +47,7 @@ public void subscribe(@Nonnull String client, @Nonnull JsonConnection connection
* @param client the client canceling the subscription
*/
public void unsubscribe(@CheckForNull String client) {
- this.clients.remove(client);
+ clients.remove(client);
}
/**
@@ -58,14 +57,10 @@ public void unsubscribe(@CheckForNull String client) {
*/
public void unsubscribe(@CheckForNull JsonConnection connection) {
List keys = new ArrayList<>();
- this.clients.entrySet().stream()
- .filter((entry) -> (entry.getValue().equals(connection)))
- .forEachOrdered((entry) -> {
- keys.add(entry.getKey());
- });
- keys.forEach((client) -> {
- this.unsubscribe(client);
- });
+ clients.entrySet().stream()
+ .filter(entry -> entry.getValue().equals(connection))
+ .forEachOrdered(entry -> keys.add(entry.getKey()));
+ keys.forEach(this::unsubscribe);
}
/**
@@ -75,29 +70,29 @@ public void unsubscribe(@CheckForNull JsonConnection connection) {
* @param message the message to send
*/
public void send(@Nonnull JsonMessage message) {
- JsonNode node = this.getJsonMessage(message);
+ JsonNode node = getJsonMessage(message);
if (message.getClient() == null) {
- new HashMap<>(this.clients).entrySet().forEach((client) -> {
+ new HashMap<>(clients).entrySet().forEach(client -> {
try {
client.getValue().sendMessage(node, 0);
} catch (IOException ex) {
- this.unsubscribe(client.getKey());
+ unsubscribe(client.getKey());
}
});
} else {
- JsonConnection connection = this.clients.get(message.getClient());
+ JsonConnection connection = clients.get(message.getClient());
if (connection != null) {
try {
connection.sendMessage(node, 0);
} catch (IOException ex) {
- this.unsubscribe(message.getClient());
+ unsubscribe(message.getClient());
}
}
}
}
private JsonNode getJsonMessage(JsonMessage message) {
- return message.toJSON(this.mapper);
+ return message.toJSON(mapper);
}
/**
@@ -108,7 +103,7 @@ private JsonNode getJsonMessage(JsonMessage message) {
*/
@CheckForNull
public synchronized String getClient(@Nonnull JsonConnection connection) {
- for (Entry entry : this.clients.entrySet()) {
+ for (Entry entry : clients.entrySet()) {
if (entry.getValue().equals(connection)) {
return entry.getKey();
}
@@ -125,7 +120,7 @@ public synchronized String getClient(@Nonnull JsonConnection connection) {
*/
public synchronized Set getClients(@Nonnull JsonConnection connection) {
Set set = new HashSet<>();
- for (Entry entry : this.clients.entrySet()) {
+ for (Entry entry : clients.entrySet()) {
if (entry.getValue().equals(connection)) {
set.add(entry.getKey());
}
diff --git a/java/src/jmri/server/json/message/JsonMessageHttpService.java b/java/src/jmri/server/json/message/JsonMessageHttpService.java
index d3ba1e8c255..ce59517e880 100644
--- a/java/src/jmri/server/json/message/JsonMessageHttpService.java
+++ b/java/src/jmri/server/json/message/JsonMessageHttpService.java
@@ -62,7 +62,7 @@ public JsonNode doSchema(String type, boolean server, Locale locale, int id) thr
"jmri/server/json/util/hello-client.json",
id);
default:
- throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, "ErrorUnknownType", type), id);
+ throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
}
diff --git a/java/src/jmri/server/json/operations/JsonOperationsHttpService.java b/java/src/jmri/server/json/operations/JsonOperationsHttpService.java
index 191affee336..746bb11b6f0 100644
--- a/java/src/jmri/server/json/operations/JsonOperationsHttpService.java
+++ b/java/src/jmri/server/json/operations/JsonOperationsHttpService.java
@@ -71,12 +71,10 @@
import jmri.server.json.JsonHttpService;
/**
- *
* @author Randall Wood (C) 2016, 2018, 2019
*/
public class JsonOperationsHttpService extends JsonHttpService {
- // private final static Logger log = LoggerFactory.getLogger(JsonOperationsHttpService.class);
private final JsonUtil utilities;
public JsonOperationsHttpService(ObjectMapper mapper) {
@@ -97,7 +95,7 @@ public JsonNode doGet(String type, String name, JsonNode data, Locale locale, in
Kernel kernel = carManager().getKernelByName(name);
if (kernel == 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);
}
return getKernel(kernel, locale, id);
case LOCATION:
@@ -155,16 +153,17 @@ public JsonNode doPost(String type, String name, JsonNode data, Locale locale, i
@Override
// Nullable overrides super class'es non-null requirement for name
- public JsonNode doPut(String type, @CheckForNull String name, JsonNode data, Locale locale, int id) throws JsonException {
+ public JsonNode doPut(String type, @CheckForNull String name, JsonNode data, Locale locale, int id)
+ throws JsonException {
switch (type) {
case CAR:
if (data.path(ROAD).isMissingNode()) {
throw new JsonException(HttpServletResponse.SC_BAD_REQUEST,
- Bundle.getMessage(locale, "ErrorMissingPropertyPut", ROAD, type), id); // NOI18N
+ Bundle.getMessage(locale, JsonException.ERROR_MISSING_PROPERTY_PUT, ROAD, type), id); // NOI18N
}
if (data.path(NUMBER).isMissingNode()) {
throw new JsonException(HttpServletResponse.SC_BAD_REQUEST,
- Bundle.getMessage(locale, "ErrorMissingPropertyPut", NUMBER, type), id); // NOI18N
+ Bundle.getMessage(locale, JsonException.ERROR_MISSING_PROPERTY_PUT, NUMBER, type), id); // NOI18N
}
String road = data.path(ROAD).asText();
String number = data.path(NUMBER).asText();
@@ -177,18 +176,18 @@ public JsonNode doPut(String type, @CheckForNull String name, JsonNode data, Loc
case CAR_TYPE:
if (name == null) {
throw new JsonException(HttpServletResponse.SC_BAD_REQUEST,
- Bundle.getMessage(locale, "ErrorMissingPropertyPut", NAME, type), id); // NOI18N
+ Bundle.getMessage(locale, JsonException.ERROR_MISSING_PROPERTY_PUT, NAME, type), id); // NOI18N
}
InstanceManager.getDefault(CarTypes.class).addName(name);
return getCarType(name, locale, id);
case ENGINE:
if (data.path(ROAD).isMissingNode()) {
throw new JsonException(HttpServletResponse.SC_BAD_REQUEST,
- Bundle.getMessage(locale, "ErrorMissingPropertyPut", ROAD, type), id); // NOI18N
+ Bundle.getMessage(locale, JsonException.ERROR_MISSING_PROPERTY_PUT, ROAD, type), id); // NOI18N
}
if (data.path(NUMBER).isMissingNode()) {
throw new JsonException(HttpServletResponse.SC_BAD_REQUEST,
- Bundle.getMessage(locale, "ErrorMissingPropertyPut", NUMBER, type), id); // NOI18N
+ Bundle.getMessage(locale, JsonException.ERROR_MISSING_PROPERTY_PUT, NUMBER, type), id); // NOI18N
}
road = data.path(ROAD).asText();
number = data.path(NUMBER).asText();
@@ -201,14 +200,14 @@ public JsonNode doPut(String type, @CheckForNull String name, JsonNode data, Loc
case KERNEL:
if (name == null) {
throw new JsonException(HttpServletResponse.SC_BAD_REQUEST,
- Bundle.getMessage(locale, "ErrorMissingPropertyPut", NAME, type), id); // NOI18N
+ Bundle.getMessage(locale, JsonException.ERROR_MISSING_PROPERTY_PUT, NAME, type), id); // NOI18N
}
Kernel kernel = carManager().newKernel(name);
return getKernel(kernel, locale, id);
case LOCATION:
if (data.path(USERNAME).isMissingNode()) {
throw new JsonException(HttpServletResponse.SC_BAD_REQUEST,
- Bundle.getMessage(locale, "ErrorMissingPropertyPut", USERNAME, type), id); // NOI18N
+ Bundle.getMessage(locale, JsonException.ERROR_MISSING_PROPERTY_PUT, USERNAME, type), id); // NOI18N
}
String userName = data.path(USERNAME).asText();
if (name != null && locationManager().getLocationById(name) != null) {
@@ -224,23 +223,23 @@ public JsonNode doPut(String type, @CheckForNull String name, JsonNode data, Loc
case TRACK:
if (data.path(USERNAME).isMissingNode()) {
throw new JsonException(HttpServletResponse.SC_BAD_REQUEST,
- Bundle.getMessage(locale, "ErrorMissingPropertyPut", USERNAME, type), id); // NOI18N
+ Bundle.getMessage(locale, JsonException.ERROR_MISSING_PROPERTY_PUT, USERNAME, type), id); // NOI18N
}
userName = data.path(USERNAME).asText();
if (data.path(TYPE).isMissingNode()) {
throw new JsonException(HttpServletResponse.SC_BAD_REQUEST,
- Bundle.getMessage(locale, "ErrorMissingPropertyPut", TYPE, type), id); // NOI18N
+ Bundle.getMessage(locale, JsonException.ERROR_MISSING_PROPERTY_PUT, TYPE, type), id); // NOI18N
}
String trackType = data.path(TYPE).asText();
if (data.path(LOCATION).isMissingNode()) {
throw new JsonException(HttpServletResponse.SC_BAD_REQUEST,
- Bundle.getMessage(locale, "ErrorMissingPropertyPut", LOCATION, type), id); // NOI18N
+ Bundle.getMessage(locale, JsonException.ERROR_MISSING_PROPERTY_PUT, LOCATION, type), id); // NOI18N
}
String locationName = data.path(LOCATION).asText();
location = locationManager().getLocationById(locationName);
if (location == null) {
throw new JsonException(HttpServletResponse.SC_NOT_FOUND,
- Bundle.getMessage(locale, "ErrorNotFound", LOCATION, locationName), id); // NOI18N
+ Bundle.getMessage(locale, JsonException.ERROR_NOT_FOUND, LOCATION, locationName), id); // NOI18N
}
if (name != null && location.getTrackById(name) != null) {
throw new JsonException(HttpServletResponse.SC_CONFLICT,
@@ -255,7 +254,7 @@ public JsonNode doPut(String type, @CheckForNull String name, JsonNode data, Loc
default:
if (name == null) {
throw new JsonException(HttpServletResponse.SC_BAD_REQUEST,
- Bundle.getMessage(locale, "ErrorMissingPropertyPut", NAME, type), id); // NOI18N
+ Bundle.getMessage(locale, JsonException.ERROR_MISSING_PROPERTY_PUT, NAME, type), id); // NOI18N
}
return super.doPut(type, name, data, locale, id);
}
@@ -294,7 +293,7 @@ public void doDelete(String type, String name, JsonNode data, Locale locale, int
switch (type) {
case CAR:
// TODO: do not remove an in use car
- deleteCar(name, data, locale, id);
+ deleteCar(name, locale, id);
break;
case CAR_TYPE:
List cars = carManager().getByTypeList(name);
@@ -304,7 +303,7 @@ public void doDelete(String type, String name, JsonNode data, Locale locale, int
locations.add(location);
}
}
- if ((cars.size() != 0 || locations.size() != 0) && !acceptForceDeleteToken(type, name, token)) {
+ if ((!cars.isEmpty() || !locations.isEmpty()) && !acceptForceDeleteToken(type, name, token)) {
ArrayNode conflicts = mapper.createArrayNode();
for (Car car : cars) {
conflicts.add(message(CAR, utilities.getCar(car, locale), 0));
@@ -318,13 +317,13 @@ public void doDelete(String type, String name, JsonNode data, Locale locale, int
break;
case ENGINE:
// TODO: do not remove an in use engine
- deleteEngine(name, data, locale, id);
+ deleteEngine(name, locale, id);
break;
case KERNEL:
Kernel kernel = carManager().getKernelByName(name);
if (kernel == 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);
}
if (kernel.getSize() != 0 && !acceptForceDeleteToken(type, name, token)) {
throwDeleteConflictException(type, name, getKernelCars(kernel, true, locale), locale, id);
@@ -333,7 +332,7 @@ public void doDelete(String type, String name, JsonNode data, Locale locale, int
break;
case LOCATION:
// TODO: do not remove an in use location
- deleteLocation(name, data, locale, id);
+ deleteLocation(name, locale, id);
break;
case TRACK:
// TODO: do not remove an in use track
@@ -348,20 +347,16 @@ private ObjectNode getCarType(String name, Locale locale, int id) throws JsonExc
CarTypes manager = InstanceManager.getDefault(CarTypes.class);
if (!manager.containsName(name)) {
throw new JsonException(HttpServletResponse.SC_NOT_FOUND,
- Bundle.getMessage(locale, "ErrorNotFound", CAR_TYPE, name), id);
+ Bundle.getMessage(locale, JsonException.ERROR_NOT_FOUND, CAR_TYPE, name), id);
}
ObjectNode data = mapper.createObjectNode();
data.put(NAME, name);
ArrayNode cars = data.putArray(CARS);
- carManager().getByTypeList(name).forEach((car) -> {
- cars.add(utilities.getCar(car, locale));
- });
+ carManager().getByTypeList(name).forEach(car -> cars.add(utilities.getCar(car, locale)));
ArrayNode locations = data.putArray(LOCATIONS);
- locationManager().getList().stream().filter((location) -> {
- return location.acceptsTypeName(name);
- }).forEach((location) -> {
- locations.add(utilities.getLocation(location, locale));
- });
+ locationManager().getList().stream()
+ .filter(location -> location.acceptsTypeName(name))
+ .forEach(location -> locations.add(utilities.getLocation(location, locale)));
return message(CAR_TYPE, data, id);
}
@@ -390,7 +385,7 @@ private ObjectNode getKernel(Kernel kernel, Locale locale, int id) {
private ArrayNode getKernelCars(Kernel kernel, boolean asMessage, Locale locale) {
ArrayNode array = mapper.createArrayNode();
- kernel.getCars().forEach((car) -> {
+ kernel.getCars().forEach(car -> {
if (asMessage) {
array.add(message(CAR, utilities.getCar(car, locale), 0));
} else {
@@ -402,35 +397,32 @@ private ArrayNode getKernelCars(Kernel kernel, boolean asMessage, Locale locale)
private JsonNode getKernels(Locale locale, int id) {
ArrayNode array = mapper.createArrayNode();
- carManager().getKernelNameList().forEach((kernel) -> {
- // individual kernels should not have id in array, but same method is used to get
- // single kernels as requested, so pass additive inverse of id to allow errors
- array.add(getKernel(carManager().getKernelByName(kernel), locale, id * -1));
- });
+ carManager().getKernelNameList()
+ // individual kernels should not have id in array, but same
+ // method is used to get single kernels as requested, so pass
+ // additive inverse of id to allow errors
+ .forEach(kernel -> array.add(getKernel(carManager().getKernelByName(kernel), locale, id * -1)));
return message(array, id);
}
public ArrayNode getCars(Locale locale, int id) {
ArrayNode array = mapper.createArrayNode();
- carManager().getByIdList().forEach((car) -> {
- array.add(message(CAR, utilities.getCar(car, locale), id));
- });
+ carManager().getByIdList()
+ .forEach(car -> array.add(message(CAR, utilities.getCar(car, locale), id)));
return array;
}
public ArrayNode getEngines(Locale locale, int id) {
ArrayNode array = mapper.createArrayNode();
- engineManager().getByIdList().forEach((engine) -> {
- array.add(message(ENGINE, utilities.getEngine(engine, locale), id));
- });
+ engineManager().getByIdList()
+ .forEach(engine -> array.add(message(ENGINE, utilities.getEngine(engine, locale), id)));
return array;
}
- public JsonNode getLocations(Locale locale, int id) throws JsonException {
+ public JsonNode getLocations(Locale locale, int id) {
ArrayNode array = mapper.createArrayNode();
- locationManager().getLocationsByIdList().forEach((location) -> {
- array.add(message(LOCATION, utilities.getLocation(location, locale), id));
- });
+ locationManager().getLocationsByIdList()
+ .forEach(location -> array.add(message(LOCATION, utilities.getLocation(location, locale), id)));
return message(array, id);
}
@@ -446,7 +438,7 @@ public JsonNode getLocations(Locale locale, int id) throws JsonException {
* @param locale locale to throw exceptions in
* @param id message id set by client
* @throws jmri.server.json.JsonException if the train cannot move to the
- * location in data.
+ * location in data.
*/
public void setTrain(String name, JsonNode data, Locale locale, int id) throws JsonException {
Train train = InstanceManager.getDefault(TrainManager.class).getTrainById(name);
@@ -473,7 +465,8 @@ public ObjectNode postLocation(Location location, JsonNode data, Locale locale,
if (reporter != null) {
location.setReporter(reporter);
} else {
- throw new JsonException(HttpServletResponse.SC_NOT_FOUND, Bundle.getMessage(locale, "ErrorNotFound", REPORTER, name), id);
+ throw new JsonException(HttpServletResponse.SC_NOT_FOUND,
+ Bundle.getMessage(locale, JsonException.ERROR_NOT_FOUND, REPORTER, name), id);
}
}
location.setName(data.path(USERNAME).asText(location.getName()));
@@ -493,7 +486,8 @@ public ObjectNode postTrack(Track track, JsonNode data, Locale locale, int id) t
if (reporter != null) {
track.setReporter(reporter);
} else {
- throw new JsonException(HttpServletResponse.SC_NOT_FOUND, Bundle.getMessage(locale, "ErrorNotFound", REPORTER, name), id);
+ throw new JsonException(HttpServletResponse.SC_NOT_FOUND,
+ Bundle.getMessage(locale, JsonException.ERROR_NOT_FOUND, REPORTER, name), id);
}
}
track.setName(data.path(USERNAME).asText(track.getName()));
@@ -505,7 +499,8 @@ public ObjectNode postTrack(Track track, JsonNode data, Locale locale, int id) t
/**
* Set the properties in the data parameter for the given car.
*
- * Note returns the modified car because changing the road or number of a car changes its name in the JSON representation.
+ * Note returns the modified car because changing the road
+ * or number of a car changes its name in the JSON representation.
*
* @param name the operations id of the car to change
* @param data car data to change
@@ -521,7 +516,8 @@ public ObjectNode postCar(String name, JsonNode data, Locale locale, int id) thr
/**
* Set the properties in the data parameter for the given car.
*
- * Note returns the modified car because changing the road or number of a car changes its name in the JSON representation.
+ * Note returns the modified car because changing the road
+ * or number of a car changes its name in the JSON representation.
*
* @param car the car to change
* @param data car data to change
@@ -540,7 +536,6 @@ public ObjectNode postCar(@Nonnull Car car, JsonNode data, Locale locale, int id
return utilities.getCar(car, result, locale);
}
-
/**
* Set the properties in the data parameter for the given engine.
*
@@ -581,7 +576,9 @@ public ObjectNode postEngine(@Nonnull Engine engine, JsonNode data, Locale local
/**
* Set the properties in the data parameter for the given rolling stock.
*
- * Note returns the modified rolling stock because changing the road or number of a rolling stock changes its name in the JSON representation.
+ * Note returns the modified rolling stock because changing
+ * the road or number of a rolling stock changes its name in the JSON
+ * representation.
*
* @param rs the rolling stock to change
* @param data rolling stock data to change
@@ -590,7 +587,8 @@ public ObjectNode postEngine(@Nonnull Engine engine, JsonNode data, Locale local
* @return the JSON representation of the rolling stock
* @throws JsonException if unable to set location
*/
- public ObjectNode postRollingStock(@Nonnull RollingStock rs, JsonNode data, Locale locale, int id) throws JsonException {
+ public ObjectNode postRollingStock(@Nonnull RollingStock rs, JsonNode data, Locale locale, int id)
+ throws JsonException {
String name = rs.getId();
// make changes that can throw an exception first
JsonNode node = data.path(LOCATION);
@@ -640,17 +638,17 @@ public ObjectNode postRollingStock(@Nonnull RollingStock rs, JsonNode data, Loca
return result;
}
- public void deleteCar(@Nonnull String name, @Nonnull JsonNode data, @Nonnull Locale locale, int id)
+ public void deleteCar(@Nonnull String name, @Nonnull Locale locale, int id)
throws JsonException {
carManager().deregister(getCarByName(name, locale, id));
}
- public void deleteEngine(@Nonnull String name, @Nonnull JsonNode data, @Nonnull Locale locale, int id)
+ public void deleteEngine(@Nonnull String name, @Nonnull Locale locale, int id)
throws JsonException {
engineManager().deregister(getEngineByName(name, locale, id));
}
- public void deleteLocation(@Nonnull String name, @Nonnull JsonNode data, @Nonnull Locale locale, int id)
+ public void deleteLocation(@Nonnull String name, @Nonnull Locale locale, int id)
throws JsonException {
locationManager().deregister(getLocationByName(name, locale, id));
}
@@ -665,30 +663,33 @@ public void deleteTrack(@Nonnull String name, @Nonnull JsonNode data, @Nonnull L
Car car = carManager().getById(name);
if (car == null) {
throw new JsonException(HttpServletResponse.SC_NOT_FOUND,
- Bundle.getMessage(locale, "ErrorNotFound", CAR, name), id);
+ Bundle.getMessage(locale, JsonException.ERROR_NOT_FOUND, CAR, name), id);
}
return car;
}
- protected @Nonnull Engine getEngineByName(@Nonnull String name, @Nonnull Locale locale, int id) throws JsonException {
+ protected @Nonnull Engine getEngineByName(@Nonnull String name, @Nonnull Locale locale, int id)
+ throws JsonException {
Engine engine = engineManager().getById(name);
if (engine == null) {
throw new JsonException(HttpServletResponse.SC_NOT_FOUND,
- Bundle.getMessage(locale, "ErrorNotFound", ENGINE, name), id);
+ Bundle.getMessage(locale, JsonException.ERROR_NOT_FOUND, ENGINE, name), id);
}
return engine;
}
- protected @Nonnull Location getLocationByName(@Nonnull String name, @Nonnull Locale locale, int id) throws JsonException {
+ protected @Nonnull Location getLocationByName(@Nonnull String name, @Nonnull Locale locale, int id)
+ throws JsonException {
Location location = locationManager().getLocationById(name);
if (location == null) {
throw new JsonException(HttpServletResponse.SC_NOT_FOUND,
- Bundle.getMessage(locale, "ErrorNotFound", LOCATION, name), id);
+ Bundle.getMessage(locale, JsonException.ERROR_NOT_FOUND, LOCATION, name), id);
}
return location;
}
- protected @Nonnull Track getTrackByName(@Nonnull String name, @Nonnull JsonNode data, @Nonnull Locale locale, int id) throws JsonException {
+ protected @Nonnull Track getTrackByName(@Nonnull String name, @Nonnull JsonNode data, @Nonnull Locale locale,
+ int id) throws JsonException {
if (data.path(LOCATION).isMissingNode()) {
throw new JsonException(HttpServletResponse.SC_BAD_REQUEST,
Bundle.getMessage(locale, "ErrorMissingAttribute", LOCATION, TRACK), id);
@@ -697,7 +698,7 @@ public void deleteTrack(@Nonnull String name, @Nonnull JsonNode data, @Nonnull L
Track track = location.getTrackById(name);
if (track == null) {
throw new JsonException(HttpServletResponse.SC_NOT_FOUND,
- Bundle.getMessage(locale, "ErrorNotFound", TRACK, name), id);
+ Bundle.getMessage(locale, JsonException.ERROR_NOT_FOUND, TRACK, name), id);
}
return track;
}
@@ -769,7 +770,7 @@ public JsonNode doSchema(String type, boolean server, Locale locale, int id) thr
id);
default:
throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
- Bundle.getMessage(locale, "ErrorUnknownType", type), id);
+ Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
}
diff --git a/java/src/jmri/server/json/operations/JsonUtil.java b/java/src/jmri/server/json/operations/JsonUtil.java
index 64c28fc1f66..9b75f12c60c 100644
--- a/java/src/jmri/server/json/operations/JsonUtil.java
+++ b/java/src/jmri/server/json/operations/JsonUtil.java
@@ -65,7 +65,7 @@
public class JsonUtil {
private final ObjectMapper mapper;
- private final static Logger log = LoggerFactory.getLogger(JsonUtil.class);
+ private static final Logger log = LoggerFactory.getLogger(JsonUtil.class);
/**
* Create utilities.
@@ -89,7 +89,7 @@ public ObjectNode getCar(String name, Locale locale, int id) throws JsonExceptio
Car car = carManager().getById(name);
if (car == null) {
throw new JsonException(HttpServletResponse.SC_NOT_FOUND,
- Bundle.getMessage(locale, "ErrorNotFound", CAR, name), id);
+ Bundle.getMessage(locale, JsonException.ERROR_NOT_FOUND, CAR, name), id);
}
return this.getCar(car, locale);
}
@@ -109,7 +109,8 @@ public ObjectNode getEngine(Engine engine, Locale locale) {
* Get the JSON representation of an Engine.
*
* @param engine the Engine
- * @param data the JSON data from {@link #getRollingStock(RollingStock, Locale)}
+ * @param data the JSON data from
+ * {@link #getRollingStock(RollingStock, Locale)}
* @param locale the client's locale
* @return the JSON representation of engine
*/
@@ -132,7 +133,7 @@ public ObjectNode getEngine(String name, Locale locale, int id) throws JsonExcep
Engine engine = engineManager().getById(name);
if (engine == null) {
throw new JsonException(HttpServletResponse.SC_NOT_FOUND,
- Bundle.getMessage(locale, "ErrorNotFound", ENGINE, name), id);
+ Bundle.getMessage(locale, JsonException.ERROR_NOT_FOUND, ENGINE, name), id);
}
return this.getEngine(engine, locale);
}
@@ -152,7 +153,8 @@ public ObjectNode getCar(@Nonnull Car car, Locale locale) {
* Get a JSON representation of a Car.
*
* @param car the Car
- * @param data the JSON data from {@link #getRollingStock(RollingStock, Locale)}
+ * @param data the JSON data from
+ * {@link #getRollingStock(RollingStock, Locale)}
* @param locale the client's locale
* @return the JSON representation of car
*/
@@ -169,12 +171,14 @@ public ObjectNode getCar(@Nonnull Car car, @Nonnull ObjectNode data, Locale loca
if (car.getFinalDestinationTrack() != null) {
data.set(JSON.FINAL_DESTINATION, this.getRSLocationAndTrack(car.getFinalDestinationTrack(), null, locale));
} else if (car.getFinalDestination() != null) {
- data.set(JSON.FINAL_DESTINATION, this.getRSLocation(car.getFinalDestination(), (RouteLocation) null, locale));
+ data.set(JSON.FINAL_DESTINATION,
+ this.getRSLocation(car.getFinalDestination(), (RouteLocation) null, locale));
} else {
data.set(JSON.FINAL_DESTINATION, null);
}
if (car.getReturnWhenEmptyDestTrack() != null) {
- data.set(JSON.RETURN_WHEN_EMPTY, this.getRSLocationAndTrack(car.getReturnWhenEmptyDestTrack(), null, locale));
+ data.set(JSON.RETURN_WHEN_EMPTY,
+ this.getRSLocationAndTrack(car.getReturnWhenEmptyDestTrack(), null, locale));
} else if (car.getReturnWhenEmptyDestination() != null) {
data.set(JSON.RETURN_WHEN_EMPTY,
this.getRSLocation(car.getReturnWhenEmptyDestination(), (RouteLocation) null, locale));
@@ -203,7 +207,7 @@ public ObjectNode getLocation(@Nonnull Location location, Locale locale) {
data.put(COMMENT, location.getComment());
Reporter reporter = location.getReporter();
data.put(REPORTER, reporter != null ? reporter.getSystemName() : null);
- // note type defaults to all in-use rolling stock types
+ // note type defaults to all in-use rolling stock types
ArrayNode types = data.putArray(CAR_TYPE);
for (String type : location.getTypeNames()) {
types.add(type);
@@ -229,17 +233,17 @@ public ObjectNode getLocation(String name, Locale locale, int id) throws JsonExc
return getLocation(locationManager().getLocationById(name), locale);
} catch (NullPointerException e) {
log.error("Unable to get location id [{}].", name);
- throw new JsonException(404, Bundle.getMessage(locale, "ErrorObject", LOCATION, name), id);
+ throw new JsonException(404, Bundle.getMessage(locale, JsonException.ERROR_OBJECT, LOCATION, name), id);
}
}
/**
* Get a Track in JSON.
*
- * Note:use {@link #getRSTrack(Track, Locale)} if
- * including in rolling stock or train.
+ * Note:use {@link #getRSTrack(Track, Locale)} if including
+ * in rolling stock or train.
*
- * @param track the track to get
+ * @param track the track to get
* @param locale the client's locale
* @return a JSON representation of the track
*/
@@ -249,11 +253,12 @@ public ObjectNode getTrack(Track track, Locale locale) {
node.put(NAME, track.getId());
node.put(COMMENT, track.getComment());
node.put(LENGTH, track.getLength());
- node.put(LOCATION, track.getLocation().getId()); // only includes ID to avoid recursion
+ node.put(LOCATION, track.getLocation().getId()); // only includes ID to
+ // avoid recursion
Reporter reporter = track.getReporter();
node.put(REPORTER, reporter != null ? reporter.getSystemName() : null);
node.put(TYPE, track.getTrackType());
- // note type defaults to all in-use rolling stock types
+ // note type defaults to all in-use rolling stock types
ArrayNode types = node.putArray(CAR_TYPE);
for (String type : track.getTypeNames()) {
types.add(type);
@@ -262,7 +267,8 @@ public ObjectNode getTrack(Track track, Locale locale) {
}
/**
- * Get the JSON representation of a Location for use in rolling stock or train.
+ * Get the JSON representation of a Location for use in rolling stock or
+ * train.
*
* Note:use {@link #getLocation(Location, Locale)} if not
* including in rolling stock or train.
@@ -297,10 +303,10 @@ private ObjectNode getRSLocationAndTrack(Track track, RouteLocation routeLocatio
/**
* Get a Track in JSON for use in rolling stock or train.
*
- * Note:use {@link #getTrack(Track, Locale)} if
- * not including in rolling stock or train.
+ * Note:use {@link #getTrack(Track, Locale)} if not
+ * including in rolling stock or train.
*
- * @param track the track to get
+ * @param track the track to get
* @param locale the client's locale
* @return a JSON representation of the track
*/
@@ -344,7 +350,8 @@ public ObjectNode getRollingStock(@Nonnull RollingStock rs, Locale locale) {
node.set(LOCATION, null);
}
if (rs.getDestinationTrack() != null) {
- node.set(DESTINATION, this.getRSLocationAndTrack(rs.getDestinationTrack(), rs.getRouteDestination(), locale));
+ node.set(DESTINATION,
+ this.getRSLocationAndTrack(rs.getDestinationTrack(), rs.getRouteDestination(), locale));
} else if (rs.getDestination() != null) {
node.set(DESTINATION, this.getRSLocation(rs.getDestination(), rs.getRouteDestination(), locale));
} else {
@@ -410,7 +417,7 @@ public ObjectNode getTrain(String name, Locale locale, int id) throws JsonExcept
return getTrain(trainManager().getTrainById(name), locale);
} catch (NullPointerException ex) {
log.error("Unable to get train id [{}].", name, ex);
- throw new JsonException(404, Bundle.getMessage(locale, "ErrorObject", JsonOperations.TRAIN, name), id);
+ throw new JsonException(404, Bundle.getMessage(locale, JsonException.ERROR_OBJECT, JsonOperations.TRAIN, name), id);
}
}
@@ -422,31 +429,28 @@ public ObjectNode getTrain(String name, Locale locale, int id) throws JsonExcept
*/
public ArrayNode getTrains(Locale locale) {
ArrayNode array = this.mapper.createArrayNode();
- trainManager().getTrainsByNameList().forEach((train) -> {
- array.add(getTrain(train, locale));
- });
+ trainManager().getTrainsByNameList()
+ .forEach(train -> array.add(getTrain(train, locale)));
return array;
}
private ArrayNode getCarsForTrain(Train train, Locale locale) {
ArrayNode array = mapper.createArrayNode();
- carManager().getByTrainDestinationList(train).forEach((car) -> {
- array.add(getCar(car, locale));
- });
+ carManager().getByTrainDestinationList(train)
+ .forEach(car -> array.add(getCar(car, locale)));
return array;
}
private ArrayNode getEnginesForTrain(Train train, Locale locale) {
ArrayNode array = mapper.createArrayNode();
- engineManager().getByTrainBlockingList(train).forEach((engine) -> {
- array.add(getEngine(engine, locale));
- });
+ engineManager().getByTrainBlockingList(train)
+ .forEach(engine -> array.add(getEngine(engine, locale)));
return array;
}
private ArrayNode getRouteLocationsForTrain(Train train, Locale locale) {
ArrayNode array = mapper.createArrayNode();
- train.getRoute().getLocationsBySequenceList().forEach((route) -> {
+ train.getRoute().getLocationsBySequenceList().forEach(route -> {
ObjectNode root = mapper.createObjectNode();
RouteLocation rl = route;
root.put(NAME, rl.getId());
@@ -457,11 +461,11 @@ private ArrayNode getRouteLocationsForTrain(Train train, Locale locale) {
root.put(EXPECTED_ARRIVAL, train.getExpectedArrivalTime(rl));
root.put(EXPECTED_DEPARTURE, train.getExpectedDepartureTime(rl));
root.set(LOCATION, getRSLocation(rl.getLocation(), locale));
- array.add(root); //add this routeLocation to the routeLocation array
+ array.add(root);
});
- return array; //return array of routeLocations
+ return array;
}
-
+
private CarManager carManager() {
return InstanceManager.getDefault(CarManager.class);
}
diff --git a/java/src/jmri/server/json/power/JsonPowerHttpService.java b/java/src/jmri/server/json/power/JsonPowerHttpService.java
index f1439000f97..1a8307c78d4 100644
--- a/java/src/jmri/server/json/power/JsonPowerHttpService.java
+++ b/java/src/jmri/server/json/power/JsonPowerHttpService.java
@@ -24,7 +24,6 @@
import org.slf4j.LoggerFactory;
/**
- *
* @author Randall Wood Copyright 2016, 2018
*/
public class JsonPowerHttpService extends JsonHttpService {
@@ -37,7 +36,8 @@ public JsonPowerHttpService(ObjectMapper mapper) {
@Override
// Nullable to override inherited NonNull requirement
- public JsonNode doGet(String type, @CheckForNull String name, JsonNode parameters, Locale locale, int id) throws JsonException {
+ public JsonNode doGet(String type, @CheckForNull String name, JsonNode parameters, Locale locale, int id)
+ throws JsonException {
ObjectNode data = mapper.createObjectNode();
try {
PowerManager manager = InstanceManager.getNullableDefault(PowerManager.class);
@@ -100,7 +100,8 @@ public JsonNode doPost(String type, String name, JsonNode data, Locale locale, i
manager.setPower(PowerManager.ON);
break;
default:
- throw new JsonException(HttpServletResponse.SC_BAD_REQUEST, Bundle.getMessage(locale, "ErrorUnknownState", POWER, state), id);
+ throw new JsonException(HttpServletResponse.SC_BAD_REQUEST,
+ Bundle.getMessage(locale, "ErrorUnknownState", POWER, state), id);
}
}
} catch (JmriException ex) {
@@ -121,15 +122,15 @@ public JsonNode doGetList(String type, JsonNode data, Locale locale, int id) thr
@Override
public JsonNode doSchema(String type, boolean server, Locale locale, int id) throws JsonException {
- switch (type) {
- case POWER:
- return doSchema(type,
- server,
- "jmri/server/json/power/power-server.json",
- "jmri/server/json/power/power-client.json",
- id);
- default:
- throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, "ErrorUnknownType", type), id);
+ if (POWER.equals(type)) {
+ return doSchema(type,
+ server,
+ "jmri/server/json/power/power-server.json",
+ "jmri/server/json/power/power-client.json",
+ id);
+ } else {
+ throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
+ Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
}
}
diff --git a/java/src/jmri/server/json/reporter/JsonReporterHttpService.java b/java/src/jmri/server/json/reporter/JsonReporterHttpService.java
index 9a2ea945b5c..6eead922bc3 100644
--- a/java/src/jmri/server/json/reporter/JsonReporterHttpService.java
+++ b/java/src/jmri/server/json/reporter/JsonReporterHttpService.java
@@ -83,7 +83,7 @@ public JsonNode doSchema(String type, boolean server, Locale locale, int id) thr
"jmri/server/json/reporter/reporter-client.json",
id);
default:
- throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, "ErrorUnknownType", type), id);
+ throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
}
diff --git a/java/src/jmri/server/json/roster/JsonRosterHttpService.java b/java/src/jmri/server/json/roster/JsonRosterHttpService.java
index 437e4258c94..a4950836c65 100644
--- a/java/src/jmri/server/json/roster/JsonRosterHttpService.java
+++ b/java/src/jmri/server/json/roster/JsonRosterHttpService.java
@@ -68,7 +68,7 @@ public JsonNode doGet(String type, String name, JsonNode data, Locale locale, in
case JsonRoster.ROSTER_GROUPS:
return this.getRosterGroups(locale, id);
default:
- throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, "ErrorUnknownType", type), id);
+ throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
}
@@ -84,7 +84,7 @@ public JsonNode doPost(String type, String name, JsonNode data, Locale locale, i
case JsonRoster.ROSTER_GROUPS:
break;
default:
- throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, "ErrorUnknownType", type), id);
+ throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
throw new JsonException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, Bundle.getMessage(locale, "PostNotAllowed", type), id);
}
@@ -99,7 +99,7 @@ public JsonNode doGetList(String type, JsonNode data, Locale locale, int id) thr
case JsonRoster.ROSTER_GROUPS:
return this.getRosterGroups(locale, id);
default:
- throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, "ErrorUnknownType", type), id);
+ throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
}
@@ -140,7 +140,7 @@ public JsonNode getRosterEntry(Locale locale, String name, int id) throws JsonEx
try {
return this.getRosterEntry(locale, Roster.getDefault().getEntryForId(name), id);
} catch (NullPointerException ex) {
- throw new JsonException(HttpServletResponse.SC_NOT_FOUND, Bundle.getMessage(locale, "ErrorNotFound", JsonRoster.ROSTER_ENTRY, name), id);
+ throw new JsonException(HttpServletResponse.SC_NOT_FOUND, Bundle.getMessage(locale, JsonException.ERROR_NOT_FOUND, JsonRoster.ROSTER_ENTRY, name), id);
}
}
@@ -161,7 +161,7 @@ public JsonNode getRosterEntry(Locale locale, String name, int id) throws JsonEx
public JsonNode getRosterEntry(Locale locale, @Nonnull RosterEntry entry, int id) throws JsonException {
String entryPath;
try {
- entryPath = "/" + JsonRoster.ROSTER + "/" + URLEncoder.encode(entry.getId(), StandardCharsets.UTF_8.toString()) + "/";
+ entryPath = String.format("/%s/%s/", JsonRoster.ROSTER, URLEncoder.encode(entry.getId(), StandardCharsets.UTF_8.toString()));
} catch (UnsupportedEncodingException ex) {
throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, "ErrorUnencodeable", JsonRoster.ROSTER_ENTRY, entry.getId(), NAME), id);
}
@@ -203,16 +203,14 @@ public JsonNode getRosterEntry(Locale locale, @Nonnull RosterEntry entry, int id
labels.add(label);
}
ArrayNode attributes = data.putArray(JsonRoster.ATTRIBUTES);
- entry.getAttributes().stream().forEach((name) -> {
+ entry.getAttributes().stream().forEach(name -> {
ObjectNode attribute = mapper.createObjectNode();
attribute.put(NAME, name);
attribute.put(VALUE, entry.getAttribute(name));
attributes.add(attribute);
});
ArrayNode rga = data.putArray(JsonRoster.ROSTER_GROUPS);
- entry.getGroups().stream().forEach((group) -> {
- rga.add(group.getName());
- });
+ entry.getGroups().stream().forEach(group -> rga.add(group.getName()));
return message(JsonRoster.ROSTER_ENTRY, data, id);
}
@@ -233,7 +231,7 @@ public JsonNode getRosterGroup(Locale locale, String name, int id) throws JsonEx
data.put(LENGTH, size);
return message(JsonRoster.ROSTER_GROUP, data, id);
} else {
- throw new JsonException(HttpServletResponse.SC_NOT_FOUND, Bundle.getMessage(locale, "ErrorNotFound", JsonRoster.ROSTER_GROUP, name), id);
+ throw new JsonException(HttpServletResponse.SC_NOT_FOUND, Bundle.getMessage(locale, JsonException.ERROR_NOT_FOUND, JsonRoster.ROSTER_GROUP, name), id);
}
}
@@ -255,7 +253,7 @@ public JsonNode doSchema(String type, boolean server, Locale locale, int id) thr
"jmri/server/json/roster/rosterGroup-client.json",
id);
default:
- throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, "ErrorUnknownType", type), id);
+ throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
}
@@ -275,12 +273,12 @@ public JsonNode postRosterEntry(Locale locale, String name, JsonNode data, int i
try {
entry = Roster.getDefault().getEntryForId(name);
} catch (NullPointerException ex) {
- throw new JsonException(HttpServletResponse.SC_NOT_FOUND, Bundle.getMessage(locale, "ErrorNotFound", JsonRoster.ROSTER_ENTRY, name), id);
+ throw new JsonException(HttpServletResponse.SC_NOT_FOUND, Bundle.getMessage(locale, JsonException.ERROR_NOT_FOUND, JsonRoster.ROSTER_ENTRY, name), id);
}
if (data.path(JsonRoster.ATTRIBUTES).isArray()) {
List toKeep = new ArrayList<>();
List toRemove = new ArrayList<>();
- data.path(JsonRoster.ATTRIBUTES).forEach((attribute) -> {
+ data.path(JsonRoster.ATTRIBUTES).forEach(attribute -> {
String key = attribute.path(NAME).asText();
String value = attribute.path(VALUE).isNull() ? null : attribute.path(VALUE).asText();
toKeep.add(key);
@@ -288,18 +286,14 @@ public JsonNode postRosterEntry(Locale locale, String name, JsonNode data, int i
});
entry.getAttributes()
.stream()
- .filter((key) -> (!toKeep.contains(key) && !key.startsWith(Roster.ROSTER_GROUP_PREFIX)))
- .forEachOrdered((key) -> {
- toRemove.add(key);
- });
- toRemove.forEach((key) -> {
- entry.deleteAttribute(key);
- });
+ .filter(key -> (!toKeep.contains(key) && !key.startsWith(Roster.ROSTER_GROUP_PREFIX)))
+ .forEachOrdered(toRemove::add);
+ toRemove.forEach(entry::deleteAttribute);
}
if (data.path(JsonRoster.ROSTER_GROUPS).isArray()) {
List toKeep = new ArrayList<>();
List toRemove = new ArrayList<>();
- data.path(JsonRoster.ROSTER_GROUPS).forEach((attribute) -> {
+ data.path(JsonRoster.ROSTER_GROUPS).forEach(attribute -> {
String key = attribute.asText();
String value = attribute.path(VALUE).isNull() ? null : attribute.path(VALUE).asText();
toKeep.add(key);
@@ -307,16 +301,12 @@ public JsonNode postRosterEntry(Locale locale, String name, JsonNode data, int i
});
entry.getGroups()
.stream()
- .filter((key) -> (!toKeep.contains(Roster.ROSTER_GROUP_PREFIX + key)))
- .forEachOrdered((key) -> {
- toRemove.add(Roster.ROSTER_GROUP_PREFIX + key);
- });
- toRemove.forEach((key) -> {
- entry.deleteAttribute(key);
- });
+ .filter(key -> (!toKeep.contains(Roster.ROSTER_GROUP_PREFIX + key)))
+ .forEachOrdered(key -> toRemove.add(Roster.ROSTER_GROUP_PREFIX + key));
+ toRemove.forEach(entry::deleteAttribute);
}
if (data.path(FUNCTION_KEYS).isArray()) {
- data.path(FUNCTION_KEYS).forEach((functionKey) -> {
+ data.path(FUNCTION_KEYS).forEach(functionKey -> {
int function = Integer.parseInt(functionKey.path(NAME).asText().substring(F.length() - 1));
entry.setFunctionLabel(function, functionKey.path(LABEL).isNull() ? null : functionKey.path(LABEL).asText());
entry.setFunctionLockable(function, functionKey.path(LOCKABLE).asBoolean());
diff --git a/java/src/jmri/server/json/roster/JsonRosterSocketService.java b/java/src/jmri/server/json/roster/JsonRosterSocketService.java
index 2f105cb31a4..822a4a1de04 100644
--- a/java/src/jmri/server/json/roster/JsonRosterSocketService.java
+++ b/java/src/jmri/server/json/roster/JsonRosterSocketService.java
@@ -34,7 +34,7 @@
*/
public class JsonRosterSocketService extends JsonSocketService {
- private final static Logger log = LoggerFactory.getLogger(JsonRosterSocketService.class);
+ private static final Logger log = LoggerFactory.getLogger(JsonRosterSocketService.class);
private final JsonRosterListener rosterListener = new JsonRosterListener();
private final JsonRosterEntryListener rosterEntryListener = new JsonRosterEntryListener();
private final JsonRosterGroupsListener rosterGroupsListener = new JsonRosterGroupsListener();
@@ -48,7 +48,7 @@ public void listen() {
if (!this.listening) {
Roster.getDefault().addPropertyChangeListener(this.rosterListener);
Roster.getDefault().addPropertyChangeListener(this.rosterGroupsListener);
- Roster.getDefault().getEntriesInGroup(Roster.ALLENTRIES).stream().forEach((re) -> {
+ Roster.getDefault().getEntriesInGroup(Roster.ALLENTRIES).stream().forEach(re -> {
re.addPropertyChangeListener(this.rosterEntryListener);
re.addPropertyChangeListener(this.rosterGroupsListener);
});
@@ -57,47 +57,55 @@ public void listen() {
}
@Override
- public void onMessage(String type, JsonNode data, String method, Locale locale, int id) throws IOException, JmriException, JsonException {
+ public void onMessage(String type, JsonNode data, String method, Locale locale, int id)
+ throws IOException, JmriException, JsonException {
switch (method) {
case DELETE:
- throw new JsonException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, Bundle.getMessage("DeleteNotAllowed", type), id);
+ throw new JsonException(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
+ Bundle.getMessage("DeleteNotAllowed", type), id);
case POST:
- switch (type) {
- case JsonRoster.ROSTER_ENTRY:
- this.connection.sendMessage(this.service.postRosterEntry(locale, data.path(NAME).asText(), data, id), id);
- break;
- default:
- throw new JsonException(HttpServletResponse.SC_NOT_IMPLEMENTED, Bundle.getMessage("MethodNotImplemented", method, type), id);
+ if (JsonRoster.ROSTER_ENTRY.equals(type)) {
+ this.connection
+ .sendMessage(this.service.postRosterEntry(locale, data.path(NAME).asText(), data, id), id);
+ } else {
+ throw new JsonException(HttpServletResponse.SC_NOT_IMPLEMENTED,
+ Bundle.getMessage("MethodNotImplemented", method, type), id);
}
break;
case PUT:
- throw new JsonException(HttpServletResponse.SC_NOT_IMPLEMENTED, Bundle.getMessage("MethodNotImplemented", method, type), id);
+ throw new JsonException(HttpServletResponse.SC_NOT_IMPLEMENTED,
+ Bundle.getMessage("MethodNotImplemented", method, type), id);
case GET:
switch (type) {
case JsonRoster.ROSTER:
this.connection.sendMessage(this.service.getRoster(locale, data, id), id);
break;
case JsonRoster.ROSTER_ENTRY:
- this.connection.sendMessage(this.service.getRosterEntry(locale, data.path(NAME).asText(), id), id);
+ this.connection.sendMessage(this.service.getRosterEntry(locale, data.path(NAME).asText(), id),
+ id);
break;
case JsonRoster.ROSTER_GROUP:
- this.connection.sendMessage(this.service.getRosterGroup(locale, data.path(NAME).asText(), id), id);
+ this.connection.sendMessage(this.service.getRosterGroup(locale, data.path(NAME).asText(), id),
+ id);
break;
case JsonRoster.ROSTER_GROUPS:
this.connection.sendMessage(this.service.getRosterGroups(locale, id), id);
break;
default:
- throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage("ErrorUnknownType", type), id);
+ throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
+ Bundle.getMessage(JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
break;
default:
- throw new JsonException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, Bundle.getMessage("UnknownMethod", method), id);
+ throw new JsonException(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
+ Bundle.getMessage("UnknownMethod", method), id);
}
this.listen();
}
@Override
- public void onList(String type, JsonNode data, Locale locale, int id) throws IOException, JmriException, JsonException {
+ public void onList(String type, JsonNode data, Locale locale, int id)
+ throws IOException, JmriException, JsonException {
this.connection.sendMessage(service.doGetList(type, data, locale, id), id);
this.listen();
}
@@ -107,7 +115,7 @@ public void onClose() {
Roster.getDefault().removePropertyChangeListener(this.rosterListener);
Roster.getDefault().removePropertyChangeListener(this.rosterGroupsListener);
- Roster.getDefault().getEntriesInGroup(Roster.ALLENTRIES).stream().forEach((re) -> {
+ Roster.getDefault().getEntriesInGroup(Roster.ALLENTRIES).stream().forEach(re -> {
re.removePropertyChangeListener(this.rosterEntryListener);
re.removePropertyChangeListener(this.rosterGroupsListener);
});
@@ -121,18 +129,25 @@ public void propertyChange(PropertyChangeEvent evt) {
try {
try {
if (evt.getPropertyName().equals(RosterEntry.ID)) {
- // send old roster entry and new roster entry to client as roster changes
+ // send old roster entry and new roster entry to client
+ // as roster changes
ObjectNode data = connection.getObjectMapper().createObjectNode();
RosterEntry old = new RosterEntry((RosterEntry) evt.getSource(), (String) evt.getOldValue());
data.set(ADD, service.getRosterEntry(connection.getLocale(), (RosterEntry) evt.getSource(), 0));
data.set(REMOVE, service.getRosterEntry(connection.getLocale(), old, 0));
- log.debug("Sending add and remove rosterEntry for {} ({} => {})", evt.getPropertyName(), evt.getOldValue(), evt.getNewValue());
+ log.debug("Sending add and remove rosterEntry for {} ({} => {})", evt.getPropertyName(),
+ evt.getOldValue(), evt.getNewValue());
connection.sendMessage(service.message(JsonRoster.ROSTER, data, 0), 0);
- } else if (!evt.getPropertyName().equals(RosterEntry.DATE_UPDATED)
- && !evt.getPropertyName().equals(RosterEntry.FILENAME)
- && !evt.getPropertyName().equals(RosterEntry.COMMENT)) { //don't send comment changes
- log.debug("Sending updated rosterEntry for {} ({} => {})", evt.getPropertyName(), evt.getOldValue(), evt.getNewValue());
- connection.sendMessage(service.getRosterEntry(connection.getLocale(), (RosterEntry) evt.getSource(), 0), 0);
+ } else if (!evt.getPropertyName().equals(RosterEntry.DATE_UPDATED) &&
+ !evt.getPropertyName().equals(RosterEntry.FILENAME) &&
+ !evt.getPropertyName().equals(RosterEntry.COMMENT)) { // don't
+ // send
+ // comment
+ // changes
+ log.debug("Sending updated rosterEntry for {} ({} => {})", evt.getPropertyName(),
+ evt.getOldValue(), evt.getNewValue());
+ connection.sendMessage(
+ service.getRosterEntry(connection.getLocale(), (RosterEntry) evt.getSource(), 0), 0);
}
} catch (JsonException ex) {
connection.sendMessage(ex.getJsonMessage(), 0);
@@ -151,17 +166,20 @@ public void propertyChange(PropertyChangeEvent evt) {
try {
try {
if (evt.getPropertyName().equals(Roster.ADD)) {
- data.set(ADD, service.getRosterEntry(connection.getLocale(), (RosterEntry) evt.getNewValue(), 0));
+ data.set(ADD,
+ service.getRosterEntry(connection.getLocale(), (RosterEntry) evt.getNewValue(), 0));
((PropertyChangeProvider) evt.getNewValue()).addPropertyChangeListener(rosterEntryListener);
connection.sendMessage(service.message(JsonRoster.ROSTER, data, 0), 0);
} else if (evt.getPropertyName().equals(Roster.REMOVE)) {
- data.set(REMOVE, service.getRosterEntry(connection.getLocale(), (RosterEntry) evt.getOldValue(), 0));
+ data.set(REMOVE,
+ service.getRosterEntry(connection.getLocale(), (RosterEntry) evt.getOldValue(), 0));
connection.sendMessage(service.message(JsonRoster.ROSTER, data, 0), 0);
- } else if (!evt.getPropertyName().equals(Roster.SAVED)
- && !evt.getPropertyName().equals(Roster.ROSTER_GROUP_ADDED)
- && !evt.getPropertyName().equals(Roster.ROSTER_GROUP_REMOVED)
- && !evt.getPropertyName().equals(Roster.ROSTER_GROUP_RENAMED)) {
- // catch all events other than SAVED and ROSTER_GROUP_* (handled elsewhere)
+ } else if (!evt.getPropertyName().equals(Roster.SAVED) &&
+ !evt.getPropertyName().equals(Roster.ROSTER_GROUP_ADDED) &&
+ !evt.getPropertyName().equals(Roster.ROSTER_GROUP_REMOVED) &&
+ !evt.getPropertyName().equals(Roster.ROSTER_GROUP_RENAMED)) {
+ // catch all events other than SAVED and ROSTER_GROUP_*
+ // (handled elsewhere)
connection.sendMessage(service.getRoster(connection.getLocale(), NullNode.getInstance(), 0), 0);
}
} catch (JsonException ex) {
@@ -178,16 +196,17 @@ private class JsonRosterGroupsListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
try {
- //handle direct roster change events
- if (evt.getPropertyName().equals(Roster.ROSTER_GROUP_ADDED)
- || evt.getPropertyName().equals(Roster.ROSTER_GROUP_REMOVED)
- || evt.getPropertyName().equals(Roster.ROSTER_GROUP_RENAMED)) {
+ // handle direct roster change events
+ if (evt.getPropertyName().equals(Roster.ROSTER_GROUP_ADDED) ||
+ evt.getPropertyName().equals(Roster.ROSTER_GROUP_REMOVED) ||
+ evt.getPropertyName().equals(Roster.ROSTER_GROUP_RENAMED)) {
try {
connection.sendMessage(service.getRosterGroups(connection.getLocale(), 0), 0);
} catch (JsonException ex) {
connection.sendMessage(ex.getJsonMessage(), 0);
}
- //handle event names of format "attributeUpdated:RosterGroup:GROUPNAME"
+ // handle event names of format
+ // "attributeUpdated:RosterGroup:GROUPNAME"
} else if (evt.getPropertyName().startsWith(RosterEntry.ATTRIBUTE_UPDATED)) {
String attrName = evt.getPropertyName().substring(RosterEntry.ATTRIBUTE_UPDATED.length());
if (attrName.startsWith(Roster.ROSTER_GROUP_PREFIX)) {
@@ -202,18 +221,18 @@ public void propertyChange(PropertyChangeEvent evt) {
}
}
}
- //handle attribute deleted, old value is of form "RosterGroup:GROUPNAME"
- } else if (evt.getPropertyName().startsWith(RosterEntry.ATTRIBUTE_DELETED)) {
- if (((String) evt.getOldValue()).startsWith(Roster.ROSTER_GROUP_PREFIX)) {
- String groupName = ((String) evt.getOldValue()).substring(Roster.ROSTER_GROUP_PREFIX.length());
- if (Roster.getDefault().getRosterGroups().containsKey(groupName)) {
- try {
- log.debug("sending changed rosterGroup {} and updated group array", groupName);
- connection.sendMessage(service.getRosterGroup(connection.getLocale(), groupName, 0), 0);
- connection.sendMessage(service.getRosterGroups(connection.getLocale(), 0), 0);
- } catch (JsonException ex) {
- connection.sendMessage(ex.getJsonMessage(), 0);
- }
+ // handle attribute deleted, old value is of form
+ // "RosterGroup:GROUPNAME"
+ } else if (evt.getPropertyName().startsWith(RosterEntry.ATTRIBUTE_DELETED) &&
+ ((String) evt.getOldValue()).startsWith(Roster.ROSTER_GROUP_PREFIX)) {
+ String groupName = ((String) evt.getOldValue()).substring(Roster.ROSTER_GROUP_PREFIX.length());
+ if (Roster.getDefault().getRosterGroups().containsKey(groupName)) {
+ try {
+ log.debug("sending changed rosterGroup {} and updated group array", groupName);
+ connection.sendMessage(service.getRosterGroup(connection.getLocale(), groupName, 0), 0);
+ connection.sendMessage(service.getRosterGroups(connection.getLocale(), 0), 0);
+ } catch (JsonException ex) {
+ connection.sendMessage(ex.getJsonMessage(), 0);
}
}
}
diff --git a/java/src/jmri/server/json/route/JsonRouteHttpService.java b/java/src/jmri/server/json/route/JsonRouteHttpService.java
index ce6f3603737..543101cd412 100644
--- a/java/src/jmri/server/json/route/JsonRouteHttpService.java
+++ b/java/src/jmri/server/json/route/JsonRouteHttpService.java
@@ -111,7 +111,7 @@ public JsonNode doSchema(String type, boolean server, Locale locale, int id) thr
"jmri/server/json/route/route-client.json",
id);
default:
- throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, "ErrorUnknownType", type), id);
+ throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
}
@@ -121,7 +121,7 @@ protected String getType() {
}
@Override
- protected ProvidingManager getManager() throws UnsupportedOperationException {
+ protected ProvidingManager getManager() {
return InstanceManager.getDefault(RouteManager.class);
}
}
diff --git a/java/src/jmri/server/json/schema/JsonSchemaHttpService.java b/java/src/jmri/server/json/schema/JsonSchemaHttpService.java
index 91f8e844dbb..34d5c447efa 100644
--- a/java/src/jmri/server/json/schema/JsonSchemaHttpService.java
+++ b/java/src/jmri/server/json/schema/JsonSchemaHttpService.java
@@ -28,7 +28,8 @@ public class JsonSchemaHttpService extends JsonHttpService {
public JsonNode doGet(String type, String name, JsonNode data, Locale locale, int id) throws JsonException {
// note use of Boolean for tristate null, true, false
// if server == null, returns both schemas in an array
- // if server != null, returns single schema for client or server as appropriate
+ // if server != null, returns single schema for client or server as
+ // appropriate
Boolean server = null;
if (data.path(JSON.SERVER).isBoolean()) {
server = data.path(JSON.SERVER).asBoolean();
@@ -36,77 +37,83 @@ public JsonNode doGet(String type, String name, JsonNode data, Locale locale, in
if (data.path(JSON.CLIENT).isBoolean()) {
if (server == null) {
server = !data.path(JSON.CLIENT).asBoolean();
- } else if (server == true) {
+ } else if (server) {
server = null; // server and client are true
}
}
switch (type) {
case JSON.SCHEMA:
- switch (name) {
- case JSON.JSON:
- if (server != null) {
- return this.doSchema(JSON.JSON, server, locale, id);
- }
- return message(mapper.createArrayNode()
- .add(this.doSchema(JSON.JSON, true, locale, id))
- .add(this.doSchema(JSON.JSON, false, locale, id)),
- id);
- default:
- try {
- ArrayNode schemas = this.mapper.createArrayNode();
- Set dedup = new HashSet<>();
- for (JsonHttpService service : InstanceManager.getDefault(JsonSchemaServiceCache.class)
- .getServices(name)) {
- // separate try/catch blocks to ensure one failure does not
- // block following from being accepted
- if (server == null || server) {
- try {
- JsonNode schema = service.doSchema(name, true, locale, id);
- if (!dedup.contains(schema)) {
- schemas.add(schema);
- dedup.add(schema);
- }
- } catch (JsonException ex) {
- if (ex.getCode() != HttpServletResponse.SC_BAD_REQUEST) {
- throw ex;
- }
+ if (JSON.JSON.equals(name)) {
+ if (server != null) {
+ return this.doSchema(JSON.JSON, server, locale, id);
+ }
+ return message(mapper.createArrayNode()
+ .add(this.doSchema(JSON.JSON, true, locale, id))
+ .add(this.doSchema(JSON.JSON, false, locale, id)),
+ id);
+ } else {
+ try {
+ ArrayNode schemas = this.mapper.createArrayNode();
+ Set dedup = new HashSet<>();
+ for (JsonHttpService service : InstanceManager.getDefault(JsonSchemaServiceCache.class)
+ .getServices(name)) {
+ // separate try/catch blocks to ensure one failure
+ // does not
+ // block following from being accepted
+ if (server == null || server) {
+ try {
+ JsonNode schema = service.doSchema(name, true, locale, id);
+ if (!dedup.contains(schema)) {
+ schemas.add(schema);
+ dedup.add(schema);
}
- }
- if (server == null || !server) {
- try {
- JsonNode schema = service.doSchema(name, false, locale, id);
- if (!dedup.contains(schema)) {
- schemas.add(schema);
- dedup.add(schema);
- }
- } catch (JsonException ex) {
- if (ex.getCode() != HttpServletResponse.SC_BAD_REQUEST) {
- throw ex;
- }
+ } catch (JsonException ex) {
+ if (ex.getCode() != HttpServletResponse.SC_BAD_REQUEST) {
+ throw ex;
}
}
}
- // return single object if only one, otherwise return complete array
- if (schemas.size() == 1) {
- return schemas.get(0);
+ if (server == null || !server) {
+ try {
+ JsonNode schema = service.doSchema(name, false, locale, id);
+ if (!dedup.contains(schema)) {
+ schemas.add(schema);
+ dedup.add(schema);
+ }
+ } catch (JsonException ex) {
+ if (ex.getCode() != HttpServletResponse.SC_BAD_REQUEST) {
+ throw ex;
+ }
+ }
}
- return message(schemas, id);
- } catch (NullPointerException ex) {
- throw new JsonException(HttpServletResponse.SC_BAD_REQUEST, Bundle.getMessage(locale, "ErrorUnknownType", name), ex, id);
}
+ // return single object if only one, otherwise return
+ // complete array
+ if (schemas.size() == 1) {
+ return schemas.get(0);
+ }
+ return message(schemas, id);
+ } catch (NullPointerException ex) {
+ throw new JsonException(HttpServletResponse.SC_BAD_REQUEST,
+ Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, name), ex, id);
+ }
}
case JSON.TYPE:
if (InstanceManager.getDefault(JsonSchemaServiceCache.class).getTypes().contains(name)) {
ObjectNode payload = this.mapper.createObjectNode();
payload.put(JSON.NAME, name);
- payload.put(JSON.SERVER, InstanceManager.getDefault(JsonSchemaServiceCache.class).getServerTypes().contains(name));
- payload.put(JSON.CLIENT, InstanceManager.getDefault(JsonSchemaServiceCache.class).getClientTypes().contains(name));
+ payload.put(JSON.SERVER,
+ InstanceManager.getDefault(JsonSchemaServiceCache.class).getServerTypes().contains(name));
+ payload.put(JSON.CLIENT,
+ InstanceManager.getDefault(JsonSchemaServiceCache.class).getClientTypes().contains(name));
return message(JSON.TYPE, payload, id);
} else {
- throw new JsonException(HttpServletResponse.SC_NOT_FOUND, Bundle.getMessage(locale, "ErrorNotFound", type, name), id);
+ throw new JsonException(HttpServletResponse.SC_NOT_FOUND,
+ Bundle.getMessage(locale, JsonException.ERROR_NOT_FOUND, type, name), id);
}
default:
- throw new JsonException(HttpServletResponse.SC_BAD_REQUEST, Bundle.getMessage(locale, "ErrorUnknownType", type), id);
+ throw new JsonException(HttpServletResponse.SC_BAD_REQUEST,
+ Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
}
@@ -118,16 +125,16 @@ public JsonNode doPost(String type, String name, JsonNode data, Locale locale, i
@Override
public JsonNode doGetList(String type, JsonNode parameters, Locale locale, int id) throws JsonException {
- switch (type) {
- case JSON.TYPE:
- ArrayNode array = this.mapper.createArrayNode();
- JsonNode data = this.mapper.createObjectNode();
- for (String name : InstanceManager.getDefault(JsonSchemaServiceCache.class).getTypes()) {
- array.add(this.doGet(type, name, data, locale, id));
- }
- return message(array, id);
- default:
- throw new JsonException(HttpServletResponse.SC_BAD_REQUEST, Bundle.getMessage(locale, "UnlistableService", type), id);
+ if (JSON.TYPE.equals(type)) {
+ ArrayNode array = this.mapper.createArrayNode();
+ JsonNode data = this.mapper.createObjectNode();
+ for (String name : InstanceManager.getDefault(JsonSchemaServiceCache.class).getTypes()) {
+ array.add(this.doGet(type, name, data, locale, id));
+ }
+ return message(array, id);
+ } else {
+ throw new JsonException(HttpServletResponse.SC_BAD_REQUEST,
+ Bundle.getMessage(locale, "UnlistableService", type), id);
}
}
@@ -143,7 +150,8 @@ public JsonNode doSchema(String type, boolean server, Locale locale, int id) thr
"jmri/server/json/schema/" + type + "-client.json",
id);
default:
- throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, "ErrorUnknownType", type), id);
+ throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
+ Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
}
}
diff --git a/java/src/jmri/server/json/schema/JsonSchemaServiceCache.java b/java/src/jmri/server/json/schema/JsonSchemaServiceCache.java
index 1832a1b8c48..a52b20f24cb 100644
--- a/java/src/jmri/server/json/schema/JsonSchemaServiceCache.java
+++ b/java/src/jmri/server/json/schema/JsonSchemaServiceCache.java
@@ -216,11 +216,10 @@ private void validateJsonNode(@Nonnull JsonNode node, @Nonnull String type, bool
}
if (errors != null && !errors.isEmpty()) {
log.warn("Errors validating {}", node);
- errors.forEach((error) -> {
+ errors.forEach(error ->
log.warn("JSON Validation Error: {}\n\t{}\n\t{}\n\t{}", error.getCode(), error.getMessage(),
- error.getPath(), error.getType());
- });
- throw new JsonException(server ? 500 : 400, Bundle.getMessage(locale, "LoggedError"), id);
+ error.getPath(), error.getType()));
+ throw new JsonException(server ? 500 : 400, Bundle.getMessage(locale, JsonException.LOGGED_ERROR), id);
}
}
@@ -230,30 +229,18 @@ private void cacheServices() {
for (JsonServiceFactory, ?> factory : ServiceLoader.load(JsonServiceFactory.class)) {
JsonHttpService service = factory.getHttpService(this.mapper);
for (String type : factory.getTypes()) {
- Set set = this.services.get(type);
- if (set == null) {
- this.services.put(type, new HashSet<>());
- set = this.services.get(type);
- }
+ Set set = services.computeIfAbsent(type, v -> new HashSet<>());
this.clientTypes.add(type);
this.serverTypes.add(type);
set.add(service);
}
for (String type : factory.getSentTypes()) {
- Set set = this.services.get(type);
- if (set == null) {
- this.services.put(type, new HashSet<>());
- set = this.services.get(type);
- }
+ Set set = services.computeIfAbsent(type, v -> new HashSet<>());
this.serverTypes.add(type);
set.add(service);
}
for (String type : factory.getReceivedTypes()) {
- Set set = this.services.get(type);
- if (set == null) {
- this.services.put(type, new HashSet<>());
- set = this.services.get(type);
- }
+ Set set = services.computeIfAbsent(type, v -> new HashSet<>());
this.clientTypes.add(type);
set.add(service);
}
diff --git a/java/src/jmri/server/json/sensor/JsonSensorHttpService.java b/java/src/jmri/server/json/sensor/JsonSensorHttpService.java
index 4679649ae96..0d5bcbeb779 100644
--- a/java/src/jmri/server/json/sensor/JsonSensorHttpService.java
+++ b/java/src/jmri/server/json/sensor/JsonSensorHttpService.java
@@ -98,7 +98,7 @@ public JsonNode doSchema(String type, boolean server, Locale locale, int id) thr
id);
default:
throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
- Bundle.getMessage(locale, "ErrorUnknownType", type), id);
+ Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
}
@@ -108,7 +108,7 @@ protected String getType() {
}
@Override
- protected ProvidingManager getManager() throws UnsupportedOperationException {
+ protected ProvidingManager getManager() {
return InstanceManager.getDefault(SensorManager.class);
}
}
diff --git a/java/src/jmri/server/json/signalHead/JsonSignalHeadHttpService.java b/java/src/jmri/server/json/signalHead/JsonSignalHeadHttpService.java
index 98bf1213fcb..a4271cee192 100644
--- a/java/src/jmri/server/json/signalHead/JsonSignalHeadHttpService.java
+++ b/java/src/jmri/server/json/signalHead/JsonSignalHeadHttpService.java
@@ -105,7 +105,7 @@ public JsonNode doSchema(String type, boolean server, Locale locale, int id) thr
"jmri/server/json/signalHead/signalHead-client.json",
id);
default:
- throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, "ErrorUnknownType", type), id);
+ throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
}
}
diff --git a/java/src/jmri/server/json/signalMast/JsonSignalMastHttpService.java b/java/src/jmri/server/json/signalMast/JsonSignalMastHttpService.java
index 742801b0f6d..51e0a441d78 100644
--- a/java/src/jmri/server/json/signalMast/JsonSignalMastHttpService.java
+++ b/java/src/jmri/server/json/signalMast/JsonSignalMastHttpService.java
@@ -87,7 +87,7 @@ public JsonNode doSchema(String type, boolean server, Locale locale, int id) thr
"jmri/server/json/signalMast/signalMast-client.json",
id);
default:
- throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, "ErrorUnknownType", type), id);
+ throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
}
@@ -97,7 +97,7 @@ protected String getType() {
}
@Override
- protected ProvidingManager getManager() throws UnsupportedOperationException {
+ protected ProvidingManager getManager() {
return InstanceManager.getDefault(SignalMastManager.class);
}
}
diff --git a/java/src/jmri/server/json/throttle/JsonThrottleHttpService.java b/java/src/jmri/server/json/throttle/JsonThrottleHttpService.java
index d982e6e561a..740144b2462 100644
--- a/java/src/jmri/server/json/throttle/JsonThrottleHttpService.java
+++ b/java/src/jmri/server/json/throttle/JsonThrottleHttpService.java
@@ -5,11 +5,11 @@
import com.fasterxml.jackson.databind.node.ArrayNode;
import java.util.Locale;
import javax.servlet.http.HttpServletResponse;
+
import jmri.server.json.JsonException;
import jmri.server.json.JsonHttpService;
/**
- *
* @author Randall Wood Copyright 2018
*/
public class JsonThrottleHttpService extends JsonHttpService {
@@ -20,30 +20,33 @@ public JsonThrottleHttpService(ObjectMapper mapper) {
@Override
public JsonNode doGet(String type, String name, JsonNode data, Locale locale, int id) throws JsonException {
- throw new JsonException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, Bundle.getMessage(locale, "GetNotAllowed", type), id);
+ throw new JsonException(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
+ Bundle.getMessage(locale, "GetNotAllowed", type), id);
}
@Override
public JsonNode doPost(String type, String name, JsonNode data, Locale locale, int id) throws JsonException {
- throw new JsonException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, Bundle.getMessage(locale, "PostNotAllowed", type), id);
+ throw new JsonException(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
+ Bundle.getMessage(locale, "PostNotAllowed", type), id);
}
@Override
public ArrayNode doGetList(String type, JsonNode data, Locale locale, int id) throws JsonException {
- throw new JsonException(HttpServletResponse.SC_BAD_REQUEST, Bundle.getMessage(locale, "UnlistableService", type), id);
+ throw new JsonException(HttpServletResponse.SC_BAD_REQUEST,
+ Bundle.getMessage(locale, "UnlistableService", type), id);
}
@Override
public JsonNode doSchema(String type, boolean server, Locale locale, int id) throws JsonException {
- switch (type) {
- case JsonThrottle.THROTTLE:
- return doSchema(type,
- server,
- "jmri/server/json/throttle/throttle-server.json",
- "jmri/server/json/throttle/throttle-client.json",
- id);
- default:
- throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, "ErrorUnknownType", type), id);
+ if (JsonThrottle.THROTTLE.equals(type)) {
+ return doSchema(type,
+ server,
+ "jmri/server/json/throttle/throttle-server.json",
+ "jmri/server/json/throttle/throttle-client.json",
+ id);
+ } else {
+ throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
+ Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
}
diff --git a/java/src/jmri/server/json/time/JsonTimeHttpService.java b/java/src/jmri/server/json/time/JsonTimeHttpService.java
index 0543ea7b532..3f727e57883 100644
--- a/java/src/jmri/server/json/time/JsonTimeHttpService.java
+++ b/java/src/jmri/server/json/time/JsonTimeHttpService.java
@@ -15,6 +15,7 @@
import java.util.Date;
import java.util.Locale;
import javax.annotation.CheckForNull;
+import javax.annotation.Nonnull;
import javax.servlet.http.HttpServletResponse;
import jmri.InstanceManager;
import jmri.Timebase;
@@ -23,7 +24,6 @@
import jmri.server.json.JsonHttpService;
/**
- *
* @author Randall Wood
*/
public class JsonTimeHttpService extends JsonHttpService {
@@ -34,12 +34,13 @@ public JsonTimeHttpService(ObjectMapper mapper) {
@Override
// using @CheckForNull to override @Nonnull in super class
- public JsonNode doGet(String type, @CheckForNull String name, JsonNode data, Locale locale, int id) throws JsonException {
+ public JsonNode doGet(String type, @CheckForNull String name, JsonNode data, Locale locale, int id)
+ throws JsonException {
Timebase timebase = InstanceManager.getDefault(Timebase.class);
- return doGet(type, timebase, timebase.getTime(), locale, id);
+ return doGet(timebase, timebase.getTime(), id);
}
- public JsonNode doGet(String type, Timebase timebase, Date date, Locale locale, int id) throws JsonException {
+ public JsonNode doGet(@Nonnull Timebase timebase, @Nonnull Date date, int id) {
ObjectNode data = this.mapper.createObjectNode();
data.put(TIME, new StdDateFormat().format(date));
data.put(RATE, timebase.getRate());
@@ -49,7 +50,8 @@ public JsonNode doGet(String type, Timebase timebase, Date date, Locale locale,
@Override
// using @CheckForNull to override @Nonnull in super class
- public JsonNode doPost(String type, @CheckForNull String name, JsonNode data, Locale locale, int id) throws JsonException {
+ public JsonNode doPost(String type, @CheckForNull String name, JsonNode data, Locale locale, int id)
+ throws JsonException {
Timebase timebase = InstanceManager.getDefault(Timebase.class);
try {
if (data.path(TIME).isTextual()) {
@@ -59,7 +61,8 @@ public JsonNode doPost(String type, @CheckForNull String name, JsonNode data, Lo
timebase.userSetRate(data.path(RATE).asDouble());
}
int state = data.findPath(STATE).asInt(0);
- if (state == ON || state == OFF) { // passing the state UNKNOWN (0) will not trigger change
+ // passing the state UNKNOWN (0) will not trigger change
+ if (state == ON || state == OFF) {
timebase.setRun(state == ON);
}
} catch (ParseException ex) {
@@ -79,15 +82,15 @@ public JsonNode doGetList(String type, JsonNode data, Locale locale, int id) thr
@Override
public JsonNode doSchema(String type, boolean server, Locale locale, int id) throws JsonException {
- switch (type) {
- case TIME:
- return doSchema(type,
- server,
- "jmri/server/json/time/time-server.json",
- "jmri/server/json/time/time-client.json",
- id);
- default:
- throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, "ErrorUnknownType", type), id);
+ if (TIME.equals(type)) {
+ return doSchema(type,
+ server,
+ "jmri/server/json/time/time-server.json",
+ "jmri/server/json/time/time-client.json",
+ id);
+ } else {
+ throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
+ Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
}
}
diff --git a/java/src/jmri/server/json/time/JsonTimeSocketService.java b/java/src/jmri/server/json/time/JsonTimeSocketService.java
index 6a140fe00de..368029a50b0 100644
--- a/java/src/jmri/server/json/time/JsonTimeSocketService.java
+++ b/java/src/jmri/server/json/time/JsonTimeSocketService.java
@@ -1,7 +1,5 @@
package jmri.server.json.time;
-import static jmri.server.json.JSON.TIME;
-
import com.fasterxml.jackson.databind.JsonNode;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
@@ -59,16 +57,12 @@ public void onClose() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
try {
- try {
- Timebase manager = InstanceManager.getDefault(Timebase.class);
- Date time = manager.getTime();
- if (evt.getPropertyName().equals("time")) {
- time = (Date) evt.getNewValue();
- }
- this.connection.sendMessage(this.service.doGet(TIME, manager, time, this.connection.getLocale(), 0), 0);
- } catch (JsonException ex) {
- this.connection.sendMessage(ex.getJsonMessage(), 0);
+ Timebase manager = InstanceManager.getDefault(Timebase.class);
+ Date time = manager.getTime();
+ if (evt.getPropertyName().equals("time")) {
+ time = (Date) evt.getNewValue();
}
+ this.connection.sendMessage(this.service.doGet(manager, time, 0), 0);
} catch (IOException ex) {
this.onClose();
}
diff --git a/java/src/jmri/server/json/turnout/JsonTurnoutHttpService.java b/java/src/jmri/server/json/turnout/JsonTurnoutHttpService.java
index 3d47ea0fff1..c4e4d57cdcf 100644
--- a/java/src/jmri/server/json/turnout/JsonTurnoutHttpService.java
+++ b/java/src/jmri/server/json/turnout/JsonTurnoutHttpService.java
@@ -90,7 +90,7 @@ public JsonNode doSchema(String type, boolean server, Locale locale, int id) thr
"jmri/server/json/turnout/turnout-client.json",
id);
default:
- throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, "ErrorUnknownType", type), id);
+ throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
}
@@ -100,7 +100,7 @@ protected String getType() {
}
@Override
- protected ProvidingManager getManager() throws UnsupportedOperationException {
+ protected ProvidingManager getManager() {
return InstanceManager.getDefault(TurnoutManager.class);
}
}
diff --git a/java/src/jmri/server/json/util/JsonUtilHttpService.java b/java/src/jmri/server/json/util/JsonUtilHttpService.java
index f6803e892da..25390bbc79f 100644
--- a/java/src/jmri/server/json/util/JsonUtilHttpService.java
+++ b/java/src/jmri/server/json/util/JsonUtilHttpService.java
@@ -21,6 +21,8 @@
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Locale;
+import java.util.Objects;
+
import javax.annotation.CheckForNull;
import javax.servlet.http.HttpServletResponse;
import jmri.DccLocoAddress;
@@ -48,21 +50,24 @@
import jmri.web.server.WebServerPreferences;
/**
- *
* @author Randall Wood Copyright 2016, 2017, 2018
*/
public class JsonUtilHttpService extends JsonHttpService {
+ private static final String RESOURCE_PATH = "jmri/server/json/util/";
+
public JsonUtilHttpService(ObjectMapper mapper) {
super(mapper);
}
@Override
// use @CheckForNull to override @Nonnull specified in superclass
- public JsonNode doGet(String type, @CheckForNull String name, JsonNode data, Locale locale, int id) throws JsonException {
+ public JsonNode doGet(String type, @CheckForNull String name, JsonNode data, Locale locale, int id)
+ throws JsonException {
switch (type) {
case JSON.HELLO:
- return this.getHello(locale, InstanceManager.getDefault(JsonServerPreferences.class).getHeartbeatInterval(), id);
+ return this.getHello(locale,
+ InstanceManager.getDefault(JsonServerPreferences.class).getHeartbeatInterval(), id);
case JSON.METADATA:
if (name == null) {
return this.getMetadata(locale, id);
@@ -77,7 +82,7 @@ public JsonNode doGet(String type, @CheckForNull String name, JsonNode data, Loc
case JSON.NODE:
return this.getNode(locale, id);
case JSON.PANELS:
- return this.getPanels(locale, id);
+ return this.getPanels(id);
case JSON.RAILROAD:
return this.getRailroad(locale, id);
case JSON.SYSTEM_CONNECTIONS:
@@ -85,7 +90,8 @@ public JsonNode doGet(String type, @CheckForNull String name, JsonNode data, Loc
case JSON.CONFIG_PROFILES:
return this.getConfigProfiles(locale, id);
default:
- throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, "ErrorUnknownType", type), id);
+ throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
+ Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
}
@@ -156,7 +162,7 @@ public JsonNode getMetadata(Locale locale, String name, int id) throws JsonExcep
data.put(JSON.NAME, name);
data.put(JSON.VALUE, Metadata.getBySystemName(name));
} else {
- throw new JsonException(404, Bundle.getMessage(locale, "ErrorObject", JSON.METADATA, name), id);
+ throw new JsonException(404, Bundle.getMessage(locale, JsonException.ERROR_OBJECT, JSON.METADATA, name), id);
}
return message(JSON.METADATA, data, id);
}
@@ -196,7 +202,7 @@ public JsonNode getNetworkService(Locale locale, String name, int id) throws Jso
return this.getNetworkService(service, id);
}
}
- throw new JsonException(404, Bundle.getMessage(locale, "ErrorObject", JSON.NETWORK_SERVICE, name), id);
+ throw new JsonException(404, Bundle.getMessage(locale, JsonException.ERROR_OBJECT, JSON.NETWORK_SERVICE, name), id);
}
private JsonNode getNetworkService(ZeroConfService service, int id) {
@@ -213,16 +219,14 @@ private JsonNode getNetworkService(ZeroConfService service, int id) {
}
/**
- *
* @param locale the client's Locale.
* @param id message id set by client
* @return the JSON networkServices message.
*/
public ArrayNode getNetworkServices(Locale locale, int id) {
ArrayNode root = mapper.createArrayNode();
- InstanceManager.getDefault(ZeroConfServiceManager.class).allServices().stream().forEach((service) -> {
- root.add(this.getNetworkService(service, id));
- });
+ InstanceManager.getDefault(ZeroConfServiceManager.class).allServices().stream()
+ .forEach(service -> root.add(this.getNetworkService(service, id)));
return root;
}
@@ -239,19 +243,19 @@ public JsonNode getNode(Locale locale, int id) {
ObjectNode data = mapper.createObjectNode();
data.put(JSON.NODE, NodeIdentity.networkIdentity());
ArrayNode nodes = mapper.createArrayNode();
- NodeIdentity.formerIdentities().stream().forEach((node) -> {
- nodes.add(node);
- });
+ NodeIdentity.formerIdentities().stream().forEach(nodes::add);
data.set(JSON.FORMER_NODES, nodes);
return message(JSON.NODE, data, id);
}
- public ObjectNode getPanel(Locale locale, Editor editor, String format, int id) {
+ public ObjectNode getPanel(Editor editor, String format, int id) {
if (editor.getAllowInFrameServlet()) {
Container container = editor.getTargetPanel().getTopLevelAncestor();
if (container instanceof JmriJFrame) {
String title = ((Frame) container).getTitle();
- if (!title.isEmpty() && !Arrays.asList(InstanceManager.getDefault(WebServerPreferences.class).getDisallowedFrames()).contains(title)) {
+ if (!title.isEmpty() &&
+ !Arrays.asList(InstanceManager.getDefault(WebServerPreferences.class).getDisallowedFrames())
+ .contains(title)) {
String type = PANEL_PANEL;
String name = "Panel";
if (editor instanceof ControlPanelEditor) {
@@ -276,32 +280,27 @@ public ObjectNode getPanel(Locale locale, Editor editor, String format, int id)
return null;
}
- public JsonNode getPanels(Locale locale, String format, int id) {
+ public JsonNode getPanels(String format, int id) {
ArrayNode root = mapper.createArrayNode();
- // list loaded Panels (ControlPanelEditor, PanelEditor, LayoutEditor, SwitchboardEditor)
+ // list loaded Panels (ControlPanelEditor, PanelEditor, LayoutEditor,
+ // SwitchboardEditor)
// list ControlPanelEditors
Editor.getEditors(ControlPanelEditor.class).stream()
- .map((editor) -> this.getPanel(locale, editor, format, id))
- .filter((panel) -> (panel != null)).forEach((panel) -> {
- root.add(panel);
- });
+ .map(editor -> this.getPanel(editor, format, id))
+ .filter(Objects::nonNull).forEach(root::add);
// list LayoutEditors and PanelEditors
Editor.getEditors(PanelEditor.class).stream()
- .map((editor) -> this.getPanel(locale, editor, format, id))
- .filter((panel) -> (panel != null)).forEach((panel) -> {
- root.add(panel);
- });
+ .map(editor -> this.getPanel(editor, format, id))
+ .filter(Objects::nonNull).forEach(root::add);
// list SwitchboardEditors
Editor.getEditors(SwitchboardEditor.class).stream()
- .map((editor) -> this.getPanel(locale, editor, format, id))
- .filter((panel) -> (panel != null)).forEach((panel) -> {
- root.add(panel);
- });
+ .map(editor -> this.getPanel(editor, format, id))
+ .filter(Objects::nonNull).forEach(root::add);
return root;
}
- public JsonNode getPanels(Locale locale, int id) {
- return this.getPanels(locale, JSON.XML, id);
+ public JsonNode getPanels(int id) {
+ return this.getPanels(JSON.XML, id);
}
/**
@@ -319,7 +318,6 @@ public JsonNode getRailroad(Locale locale, int id) {
}
/**
- *
* @param locale the client's Locale.
* @param id message id set by client
* @return the JSON systemConnections message.
@@ -333,24 +331,29 @@ public ArrayNode getSystemConnections(Locale locale, int id) {
data.put(JSON.NAME, config.getConnectionName());
data.put(JSON.MFG, config.getManufacturer());
data.put(JSON.PREFIX, config.getAdapter().getSystemConnectionMemo().getSystemPrefix());
- data.put(JSON.DESCRIPTION, Bundle.getMessage(locale, "ConnectionSucceeded", config.getConnectionName(), config.name(), config.getInfo()));
+ data.put(JSON.DESCRIPTION, Bundle.getMessage(locale, "ConnectionSucceeded", config.getConnectionName(),
+ config.name(), config.getInfo()));
prefixes.add(config.getAdapter().getSystemConnectionMemo().getSystemPrefix());
root.add(message(JSON.SYSTEM_CONNECTION, data, id));
}
}
- InstanceManager.getList(SystemConnectionMemo.class).stream().map((instance) -> instance)
- .filter((memo) -> (!memo.getDisabled() && !prefixes.contains(memo.getSystemPrefix()))).forEach((memo) -> {
- ObjectNode data = mapper.createObjectNode();
- data.put(JSON.NAME, memo.getUserName());
- data.put(JSON.PREFIX, memo.getSystemPrefix());
- data.putNull(JSON.MFG);
- data.putNull(JSON.DESCRIPTION);
- prefixes.add(memo.getSystemPrefix());
- root.add(message(JSON.SYSTEM_CONNECTION, data, id));
- });
- // Following is required because despite there being a SystemConnectionMemo
- // for the default internal connection, it is not used for the default internal
- // connection. This allows a client to map the server's internal objects.
+ InstanceManager.getList(SystemConnectionMemo.class).stream().map(instance -> instance)
+ .filter(memo -> (!memo.getDisabled() && !prefixes.contains(memo.getSystemPrefix())))
+ .forEach(memo -> {
+ ObjectNode data = mapper.createObjectNode();
+ data.put(JSON.NAME, memo.getUserName());
+ data.put(JSON.PREFIX, memo.getSystemPrefix());
+ data.putNull(JSON.MFG);
+ data.putNull(JSON.DESCRIPTION);
+ prefixes.add(memo.getSystemPrefix());
+ root.add(message(JSON.SYSTEM_CONNECTION, data, id));
+ });
+ // Following is required because despite there being a
+ // SystemConnectionMemo
+ // for the default internal connection, it is not used for the default
+ // internal
+ // connection. This allows a client to map the server's internal
+ // objects.
SystemConnectionMemo internal = InstanceManager.getDefault(InternalSystemConnectionMemo.class);
if (!prefixes.contains(internal.getSystemPrefix())) {
ObjectNode data = mapper.createObjectNode();
@@ -364,24 +367,26 @@ public ArrayNode getSystemConnections(Locale locale, int id) {
}
/**
- *
* @param locale the client's Locale.
* @param id message id set by client
* @return the JSON configProfiles message.
*/
public ArrayNode getConfigProfiles(Locale locale, int id) {
ArrayNode root = mapper.createArrayNode();
-
- for (Profile p : ProfileManager.getDefault().getProfiles()) {
- boolean isActiveProfile = (p == ProfileManager.getDefault().getActiveProfile());
- boolean isAutoStart = (isActiveProfile && ProfileManager.getDefault().isAutoStartActiveProfile()); // only true for activeprofile
- ObjectNode data = mapper.createObjectNode();
- data.put(JSON.USERNAME, p.getName());
- data.put(JSON.UNIQUE_ID, p.getUniqueId());
- data.put(JSON.NAME, p.getId());
- data.put(JSON.IS_ACTIVE_PROFILE, isActiveProfile);
- data.put(JSON.IS_AUTO_START, isAutoStart);
- root.add(message(JSON.CONFIG_PROFILE, data, id));
+ ProfileManager pm = ProfileManager.getDefault();
+ for (Profile p : pm.getProfiles()) {
+ if (p != null) {
+ boolean isActiveProfile = (p == pm.getActiveProfile());
+ // isAutoStart is only possibly true for active profile
+ boolean isAutoStart = (isActiveProfile && pm.isAutoStartActiveProfile());
+ ObjectNode data = mapper.createObjectNode();
+ data.put(JSON.USERNAME, p.getName());
+ data.put(JSON.UNIQUE_ID, p.getUniqueId());
+ data.put(JSON.NAME, p.getId());
+ data.put(JSON.IS_ACTIVE_PROFILE, isActiveProfile);
+ data.put(JSON.IS_AUTO_START, isAutoStart);
+ root.add(message(JSON.CONFIG_PROFILE, data, id));
+ }
}
return root;
}
@@ -396,11 +401,11 @@ public ArrayNode getConfigProfiles(Locale locale, int id) {
* @param address the address
* @return The DccLocoAddress for address
*/
- static public DccLocoAddress addressForString(String address) {
+ public static DccLocoAddress addressForString(String address) {
String[] components = address.split("[()]");
int number = Integer.parseInt(components[0]);
boolean isLong = false;
- if (components.length > 1 && "L".equals(components[1].toUpperCase())) {
+ if (components.length > 1 && "L".equalsIgnoreCase(components[1])) {
isLong = true;
}
return new DccLocoAddress(number, isLong);
@@ -443,17 +448,23 @@ public JsonNode doSchema(String type, boolean server, Locale locale, int id) thr
case JSON.PONG:
if (server) {
return doSchema(type, server,
- this.mapper.readTree(this.getClass().getClassLoader().getResource("jmri/server/json/util/" + type + "-server.json")), id);
+ this.mapper.readTree(this.getClass().getClassLoader()
+ .getResource(RESOURCE_PATH + type + "-server.json")),
+ id);
} else {
- throw new JsonException(HttpServletResponse.SC_BAD_REQUEST, Bundle.getMessage(locale, "NotAClientType", type), id);
+ throw new JsonException(HttpServletResponse.SC_BAD_REQUEST,
+ Bundle.getMessage(locale, "NotAClientType", type), id);
}
case JSON.LOCALE:
case JSON.PING:
if (!server) {
return doSchema(type, server,
- this.mapper.readTree(this.getClass().getClassLoader().getResource("jmri/server/json/util/" + type + "-client.json")), id);
+ this.mapper.readTree(this.getClass().getClassLoader()
+ .getResource(RESOURCE_PATH + type + "-client.json")),
+ id);
} else {
- throw new JsonException(HttpServletResponse.SC_BAD_REQUEST, Bundle.getMessage(locale, "NotAServerType", type), id);
+ throw new JsonException(HttpServletResponse.SC_BAD_REQUEST,
+ Bundle.getMessage(locale, "NotAServerType", type), id);
}
case JSON.GOODBYE:
case JSON.HELLO:
@@ -462,11 +473,12 @@ public JsonNode doSchema(String type, boolean server, Locale locale, int id) thr
case JSON.RAILROAD:
return doSchema(type,
server,
- "jmri/server/json/util/" + type + "-server.json",
- "jmri/server/json/util/" + type + "-client.json",
+ RESOURCE_PATH + type + "-server.json",
+ RESOURCE_PATH + type + "-client.json",
id);
default:
- throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Bundle.getMessage(locale, "ErrorUnknownType", type), id);
+ throw new JsonException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
+ Bundle.getMessage(locale, JsonException.ERROR_UNKNOWN_TYPE, type), id);
}
} catch (IOException ex) {
throw new JsonException(500, ex, id);
diff --git a/java/src/jmri/server/web/DefaultWebServerConfiguration.java b/java/src/jmri/server/web/DefaultWebServerConfiguration.java
index c6dd6ebd5e4..ce1ebe35e83 100644
--- a/java/src/jmri/server/web/DefaultWebServerConfiguration.java
+++ b/java/src/jmri/server/web/DefaultWebServerConfiguration.java
@@ -22,26 +22,20 @@ public final class DefaultWebServerConfiguration extends AbstractWebServerConfig
private final HashMap redirections = new HashMap<>();
private final HashMap files = new HashMap<>();
- private final static Logger log = LoggerFactory.getLogger(DefaultWebServerConfiguration.class);
+ private static final Logger log = LoggerFactory.getLogger(DefaultWebServerConfiguration.class);
public DefaultWebServerConfiguration() {
- try (InputStream in = this.getClass().getResourceAsStream("FilePaths.properties")) { // NOI18N
+ try (InputStream in = getClass().getResourceAsStream("FilePaths.properties")) { // NOI18N
Properties properties = new Properties();
properties.load(in);
- in.close();
- properties.stringPropertyNames().forEach((path) -> {
- this.files.put(path, properties.getProperty(path));
- });
+ properties.stringPropertyNames().forEach(path -> files.put(path, properties.getProperty(path)));
} catch (IOException ex) {
log.error(ex.getMessage());
}
- try (InputStream in = this.getClass().getResourceAsStream("Redirections.properties")) { // NOI18N
+ try (InputStream in = getClass().getResourceAsStream("Redirections.properties")) { // NOI18N
Properties properties = new Properties();
properties.load(in);
- in.close();
- properties.stringPropertyNames().forEach((path) -> {
- this.redirections.put(path, properties.getProperty(path));
- });
+ properties.stringPropertyNames().forEach(path -> redirections.put(path, properties.getProperty(path)));
} catch (IOException ex) {
log.error(ex.getMessage());
}
diff --git a/java/src/jmri/server/web/spi/AngularRoute.java b/java/src/jmri/server/web/spi/AngularRoute.java
index 4f38f72d049..e1614bed51d 100644
--- a/java/src/jmri/server/web/spi/AngularRoute.java
+++ b/java/src/jmri/server/web/spi/AngularRoute.java
@@ -3,7 +3,6 @@
import java.util.Objects;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
-import javax.annotation.CheckForNull;
/**
*
@@ -37,8 +36,8 @@ public AngularRoute(@Nonnull String when, @CheckForNull String template, @CheckF
if ((template == null && controller != null) || (template != null && controller == null)) {
throw new IllegalArgumentException("template and controller must both be non-null or null");
}
- if ((redirection != null && (template != null || controller != null))
- || (redirection == null && (template == null || controller == null))) {
+ if ((redirection != null && template != null)
+ || (redirection == null && template == null)) {
throw new IllegalArgumentException("redirection must be null if template or controller is non-null");
}
this.when = when;
diff --git a/java/src/jmri/web/servlet/frameimage/JmriJFrameServlet.java b/java/src/jmri/web/servlet/frameimage/JmriJFrameServlet.java
index c4dddfde2f6..0fb27f00990 100644
--- a/java/src/jmri/web/servlet/frameimage/JmriJFrameServlet.java
+++ b/java/src/jmri/web/servlet/frameimage/JmriJFrameServlet.java
@@ -360,7 +360,7 @@ private void doList(HttpServletRequest request, HttpServletResponse response) th
JsonUtilHttpService service = new JsonUtilHttpService(new ObjectMapper());
for (JmriJFrame frame : JmriJFrame.getFrameList()) {
if (usePanels && frame instanceof Editor) {
- ObjectNode node = service.getPanel(request.getLocale(), (Editor) frame, JSON.XML, 0);
+ ObjectNode node = service.getPanel((Editor) frame, JSON.XML, 0);
if (node != null) {
root.add(node);
frames.add(((Editor) frame).getTargetFrame());
diff --git a/java/src/jmri/web/servlet/panel/AbstractPanelServlet.java b/java/src/jmri/web/servlet/panel/AbstractPanelServlet.java
index 3b987b327ed..879e1de2a31 100644
--- a/java/src/jmri/web/servlet/panel/AbstractPanelServlet.java
+++ b/java/src/jmri/web/servlet/panel/AbstractPanelServlet.java
@@ -155,7 +155,7 @@ protected void listPanels(HttpServletRequest request, HttpServletResponse respon
response.setContentType(UTF8_APPLICATION_JSON);
InstanceManager.getDefault(ServletUtil.class).setNonCachingHeaders(response);
JsonUtilHttpService service = new JsonUtilHttpService(new ObjectMapper());
- response.getWriter().print(service.getPanels(request.getLocale(), JSON.XML, 0));
+ response.getWriter().print(service.getPanels(JSON.XML, 0));
} else {
response.setContentType(UTF8_TEXT_HTML);
response.getWriter().print(String.format(request.getLocale(),
diff --git a/java/test/jmri/server/json/time/JsonTimeSocketServiceTest.java b/java/test/jmri/server/json/time/JsonTimeSocketServiceTest.java
index b87c784ffbe..6ed67b5f149 100644
--- a/java/test/jmri/server/json/time/JsonTimeSocketServiceTest.java
+++ b/java/test/jmri/server/json/time/JsonTimeSocketServiceTest.java
@@ -14,7 +14,6 @@
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.util.StdDateFormat;
@@ -152,23 +151,15 @@ public void testOnList() {
@Test
public void testListenerErrorHandling() throws IOException, JmriException, JsonException {
JsonMockConnection connection = new JsonMockConnection((DataOutputStream) null);
- TestJsonTimeHttpService http = new TestJsonTimeHttpService(connection.getObjectMapper());
+ JsonTimeHttpService http = new JsonTimeHttpService(connection.getObjectMapper());
JsonTimeSocketService service = new JsonTimeSocketService(connection, http);
Timebase manager = InstanceManager.getDefault(Timebase.class);
manager.setRun(false); // stop for testing
// GET method
service.onMessage(JSON.TIME, connection.getObjectMapper().createObjectNode(), JSON.GET,
locale, 42);
- // Thrown JsonException on next message
- http.setThrowException(true);
// We should be listening so make a change
manager.setRate(60); // one minute per second
- JsonNode message = connection.getMessage();
- Assert.assertNotNull("Message is not null", message);
- Assert.assertEquals("Message is error", JsonException.ERROR, message.path(JSON.TYPE).asText());
- Assert.assertEquals("Error code is HTTP 499", 499, message.path(JSON.DATA).path(JsonException.CODE).asInt());
- Assert.assertEquals("Error message is mocked", "Mock Exception",
- message.path(JSON.DATA).path(JsonException.MESSAGE).asText());
// Thrown IOException on next message
connection.setThrowIOException(true);
manager.setRate(10);
@@ -185,29 +176,6 @@ public void setUp() {
public void tearDown() {
JUnitUtil.tearDown();
}
-
- private static class TestJsonTimeHttpService extends JsonTimeHttpService {
-
- private boolean throwException = false;
-
- public TestJsonTimeHttpService(ObjectMapper mapper) {
- super(mapper);
- }
-
- @Override
- public JsonNode doGet(String type, Timebase timebase, Date time, Locale locale, int id) throws JsonException {
- if (throwException) {
- throwException = false;
- throw new JsonException(499, "Mock Exception", id);
- }
- return super.doGet(type, timebase, time, locale, id);
- }
-
- public void setThrowException(boolean throwException) {
- this.throwException = throwException;
- }
-
- }
private static class TimebaseTimeListener implements PropertyChangeListener {
diff --git a/java/test/jmri/server/json/util/JsonUtilHttpServiceTest.java b/java/test/jmri/server/json/util/JsonUtilHttpServiceTest.java
index 42bf957be53..e629992b1c3 100644
--- a/java/test/jmri/server/json/util/JsonUtilHttpServiceTest.java
+++ b/java/test/jmri/server/json/util/JsonUtilHttpServiceTest.java
@@ -342,7 +342,7 @@ public void testGetRailroad() throws JsonException {
public void testGetPanel() throws JsonException {
Assume.assumeFalse("Needs GUI", GraphicsEnvironment.isHeadless());
Editor editor = new SwitchboardEditor("test");
- ObjectNode result = service.getPanel(locale, editor, JSON.XML, 42);
+ ObjectNode result = service.getPanel(editor, JSON.XML, 42);
validate(result);
JUnitUtil.dispose(editor.getTargetFrame());
JUnitUtil.dispose(editor);
@@ -357,7 +357,7 @@ public void testGetPanel() throws JsonException {
public void testGetPanels_Locale_String() throws JsonException {
Assume.assumeFalse("Needs GUI", GraphicsEnvironment.isHeadless());
Editor editor = new SwitchboardEditor("test");
- JsonNode result = service.getPanels(locale, JSON.XML, 42);
+ JsonNode result = service.getPanels(JSON.XML, 42);
validate(result);
JUnitUtil.dispose(editor.getTargetFrame());
JUnitUtil.dispose(editor);
@@ -372,7 +372,7 @@ public void testGetPanels_Locale_String() throws JsonException {
public void testGetPanels_Locale() throws JsonException {
Assume.assumeFalse("Needs GUI", GraphicsEnvironment.isHeadless());
Editor editor = new SwitchboardEditor("test");
- JsonNode result = service.getPanels(locale, 42);
+ JsonNode result = service.getPanels(42);
validate(result);
JUnitUtil.dispose(editor.getTargetFrame());
JUnitUtil.dispose(editor);