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:com.crushpaper.JsonNodeHelper.java

/**
 * Returns the long value for the key, false if it does not exist, or throws
 * an exception if the value is not a long.
 * //from   w w  w.ja v a 2s . c  om
 * @throws IOException
 */
public Long getLong(String key) throws IOException {
    JsonNode value = node.get(key);

    if (value == null) {
        return null;
    }

    if (!value.isNumber()) {
        throw new IOException();
    }

    return value.asLong();
}

From source file:com.monarchapis.driver.configuration.JsonConfiguration.java

@Override
@SuppressWarnings("unchecked")
public Optional<Long> getLong(String path) {
    JsonNode node = getPathNode(path);

    if (node.isInt()) {
        return Optional.of((long) node.asInt());
    }/*w w  w . j ava 2s . com*/

    return (Optional<Long>) (!node.isLong() ? Optional.absent() : Optional.of(node.asLong()));
}

From source file:com.marklogic.samplestack.web.QnADocumentController.java

/**
 * Exposes an endpoint for searching QnADocuments.
 * @param structuredQuery A JSON structured query.
 * @param start The index of the first result to return.
 * @return A Search Results JSON response.
 *//*from  ww  w . j  a  v a 2 s  .  c  o m*/
@RequestMapping(value = "search", method = RequestMethod.POST)
public @ResponseBody JsonNode search(@RequestBody ObjectNode structuredQuery,
        @RequestParam(defaultValue = "1", required = false) long start) {

    JsonNode postedStartNode = structuredQuery.get("start");
    if (postedStartNode != null) {
        start = postedStartNode.asLong();
        structuredQuery.remove("start");
    }
    return qnaService.rawSearch(ClientRole.securityContextRole(), structuredQuery, start);
}

From source file:com.redhat.lightblue.crud.validator.MinMaxCheckerTest.java

protected JsonNode mockFieldValue(JsonNode mock, int value) {
    if ((number instanceof Integer) || (number instanceof Byte) || (number instanceof Short)
            || (number instanceof Long)) {
        when(mock.asLong()).thenReturn(new Long(value));
    } else if ((number instanceof Float) || (number instanceof Double)) {
        when(mock.asDouble()).thenReturn(new Double(value));
    } else if (number instanceof BigInteger) {
        when(mock.bigIntegerValue()).thenReturn(new BigInteger(String.valueOf(value)));
    } else if (number instanceof BigDecimal) {
        when(mock.decimalValue()).thenReturn(new BigDecimal(value));
    } else {/*from  w ww. j a  v a 2s. c  om*/
        throw new IllegalArgumentException("Not a supported Number type: " + number.getClass());
    }

    return mock;
}

From source file:com.monarchapis.driver.model.Claims.java

@SuppressWarnings("unchecked")
public Optional<Long> getLong(String... path) {
    JsonNode node = getPathNode(path);

    if (node.isInt()) {
        return Optional.of((long) node.asInt());
    }/*from w  ww.j  av a 2  s.  c  o  m*/

    return (Optional<Long>) (!node.isLong() ? Optional.absent() : Optional.of(node.asLong()));
}

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

private String parseGraphAggregation(JsonNode sourceParent, List<String> fields, EnumSet<Option> options,
        RateUnit rateUnit, ArrayNode targetGraph) {

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

    while (iter.hasNext()) {
        aggregation = iter.next();/*from w w w .  ja  v  a  2s.  co m*/
        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";
            }

            String error = parseGraphAggregation(bucketObj, fields, options, rateUnit, targetGraph);
            if (error != null) {
                return error;
            }
        }
        return null;
    } else {
        SimpleDateFormat formatter = new SimpleDateFormat(DT_FORMAT);
        boolean allowEmptyBins = options.contains(Option.EMPTY_BINS);

        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";
            }

            JsonNode docCountNode = bucketObj.get(SAMPLES_KEY);
            long samples = docCountNode != null ? docCountNode.asLong() : 0L;

            if (allowEmptyBins || samples > 0L) {

                ObjectNode sampleObj = targetGraph.addObject();
                sampleObj.put("timestamp", keyNode.asLong());
                sampleObj.put("date", formatter.format(keyNode.asLong()));
                sampleObj.put("samples", samples);

                for (String field : fields) {
                    JsonNode fieldObj = bucketObj.get(field);
                    if (fieldObj != null) {
                        JsonNode valueNode = fieldObj.get("value");
                        if (valueNode != null) {
                            if (!valueNode.isNull()) {
                                setFieldValue(rateUnit, sampleObj, field, valueNode);
                            }
                        }
                    }
                }
            }
        }
        return null;
    }
}

From source file:org.dswarm.graph.json.deserializer.StatementDeserializer.java

@Override
public Statement deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException {

    final ObjectCodec oc = jp.getCodec();

    if (oc == null) {

        return null;
    }//w w  w. j  av  a2 s.c o  m

    final JsonNode node = oc.readTree(jp);

    if (node == null) {

        return null;
    }

    final JsonNode idNode = node.get("id");

    Long id = null;

    if (idNode != null) {

        try {

            id = idNode.asLong();
        } catch (final Exception e) {

            id = null;
        }
    }

    final JsonNode uuidNode = node.get("uuid");

    String uuid = null;

    if (uuidNode != null && JsonNodeType.NULL != uuidNode.getNodeType()) {

        uuid = uuidNode.asText();
    }

    final JsonNode subjectNode = node.get("s");

    if (subjectNode == null) {

        throw new JsonParseException("expected JSON node that represents the subject of a statement",
                jp.getCurrentLocation());
    }

    final Node subject;

    if (subjectNode.get("uri") != null) {

        // resource node
        subject = subjectNode.traverse(oc).readValueAs(ResourceNode.class);
    } else {

        // bnode
        subject = subjectNode.traverse(oc).readValueAs(Node.class);
    }

    final JsonNode predicateNode = node.get("p");

    if (predicateNode == null) {

        throw new JsonParseException("expected JSON node that represents the predicate of a statement",
                jp.getCurrentLocation());
    }

    final Predicate predicate = predicateNode.traverse(oc).readValueAs(Predicate.class);

    final JsonNode objectNode = node.get("o");

    if (objectNode == null) {

        throw new JsonParseException("expected JSON node that represents the object of a statement",
                jp.getCurrentLocation());
    }

    final Node object;

    if (objectNode.get("uri") != null) {

        // resource node
        object = objectNode.traverse(oc).readValueAs(ResourceNode.class);
    } else if (objectNode.get("v") != null) {

        // literal node
        object = objectNode.traverse(oc).readValueAs(LiteralNode.class);
    } else {

        // bnode
        object = objectNode.traverse(oc).readValueAs(Node.class);
    }

    final JsonNode orderNode = node.get("order");

    Long order = null;

    if (orderNode != null) {

        try {

            order = orderNode.asLong();
        } catch (final Exception e) {

            order = null;
        }
    }

    final JsonNode evidenceNode = node.get("evidence");

    String evidence = null;

    if (evidenceNode != null) {

        evidence = evidenceNode.asText();
    }

    final JsonNode confidenceNode = node.get("confidence");

    String confidence = null;

    if (confidenceNode != null) {

        confidence = confidenceNode.asText();
    }

    final Statement statement = new Statement(subject, predicate, object);

    if (id != null) {

        statement.setId(id);
    }

    if (uuid != null) {

        statement.setUUID(uuid);
    }

    if (order != null) {

        statement.setOrder(order);
    }

    if (evidence != null) {

        statement.setEvidence(evidence);
    }

    if (confidence != null) {

        statement.setConfidence(confidence);
    }

    return statement;
}

From source file:com.ottogroup.bi.asap.operator.json.aggregator.JsonContentAggregator.java

/**
 * Walks along the path provided and reads out the leaf value which is returned as long value
 * @param jsonNode/*from  www  . j  av a  2s  .  c  o  m*/
 * @param fieldPath
 * @return
 */
protected long getNumericalFieldValue(final JsonNode jsonNode, final String[] fieldPath) {

    int fieldAccessStep = 0;
    JsonNode contentNode = jsonNode;
    while (fieldAccessStep < fieldPath.length) {
        contentNode = contentNode.get(fieldPath[fieldAccessStep]);
        fieldAccessStep++;
    }

    return contentNode.asLong();
}

From source file:com.squarespace.template.Instructions.java

private static void emitJsonNode(StringBuilder buf, JsonNode node) {
    if (node.isNumber()) {
        // Formatting of numbers depending on type
        switch (node.numberType()) {
        case BIG_INTEGER:
            buf.append(((BigIntegerNode) node).bigIntegerValue().toString());
            break;

        case BIG_DECIMAL:
            buf.append(((DecimalNode) node).decimalValue().toPlainString());
            break;

        case INT:
        case LONG:
            buf.append(node.asLong());
            break;

        case FLOAT:
        case DOUBLE:
            double val = node.asDouble();
            buf.append(Double.toString(val));
            break;

        default://ww w. j  ava  2  s.c o  m
            break;
        }

    } else if (node.isArray()) {
        // JavaScript Array.toString() will comma-delimit the elements.
        for (int i = 0, size = node.size(); i < size; i++) {
            if (i >= 1) {
                buf.append(",");
            }
            buf.append(node.path(i).asText());
        }

    } else if (!node.isNull() && !node.isMissingNode()) {
        buf.append(node.asText());
    }
}

From source file:org.waarp.gateway.kernel.rest.DbTransferLogDataModelRestMethodHandler.java

@Override
protected DbTransferLog getItem(HttpRestHandler handler, RestArgument arguments, RestArgument result,
        Object body)// ww  w  .  j a v  a  2 s  .  co m
        throws HttpIncorrectRequestException, HttpInvalidAuthenticationException, HttpNotFoundRequestException {
    ObjectNode arg = arguments.getUriArgs().deepCopy();
    arg.setAll(arguments.getBody());
    try {
        JsonNode node = RestArgument.getId(arg);
        long id;
        if (node.isMissingNode()) {
            // shall not be but continue however
            id = arg.path(DbTransferLog.Columns.SPECIALID.name()).asLong();
        } else {
            id = node.asLong();
        }
        return new DbTransferLog(handler.getDbSession(), user, account, id);
    } catch (WaarpDatabaseException e) {
        throw new HttpNotFoundRequestException("Issue while reading from database " + arg, e);
    }
}