Example usage for com.fasterxml.jackson.databind JsonNode asLong

List of usage examples for com.fasterxml.jackson.databind JsonNode asLong

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind JsonNode asLong.

Prototype

public long asLong() 

Source Link

Usage

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

/**
 * Asserts that the JSON document matches what we expected.
 * @param expectedJson// ww w.  j  a v  a 2  s . com
 * @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:org.opendaylight.nemo.renderer.openflow.physicalnetwork.PhyConfigLoaderTest.java

@Test
public void testBuildLinks() throws Exception {
    List<PhysicalLink> list;
    JsonNode hostsNode = mock(JsonNode.class);
    JsonNode hosts = mock(JsonNode.class);
    JsonNode jsonNode = mock(JsonNode.class);
    JsonNode jsonNode1 = mock(JsonNode.class);
    PhysicalHost physicalHost;/* w w  w. j ava  2  s.c  o  m*/

    Class<PhyConfigLoader> class1 = PhyConfigLoader.class;
    Method method = class1.getDeclaredMethod("buildLinks", new Class[] { JsonNode.class });
    method.setAccessible(true);

    when(hostsNode.path(any(String.class))).thenReturn(hosts);
    when(hosts.size()).thenReturn(1);
    when(hosts.get(any(Integer.class))).thenReturn(jsonNode);
    when(jsonNode.get(any(String.class))).thenReturn(jsonNode1).thenReturn(jsonNode1);
    when(jsonNode1.asText()).thenReturn(new String("test"));
    when(jsonNode1.asLong()).thenReturn((long) 1);

    list = (List<PhysicalLink>) method.invoke(phyConfigLoader, hostsNode);
    Assert.assertTrue(list.size() == 1);
}

From source file:com.aol.one.patch.DefaultPatcher.java

private List<MethodData> generateMethodData(List<String> methodNames, JsonNode valueNode) {

    List<MethodData> dataList = new ArrayList<>();
    if (valueNode.isTextual()) {
        for (String methodName : methodNames) {
            dataList.add(new MethodData(methodName, String.class, valueNode.asText()));
        }//from w ww .  j  a  v a2 s .  com
    } else if (valueNode.isNumber()) {
        for (String methodName : methodNames) {
            if (valueNode.isIntegralNumber()) {
                dataList.add(new MethodData(methodName, Long.TYPE, valueNode.asLong()));
                dataList.add(new MethodData(methodName, Long.class, valueNode.asLong()));
                dataList.add(new MethodData(methodName, Integer.TYPE, valueNode.asInt()));
                dataList.add(new MethodData(methodName, Integer.class, valueNode.asInt()));
                dataList.add(new MethodData(methodName, Short.TYPE, (short) valueNode.asInt()));
                dataList.add(new MethodData(methodName, Short.class, (short) valueNode.asInt()));
            } else {
                dataList.add(new MethodData(methodName, Double.TYPE, valueNode.asDouble()));
                dataList.add(new MethodData(methodName, Double.class, valueNode.asDouble()));
                dataList.add(new MethodData(methodName, Float.TYPE, valueNode.asDouble()));
                dataList.add(new MethodData(methodName, Float.class, valueNode.asDouble()));
            }
        }
    } else if (valueNode.isBoolean()) {
        for (String methodName : methodNames) {
            dataList.add(new MethodData(methodName, Boolean.TYPE, valueNode.asBoolean()));
            dataList.add(new MethodData(methodName, Boolean.class, valueNode.asBoolean()));
        }

    }

    // default
    for (String methodName : methodNames) {
        dataList.add(new MethodData(methodName, JsonNode.class, valueNode));
    }

    return dataList;
}

From source file:org.opendaylight.nemo.renderer.cli.physicalnetwork.PhysicalResourceLoaderTest.java

@Test
public void testBuildLinks() throws Exception {
    List<PhysicalLink> list;
    Class<PhysicalResourceLoader> class1 = PhysicalResourceLoader.class;
    Method method = class1.getDeclaredMethod("buildLinks", new Class[] { JsonNode.class });
    method.setAccessible(true);/*from w  w  w . j  a v a 2 s  .  c om*/

    JsonNode linksRoot = mock(JsonNode.class);
    JsonNode links = mock(JsonNode.class);
    JsonNode link = mock(JsonNode.class);
    JsonNode link_temp_buildlink = mock(JsonNode.class);

    when(linksRoot.path(any(String.class))).thenReturn(links);
    when(links.size()).thenReturn(1);
    when(links.get(any(Integer.class))).thenReturn(link);
    //get into method "build link" args(link)
    when(link.get(any(String.class))).thenReturn(link_temp_buildlink);
    when(link_temp_buildlink.asText()).thenReturn(new String("1"))//new PhysicalLinkId(strLinkId)
            .thenReturn(new String("2"))//new PhysicalNodeId
            .thenReturn(new String("3"))//new PhysicalPortId
            .thenReturn(new String("4"))//new PhysicalNodeId
            .thenReturn(new String("5"))//new PhysicalPortId
            .thenReturn(new String(""));//linkNode.get("link-bandwidth").asText().equals("")
    when(link_temp_buildlink.asLong()).thenReturn((long) 1);

    list = (List<PhysicalLink>) method.invoke(physicalResourceLoader, linksRoot);
    Assert.assertTrue(list.size() == 1);
    verify(link_temp_buildlink, times(6)).asText();
}

From source file:ru.gkpromtech.exhibition.db.Table.java

private ContentValues jsonToRow(ObjectNode object) throws IllegalAccessException, ParseException {
    ContentValues values = new ContentValues();

    for (int i = 0; i < mFields.length; ++i) {
        String fieldName = mFields[i].getName();
        JsonNode field = object.get(fieldName);
        if (field == null)
            continue;
        if (field.isNull()) {
            values.putNull(mColumns[i]);
            continue;
        }//  w ww . j a v a  2  s .c  om

        switch (mType[i]) {
        case INTEGER:
            values.put(mColumns[i], field.asInt());
            break;
        case SHORT:
            values.put(mColumns[i], (short) field.asInt());
            break;
        case LONG:
            values.put(mColumns[i], field.asLong());
            break;
        case FLOAT:
            values.put(mColumns[i], (float) field.asDouble());
            break;
        case DOUBLE:
            values.put(mColumns[i], field.asDouble());
            break;
        case STRING:
            values.put(mColumns[i], field.asText());
            break;
        case BYTE_ARRAY:
            values.put(mColumns[i], Base64.decode(field.asText(), Base64.DEFAULT));
            break;
        case DATE:
            values.put(mColumns[i], mDateFormat.parse(field.asText()).getTime());
            break;
        case BOOLEAN:
            values.put(mColumns[i], field.asBoolean() ? 1 : 0);
            break;
        }
    }
    return values;
}

From source file:com.discover.cls.processors.cls.JSONToAttributes.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();/*from w ww .j a v a2s  . c o m*/
    if (flowFile == null) {
        return;
    }

    final String flattenJsonSeparator = context.getProperty(FLATTEN_JSON_SEPARATOR).getValue();
    final boolean flattenJson = context.getProperty(FLATTEN_JSON).asBoolean();
    final boolean flattenJsonArrays = context.getProperty(FLATTEN_JSON_ARRAYS).asBoolean();
    final String attributeNameFromProperty = context.getProperty(JSON_ATTRIBUTE_NAME)
            .evaluateAttributeExpressions().getValue();
    final String attributeContent = flowFile.getAttribute(attributeNameFromProperty);
    final byte[] content = getContent(session, flowFile, attributeNameFromProperty, attributeContent);
    final boolean toOverride = context.getProperty(OVERRIDE_ATTRIBUTES).asBoolean();
    final boolean preserveType = context.getProperty(PRESERVE_TYPE).asBoolean();

    if (attributeNameFromProperty != null && !"".equals(attributeNameFromProperty)
            && attributeContent == null) {
        getLogger().error(JSON_ATTRIBUTE_NAME.getDisplayName() + " is defined, but the attribute '"
                + attributeNameFromProperty + "' does not exist.");
        session.transfer(flowFile, REL_FAILURE);
        return;
    }

    if (content == null || Arrays.equals(content, new byte[0])) {
        // No content. push through.
        getLogger().debug("No content is defined. Passing flow file to 'no content' relationship.");
        session.transfer(flowFile, REL_NO_CONTENT);
        return;
    }

    try {
        final JsonNode jsonNode = OBJECT_MAPPER.readTree(content);
        final Map<String, String> attributes = new LinkedHashMap<>();

        if (flattenJson) {
            addKeys("", jsonNode, flattenJsonSeparator, preserveType, flattenJsonArrays, attributes);
        } else {
            final Iterator<Map.Entry<String, JsonNode>> fields = jsonNode.fields();
            while (fields.hasNext()) {
                Map.Entry<String, JsonNode> entry = fields.next();
                if (toOverride || flowFile.getAttribute(entry.getKey()) == null) {
                    JsonNode value = entry.getValue();
                    switch (value.getNodeType()) {
                    case ARRAY:
                        attributes.put(entry.getKey(), value.toString());
                        break;
                    case BINARY:
                        attributes.put(entry.getKey(), value.toString());
                        break;
                    case BOOLEAN:
                        attributes.put(entry.getKey(), Boolean.toString(value.asBoolean()));
                        break;
                    case MISSING:
                        attributes.put(entry.getKey(), value.toString());
                        break;
                    case NULL:
                        attributes.put(entry.getKey(), value.toString());
                        break;
                    case NUMBER:
                        attributes.put(entry.getKey(), Long.toString(value.asLong()));
                        break;
                    case OBJECT:
                        attributes.put(entry.getKey(), value.toString());
                        break;
                    case POJO:
                        attributes.put(entry.getKey(), value.toString());
                        break;
                    case STRING:
                        attributes.put(entry.getKey(), preserveType ? value.toString() : value.textValue());
                        break;
                    }
                }
            }
        }

        flowFile = session.putAllAttributes(flowFile, attributes);
        session.getProvenanceReporter().modifyAttributes(flowFile);
        session.transfer(flowFile, REL_SUCCESS);
    } catch (IOException e) {
        getLogger().error("Failed parsing JSON.", new Object[] { e });
        session.transfer(flowFile, REL_FAILURE);
    }
}

From source file:org.waarp.common.database.data.AbstractDbData.java

/**
 * Set the values from the Json node to the current object (no database access)
 * /*from  ww  w.  j a v a2 s .  co m*/
 * @param node
 * @param ignorePrimaryKey
 *            True will ignore primaryKey from Json
 * @throws WaarpDatabaseSqlException
 */
public void setFromJson(ObjectNode node, boolean ignorePrimaryKey) throws WaarpDatabaseSqlException {
    DbValue[] list = allFields;
    if (ignorePrimaryKey) {
        list = otherFields;
    }
    for (DbValue value : list) {
        if (value.column.equalsIgnoreCase("UPDATEDINFO")) {
            continue;
        }
        JsonNode item = node.get(value.column);
        if (item != null && !item.isMissingNode() && !item.isNull()) {
            isSaved = false;
            switch (value.type) {
            case Types.VARCHAR:
            case Types.LONGVARCHAR:
                value.setValue(item.asText());
                break;
            case Types.BIT:
                value.setValue(item.asBoolean());
                break;
            case Types.TINYINT:
            case Types.SMALLINT:
            case Types.INTEGER:
                value.setValue(item.asInt());
                break;
            case Types.BIGINT:
                value.setValue(item.asLong());
                break;
            case Types.REAL:
            case Types.DOUBLE:
                value.setValue(item.asDouble());
                break;
            case Types.VARBINARY:
                try {
                    value.setValue(item.binaryValue());
                } catch (IOException e) {
                    throw new WaarpDatabaseSqlException("Issue while assigning array of bytes", e);
                }
                break;
            case Types.DATE:
                value.setValue(new Date(item.asLong()));
                break;
            case Types.TIMESTAMP:
                value.setValue(new Timestamp(item.asLong()));
                break;
            case Types.CLOB:
            case Types.BLOB:
            default:
                throw new WaarpDatabaseSqlException("Unsupported type: " + value.type);
            }
        }
    }
    setFromArray();
}

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

/**
 * Parses an ID.//from   w  w w  . j  a  v a2s.c o m
 * @param node
 * @return
 */
private Object parseId(JsonNode node) {
    if (node == null || node.isNull()) {
        return null;
    } else if (node.isDouble()) {
        return node.asDouble();
    } else if (node.isFloatingPointNumber()) {
        return node.asDouble();
    } else if (node.isInt()) {
        return node.asInt();
    } else if (node.isIntegralNumber()) {
        return node.asInt();
    } else if (node.isLong()) {
        return node.asLong();
    } else if (node.isTextual()) {
        return node.asText();
    }
    throw new IllegalArgumentException("Unknown id type");
}

From source file:com.attribyte.essem.DefaultResponseGenerator.java

protected String parseGraphAggregation(JsonNode sourceParent, List<String> fields, RateUnit rateUnit,
        ObjectNode targetMeta, ArrayNode targetGraph) {

    Iterator<Map.Entry<String, JsonNode>> iter = sourceParent.fields();
    Map.Entry<String, JsonNode> aggregation = null;

    while (iter.hasNext()) {
        aggregation = iter.next();// w ww  .ja  va2 s.  c  om
        if (aggregation.getValue().isObject()) {
            break;
        } else {
            aggregation = null;
        }
    }

    if (aggregation == null) {
        return "Aggregation is invalid";
    }

    String bucketName = aggregation.getKey();

    JsonNode obj = aggregation.getValue();
    JsonNode bucketsObj = obj.get("buckets");
    if (bucketsObj == null || !bucketsObj.isArray()) {
        return "Aggregation is invalid";
    }

    if (keyComponents.contains(bucketName)) {
        for (final JsonNode bucketObj : bucketsObj) {
            if (!bucketObj.isObject()) {
                return "Aggregation is invalid";
            }

            JsonNode keyNode = bucketObj.get(KEY_NODE_KEY);
            if (keyNode == null) {
                return "Aggregation is invalid";
            }

            targetMeta.put(translateBucketName(bucketName), keyNode.asText());
            String error = parseGraphAggregation(bucketObj, fields, rateUnit, targetMeta.deepCopy(),
                    targetGraph);
            if (error != null) {
                return error;
            }
        }
        return null;
    } else {
        ObjectNode graphObj = targetGraph.addObject();
        addAggregationMeta(graphObj, targetMeta);

        ArrayNode samplesArr = graphObj.putArray("samples");

        for (final JsonNode bucketObj : bucketsObj) {
            if (!bucketObj.isObject()) {
                return "Aggregation is invalid";
            }

            JsonNode keyNode = bucketObj.get(KEY_NODE_KEY);
            if (keyNode == null) {
                return "Aggregation is invalid";
            }

            ArrayNode sampleArr = samplesArr.addArray();
            sampleArr.add(keyNode.asLong());
            JsonNode docCountNode = bucketObj.get(SAMPLES_KEY);
            long samples = docCountNode != null ? docCountNode.asLong() : 0L;
            sampleArr.add(samples);

            for (String field : fields) {
                JsonNode fieldObj = bucketObj.get(field);
                if (fieldObj != null) {
                    JsonNode valueNode = fieldObj.get("value");
                    if (rateUnit == RAW_RATE_UNIT || valueNode == null || !rateFields.contains(field)) {
                        if (valueNode != null) {
                            sampleArr.add(valueNode);
                        } else {
                            sampleArr.add(0L);
                        }
                    } else {
                        sampleArr.add(valueNode.doubleValue() * rateUnit.mult);
                    }
                } else {
                    sampleArr.add(0L);
                }
            }
        }

        return null;
    }
}

From source file:org.level28.android.moca.json.TwitterSearchDeserializer.java

/**
 * Deserialize a JSON search result from the given {@link InputStream}.
 * /*from   ww w  .  j  av  a  2  s  .co m*/
 * @param in
 *            the input stream from which the JSON document should be parsed
 * @return a list of results with relevant search metadata
 * @throws JsonDeserializerException
 *             if the JSON document is invalid
 */
@Override
public TwitterSearchReply fromInputStream(InputStream in) throws JsonDeserializerException {
    JsonNode root;
    try {
        root = sJsonMapper.readTree(in);
    } catch (IOException e) {
        throw new JsonDeserializerException("Internal Jackson error: " + e.getMessage(), e);
    }

    // Root should be an object
    if (!root.isObject()) {
        throw new JsonDeserializerException("Root JsonNode is not an object!");
    }

    JsonNode node, resultsArray;
    TwitterSearchReply reply = new TwitterSearchReply();

    // Get all required attributes starting with the all-important results
    // array
    resultsArray = root.path("results");
    if (resultsArray.isMissingNode() || !resultsArray.isArray()) {
        throw new JsonDeserializerException("Invalid search reply (results missing or not an array)");
    }
    // We'll get to results deserialization later, continue to hunt down
    // required search reply fields

    // Original query (not really needed, just checked for sanity reasons)
    node = root.path("query");
    if (node.isMissingNode() || !node.isTextual()) {
        throw new JsonDeserializerException("'query' missing or invalid");
    }
    reply.setQuery(node.textValue());

    // Refresh url for this query
    node = root.path("refresh_url");
    if (node.isMissingNode() || !node.isTextual()) {
        throw new JsonDeserializerException("'refresh_url' missing or invalid");
    }
    reply.setRefreshUrl(node.textValue());

    // Maximum tweet id
    node = root.path("max_id");
    if (node.isMissingNode() || !node.canConvertToLong()) {
        throw new JsonDeserializerException("'max_id' missing or invalid");
    }
    reply.setMaxId(node.asLong());

    // Starting tweet id
    node = root.path("since_id");
    if (node.isMissingNode() || !node.canConvertToLong()) {
        throw new JsonDeserializerException("'since_id' missing or invalid");
    }
    reply.setSinceId(node.asLong());

    // Results per page
    node = root.path("results_per_page");
    if (node.isMissingNode() || !node.isInt()) {
        throw new JsonDeserializerException("'results_per_page' missing or invalid");
    }
    reply.setResultsPerPage(node.intValue());

    // Current page
    node = root.path("page");
    if (node.isMissingNode() || !node.isInt()) {
        throw new JsonDeserializerException("'page' missing or invalid");
    }
    reply.setPage(node.intValue());

    // Parse all results
    ArrayList<Tweet> tweets = Lists.newArrayList();
    for (JsonNode child : resultsArray) {
        tweets.add(parseSingleTweet(child));
    }
    reply.setResults(tweets);

    // Go for optional and low-priority attributes
    reply.setCompletedIn(root.path("completed_in").asDouble(666.0));
    reply.setNextPage(root.path("next_page").textValue());

    // Aaaaand we're done :-)
    return reply;
}