Example usage for com.fasterxml.jackson.databind.node ArrayNode get

List of usage examples for com.fasterxml.jackson.databind.node ArrayNode get

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind.node ArrayNode get.

Prototype

public JsonNode get(String paramString) 

Source Link

Usage

From source file:org.modeshape.web.jcr.rest.handler.ItemHandlerImpl.java

protected List<JSONChild> getChildren(JsonNode jsonNode) {
    List<JSONChild> children;
    JsonNode childrenNode = jsonNode.get(CHILD_NODE_HOLDER);
    if (childrenNode instanceof ObjectNode) {
        ObjectNode childrenObject = (ObjectNode) childrenNode;
        children = new ArrayList<>(childrenObject.size());
        for (Iterator<?> iterator = childrenObject.fields(); iterator.hasNext();) {
            String childName = iterator.next().toString();
            //it is not possible to have SNS in the object form, so the index will always be 1
            children.add(new JSONChild(childName, childrenObject.get(childName), 1));
        }//from w  w w  . j  a v a  2 s .  c o m
        return children;
    } else {
        ArrayNode childrenArray = (ArrayNode) childrenNode;
        children = new ArrayList<>(childrenArray.size());
        Map<String, Integer> visitedNames = new HashMap<>(childrenArray.size());

        for (int i = 0; i < childrenArray.size(); i++) {
            JsonNode child = childrenArray.get(i);
            if (child.size() == 0) {
                continue;
            }
            if (child.size() > 1) {
                logger.warn(
                        "The child object {0} has more than 1 elements, only the first one will be taken into account",
                        child);
            }
            String childName = child.fields().next().toString();
            int sns = visitedNames.containsKey(childName) ? visitedNames.get(childName) + 1 : 1;
            visitedNames.put(childName, sns);

            children.add(new JSONChild(childName, child.get(childName), sns));
        }
        return children;
    }
}

From source file:org.wisdom.wamp.WampController.java

private void handlePublication(String id, Map.Entry<String, WampClient> entry, ArrayNode message) {
    if (entry == null) {
        LOGGER.error("Invalid PUBLISH message, cannot identify the client {}", id);
        return;//  ww w  .  jav a  2s . c o  m
    }
    // The message parsing is a bit more complicated, as the argument type is important.
    if (message.get(1) == null || message.get(1).asText().isEmpty()) {
        // no error handling possible
        LOGGER.error("Invalid PUBLISH message, missing topic in {}", message);
        return;
    }
    String topic = message.get(1).asText();
    if (message.get(2) == null) {
        LOGGER.error("Invalid PUBLISH message, missing payload in {}", message);
        // no error handling possible
        return;
    }
    JsonNode event = message.get(2);

    List<String> exclusions = new ArrayList<>();
    if (message.get(3) != null) {
        // Two cases : boolean (excludeMe), or exclusion list
        if (message.get(3).isArray()) {
            ArrayNode array = (ArrayNode) message.get(3);
            for (JsonNode node : array) {
                exclusions.add(node.asText());
            }
        } else if (message.get(3).isBoolean()) {
            if (message.get(3).asBoolean()) {
                exclusions.add(entry.getValue().session());
            }
        } else {
            // Invalid format
            LOGGER.error("Invalid PUBLISH message, malformed message {} - the third argument must be either a "
                    + "boolean or an array", message);
            return;
        }
    }

    List<String> eligible = null;
    if (message.get(4) != null && message.get(4).isArray()) {
        eligible = new ArrayList<>();
        ArrayNode array = (ArrayNode) message.get(4);
        for (JsonNode node : array) {
            eligible.add(node.asText());
        }
    }

    dispatchEvent(topic, event, exclusions, eligible);
    sendOnEventAdmin(topic, event, exclusions, eligible);
}

From source file:org.apache.flink.yarn.YARNSessionCapacitySchedulerITCase.java

/**
 * Test TaskManager failure and also if the vcores are set correctly (see issue FLINK-2213).
 *///from w  w  w  . java  2s .  com
@Test(timeout = 100000) // timeout after 100 seconds
public void testTaskManagerFailure() {
    LOG.info("Starting testTaskManagerFailure()");
    Runner runner = startWithArgs(
            new String[] { "-j", flinkUberjar.getAbsolutePath(), "-t", flinkLibFolder.getAbsolutePath(), "-n",
                    "1", "-jm", "768", "-tm", "1024", "-s", "3", // set the slots 3 to check if the vCores are set properly!
                    "-nm", "customName", "-Dfancy-configuration-value=veryFancy",
                    "-Dyarn.maximum-failed-containers=3", "-D" + ConfigConstants.YARN_VCORES + "=2" },
            "Number of connected TaskManagers changed to 1. Slots available: 3", RunTypes.YARN_SESSION);

    Assert.assertEquals(2, getRunningContainers());

    // ------------------------ Test if JobManager web interface is accessible -------

    YarnClient yc = null;
    try {
        yc = YarnClient.createYarnClient();
        yc.init(yarnConfiguration);
        yc.start();

        List<ApplicationReport> apps = yc.getApplications(EnumSet.of(YarnApplicationState.RUNNING));
        Assert.assertEquals(1, apps.size()); // Only one running
        ApplicationReport app = apps.get(0);
        Assert.assertEquals("customName", app.getName());
        String url = app.getTrackingUrl();
        if (!url.endsWith("/")) {
            url += "/";
        }
        if (!url.startsWith("http://")) {
            url = "http://" + url;
        }
        LOG.info("Got application URL from YARN {}", url);

        String response = TestBaseUtils.getFromHTTP(url + "taskmanagers/");

        JsonNode parsedTMs = new ObjectMapper().readTree(response);
        ArrayNode taskManagers = (ArrayNode) parsedTMs.get("taskmanagers");
        Assert.assertNotNull(taskManagers);
        Assert.assertEquals(1, taskManagers.size());
        Assert.assertEquals(3, taskManagers.get(0).get("slotsNumber").asInt());

        // get the configuration from webinterface & check if the dynamic properties from YARN show up there.
        String jsonConfig = TestBaseUtils.getFromHTTP(url + "jobmanager/config");
        Map<String, String> parsedConfig = WebMonitorUtils.fromKeyValueJsonArray(jsonConfig);

        Assert.assertEquals("veryFancy", parsedConfig.get("fancy-configuration-value"));
        Assert.assertEquals("3", parsedConfig.get("yarn.maximum-failed-containers"));
        Assert.assertEquals("2", parsedConfig.get(ConfigConstants.YARN_VCORES));

        // -------------- FLINK-1902: check if jobmanager hostname/port are shown in web interface
        // first, get the hostname/port
        String oC = outContent.toString();
        Pattern p = Pattern.compile("Flink JobManager is now running on ([a-zA-Z0-9.-]+):([0-9]+)");
        Matcher matches = p.matcher(oC);
        String hostname = null;
        String port = null;
        while (matches.find()) {
            hostname = matches.group(1).toLowerCase();
            port = matches.group(2);
        }
        LOG.info("Extracted hostname:port: {} {}", hostname, port);

        Assert.assertEquals("unable to find hostname in " + jsonConfig, hostname,
                parsedConfig.get(ConfigConstants.JOB_MANAGER_IPC_ADDRESS_KEY));
        Assert.assertEquals("unable to find port in " + jsonConfig, port,
                parsedConfig.get(ConfigConstants.JOB_MANAGER_IPC_PORT_KEY));

        // test logfile access
        String logs = TestBaseUtils.getFromHTTP(url + "jobmanager/log");
        Assert.assertTrue(logs.contains("Starting YARN ApplicationMaster"));
        Assert.assertTrue(logs.contains("Starting JobManager"));
        Assert.assertTrue(logs.contains("Starting JobManager Web Frontend"));
    } catch (Throwable e) {
        LOG.warn("Error while running test", e);
        Assert.fail(e.getMessage());
    }

    // ------------------------ Kill container with TaskManager and check if vcores are set correctly -------

    // find container id of taskManager:
    ContainerId taskManagerContainer = null;
    NodeManager nodeManager = null;
    UserGroupInformation remoteUgi = null;
    NMTokenIdentifier nmIdent = null;
    try {
        remoteUgi = UserGroupInformation.getCurrentUser();
    } catch (IOException e) {
        LOG.warn("Unable to get curr user", e);
        Assert.fail();
    }
    for (int nmId = 0; nmId < NUM_NODEMANAGERS; nmId++) {
        NodeManager nm = yarnCluster.getNodeManager(nmId);
        ConcurrentMap<ContainerId, Container> containers = nm.getNMContext().getContainers();
        for (Map.Entry<ContainerId, Container> entry : containers.entrySet()) {
            String command = Joiner.on(" ").join(entry.getValue().getLaunchContext().getCommands());
            if (command.contains(YarnTaskManager.class.getSimpleName())) {
                taskManagerContainer = entry.getKey();
                nodeManager = nm;
                nmIdent = new NMTokenIdentifier(taskManagerContainer.getApplicationAttemptId(), null, "", 0);
                // allow myself to do stuff with the container
                // remoteUgi.addCredentials(entry.getValue().getCredentials());
                remoteUgi.addTokenIdentifier(nmIdent);
            }
        }
        sleep(500);
    }

    Assert.assertNotNull("Unable to find container with TaskManager", taskManagerContainer);
    Assert.assertNotNull("Illegal state", nodeManager);

    yc.stop();

    List<ContainerId> toStop = new LinkedList<ContainerId>();
    toStop.add(taskManagerContainer);
    StopContainersRequest scr = StopContainersRequest.newInstance(toStop);

    try {
        nodeManager.getNMContext().getContainerManager().stopContainers(scr);
    } catch (Throwable e) {
        LOG.warn("Error stopping container", e);
        Assert.fail("Error stopping container: " + e.getMessage());
    }

    // stateful termination check:
    // wait until we saw a container being killed and AFTERWARDS a new one launched
    boolean ok = false;
    do {
        LOG.debug("Waiting for correct order of events. Output: {}", errContent.toString());

        String o = errContent.toString();
        int killedOff = o.indexOf("Container killed by the ApplicationMaster");
        if (killedOff != -1) {
            o = o.substring(killedOff);
            ok = o.indexOf("Launching TaskManager") > 0;
        }
        sleep(1000);
    } while (!ok);

    // send "stop" command to command line interface
    runner.sendStop();
    // wait for the thread to stop
    try {
        runner.join(1000);
    } catch (InterruptedException e) {
        LOG.warn("Interrupted while stopping runner", e);
    }
    LOG.warn("stopped");

    // ----------- Send output to logger
    System.setOut(originalStdout);
    System.setErr(originalStderr);
    String oC = outContent.toString();
    String eC = errContent.toString();
    LOG.info("Sending stdout content through logger: \n\n{}\n\n", oC);
    LOG.info("Sending stderr content through logger: \n\n{}\n\n", eC);

    // ------ Check if everything happened correctly
    Assert.assertTrue("Expect to see failed container", eC.contains("New messages from the YARN cluster"));

    Assert.assertTrue("Expect to see failed container",
            eC.contains("Container killed by the ApplicationMaster"));

    Assert.assertTrue("Expect to see new container started",
            eC.contains("Launching TaskManager") && eC.contains("on host"));

    // cleanup auth for the subsequent tests.
    remoteUgi.getTokenIdentifiers().remove(nmIdent);

    LOG.info("Finished testTaskManagerFailure()");
}

From source file:com.heliosapm.mws.server.net.json.JSONRequest.java

/**
 * Creates a new JSONRequest/*from w w  w .  ja  v  a  2 s  . c  om*/
 * @param channel The channel that the request came in on. Ignored if null 
 * @param tCode the type code of the request
 * @param requestId The client supplied request ID
 * @param inReferenceToRequestId The client supplied in regards to request ID
 * @param serviceName The service name requested
 * @param opName The op name requested
 * @param request The original request
 */
protected JSONRequest(Channel channel, String tCode, long rid, long rerid, String serviceName, String opName,
        JsonNode request) {
    this.channel = channel;
    this.tCode = tCode;
    this.requestId = rid;
    this.inReferenceToRequestId = rerid;
    this.serviceName = serviceName;
    this.opName = opName;
    this.request = request;
    JsonNode argNode = request.get("args");
    if (argNode != null) {
        if (argNode instanceof ArrayNode) {
            ArrayNode an = (ArrayNode) argNode;
            for (int i = 0; i < an.size(); i++) {
                arguments.put("" + i, an.get(i));
            }
        } else if (argNode instanceof ObjectNode) {
            ObjectNode on = (ObjectNode) argNode;
            for (Iterator<String> siter = on.fieldNames(); siter.hasNext();) {
                String fieldName = siter.next();
                arguments.put(fieldName, on.get(fieldName));
            }
        }
    }
}

From source file:UploadTest.java

@Test
public void jackson_test() {
    try {/*from www .  ja  v  a2  s . c o  m*/
        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = mapper.readTree(new File("/home/raul/test/frl%3A6376984/6376984.json"));

        JsonNode curValue = root.at("/hasPart");
        System.out.println("curValue: " + curValue);
        if (curValue.isArray()) {
            ArrayNode hasPartArray = (ArrayNode) curValue;
            for (int i = 0; i < hasPartArray.size(); i++) {
                JsonNode curPart = getFirst((ObjectNode) hasPartArray.get(i));
                System.out.println("curPart: " + curPart);
                System.out.println("Found " + curPart);
            }

        } else {
            throw new RuntimeException(
                    "Unexpected type " + curValue.getNodeType() + " found: " + curValue.asText());
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.openmhealth.reference.request.DataWriteRequest.java

/**
 * Validates the data and, if valid, stores it.
 *///from   www . j a  v  a2 s .  c  o m
@Override
public void service() throws OmhException {
    // First, short-circuit if this request has already been serviced.
    if (isServiced()) {
        return;
    } else {
        setServiced();
    }

    // Check to be sure the schema is known.
    MultiValueResult<? extends Schema> schemas = Registry.getInstance().getSchemas(schemaId, version, 0, 1);
    if (schemas.count() == 0) {
        throw new OmhException(
                "The schema ID, '" + schemaId + "', and version, '" + version + "', pair is unknown.");
    }
    Schema schema = schemas.iterator().next();

    // Get the user that owns this token.
    User requestingUser = authToken.getUser();

    // Parse the data.
    JsonNode dataNode;
    try {
        dataNode = JSON_FACTORY.createJsonParser(data).readValueAs(JsonNode.class);
    } catch (JsonParseException e) {
        throw new OmhException("The data was not well-formed JSON.", e);
    } catch (JsonProcessingException e) {
        throw new OmhException("The data was not well-formed JSON.", e);
    } catch (IOException e) {
        throw new OmhException("The data could not be read.", e);
    }

    // Make sure it is a JSON array.
    if (!(dataNode instanceof ArrayNode)) {
        throw new OmhException("The data was not a JSON array.");
    }
    ArrayNode dataArray = (ArrayNode) dataNode;

    // Get the number of data points.
    int numDataPoints = dataArray.size();

    // Create the result list of data points.
    List<Data> dataPoints = new ArrayList<Data>(numDataPoints);

    // Create a new ObjectMapper that will be used to convert the meta-data
    // node into a MetaData object.
    ObjectMapper mapper = new ObjectMapper();

    // For each element in the array, be sure it is a JSON object that
    // represents a valid data point for this schema.
    for (int i = 0; i < numDataPoints; i++) {
        // Get the current data point.
        JsonNode dataPoint = dataArray.get(i);

        // Validate that it is a JSON object.
        if (!(dataPoint instanceof ObjectNode)) {
            throw new OmhException("A data point was not a JSON object: " + i);
        }
        ObjectNode dataObject = (ObjectNode) dataPoint;

        // Attempt to get the meta-data;
        MetaData metaData = null;
        JsonNode metaDataNode = dataObject.get(Data.JSON_KEY_METADATA);
        if (metaDataNode != null) {
            metaData = mapper.convertValue(metaDataNode, MetaData.class);
        }

        // Attempt to get the schema data.
        JsonNode schemaData = dataObject.get(Data.JSON_KEY_DATA);

        // If the data is missing, fail the request.
        if (schemaData == null) {
            throw new OmhException("A data point's '" + Data.JSON_KEY_DATA + "' field is missing.");
        }

        // Create and add the point to the set of data.
        dataPoints.add(schema.validateData(requestingUser.getUsername(), metaData, schemaData));
    }

    // Store the data.
    DataSet.getInstance().storeData(dataPoints);
}

From source file:com.unboundid.scim2.common.utils.JsonDiff.java

/**
 * Removes the value from an ArrayNode that matches the provided node.
 *
 * @param sourceValue The sourceValue node to match.
 * @param targetValues The ArrayNode containing the values to remove from.
 * @return The matching value that was removed or {@code null} if no matching
 *         value was found./*from w ww  .  java  2  s. c  o m*/
 */
private JsonNode removeMatchingValue(final JsonNode sourceValue, final ArrayNode targetValues) {
    if (sourceValue.isObject()) {
        // Find a target value that has the most fields in common with the source
        // and have identical values. Common fields that are also one of the
        // SCIM standard multi-value sub-attributes (ie. type, value, etc...) have
        // a higher weight when determining the best matching value.
        TreeMap<Integer, Integer> matchScoreToIndex = new TreeMap<Integer, Integer>();
        for (int i = 0; i < targetValues.size(); i++) {
            JsonNode targetValue = targetValues.get(i);
            if (targetValue.isObject()) {
                int matchScore = 0;
                Iterator<String> si = sourceValue.fieldNames();
                while (si.hasNext()) {
                    String field = si.next();
                    if (sourceValue.get(field).equals(targetValue.path(field))) {
                        if (field.equals("value") || field.equals("$ref")) {
                            // These fields have the highest chance of having unique values.
                            matchScore += 3;
                        } else if (field.equals("type") || field.equals("display")) {
                            // These fields should mostly be unique.
                            matchScore += 2;
                        } else if (field.equals("primary")) {
                            // This field will definitely not be unique.
                            matchScore += 0;
                        } else {
                            // Not one of the normative fields. Use the default weight.
                            matchScore += 1;
                        }
                    }
                }
                // Only consider the match if there is not already match with the same
                // score. This will prefer matches at the same index in the array.
                if (matchScore > 0 && !matchScoreToIndex.containsKey(matchScore)) {
                    matchScoreToIndex.put(matchScore, i);
                }
            }
        }
        if (!matchScoreToIndex.isEmpty()) {
            return targetValues.remove(matchScoreToIndex.lastEntry().getValue());
        }
    } else {
        // Find an exact match
        for (int i = 0; i < targetValues.size(); i++) {
            if (JsonUtils.compareTo(sourceValue, targetValues.get(i), null) == 0) {
                return targetValues.remove(i);
            }
        }
    }

    // Can't find a match at all.
    return null;
}

From source file:org.talend.dataprep.api.service.DataSetAPITest.java

@Test
public void testLookupActionsActions() throws Exception {
    // given// ww w .  ja v  a  2  s.c  om
    final String firstDataSetId = createDataset("dataset/dataset.csv", "testDataset", "text/csv");
    final String dataSetId = createDataset("dataset/dataset_cars.csv", "cars", "text/csv");
    final String thirdDataSetId = createDataset("dataset/dataset.csv", "third", "text/csv");

    List<String> expectedIds = Arrays.asList(firstDataSetId, thirdDataSetId);

    // when
    final String actions = when().get("/api/datasets/{id}/actions", dataSetId).asString();

    // then
    final JsonNode jsonNode = mapper.readTree(actions);
    // response is an array
    assertTrue("json not an array:" + actions, jsonNode.isArray());
    Assertions.assertThat(jsonNode.isArray()).isTrue();
    // an array of 2 entries
    ArrayNode lookups = (ArrayNode) jsonNode;
    assertThat(lookups.size(), is(2));

    // let's check the url of the possible lookups
    for (int i = 0; i < lookups.size(); i++) {
        final JsonNode lookup = lookups.get(i);
        final ArrayNode parameters = (ArrayNode) lookup.get("parameters");
        for (int j = 0; j < parameters.size(); j++) {
            final JsonNode parameter = parameters.get(j);
            if (StringUtils.equals(parameter.get("name").asText(), "url")) {
                final String url = parameter.get("default").asText();
                // the url id must be known
                assertThat(expectedIds.stream().filter(url::contains).count(), is(1L));
            }
        }
    }
}

From source file:easyrpc.server.serialization.jsonrpc.JSONCallee.java

@Override
public byte[] matchMethod(Object object, byte[] callInfo) {
    try {/*from  w  w w.  j  a v a  2s .  c  o  m*/
        Object returnedObject = null;
        ObjectNode call = (ObjectNode) MAPPER.readTree(callInfo);

        String jsonrpc = call.get("jsonrpc").textValue();
        if (jsonrpc == null || !"2.0".equals(jsonrpc)) {
            throw new SerializationException(
                    "'jsonrpc' value must be '2.0' and actually is: '" + jsonrpc + "'");
        }

        String methodName = call.get("method").textValue();
        if (methodName == null)
            throw new SerializationException("The 'method' field must not be null: " + call.toString());

        Class iface = object.getClass();
        for (Method m : iface.getMethods()) {
            if (methodName.equals(m.getName())) {
                ArrayNode jsParams = (ArrayNode) call.get("params");
                if (jsParams == null || jsParams.size() == 0) {
                    try {
                        returnedObject = m.invoke(object);
                        //                            System.out.println("returnedObject = " + returnedObject);
                    } catch (Exception e) {
                        e.printStackTrace();
                        return returnJsonRpcError(call.get("id"), e);
                    }
                } else {
                    //                        System.out.println("methodName = " + methodName);
                    Object[] params = new Object[jsParams.size()];
                    for (int i = 0; i < params.length; i++) {
                        params[i] = MAPPER.convertValue(jsParams.get(i), m.getParameters()[i].getType());
                        //                            System.out.println("params[i] = " + params[i] + "("+ params[i].getClass().getName() +")");
                    }
                    try {
                        returnedObject = m.invoke(object, params);
                        //                            System.out.println("returnedObject = " + returnedObject);
                    } catch (Exception e) {
                        e.printStackTrace();
                        return returnJsonRpcError(call.get("id"), e);
                    }
                }
                break;
            }
        }
        ObjectNode jsret = JsonNodeFactory.instance.objectNode();
        jsret.put("jsonrpc", "2.0");
        jsret.put("id", call.get("id").toString());
        if (returnedObject != null) {
            addResult(jsret, returnedObject);
        }

        //            System.out.println("jsret.toString() = " + jsret.toString());
        return jsret.toString().getBytes();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.alliander.osgp.shared.usermanagement.KeycloakClient.java

/**
 * Performs a user lookup by username.//  w  ww .  j  a va  2  s  . com
 * <p>
 * This method assumes an existing unique username is provided, so a exactly
 * one user will be found in the lookup.
 *
 * @param username
 *            an existing Keycloak username for the configured realm.
 * @return the user ID for the user with the given username.
 * @throws KeycloakClientException
 *             if retrieving a single user ID for the given username does
 *             not succeed.
 */
public String getUserId(final String username) throws KeycloakClientException {

    LOGGER.info("Retrieving Keycloak user ID for user '{}' and realm '{}'.", username, this.realm);

    final WebClient getUserIdWebClient = this.getWebClientInstance().path(this.usersPath).query("username",
            username);

    Response response = this.withBearerToken(getUserIdWebClient).get();

    JsonNode jsonNode;
    try {
        jsonNode = this.getJsonResponseBody(response);
    } catch (final KeycloakBearerException e) {
        LOGGER.debug("It looks like the bearer token expired, retry API call to the user lookup.", e);
        this.refreshToken();
        response = this.withBearerToken(getUserIdWebClient).get();
        jsonNode = this.getJsonResponseBody(response);
    }

    if (!jsonNode.isArray()) {
        throw new KeycloakClientException(
                "Expected array result from Keycloak API user lookup, got: " + jsonNode.getNodeType().name());
    }
    final ArrayNode jsonArray = (ArrayNode) jsonNode;

    if (jsonArray.size() != 1) {
        throw new KeycloakClientException("Expected 1 array result from Keycloak API user lookup for username '"
                + username + "', got: " + jsonArray.size());
    }

    final JsonNode userRepresentation = jsonArray.get(0);

    final JsonNode userId = userRepresentation.get("id");

    if (userId == null || !userId.isTextual()) {
        throw new KeycloakClientException(
                "Keycloak API user representation does not contain a JSON text field 'id'.");
    }

    return userId.textValue();
}