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:org.elasticsearch.river.solr.SolrRiver.java

@Override
public void start() {

    if (!client.admin().indices().prepareExists(indexName).execute().actionGet().isExists()) {

        CreateIndexRequestBuilder createIndexRequest = client.admin().indices().prepareCreate(indexName);

        if (settings != null) {
            createIndexRequest.setSettings(settings);
        }/*from w w  w . j  av a2s.c o  m*/
        if (mapping != null) {
            createIndexRequest.addMapping(typeName, mapping);
        }

        createIndexRequest.execute().actionGet();
    }

    StringBuilder baseSolrQuery = createSolrQuery();

    Long numFound = null;
    int startParam;
    while ((startParam = start.getAndAdd(rows)) == 0 || startParam < numFound) {
        String solrQuery = baseSolrQuery.toString() + "&start=" + startParam;
        CloseableHttpResponse httpResponse = null;
        try {
            logger.info("Sending query to Solr: {}", solrQuery);
            httpResponse = httpClient.execute(new HttpGet(solrQuery));

            if (httpResponse.getStatusLine().getStatusCode() != 200) {
                logger.error("Solr returned non ok status code: {}",
                        httpResponse.getStatusLine().getReasonPhrase());
                EntityUtils.consume(httpResponse.getEntity());
                continue;
            }

            JsonNode jsonNode = objectMapper.readTree(EntityUtils.toString(httpResponse.getEntity()));
            JsonNode response = jsonNode.get("response");
            JsonNode numFoundNode = response.get("numFound");
            numFound = numFoundNode.asLong();
            if (logger.isWarnEnabled() && numFound == 0) {
                logger.warn("The solr query {} returned 0 documents", solrQuery);
            }

            Iterator<JsonNode> docsIterator = response.get("docs").iterator();

            while (docsIterator.hasNext()) {
                JsonNode docNode = docsIterator.next();

                try {
                    JsonNode uniqueKeyNode = docNode.get(uniqueKey);

                    if (uniqueKeyNode == null) {
                        logger.error("The uniqueKey value is null");
                    } else {
                        String id = uniqueKeyNode.asText();
                        ((ObjectNode) docNode).remove(uniqueKey);

                        IndexRequest indexRequest = Requests.indexRequest(indexName).type(typeName).id(id);
                        String source = objectMapper.writeValueAsString(docNode);
                        if (this.script == null) {
                            indexRequest.source(source);
                        } else {
                            Tuple<XContentType, Map<String, Object>> newSourceAndContent = transformDocument(
                                    source);
                            indexRequest.source(newSourceAndContent.v2(), newSourceAndContent.v1());
                        }

                        bulkProcessor.add(indexRequest);

                    }
                } catch (IOException e) {
                    logger.warn("Error while importing documents from solr to elasticsearch", e);
                }
            }
        } catch (IOException e) {
            logger.error("Error while executing the solr query [" + solrQuery + "]", e);
            bulkProcessor.close();
            try {
                httpClient.close();
            } catch (IOException ioe) {
                logger.warn(e.getMessage(), ioe);
            }
            //if a query fails the next ones are most likely going to fail too
            return;
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }

    bulkProcessor.close();
    try {
        httpClient.close();
    } catch (IOException e) {
        logger.warn(e.getMessage(), e);
    }

    logger.info("Data import from solr to elasticsearch completed");

    if (closeOnCompletion) {
        logger.info("Deleting river");
        client.admin().indices().prepareDeleteMapping("_river").setType(riverName.name()).execute();
    }
}

From source file:org.createnet.raptor.models.data.types.NumberRecord.java

@Override
public Number parseValue(Object value) {
    try {//ww  w  . jav a  2 s  .co m

        if (value instanceof Number) {
            return (Number) value;
        }

        if (value instanceof JsonNode) {

            JsonNode node = (JsonNode) value;

            if (node.isNumber()) {

                if (node.isInt() || node.isShort()) {
                    return (Number) node.asInt();
                }

                if (node.isDouble() || node.isFloat()) {
                    return (Number) node.asDouble();
                }

                if (node.isLong()) {
                    return (Number) node.asLong();
                }
            }

            if (node.isTextual()) {
                value = node.asText();
            }

        }

        NumberFormat formatter = NumberFormat.getInstance();
        ParsePosition pos = new ParsePosition(0);
        Number numVal = formatter.parse((String) value, pos);

        return numVal;
    } catch (Exception e) {
        throw new RaptorComponent.ParserException(e);
    }
}

From source file:org.waarp.openr66.protocol.http.rest.handler.DbTaskRunnerR66RestMethodHandler.java

protected DbTaskRunner getItem(HttpRestHandler handler, RestArgument arguments, RestArgument result,
        Object body)//ww  w .  j a v  a  2s  .com
        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(DbTaskRunner.Columns.SPECIALID.name()).asLong();
        } else {
            id = node.asLong();
        }
        return new DbTaskRunner(handler.getDbSession(), id,
                arg.path(DbTaskRunner.Columns.REQUESTER.name()).asText(),
                arg.path(DbTaskRunner.Columns.REQUESTED.name()).asText(),
                arg.path(DbTaskRunner.Columns.OWNERREQ.name()).asText());
    } catch (WaarpDatabaseException e) {
        throw new HttpNotFoundRequestException("Issue while reading from database " + arg, e);
    }
}

From source file:org.hawkular.metrics.clients.ptrans.backend.RestForwardingHandlerITest.java

private boolean expectedMetricIsPresent(SingleMetric metric, JsonNode jsonNode) {
    assertTrue("Data is not an array", jsonNode.isArray());

    for (JsonNode numericData : jsonNode) {
        JsonNode timestamp = numericData.get("timestamp");
        assertNotNull("Numeric data has no timestamp attribute", timestamp);
        assertTrue("Timestamp is not a number", timestamp.isNumber());
        JsonNode value = numericData.get("value");
        assertNotNull("Numeric data has no value attribute", value);
        assertTrue("Value is not a floating point number", value.isFloatingPointNumber());

        if (timestamp.asLong() == metric.getTimestamp() && value.asDouble() == metric.getValue()) {
            return true;
        }//from w  w w. j  a va  2 s .c  o m
    }
    return false;
}

From source file:com.vaushell.superpipes.tools.scribe.twitter.TwitterClient.java

/**
 * Delete a tweet.//from   ww w .  j a va  2  s  . c om
 *
 * @param ID Tweet ID
 * @return True if successfull
 * @throws IOException
 * @throws com.vaushell.superpipes.tools.scribe.OAuthException
 */
public boolean deleteTweet(final long ID) throws IOException, OAuthException {
    if (ID < 0) {
        throw new IllegalArgumentException();
    }

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("[" + getClass().getSimpleName() + "] deleteTweet() : ID=" + ID);
    }

    final OAuthRequest request = new OAuthRequest(Verb.POST,
            "https://api.twitter.com/1.1/statuses/destroy/" + ID + ".json");

    final Response response = sendSignedRequest(request);

    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode node = (JsonNode) mapper.readTree(response.getStream());

    checkErrors(response, node);

    final JsonNode nodeID = node.get("id");
    if (nodeID == null) {
        return false;
    } else {
        return ID == nodeID.asLong();
    }
}

From source file:org.schedoscope.export.kafka.avro.HCatToAvroRecordConverter.java

private List<Object> convertArray(JsonNode json, Schema schema) throws IOException {

    List<Object> res = new ArrayList<>();
    Iterator<JsonNode> it = json.elements();

    while (it.hasNext()) {

        JsonNode n = it.next();
        if (!n.isNull()) {
            for (Schema s : schema.getElementType().getTypes()) {
                if (s.getType().equals(Schema.Type.STRING)) {
                    res.add(n.asText());
                } else if (s.getType().equals(Schema.Type.INT)) {
                    res.add(n.asInt());//  w w w. j a  v  a 2s  .  co m
                } else if (s.getType().equals(Schema.Type.LONG)) {
                    res.add(n.asLong());
                } else if (s.getType().equals(Schema.Type.BOOLEAN)) {
                    res.add(n.asBoolean());
                } else if (s.getType().equals(Schema.Type.DOUBLE)) {
                    res.add(n.asDouble());
                } else if (s.getType().equals(Schema.Type.FLOAT)) {
                    res.add(n.asDouble());
                } else if (s.getType().equals(Schema.Type.RECORD)) {
                    res.add(convertRecord(n, s));
                } else if (s.getType().equals(Schema.Type.ARRAY)) {
                    res.addAll(convertArray(n, s));
                } else if (s.getType().equals(Schema.Type.MAP)) {
                    res.add(convertMap(n, s));
                }
            }
        }
    }
    return res;
}

From source file:org.springframework.data.rest.webmvc.json.patch.JsonPatchPatchConverter.java

private Object valueFromJsonNode(String path, JsonNode valueNode) {
    if (valueNode == null || valueNode.isNull()) {
        return null;
    } else if (valueNode.isTextual()) {
        return valueNode.asText();
    } else if (valueNode.isFloatingPointNumber()) {
        return valueNode.asDouble();
    } else if (valueNode.isBoolean()) {
        return valueNode.asBoolean();
    } else if (valueNode.isInt()) {
        return valueNode.asInt();
    } else if (valueNode.isLong()) {
        return valueNode.asLong();
    } else if (valueNode.isObject()) {
        return new JsonLateObjectEvaluator(valueNode);
    } else if (valueNode.isArray()) {
        // TODO: Convert valueNode to array
    }/*from   ww  w  .j  a v  a2  s  .c om*/

    return null;
}

From source file:org.opendaylight.nemo.renderer.openflow.physicalnetwork.PhyConfigLoaderTest.java

@Test
public PhysicalLink testBuildLink(JsonNode arg) throws Exception {
    if (arg == null)
        return null;

    PhysicalLink physicalLink = mock(PhysicalLink.class);
    JsonNode jsonNode = mock(JsonNode.class);
    JsonNode jsonNode1 = mock(JsonNode.class);

    Class<PhyConfigLoader> class1 = PhyConfigLoader.class;
    Method method = class1.getDeclaredMethod("buildLink", new Class[] { JsonNode.class });
    method.setAccessible(true);//from  w w w  .j a v a2 s  .  c o  m

    when(jsonNode.get(any(String.class))).thenReturn(jsonNode1).thenReturn(jsonNode1);
    when(jsonNode1.asText()).thenReturn(new String("test"));
    when(jsonNode1.asLong()).thenReturn((long) 1);

    physicalLink = (PhysicalLink) method.invoke(phyConfigLoader, jsonNode);
    Assert.assertTrue(physicalLink != null);
    Assert.assertTrue(physicalLink != mock(PhysicalLink.class));

    return physicalLink;
}

From source file:uk.ac.imperial.presage2.db.json.JsonStorage.java

private <T> T returnAsType(JsonNode n, Class<T> type) {
    if (type == String.class)
        return type.cast(n.textValue());
    else if (type == Integer.class || type == Integer.TYPE)
        return type.cast(n.asInt());
    else if (type == Double.class || type == Double.TYPE)
        return type.cast(n.asDouble());
    else if (type == Boolean.class || type == Boolean.TYPE)
        return type.cast(n.asBoolean());
    else if (type == Long.class || type == Long.TYPE)
        return type.cast(n.asLong());

    throw new RuntimeException("Unknown type cast request");
}

From source file:org.walkmod.conf.entities.JSONConfigParser.java

public Map<String, Object> getParams(JsonNode next) {
    if (next.has("params")) {
        Iterator<Entry<String, JsonNode>> it2 = next.get("params").fields();
        Map<String, Object> params = new HashMap<String, Object>();
        while (it2.hasNext()) {
            Entry<String, JsonNode> param = it2.next();
            JsonNode value = param.getValue();
            if (value.isTextual()) {
                params.put(param.getKey(), value.asText());
            } else if (value.isInt()) {
                params.put(param.getKey(), value.asInt());
            } else if (value.isBoolean()) {
                params.put(param.getKey(), value.asBoolean());
            } else if (value.isDouble() || value.isFloat() || value.isBigDecimal()) {
                params.put(param.getKey(), value.asDouble());
            } else if (value.isLong() || value.isBigInteger()) {
                params.put(param.getKey(), value.asLong());
            } else {
                params.put(param.getKey(), value);
            }//from   w  w w. j av  a2  s . c o m
            params.put(param.getKey(), param.getValue().asText());
        }
        return params;

    }
    return null;
}