Search in sources :

Example 76 with ArrayNode

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.node.ArrayNode in project JMRI by JMRI.

the class JsonUtilHttpService method doGetList.

@Override
public ArrayNode doGetList(String type, Locale locale) throws JsonException {
    switch(type) {
        case JSON.METADATA:
            return this.getMetadata(locale);
        case JSON.NETWORK_SERVICES:
            return this.getNetworkServices(locale);
        case JSON.SYSTEM_CONNECTIONS:
            return this.getSystemConnections(locale);
        case JSON.CONFIG_PROFILES:
            return this.getConfigProfiles(locale);
        default:
            ArrayNode array = this.mapper.createArrayNode();
            JsonNode node = this.doGet(type, null, locale);
            if (node.isArray()) {
                array.addAll((ArrayNode) node);
            } else {
                array.add(node);
            }
            return array;
    }
}
Also used : JsonNode(com.fasterxml.jackson.databind.JsonNode) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode)

Example 77 with ArrayNode

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.node.ArrayNode 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 78 with ArrayNode

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.node.ArrayNode in project JMRI by JMRI.

the class HtmlManifest method getLocations.

// TODO cache the results so a quick check that if the JsonManifest file is not
// newer than the Html manifest, the cached copy is returned instead.
public String getLocations() throws IOException {
    // build manifest from JSON manifest
    if (this.getJsonManifest() == null) {
        return "Error manifest file not found for this train";
    }
    StringBuilder builder = new StringBuilder();
    ArrayNode locations = (ArrayNode) this.getJsonManifest().path(JsonOperations.LOCATIONS);
    String previousLocationName = null;
    boolean hasWork;
    for (JsonNode location : locations) {
        RouteLocation routeLocation = train.getRoute().getLocationById(location.path(JSON.ID).textValue());
        log.debug("Processing {} ({})", routeLocation.getName(), location.path(JSON.ID).textValue());
        String routeLocationName = location.path(JSON.NAME).textValue();
        // NOI18N
        builder.append(String.format(locale, strings.getProperty("LocationStart"), routeLocation.getId()));
        hasWork = (location.path(JsonOperations.CARS).path(JSON.ADD).size() > 0 || location.path(JsonOperations.CARS).path(JSON.REMOVE).size() > 0 || location.path(JSON.ENGINES).path(JSON.ADD).size() > 0 || location.path(JSON.ENGINES).path(JSON.REMOVE).size() > 0);
        if (hasWork && !routeLocationName.equals(previousLocationName)) {
            if (!train.isShowArrivalAndDepartureTimesEnabled()) {
                // NOI18N
                builder.append(String.format(locale, strings.getProperty("ScheduledWorkAt"), routeLocationName));
            } else if (routeLocation == train.getRoute().getDepartsRouteLocation()) {
                builder.append(String.format(locale, strings.getProperty("WorkDepartureTime"), routeLocationName, // NOI18N
                train.getFormatedDepartureTime()));
            } else if (!routeLocation.getDepartureTime().equals(RouteLocation.NONE)) {
                builder.append(String.format(locale, strings.getProperty("WorkDepartureTime"), routeLocationName, // NOI18N
                routeLocation.getFormatedDepartureTime()));
            } else if (Setup.isUseDepartureTimeEnabled() && routeLocation != train.getRoute().getTerminatesRouteLocation()) {
                builder.append(String.format(locale, strings.getProperty("WorkDepartureTime"), routeLocationName, // NOI18N
                train.getExpectedDepartureTime(routeLocation)));
            } else if (!train.getExpectedArrivalTime(routeLocation).equals(Train.ALREADY_SERVICED)) {
                // NOI18N
                builder.append(String.format(locale, strings.getProperty("WorkArrivalTime"), routeLocationName, // NOI18N
                train.getExpectedArrivalTime(routeLocation)));
            } else {
                // NOI18N
                builder.append(String.format(locale, strings.getProperty("ScheduledWorkAt"), routeLocationName));
            }
            // add route comment
            if (!location.path(JSON.COMMENT).textValue().trim().isEmpty()) {
                builder.append(String.format(locale, strings.getProperty("RouteLocationComment"), location.path(JSON.COMMENT).textValue()));
            }
            builder.append(getTrackComments(location.path(JsonOperations.TRACK), location.path(JsonOperations.CARS)));
            // add location comment
            if (Setup.isPrintLocationCommentsEnabled() && !location.path(JsonOperations.LOCATION).path(JSON.COMMENT).textValue().trim().isEmpty()) {
                builder.append(String.format(locale, strings.getProperty("LocationComment"), location.path(JsonOperations.LOCATION).path(JSON.COMMENT).textValue()));
            }
        }
        previousLocationName = routeLocationName;
        // engine change or helper service?
        if (location.path(JSON.OPTIONS).size() > 0) {
            Iterator<JsonNode> options = location.path(JSON.OPTIONS).elements();
            boolean changeEngines = false;
            boolean changeCaboose = false;
            while (options.hasNext()) {
                String option = options.next().textValue();
                if (option.equals(JSON.CHANGE_ENGINES)) {
                    changeEngines = true;
                } else if (option.equals(JSON.CHANGE_CABOOSE)) {
                    changeCaboose = true;
                } else if (option.equals(JSON.ADD_HELPERS)) {
                    builder.append(String.format(strings.getProperty("AddHelpersAt"), routeLocationName));
                } else if (option.equals(JSON.REMOVE_HELPERS)) {
                    builder.append(String.format(strings.getProperty("RemoveHelpersAt"), routeLocationName));
                }
            }
            if (changeEngines && changeCaboose) {
                // NOI18N
                builder.append(String.format(strings.getProperty("LocoAndCabooseChangeAt"), routeLocationName));
            } else if (changeEngines) {
                // NOI18N
                builder.append(String.format(strings.getProperty("LocoChangeAt"), routeLocationName));
            } else if (changeCaboose) {
                // NOI18N
                builder.append(String.format(strings.getProperty("CabooseChangeAt"), routeLocationName));
            }
        }
        builder.append(pickupEngines(location.path(JSON.ENGINES).path(JSON.ADD)));
        builder.append(blockCars(location.path(JsonOperations.CARS), routeLocation, true));
        builder.append(dropEngines(location.path(JSON.ENGINES).path(JSON.REMOVE)));
        if (routeLocation != train.getRoute().getTerminatesRouteLocation()) {
            // Is the next location the same as the current?
            RouteLocation rlNext = train.getRoute().getNextRouteLocation(routeLocation);
            if (!routeLocationName.equals(splitString(rlNext.getName()))) {
                if (hasWork) {
                    if (!Setup.isPrintLoadsAndEmptiesEnabled()) {
                        // Message format: Train departs Boston Westbound with 12 cars, 450 feet, 3000 tons
                        builder.append(String.format(strings.getProperty("TrainDepartsCars"), routeLocationName, strings.getProperty("Heading" + Setup.getDirectionString(location.path(JSON.DIRECTION).intValue())), location.path(JSON.LENGTH).path(JSON.LENGTH).intValue(), location.path(JSON.LENGTH).path(JSON.UNIT).asText().toLowerCase(), location.path(JsonOperations.WEIGHT).intValue(), location.path(JsonOperations.CARS).path(JSON.TOTAL).intValue()));
                    } else {
                        // Message format: Train departs Boston Westbound with 4 loads, 8 empties, 450 feet, 3000
                        // tons
                        builder.append(String.format(strings.getProperty("TrainDepartsLoads"), routeLocationName, strings.getProperty("Heading" + Setup.getDirectionString(location.path(JSON.DIRECTION).intValue())), location.path(JSON.LENGTH).path(JSON.LENGTH).intValue(), location.path(JSON.LENGTH).path(JSON.UNIT).asText().toLowerCase(), location.path(JsonOperations.WEIGHT).intValue(), location.path(JsonOperations.CARS).path(JSON.LOADS).intValue(), location.path(JsonOperations.CARS).path(JSON.EMPTIES).intValue()));
                    }
                } else {
                    log.debug("No work ({})", routeLocation.getComment());
                    if (routeLocation.getComment().trim().isEmpty()) {
                        // no route comment, no work at this location
                        if (train.isShowArrivalAndDepartureTimesEnabled()) {
                            if (routeLocation == train.getRoute().getDepartsRouteLocation()) {
                                builder.append(String.format(locale, strings.getProperty("NoScheduledWorkAtWithDepartureTime"), routeLocationName, train.getFormatedDepartureTime()));
                            } else if (!routeLocation.getDepartureTime().isEmpty()) {
                                builder.append(String.format(locale, strings.getProperty("NoScheduledWorkAtWithDepartureTime"), routeLocationName, routeLocation.getFormatedDepartureTime()));
                            } else if (Setup.isUseDepartureTimeEnabled()) {
                                builder.append(String.format(locale, strings.getProperty("NoScheduledWorkAtWithDepartureTime"), routeLocationName, location.path(JSON.EXPECTED_DEPARTURE)));
                            } else {
                                // fall back to generic no scheduled work message
                                builder.append(String.format(locale, strings.getProperty("NoScheduledWorkAt"), routeLocationName));
                            }
                        } else {
                            builder.append(String.format(locale, strings.getProperty("NoScheduledWorkAt"), routeLocationName));
                        }
                    } else {
                        // route comment, so only use location and route comment (for passenger trains)
                        if (train.isShowArrivalAndDepartureTimesEnabled()) {
                            if (routeLocation == train.getRoute().getDepartsRouteLocation()) {
                                builder.append(String.format(locale, strings.getProperty("CommentAtWithDepartureTime"), routeLocationName, train.getFormatedDepartureTime(), routeLocation.getComment()));
                            } else if (!routeLocation.getDepartureTime().isEmpty()) {
                                builder.append(String.format(locale, strings.getProperty("CommentAtWithDepartureTime"), routeLocationName, routeLocation.getFormatedDepartureTime(), routeLocation.getComment()));
                            }
                        } else {
                            builder.append(String.format(locale, strings.getProperty("CommentAt"), routeLocationName, null, routeLocation.getComment()));
                        }
                    }
                    // add location comment
                    if (Setup.isPrintLocationCommentsEnabled() && !routeLocation.getLocation().getComment().isEmpty()) {
                        builder.append(String.format(locale, strings.getProperty("LocationComment"), routeLocation.getLocation().getComment()));
                    }
                }
            }
        } else {
            builder.append(String.format(strings.getProperty("TrainTerminatesIn"), routeLocationName));
        }
    }
    return builder.toString();
}
Also used : JsonNode(com.fasterxml.jackson.databind.JsonNode) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) RouteLocation(jmri.jmrit.operations.routes.RouteLocation)

Example 79 with ArrayNode

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.node.ArrayNode in project indy by Commonjava.

the class IndyZabbixApi method getItem.

public String getItem(String host, String item, String hostid) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode groups = mapper.createArrayNode();
    ObjectNode search = mapper.createObjectNode();
    search.put("key_", item);
    Request getRequest = RequestBuilder.newBuilder().method("item.get").paramEntry("hostids", hostid).paramEntry("search", search).build();
    JsonNode response = call(getRequest);
    if (response.get("result").isNull() || response.get("result").get(0) == null) {
        return null;
    }
    return response.get("result").get(0).get("itemid").asText();
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) JsonNode(com.fasterxml.jackson.databind.JsonNode) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 80 with ArrayNode

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.node.ArrayNode in project indy by Commonjava.

the class IndyZabbixApi method getHost.

/**
     *
     * @param name
     * @return hostid
     */
public String getHost(String name) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode jsonNode = mapper.createObjectNode();
    ArrayNode arrayNode = mapper.createArrayNode();
    arrayNode.add(name);
    jsonNode.put("host", arrayNode);
    Request request = RequestBuilder.newBuilder().method("host.get").paramEntry("filter", jsonNode).build();
    JsonNode response = call(request);
    if (response.get("result").isNull() || response.get("result").get(0) == null) {
        return null;
    }
    return response.get("result").get(0).get("hostid").asText();
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) JsonNode(com.fasterxml.jackson.databind.JsonNode) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)979 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)542 JsonNode (com.fasterxml.jackson.databind.JsonNode)402 Test (org.junit.Test)140 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)125 ArrayList (java.util.ArrayList)110 IOException (java.io.IOException)93 Map (java.util.Map)74 HashMap (java.util.HashMap)68 List (java.util.List)50 TextNode (com.fasterxml.jackson.databind.node.TextNode)38 Test (org.testng.annotations.Test)35 DefaultSerializerProvider (com.fasterxml.jackson.databind.ser.DefaultSerializerProvider)30 HashSet (java.util.HashSet)30 JsonNodeFactory (com.fasterxml.jackson.databind.node.JsonNodeFactory)25 Deployment (org.activiti.engine.test.Deployment)23 File (java.io.File)22 InputStream (java.io.InputStream)20 Iterator (java.util.Iterator)20 StringEntity (org.apache.http.entity.StringEntity)20