Search in sources :

Example 1 with JsonHttpService

use of jmri.server.json.JsonHttpService in project JMRI by JMRI.

the class JsonServlet method doGet.

/**
     * Handle HTTP get requests for JSON data. Examples:
     * <ul>
     * <li>/json/sensor/IS22 (return data for sensor with system name
     * "IS22")</li>
     * <li>/json/sensors (returns a list of all sensors known to JMRI)</li>
     * </ul>
     * sample responses:
     * <ul>
     * <li>{"type":"sensor","data":{"name":"IS22","userName":"FarEast","comment":null,"inverted":false,"state":4}}</li>
     * <li>[{"type":"sensor","data":{"name":"IS22","userName":"FarEast","comment":null,"inverted":false,"state":4}}]</li>
     * </ul>
     * Note that data will vary for each type.
     *
     * @param request  an HttpServletRequest object that contains the request
     *                 the client has made of the servlet
     * @param response an HttpServletResponse object that contains the response
     *                 the servlet sends to the client
     * @throws java.io.IOException if an input or output error is detected when
     *                             the servlet handles the GET request
     */
@Override
protected void doGet(final HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setStatus(HttpServletResponse.SC_OK);
    // NOI18N
    response.setHeader("Connection", "Keep-Alive");
    if (request.getAttribute("result") != null) {
        JsonNode result = (JsonNode) request.getAttribute("result");
        // use HTTP error codes when possible
        int code = result.path(DATA).path(CODE).asInt(HttpServletResponse.SC_OK);
        if (code == HttpServletResponse.SC_OK) {
            response.getWriter().write(this.mapper.writeValueAsString(result));
        } else {
            this.sendError(response, code, this.mapper.writeValueAsString(result));
        }
        return;
    }
    // NOI18N
    String[] rest = request.getPathInfo().split("/");
    String type = (rest.length > 1) ? rest[1] : null;
    if (type != null) {
        response.setContentType(UTF8_APPLICATION_JSON);
        ServletUtil.getInstance().setNonCachingHeaders(response);
        final String name = (rest.length > 2) ? URLDecoder.decode(rest[2], StandardCharsets.UTF_8.name()) : null;
        ObjectNode parameters = this.mapper.createObjectNode();
        for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
            parameters.put(entry.getKey(), URLDecoder.decode(entry.getValue()[0], "UTF-8"));
        }
        JsonNode reply = null;
        try {
            if (name == null) {
                if (this.services.get(type) != null) {
                    ArrayNode array = this.mapper.createArrayNode();
                    JsonException exception = null;
                    try {
                        for (JsonHttpService service : this.services.get(type)) {
                            array.addAll(service.doGetList(type, 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 {
                if (this.services.get(type) != null) {
                    ArrayNode array = this.mapper.createArrayNode();
                    JsonException exception = null;
                    try {
                        for (JsonHttpService service : this.services.get(type)) {
                            array.add(service.doGet(type, name, 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("Requested type '{}' unknown.", type);
                    throw new JsonException(HttpServletResponse.SC_NOT_FOUND, Bundle.getMessage(request.getLocale(), "ErrorUnknownType", type));
                }
            }
        } 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));
        }
    } else {
        // NOI18N
        response.setContentType(ServletUtil.UTF8_TEXT_HTML);
        response.getWriter().print(String.format(request.getLocale(), FileUtil.readURL(FileUtil.findURL(Bundle.getMessage(request.getLocale(), "Json.html"))), String.format(request.getLocale(), Bundle.getMessage(request.getLocale(), "HtmlTitle"), ServletUtil.getInstance().getRailroadName(false), Bundle.getMessage(request.getLocale(), "JsonTitle")), ServletUtil.getInstance().getNavBar(request.getLocale(), request.getContextPath()), ServletUtil.getInstance().getRailroadName(false), ServletUtil.getInstance().getFooter(request.getLocale(), request.getContextPath())));
    }
}
Also used : JsonException(jmri.server.json.JsonException) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) JsonNode(com.fasterxml.jackson.databind.JsonNode) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) JsonHttpService(jmri.server.json.JsonHttpService) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with JsonHttpService

use of jmri.server.json.JsonHttpService in project JMRI by JMRI.

the class JsonServlet method doDelete.

@Override
protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, 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 reply = mapper.createObjectNode();
    try {
        if (type != null) {
            if (name == null) {
                // need to I18N
                throw new JsonException(HttpServletResponse.SC_BAD_REQUEST, "name must be specified");
            }
            for (JsonHttpService service : this.services.get(type)) {
                service.doDelete(type, name, request.getLocale());
            }
        } 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);
    // only include a response body if something went wrong
    if (code != HttpServletResponse.SC_OK) {
        this.sendError(response, code, this.mapper.writeValueAsString(reply));
    }
}
Also used : JsonException(jmri.server.json.JsonException) JsonNode(com.fasterxml.jackson.databind.JsonNode) JsonHttpService(jmri.server.json.JsonHttpService)

Example 3 with JsonHttpService

use of jmri.server.json.JsonHttpService in project JMRI by JMRI.

the class JsonThrottleServiceFactoryTest method testGetHttpService.

/**
     * Test of getHttpService method, of class JsonThrottleServiceFactory.
     */
@Test
public void testGetHttpService() {
    JsonThrottleServiceFactory instance = new JsonThrottleServiceFactory();
    JsonHttpService result = instance.getHttpService(new ObjectMapper());
    Assert.assertNull(result);
}
Also used : JsonHttpService(jmri.server.json.JsonHttpService) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test)

Example 4 with JsonHttpService

use of jmri.server.json.JsonHttpService in project JMRI by JMRI.

the class JsonServlet method init.

@Override
public void init() throws ServletException {
    super.init();
    this.mapper = new ObjectMapper();
    for (JsonServiceFactory factory : ServiceLoader.load(JsonServiceFactory.class)) {
        JsonHttpService service = factory.getHttpService(this.mapper);
        if (service != null) {
            for (String type : factory.getTypes()) {
                HashSet<JsonHttpService> set = this.services.get(type);
                if (set == null) {
                    this.services.put(type, new HashSet<>());
                    set = this.services.get(type);
                }
                set.add(factory.getHttpService(this.mapper));
            }
        }
    }
}
Also used : JsonHttpService(jmri.server.json.JsonHttpService) JsonServiceFactory(jmri.spi.JsonServiceFactory) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 5 with JsonHttpService

use of jmri.server.json.JsonHttpService in project JMRI by JMRI.

the class JsonServlet method doPut.

@Override
protected void doPut(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 {
            // need to I18N
            throw new JsonException(HttpServletResponse.SC_BAD_REQUEST, "PUT request must be a JSON object");
        }
        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();
            }
            if (name != null) {
                if (this.services.get(type) != null) {
                    ArrayNode array = this.mapper.createArrayNode();
                    JsonException exception = null;
                    try {
                        for (JsonHttpService service : this.services.get(type)) {
                            array.add(service.doPut(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) {
                    // need to I18N
                    throw new JsonException(HttpServletResponse.SC_BAD_REQUEST, type + " is not a creatable type");
                }
            } else {
                log.warn("Type {} unknown.", type);
                throw new JsonException(HttpServletResponse.SC_NOT_FOUND, Bundle.getMessage(request.getLocale(), "ErrorUnknownType", type));
            }
        } 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));
    }
}
Also used : JsonException(jmri.server.json.JsonException) JsonNode(com.fasterxml.jackson.databind.JsonNode) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) JsonHttpService(jmri.server.json.JsonHttpService)

Aggregations

JsonHttpService (jmri.server.json.JsonHttpService)6 JsonNode (com.fasterxml.jackson.databind.JsonNode)4 JsonException (jmri.server.json.JsonException)4 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)2 HashMap (java.util.HashMap)1 Map (java.util.Map)1 JsonServiceFactory (jmri.spi.JsonServiceFactory)1 Test (org.junit.Test)1