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:com.almende.eve.agent.google.GoogleCalendarAgent.java

/**
 * Get all events in given interval.//ww w .j  a  va2s .co m
 * 
 * @param timeMin
 *            start of the interval
 * @param timeMax
 *            end of the interval
 * @param calendarId
 *            optional calendar id. If not provided, the default calendar is
 *            used
 * @return the events
 * @throws Exception
 *             the exception
 */
@Override
public ArrayNode getEvents(@Optional @Name("timeMin") final String timeMin,
        @Optional @Name("timeMax") final String timeMax, @Optional @Name("calendarId") String calendarId)
        throws Exception {
    // initialize optional parameters
    if (calendarId == null) {
        calendarId = getState().get("email", String.class);
    }

    // built url with query parameters
    String url = CALENDAR_URI + calendarId + "/events";
    final Map<String, String> params = new HashMap<String, String>();
    if (timeMin != null) {
        params.put("timeMin", new DateTime(timeMin).toString());
    }
    if (timeMax != null) {
        params.put("timeMax", new DateTime(timeMax).toString());
    }
    // Set singleEvents=true to expand recurring events into instances
    params.put("singleEvents", "true");
    url = HttpUtil.appendQueryParams(url, params);

    // perform GET request
    final Map<String, String> headers = getAuthorizationHeaders();
    final String resp = HttpUtil.get(url, headers);
    final ObjectMapper mapper = JOM.getInstance();
    final ObjectNode json = mapper.readValue(resp, ObjectNode.class);

    // check for errors
    if (json.has("error")) {
        final ObjectNode error = (ObjectNode) json.get("error");
        throw new JSONRPCException(error);
    }

    // get items from the response
    ArrayNode items = null;
    if (json.has("items")) {
        items = (ArrayNode) json.get("items");

        // convert from Google to Eve event
        for (int i = 0; i < items.size(); i++) {
            final ObjectNode item = (ObjectNode) items.get(i);
            toEveEvent(item);
        }
    } else {
        items = JOM.createArrayNode();
    }

    return items;
}

From source file:org.activiti.kickstart.service.alfresco.AlfrescoKickstartServiceImpl.java

protected List<String> retrieveWorkflowInstanceIds(String workflowName) {
    String url = ALFRESCO_BASE_URL + "api/workflow-instances?state=active";
    JsonNode json = executeGet(url);// w ww.  ja v  a 2 s . com
    ArrayNode data = (ArrayNode) json.get("data");

    ArrayList<String> workflowInstanceIds = new ArrayList<String>();
    for (int i = 0; i < data.size(); i++) {
        String title = data.get(i).get("title").asText();
        if (title.equalsIgnoreCase(workflowName)) {
            workflowInstanceIds.add(data.get(i).get("id").asText());
        }
    }

    return workflowInstanceIds;
}

From source file:fr.gouv.vitam.mdbes.QueryBench.java

private TypeField getField(JsonNode bfield, int level) throws InvalidParseOperationException {
    String name = bfield.get(FIELD_ARGS.__name.name()).asText();
    String type = bfield.get(FIELD_ARGS.__type.name()).asText();
    String sftype = bfield.path(FIELD_ARGS.__ftype.name()).asText();
    if (type == null || type.isEmpty()) {
        LOGGER.warn("Unknown empty type: {}", type);
        throw new InvalidParseOperationException("Unknown empty type: " + type);
    }/*from w w w.ja va  2 s.c om*/
    TypeField field = new TypeField();
    FIELD fieldType = null;
    try {
        fieldType = FIELD.valueOf(type);
    } catch (IllegalArgumentException e) {
        LOGGER.warn("Unknown type: {}", bfield);
        throw new InvalidParseOperationException("Unknown type: " + bfield);
    }
    field.name = name;
    field.type = fieldType;
    FIELD_TYPE ftype = FIELD_TYPE.chaine;
    if (sftype != null && !sftype.isEmpty()) {
        try {
            ftype = FIELD_TYPE.valueOf(sftype);
        } catch (final IllegalArgumentException e) {
            LOGGER.error("Unknown ftype: " + bfield);
            ftype = FIELD_TYPE.chaine;
        }
    }
    field.ftype = ftype;
    switch (fieldType) {
    case setdistrib: {
        // no field but CPT level
        distribCpt = context.cpts.get(CPTLEVEL + level);
        return null;
    }
    case save: {
        break;
    }
    case liste:
    case listeorder: {
        ArrayNode liste = (ArrayNode) bfield.get("__" + fieldType.name());
        if (liste == null || !liste.has(0)) {
            LOGGER.warn("Empty List: {}", liste);
            throw new InvalidParseOperationException("Empty List: " + bfield);
        }
        field.listeValeurs = new String[liste.size()];
        for (int i = 0; i < liste.size(); i++) {
            field.listeValeurs[i] = liste.get(i).asText();
        }
        break;
    }
    case serie: {
        JsonNode bson = bfield.get(FIELD_ARGS.__serie.name());
        if (bson == null) {
            LOGGER.warn("Empty serie: {}", bfield);
            throw new InvalidParseOperationException("Empty serie: " + bfield);
        }
        if (bson.has(FIELD_ARGS.__prefix.name())) {
            String prefix = bson.get(FIELD_ARGS.__prefix.name()).asText();
            if (prefix == null) {
                prefix = "";
            }
            field.prefix = prefix;
        }
        if (bson.has(FIELD_ARGS.__idcpt.name())) {
            String idcpt = bson.get(FIELD_ARGS.__idcpt.name()).asText();
            if (idcpt != null && !idcpt.isEmpty()) {
                field.idcpt = idcpt;
                context.cpts.put(idcpt, new AtomicLong(0));
            }
        }
        field.modulo = -1;
        if (bson.has(FIELD_ARGS.__modulo.name())) {
            int modulo = bson.get(FIELD_ARGS.__modulo.name()).asInt();
            if (modulo > 0) {
                field.modulo = modulo;
            }
        }
        break;
    }
    case interval: {
        Integer low = bfield.get(FIELD_ARGS.__low.name()).asInt();
        if (low == null) {
            LOGGER.warn("Empty interval: {}", bfield);
            throw new InvalidParseOperationException("Empty interval: " + bfield);
        }
        Integer high = bfield.get(FIELD_ARGS.__high.name()).asInt();
        if (high == null) {
            LOGGER.warn("Empty interval: {}", bfield);
            throw new InvalidParseOperationException("Empty interval: " + bfield);
        }
        field.low = low;
        field.high = high;
        break;
    }
    default:
        LOGGER.warn("Incorrect type: {}", bfield);
        throw new InvalidParseOperationException("Incorrect type: " + bfield);
    }
    if (bfield.has(FIELD_ARGS.__save.name())) {
        String savename = bfield.get(FIELD_ARGS.__save.name()).asText();
        if (savename != null && !savename.isEmpty()) {
            field.saveName = savename;
        }
    }
    if (bfield.has(FIELD_ARGS.__subprefix.name())) {
        ArrayNode liste = (ArrayNode) bfield.get(FIELD_ARGS.__subprefix.name());
        if (liste == null || !liste.has(0)) {
            LOGGER.warn("Empty SubPrefix List: {}", liste);
            throw new InvalidParseOperationException("Empty SubPrefix List: " + bfield);
        }
        field.subprefixes = new String[liste.size()];
        for (int i = 0; i < liste.size(); i++) {
            field.subprefixes[i] = liste.get(i).asText();
        }
    }
    return field;
}

From source file:org.apache.nifi.processors.elasticsearch.PutElasticsearchHttpRecord.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {

    FlowFile flowFile = session.get();//from ww w  .ja  v a2  s  .  c om
    if (flowFile == null) {
        return;
    }

    final RecordReaderFactory readerFactory = context.getProperty(RECORD_READER)
            .asControllerService(RecordReaderFactory.class);

    // Authentication
    final String username = context.getProperty(USERNAME).evaluateAttributeExpressions(flowFile).getValue();
    final String password = context.getProperty(PASSWORD).evaluateAttributeExpressions(flowFile).getValue();

    OkHttpClient okHttpClient = getClient();
    final ComponentLog logger = getLogger();

    final String baseUrl = trimToEmpty(context.getProperty(ES_URL).evaluateAttributeExpressions().getValue());
    HttpUrl.Builder urlBuilder = HttpUrl.parse(baseUrl).newBuilder().addPathSegment("_bulk");

    // Find the user-added properties and set them as query parameters on the URL
    for (Map.Entry<PropertyDescriptor, String> property : context.getProperties().entrySet()) {
        PropertyDescriptor pd = property.getKey();
        if (pd.isDynamic()) {
            if (property.getValue() != null) {
                urlBuilder = urlBuilder.addQueryParameter(pd.getName(),
                        context.getProperty(pd).evaluateAttributeExpressions().getValue());
            }
        }
    }
    final URL url = urlBuilder.build().url();

    final String index = context.getProperty(INDEX).evaluateAttributeExpressions(flowFile).getValue();
    if (StringUtils.isEmpty(index)) {
        logger.error("No value for index in for {}, transferring to failure", new Object[] { flowFile });
        session.transfer(flowFile, REL_FAILURE);
        return;
    }
    final String docType = context.getProperty(TYPE).evaluateAttributeExpressions(flowFile).getValue();
    String indexOp = context.getProperty(INDEX_OP).evaluateAttributeExpressions(flowFile).getValue();
    if (StringUtils.isEmpty(indexOp)) {
        logger.error("No Index operation specified for {}, transferring to failure.",
                new Object[] { flowFile });
        session.transfer(flowFile, REL_FAILURE);
        return;
    }

    switch (indexOp.toLowerCase()) {
    case "index":
    case "update":
    case "upsert":
    case "delete":
        break;
    default:
        logger.error("Index operation {} not supported for {}, transferring to failure.",
                new Object[] { indexOp, flowFile });
        session.transfer(flowFile, REL_FAILURE);
        return;
    }

    final String id_path = context.getProperty(ID_RECORD_PATH).evaluateAttributeExpressions(flowFile)
            .getValue();
    final RecordPath recordPath = StringUtils.isEmpty(id_path) ? null : recordPathCache.getCompiled(id_path);
    final StringBuilder sb = new StringBuilder();

    try (final InputStream in = session.read(flowFile);
            final RecordReader reader = readerFactory.createRecordReader(flowFile, in, getLogger())) {

        Record record;
        while ((record = reader.nextRecord()) != null) {

            final String id;
            if (recordPath != null) {
                Optional<FieldValue> idPathValue = recordPath.evaluate(record).getSelectedFields().findFirst();
                if (!idPathValue.isPresent() || idPathValue.get().getValue() == null) {
                    throw new IdentifierNotFoundException(
                            "Identifier Record Path specified but no value was found, transferring {} to failure.");
                }
                id = idPathValue.get().getValue().toString();
            } else {
                id = null;
            }

            // The ID must be valid for all operations except "index". For that case,
            // a missing ID indicates one is to be auto-generated by Elasticsearch
            if (id == null && !indexOp.equalsIgnoreCase("index")) {
                throw new IdentifierNotFoundException(
                        "Index operation {} requires a valid identifier value from a flow file attribute, transferring to failure.");
            }

            final StringBuilder json = new StringBuilder();

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            JsonGenerator generator = factory.createJsonGenerator(out);
            writeRecord(record, record.getSchema(), generator);
            generator.flush();
            generator.close();
            json.append(out.toString());

            if (indexOp.equalsIgnoreCase("index")) {
                sb.append("{\"index\": { \"_index\": \"");
                sb.append(index);
                sb.append("\", \"_type\": \"");
                sb.append(docType);
                sb.append("\"");
                if (!StringUtils.isEmpty(id)) {
                    sb.append(", \"_id\": \"");
                    sb.append(id);
                    sb.append("\"");
                }
                sb.append("}}\n");
                sb.append(json);
                sb.append("\n");
            } else if (indexOp.equalsIgnoreCase("upsert") || indexOp.equalsIgnoreCase("update")) {
                sb.append("{\"update\": { \"_index\": \"");
                sb.append(index);
                sb.append("\", \"_type\": \"");
                sb.append(docType);
                sb.append("\", \"_id\": \"");
                sb.append(id);
                sb.append("\" }\n");
                sb.append("{\"doc\": ");
                sb.append(json);
                sb.append(", \"doc_as_upsert\": ");
                sb.append(indexOp.equalsIgnoreCase("upsert"));
                sb.append(" }\n");
            } else if (indexOp.equalsIgnoreCase("delete")) {
                sb.append("{\"delete\": { \"_index\": \"");
                sb.append(index);
                sb.append("\", \"_type\": \"");
                sb.append(docType);
                sb.append("\", \"_id\": \"");
                sb.append(id);
                sb.append("\" }\n");
            }
        }
    } catch (IdentifierNotFoundException infe) {
        logger.error(infe.getMessage(), new Object[] { flowFile });
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, REL_FAILURE);
        return;

    } catch (final IOException | SchemaNotFoundException | MalformedRecordException e) {
        logger.error("Could not parse incoming data", e);
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, REL_FAILURE);
        return;
    }

    RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), sb.toString());
    final Response getResponse;
    try {
        getResponse = sendRequestToElasticsearch(okHttpClient, url, username, password, "PUT", requestBody);
    } catch (final Exception e) {
        logger.error("Routing to {} due to exception: {}", new Object[] { REL_FAILURE.getName(), e }, e);
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, REL_FAILURE);
        return;
    }
    final int statusCode = getResponse.code();

    if (isSuccess(statusCode)) {
        ResponseBody responseBody = getResponse.body();
        try {
            final byte[] bodyBytes = responseBody.bytes();

            JsonNode responseJson = parseJsonResponse(new ByteArrayInputStream(bodyBytes));
            boolean errors = responseJson.get("errors").asBoolean(false);
            // ES has no rollback, so if errors occur, log them and route the whole flow file to failure
            if (errors) {
                ArrayNode itemNodeArray = (ArrayNode) responseJson.get("items");
                if (itemNodeArray.size() > 0) {
                    // All items are returned whether they succeeded or failed, so iterate through the item array
                    // at the same time as the flow file list, logging failures accordingly
                    for (int i = itemNodeArray.size() - 1; i >= 0; i--) {
                        JsonNode itemNode = itemNodeArray.get(i);
                        int status = itemNode.findPath("status").asInt();
                        if (!isSuccess(status)) {
                            String reason = itemNode.findPath("//error/reason").asText();
                            logger.error(
                                    "Failed to insert {} into Elasticsearch due to {}, transferring to failure",
                                    new Object[] { flowFile, reason });
                        }
                    }
                }
                session.transfer(flowFile, REL_FAILURE);
            } else {
                session.transfer(flowFile, REL_SUCCESS);
                session.getProvenanceReporter().send(flowFile, url.toString());
            }

        } catch (IOException ioe) {
            // Something went wrong when parsing the response, log the error and route to failure
            logger.error("Error parsing Bulk API response: {}", new Object[] { ioe.getMessage() }, ioe);
            session.transfer(flowFile, REL_FAILURE);
            context.yield();
        }
    } else if (statusCode / 100 == 5) {
        // 5xx -> RETRY, but a server error might last a while, so yield
        logger.warn(
                "Elasticsearch returned code {} with message {}, transferring flow file to retry. This is likely a server problem, yielding...",
                new Object[] { statusCode, getResponse.message() });
        session.transfer(flowFile, REL_RETRY);
        context.yield();
    } else { // 1xx, 3xx, 4xx, etc. -> NO RETRY
        logger.warn("Elasticsearch returned code {} with message {}, transferring flow file to failure",
                new Object[] { statusCode, getResponse.message() });
        session.transfer(flowFile, REL_FAILURE);
    }
    getResponse.close();
}

From source file:com.almende.dht.rpc.DHT.java

/**
 * Find_value, optionally get all values for key.
 *
 * @param key/*w  ww.  ja  v a 2  s . c  o m*/
 *            the key
 * @param remote
 *            the remote
 * @param multiple
 *            Request all values or just the newest?
 * @param sender
 *            the sender
 * @return And objectNode containing either: {"value":....} or
 *         {"nodes":[....]}
 */
@Access(AccessType.PUBLIC)
public ObjectNode find_value(@Name("key") Key key, @Name("me") Key remote, @Name("multiple") Boolean multiple,
        @Sender URI sender) {
    rt.seenNode(new Node(remote, sender));
    if (values.containsKey(key)) {
        final ObjectNode result = JOM.createObjectNode();
        final ArrayNode arr = JOM.createArrayNode();
        final Set<TimedValue> current = values.get(key);

        final int size = current.size();
        final Iterator<TimedValue> iter = values.get(key).iterator();
        while (iter.hasNext()) {
            final TimedValue item = iter.next();
            if (item.getTtl() > 0) {
                arr.add(item.getValue());
            } else {
                iter.remove();
            }
        }
        if (current.size() < size) {
            values.put(key, current);
        }
        if (multiple) {
            result.set("values", arr);
        } else {
            result.set("value", arr.get(0));
        }
        return result;
    } else {
        return loc_find_close_nodes(key);
    }
}

From source file:io.apiman.test.common.json.JsonCompare.java

/**
 * Asserts that the JSON document matches what we expected.
 * @param expectedJson/*from  w  w  w.java 2 s . c o m*/
 * @param actualJson
 */
public void assertJson(JsonNode expectedJson, JsonNode actualJson) {
    if (expectedJson instanceof ArrayNode) {
        JsonNode actualValue = actualJson;
        ArrayNode expectedArray = (ArrayNode) expectedJson;
        Assert.assertEquals(
                message("Expected JSON array but found non-array [{0}] instead.",
                        actualValue.getClass().getSimpleName()),
                expectedJson.getClass(), actualValue.getClass());
        ArrayNode actualArray = (ArrayNode) actualValue;
        Assert.assertEquals(message("Array size mismatch."), expectedArray.size(), actualArray.size());

        JsonNode[] expected = new JsonNode[expectedArray.size()];
        JsonNode[] actual = new JsonNode[actualArray.size()];
        for (int idx = 0; idx < expected.length; idx++) {
            expected[idx] = expectedArray.get(idx);
            actual[idx] = actualArray.get(idx);
        }
        // If strict ordering is disabled, then sort both arrays
        if (getArrayOrdering() == JsonArrayOrderingType.any) {
            Comparator<? super JsonNode> comparator = new Comparator<JsonNode>() {
                @Override
                public int compare(JsonNode o1, JsonNode o2) {
                    String str1 = o1.asText();
                    String str2 = o2.asText();
                    if (o1.isObject() && o2.isObject()) {
                        // Try name (PermissionBean only)
                        JsonNode o1NameNode = o1.get("name");
                        JsonNode o2NameNode = o2.get("name");
                        if (o1NameNode != null && o2NameNode != null) {
                            str1 = o1NameNode.asText();
                            str2 = o2NameNode.asText();
                        }

                        // Try username (UserBean only)
                        JsonNode o1UsernameNode = o1.get("username");
                        JsonNode o2UsernameNode = o2.get("username");
                        if (o1UsernameNode != null && o2UsernameNode != null) {
                            str1 = o1UsernameNode.asText();
                            str2 = o2UsernameNode.asText();
                        }

                        // Try version (*VersionBeans)
                        JsonNode o1VersionNode = o1.get("version");
                        JsonNode o2VersionNode = o2.get("version");
                        if (o1VersionNode != null && o2VersionNode != null) {
                            str1 = o1VersionNode.asText();
                            str2 = o2VersionNode.asText();
                        }

                        // Try OrganizationBean.id (Orgs)
                        JsonNode o1OrgNode = o1.get("OrganizationBean");
                        JsonNode o2OrgNode = o2.get("OrganizationBean");
                        if (o1OrgNode != null && o2OrgNode != null) {
                            str1 = o1OrgNode.get("id").asText();
                            str2 = o2OrgNode.get("id").asText();
                        }

                        // Try ClientBean.id (Orgs)
                        JsonNode o1ClientNode = o1.get("ClientBean");
                        JsonNode o2ClientNode = o2.get("ClientBean");
                        if (o1ClientNode != null && o2ClientNode != null) {
                            str1 = o1ClientNode.get("id").asText();
                            str2 = o2ClientNode.get("id").asText();
                        }

                        // Try PlanBean.id (Orgs)
                        JsonNode o1PlanNode = o1.get("PlanBean");
                        JsonNode o2PlanNode = o2.get("PlanBean");
                        if (o1PlanNode != null && o2PlanNode != null) {
                            str1 = o1PlanNode.get("id").asText();
                            str2 = o2PlanNode.get("id").asText();
                        }

                        // Try ApiBean.id (Orgs)
                        JsonNode o1ApiNode = o1.get("ApiBean");
                        JsonNode o2ApiNode = o2.get("ApiBean");
                        if (o1ApiNode != null && o2ApiNode != null) {
                            str1 = o1ApiNode.get("id").asText();
                            str2 = o2ApiNode.get("id").asText();
                        }

                        // Try Id (all other beans)
                        JsonNode o1IdNode = o1.get("id");
                        JsonNode o2IdNode = o2.get("id");
                        if (o1IdNode != null && o2IdNode != null) {
                            if (o1IdNode.isNumber()) {
                                return new Long(o1IdNode.asLong()).compareTo(o2IdNode.asLong());
                            }
                            str1 = o1IdNode.asText();
                            str2 = o2IdNode.asText();
                        }
                    }
                    int cmp = str1.compareTo(str2);
                    if (cmp == 0)
                        cmp = 1;
                    return cmp;
                }
            };
            Arrays.sort(expected, comparator);
            Arrays.sort(actual, comparator);
        }
        for (int idx = 0; idx < expected.length; idx++) {
            currentPath.push(idx);
            assertJson(expected[idx], actual[idx]);
            currentPath.pop();
        }
    } else {
        Iterator<Entry<String, JsonNode>> fields = expectedJson.fields();
        Set<String> expectedFieldNames = new HashSet<>();
        while (fields.hasNext()) {
            Entry<String, JsonNode> entry = fields.next();
            String expectedFieldName = entry.getKey();
            expectedFieldNames.add(expectedFieldName);
            JsonNode expectedValue = entry.getValue();
            currentPath.push(expectedFieldName);
            if (expectedValue instanceof TextNode) {
                TextNode tn = (TextNode) expectedValue;
                String expected = tn.textValue();
                JsonNode actualValue = actualJson.get(expectedFieldName);

                if (isIgnoreCase()) {
                    expected = expected.toLowerCase();
                    if (actualValue == null) {
                        actualValue = actualJson.get(expectedFieldName.toLowerCase());
                    }
                }

                Assert.assertNotNull(
                        message("Expected JSON text field \"{0}\" with value \"{1}\" but was not found.",
                                expectedFieldName, expected),
                        actualValue);
                Assert.assertEquals(message(
                        "Expected JSON text field \"{0}\" with value \"{1}\" but found non-text [{2}] field with that name instead.",
                        expectedFieldName, expected, actualValue.getClass().getSimpleName()), TextNode.class,
                        actualValue.getClass());
                String actual = ((TextNode) actualValue).textValue();

                if (isIgnoreCase()) {
                    if (actual != null) {
                        actual = actual.toLowerCase();
                    }
                }

                if (!expected.equals("*")) {
                    Assert.assertEquals(message("Value mismatch for text field \"{0}\".", expectedFieldName),
                            expected, actual);
                }
            } else if (expectedValue.isNumber()) {
                NumericNode numeric = (NumericNode) expectedValue;
                Number expected = numeric.numberValue();
                JsonNode actualValue = actualJson.get(expectedFieldName);
                try {
                    Assert.assertNotNull(
                            message("Expected JSON numeric field \"{0}\" with value \"{1}\" but was not found.",
                                    expectedFieldName, expected),
                            actualValue);
                } catch (Error e) {
                    throw e;
                }
                Assert.assertTrue(message(
                        "Expected JSON numeric field \"{0}\" with value \"{1}\" but found non-numeric [{2}] field with that name instead.",
                        expectedFieldName, expected, actualValue.getClass().getSimpleName()),
                        actualValue.isNumber());
                Number actual = ((NumericNode) actualValue).numberValue();
                if (!"id".equals(expectedFieldName) || isCompareNumericIds()) {
                    Assert.assertEquals(message("Value mismatch for numeric field \"{0}\".", expectedFieldName),
                            expected, actual);
                }
            } else if (expectedValue instanceof BooleanNode) {
                BooleanNode bool = (BooleanNode) expectedValue;
                Boolean expected = bool.booleanValue();
                JsonNode actualValue = actualJson.get(expectedFieldName);
                Assert.assertNotNull(
                        message("Expected JSON boolean field \"{0}\" with value \"{1}\" but was not found.",
                                expectedFieldName, expected),
                        actualValue);
                Assert.assertEquals(message(
                        "Expected JSON boolean field \"{0}\" with value \"{1}\" but found non-boolean [{2}] field with that name instead.",
                        expectedFieldName, expected, actualValue.getClass().getSimpleName()),
                        expectedValue.getClass(), actualValue.getClass());
                Boolean actual = ((BooleanNode) actualValue).booleanValue();
                Assert.assertEquals(message("Value mismatch for boolean field \"{0}\".", expectedFieldName),
                        expected, actual);
            } else if (expectedValue instanceof ObjectNode) {
                JsonNode actualValue = actualJson.get(expectedFieldName);
                Assert.assertNotNull(
                        message("Expected parent JSON field \"{0}\" but was not found.", expectedFieldName),
                        actualValue);
                Assert.assertEquals(
                        message("Expected parent JSON field \"{0}\" but found field of type \"{1}\".",
                                expectedFieldName, actualValue.getClass().getSimpleName()),
                        ObjectNode.class, actualValue.getClass());
                assertJson(expectedValue, actualValue);
            } else if (expectedValue instanceof ArrayNode) {
                JsonNode actualValue = actualJson.get(expectedFieldName);
                Assert.assertNotNull(
                        message("Expected JSON array field \"{0}\" but was not found.", expectedFieldName),
                        actualValue);
                ArrayNode expectedArray = (ArrayNode) expectedValue;
                Assert.assertEquals(message(
                        "Expected JSON array field \"{0}\" but found non-array [{1}] field with that name instead.",
                        expectedFieldName, actualValue.getClass().getSimpleName()), expectedValue.getClass(),
                        actualValue.getClass());
                ArrayNode actualArray = (ArrayNode) actualValue;
                Assert.assertEquals(message("Field \"{0}\" array size mismatch.", expectedFieldName),
                        expectedArray.size(), actualArray.size());
                assertJson(expectedArray, actualArray);
            } else if (expectedValue instanceof NullNode) {
                JsonNode actualValue = actualJson.get(expectedFieldName);
                Assert.assertNotNull(
                        message("Expected Null JSON field \"{0}\" but was not found.", expectedFieldName),
                        actualValue);
                Assert.assertEquals(
                        message("Expected Null JSON field \"{0}\" but found field of type \"{0}\".",
                                expectedFieldName, actualValue.getClass().getSimpleName()),
                        NullNode.class, actualValue.getClass());
            } else {
                Assert.fail(message("Unsupported field type: {0}", expectedValue.getClass().getSimpleName()));
            }
            currentPath.pop();
        }

        if (getMissingField() == JsonMissingFieldType.fail) {
            Set<String> actualFieldNames = new HashSet();
            Iterator<String> names = actualJson.fieldNames();
            while (names.hasNext()) {
                actualFieldNames.add(names.next());
            }
            actualFieldNames.removeAll(expectedFieldNames);
            Assert.assertTrue(message("Found unexpected fields: {0}", StringUtils.join(actualFieldNames, ", ")),
                    actualFieldNames.isEmpty());
        }
    }
}

From source file:com.googlecode.jsonrpc4j.JsonRpcServer.java

/**
 * Handles the given {@link ArrayNode} and writes the
 * responses to the given {@link OutputStream}.
 *
 * @param node the {@link JsonNode}/* w  ww  .j  a  v a  2  s. c  om*/
 * @param ops the {@link OutputStream}
 * @throws IOException on error
 */
public void handleArray(ArrayNode node, OutputStream ops) throws IOException {
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(Level.FINE, "Handing " + node.size() + " requests");
    }

    // loop through each array element
    ops.write('[');
    for (int i = 0; i < node.size(); i++) {
        handleNode(node.get(i), ops);
        if (i != node.size() - 1)
            ops.write(',');
    }
    ops.write(']');
}

From source file:de.jlo.talendcomp.json.JsonDocument.java

private JsonNode getNodeFromArray(JsonNode node, int arrayIndex, boolean allowMissing) throws Exception {
    if (node instanceof ArrayNode) {
        ArrayNode arrayNode = (ArrayNode) node;
        if (arrayIndex < arrayNode.size()) {
            return arrayNode.get(arrayIndex);
        } else if (allowMissing) {
            return null;
        } else {/*  w ww  .  j  av  a2  s.c  o m*/
            throw new Exception(
                    "Node: " + node + " has less elements than expected array index: " + arrayIndex);
        }
    }
    return node;
}

From source file:com.almende.eve.agent.MeetingAgent.java

/**
 * Retrieve the busy intervals of a calendar agent
 * /*  w ww  .ja v a  2s. c  o  m*/
 * @param agent
 */
private void updateBusyInterval(@Name("agent") final String agent) {
    try {
        // create parameters with the boundaries of the interval to be
        // retrieved
        final ObjectNode params = JOM.createObjectNode();
        final DateTime timeMin = DateTime.now();
        final DateTime timeMax = timeMin.plusDays(LOOK_AHEAD_DAYS);
        params.put("timeMin", timeMin.toString());
        params.put("timeMax", timeMax.toString());

        // exclude the event managed by this agent from the busy intervals
        final String eventId = getAgentData(agent).eventId;
        if (eventId != null) {
            final ArrayNode excludeEventIds = JOM.createArrayNode();
            excludeEventIds.add(eventId);
            params.put("excludeEventIds", excludeEventIds);
        }

        // get the busy intervals from the agent
        final ArrayNode array = send(URI.create(agent), "getBusy", params, ArrayNode.class);

        // convert from ArrayNode to List
        final List<Interval> busy = new ArrayList<Interval>();
        for (int i = 0; i < array.size(); i++) {
            final ObjectNode obj = (ObjectNode) array.get(i);
            final String start = obj.has("start") ? obj.get("start").asText() : null;
            final String end = obj.has("end") ? obj.get("end").asText() : null;
            busy.add(new Interval(new DateTime(start), new DateTime(end)));
        }

        // store the interval in the state
        putAgentBusy(agent, busy);

    } catch (final JSONRPCException e) {
        addIssue(TYPE.warning, Issue.JSONRPCEXCEPTION, e.getMessage());
        LOG.log(Level.WARNING, "", e);
    } catch (final Exception e) {
        addIssue(TYPE.warning, Issue.EXCEPTION, e.getMessage());
        LOG.log(Level.WARNING, "", e);
    }
}