use of jmri.server.json.JsonHttpService in project JMRI by JMRI.
the class JsonServlet method doPost.
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType(UTF8_APPLICATION_JSON);
// NOI18N
response.setHeader("Connection", "Keep-Alive");
ServletUtil.getInstance().setNonCachingHeaders(response);
// NOI18N
String[] rest = request.getPathInfo().split("/");
String type = (rest.length > 1) ? rest[1] : null;
String name = (rest.length > 2) ? rest[2] : null;
JsonNode data;
JsonNode reply = null;
try {
if (request.getContentType().contains(APPLICATION_JSON)) {
data = this.mapper.readTree(request.getReader());
if (!data.path(DATA).isMissingNode()) {
data = data.path(DATA);
}
} else {
data = this.mapper.createObjectNode();
if (request.getParameter(STATE) != null) {
((ObjectNode) data).put(STATE, Integer.parseInt(request.getParameter(STATE)));
} else if (request.getParameter(LOCATION) != null) {
((ObjectNode) data).put(LOCATION, request.getParameter(LOCATION));
} else if (request.getParameter(VALUE) != null) {
// values other than Strings should be sent in a JSON object
((ObjectNode) data).put(VALUE, request.getParameter(VALUE));
}
}
if (type != null) {
// for historical reasons, set the name to POWER on a power request
if (type.equals(POWER)) {
name = POWER;
} else if (name == null) {
name = data.path(NAME).asText();
}
log.debug("POST operation for {}/{} with {}", type, name, data);
if (name != null) {
if (this.services.get(type) != null) {
log.debug("Using data: {}", data);
ArrayNode array = this.mapper.createArrayNode();
JsonException exception = null;
try {
for (JsonHttpService service : this.services.get(type)) {
array.add(service.doPost(type, name, data, request.getLocale()));
}
} catch (JsonException ex) {
exception = ex;
}
switch(array.size()) {
case 0:
if (exception != null) {
throw exception;
}
reply = array;
break;
case 1:
reply = array.get(0);
break;
default:
reply = array;
break;
}
}
if (reply == null) {
log.warn("Type {} unknown.", type);
throw new JsonException(HttpServletResponse.SC_NOT_FOUND, Bundle.getMessage(request.getLocale(), "ErrorUnknownType", type));
}
} else {
log.error("Name must be defined.");
// Need to I18N
throw new JsonException(HttpServletResponse.SC_BAD_REQUEST, "Name must be defined.");
}
} else {
log.warn("Type not specified.");
// Need to I18N
throw new JsonException(HttpServletResponse.SC_BAD_REQUEST, "Type must be specified.");
}
} catch (JsonException ex) {
reply = ex.getJsonMessage();
}
// use HTTP error codes when possible
int code = reply.path(DATA).path(CODE).asInt(HttpServletResponse.SC_OK);
if (code == HttpServletResponse.SC_OK) {
response.getWriter().write(this.mapper.writeValueAsString(reply));
} else {
this.sendError(response, code, this.mapper.writeValueAsString(reply));
}
}
Aggregations