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

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

Introduction

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

Prototype

public long longValue() 

Source Link

Usage

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

/**
 * Compares two JsonNodes for order. Nodes containing datetime and numerical
 * values are ordered accordingly. Otherwise, the values' string
 * representation will be compared lexicographically.
 *
 * @param n1 the first node to be compared.
 * @param n2 the second node to be compared.
 * @param attributeDefinition The attribute definition of the attribute
 *                            whose values to compare or {@code null} to
 *                            compare string values using case insensitive
 *                            matching.//from ww  w.j a v a 2s . co m
 * @return a negative integer, zero, or a positive integer as the
 *         first argument is less than, equal to, or greater than the second.
 */
public static int compareTo(final JsonNode n1, final JsonNode n2,
        final AttributeDefinition attributeDefinition) {
    if (n1.isTextual() && n2.isTextual()) {
        Date d1 = dateValue(n1);
        Date d2 = dateValue(n2);
        if (d1 != null && d2 != null) {
            return d1.compareTo(d2);
        } else {
            if (attributeDefinition != null && attributeDefinition.getType() == AttributeDefinition.Type.STRING
                    && attributeDefinition.isCaseExact()) {
                return n1.textValue().compareTo(n2.textValue());
            }
            return StaticUtils.toLowerCase(n1.textValue()).compareTo(StaticUtils.toLowerCase(n2.textValue()));
        }
    }

    if (n1.isNumber() && n2.isNumber()) {
        if (n1.isBigDecimal() || n2.isBigDecimal()) {
            return n1.decimalValue().compareTo(n2.decimalValue());
        }

        if (n1.isFloatingPointNumber() || n2.isFloatingPointNumber()) {
            return Double.compare(n1.doubleValue(), n2.doubleValue());
        }

        if (n1.isBigInteger() || n2.isBigInteger()) {
            return n1.bigIntegerValue().compareTo(n2.bigIntegerValue());
        }

        return Long.compare(n1.longValue(), n2.longValue());
    }

    // Compare everything else lexicographically
    return n1.asText().compareTo(n2.asText());
}

From source file:de.fhg.fokus.odp.registry.ckan.ODRClientImpl.java

/**
 * ACHTUNG!!!<br/>//from   w  ww . j  a  v a2s .  c o m
 * Die Methode sollte nur mit bedacht genutzt werden, da Abfragen an eine CKAN-Instanz mit sehr
 * vielen Datenstzen sehr, sehr laaaaange dauern.
 */
@Override
@Deprecated
public List<Tag> getTagCounts() {
    List<Tag> tags = new ArrayList<Tag>();

    log.trace("REST > calling search api 'tag_counts' with nothing");
    long start = System.currentTimeMillis();
    JsonNode result = search.getTagCounts();
    log.debug("/api/2/tag_counts: {}ms", System.currentTimeMillis() - start);
    log.trace("REST < returns: {}", result);

    if (result != null && result.isArray()) {
        log.info("number of tags: {}", result.size());
        for (JsonNode node : result) {
            if (node.isArray()) {

                TagBean tag = new TagBean();
                TagImpl impl = new TagImpl(tag);
                for (JsonNode elem : node) {
                    if (elem.isTextual()) {
                        tag.setName(elem.textValue());
                    } else if (elem.isInt()) {
                        impl.setCount(elem.longValue());
                    }
                }
                tags.add(impl);
            }
        }
    }
    return tags;
}

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

/**
 * Deletes keys with a specified prefix older than N days.
 * @param request The request./*w  ww  .  j  a  v  a  2s .  co  m*/
 * @param index The index.
 * @param app The application name.
 * @param response The response.
 * @throws IOException on output error.
 */
protected void doKeyDelete(final HttpServletRequest request, final String index, final String app,
        final HttpServletResponse response) throws IOException {

    String prefix = Strings.nullToEmpty(request.getParameter("prefix")).trim();
    if (prefix.isEmpty()) {
        sendError(request, response, HttpServletResponse.SC_BAD_REQUEST, "A 'prefix' is required");
        return;
    }

    String host = request.getParameter("host");
    String instance = request.getParameter("instance");

    int retainDays = Util.getParameter(request, "retainDays", 0);
    boolean test = Util.getParameter(request, "test", true);

    try {

        MetricKey key = new MetricKey(prefix + "*", app, host, instance);

        URI searchURI = esEndpoint.buildIndexURI(index);
        SelectForDeleteQuery deleteQuery = new SelectForDeleteQuery(key, retainDays);
        Request esRequest = esEndpoint
                .postRequestBuilder(searchURI,
                        deleteQuery.searchRequest.toJSON().getBytes(org.apache.commons.codec.Charsets.UTF_8))
                .create();
        Response esResponse = client.send(esRequest);
        final long maxDeleted;
        int status = esResponse.getStatusCode();
        if (status == 200) {
            ObjectNode indexObject = Util.mapper
                    .readTree(Util.parserFactory.createParser(esResponse.getBody().toByteArray()));
            JsonNode hits = indexObject.path("hits").path("total");
            if (!hits.isMissingNode()) {
                maxDeleted = hits.longValue();
            } else {
                maxDeleted = 0L;
            }
        } else {
            maxDeleted = 0L;
        }

        if (status == 200 && !test) {
            URI deleteURI = esEndpoint.buildDeleteByQueryURI(index, deleteQuery.searchRequest.toJSON());
            Request esDeleteRequest = esEndpoint.deleteRequestBuilder(deleteURI).create();
            Response esDeleteResponse = client.send(esDeleteRequest);
            status = esDeleteResponse.getStatusCode();
        }

        response.setStatus(status);
        response.setContentType("text/plain");
        if (test) {
            response.getWriter().print("Would delete: " + Long.toString(maxDeleted));
        } else {
            response.getWriter().print("Deleted: " + Long.toString(maxDeleted));
        }
        response.getWriter().flush();
    } catch (Exception e) {
        sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.mapr.data.sputnik.log.Log4JLogger.java

public void printAll(String name, JsonNode node) {
    if (!node.isValueNode()) {
        Iterator<String> fieldNames = node.fieldNames();
        System.out.print("{ ");
        while (fieldNames.hasNext()) {
            String fieldName = fieldNames.next();
            JsonNode fieldValue = node.get(fieldName);
            if (fieldValue.isArray()) {
                System.out.print(fieldName + " [ ");
                List<String> a = new ArrayList<>(1);
                Iterator<JsonNode> itr = fieldValue.iterator();
                while (itr.hasNext()) {
                    JsonNode n = itr.next();
                    printAll(fieldName, n);
                    System.out.print(", ");
                }//from ww  w  .  j a  v a2  s  .  c om
                System.out.print(" ] ");
            } else {
                printAll(fieldName, fieldValue);
                System.out.print(", ");
            }
        }
        System.out.print(" } ");
    } else {
        Iterator<Entry<String, JsonNode>> itParams = node.fields();
        while (itParams.hasNext()) {
            Entry<String, JsonNode> elt = itParams.next();
            System.out.println(elt.getKey());
        }
        if (node.isInt()) {
            System.out.print(name + " : " + node.intValue());
        } else if (node.isDouble()) {
            System.out.print(name + " : " + node.doubleValue());
        } else if (node.isTextual()) {
            System.out.print(name + " : " + node.textValue());
        } else if (node.isLong()) {
            System.out.print(name + " : " + node.longValue());
        } else
            System.out.print(name + " : " + node.textValue());

    }

}

From source file:org.apache.parquet.cli.json.AvroJson.java

public static Object convertToAvro(GenericData model, JsonNode datum, Schema schema) {
    if (datum == null) {
        return null;
    }//from  w w  w  .  jav  a 2 s.  c o m
    switch (schema.getType()) {
    case RECORD:
        RecordException.check(datum.isObject(), "Cannot convert non-object to record: %s", datum);
        Object record = model.newRecord(null, schema);
        for (Schema.Field field : schema.getFields()) {
            model.setField(record, field.name(), field.pos(),
                    convertField(model, datum.get(field.name()), field));
        }
        return record;

    case MAP:
        RecordException.check(datum.isObject(), "Cannot convert non-object to map: %s", datum);
        Map<String, Object> map = Maps.newLinkedHashMap();
        Iterator<Map.Entry<String, JsonNode>> iter = datum.fields();
        while (iter.hasNext()) {
            Map.Entry<String, JsonNode> entry = iter.next();
            map.put(entry.getKey(), convertToAvro(model, entry.getValue(), schema.getValueType()));
        }
        return map;

    case ARRAY:
        RecordException.check(datum.isArray(), "Cannot convert to array: %s", datum);
        List<Object> list = Lists.newArrayListWithExpectedSize(datum.size());
        for (JsonNode element : datum) {
            list.add(convertToAvro(model, element, schema.getElementType()));
        }
        return list;

    case UNION:
        return convertToAvro(model, datum, resolveUnion(datum, schema.getTypes()));

    case BOOLEAN:
        RecordException.check(datum.isBoolean(), "Cannot convert to boolean: %s", datum);
        return datum.booleanValue();

    case FLOAT:
        RecordException.check(datum.isFloat() || datum.isInt(), "Cannot convert to float: %s", datum);
        return datum.floatValue();

    case DOUBLE:
        RecordException.check(datum.isDouble() || datum.isFloat() || datum.isLong() || datum.isInt(),
                "Cannot convert to double: %s", datum);
        return datum.doubleValue();

    case INT:
        RecordException.check(datum.isInt(), "Cannot convert to int: %s", datum);
        return datum.intValue();

    case LONG:
        RecordException.check(datum.isLong() || datum.isInt(), "Cannot convert to long: %s", datum);
        return datum.longValue();

    case STRING:
        RecordException.check(datum.isTextual(), "Cannot convert to string: %s", datum);
        return datum.textValue();

    case ENUM:
        RecordException.check(datum.isTextual(), "Cannot convert to string: %s", datum);
        return model.createEnum(datum.textValue(), schema);

    case BYTES:
        RecordException.check(datum.isBinary(), "Cannot convert to binary: %s", datum);
        try {
            return ByteBuffer.wrap(datum.binaryValue());
        } catch (IOException e) {
            throw new RecordException("Failed to read JSON binary", e);
        }

    case FIXED:
        RecordException.check(datum.isBinary(), "Cannot convert to fixed: %s", datum);
        byte[] bytes;
        try {
            bytes = datum.binaryValue();
        } catch (IOException e) {
            throw new RecordException("Failed to read JSON binary", e);
        }
        RecordException.check(bytes.length < schema.getFixedSize(), "Binary data is too short: %s bytes for %s",
                bytes.length, schema);
        return model.createFixed(null, bytes, schema);

    case NULL:
        return null;

    default:
        // don't use DatasetRecordException because this is a Schema problem
        throw new IllegalArgumentException("Unknown schema type: " + schema);
    }
}

From source file:com.unboundid.scim2.common.GenericScimResource.java

/**
 * Gets a Long value from a generic SCIM resource.  If the path exists,
 * the JSON node at the path must be a Long.  If the path does not exist,
 * "{@code null}" will be returned.// w  w  w .ja va  2  s.  c om
 *   <p>
 *
 * For example:
 *   In a GenericScimResource (gsr) representing the following resource:
 * <pre><code>
 *   {
 *     "path1":7
 *   }
 * </code></pre>
 *   <p>
 *
 *   getLongValue(Path.fromString("path1"))
 *   returns 7
 *   <p>
 *
 *   getLongValue(Path.fromString("bogusPath"))
 *   returns null
 *
 * @param path the path to get the value from.
 * @return the value at the path, or null.
 * @throws ScimException thrown if an error occurs.
 */
public Long getLongValue(final Path path) throws ScimException {
    JsonNode jsonNode = getValue(path);
    return jsonNode.isNull() ? null : jsonNode.longValue();
}