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.redhat.lightblue.crud.validator.MinMaxChecker.java

private int cmp(JsonNode node, Number value) {
    if (value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long) {
        return cmp(node.asLong(), value.longValue());
    } else if (value instanceof Float || value instanceof Double) {
        return cmp(node.asDouble(), value.doubleValue());
    } else if (value instanceof BigInteger) {
        return cmp(node.bigIntegerValue(), (BigInteger) value);
    } else {// w  w w. ja va  2s. c o  m
        return cmp(node.decimalValue(), (BigDecimal) value);
    }
}

From source file:com.ikanow.aleph2.graph.titan.utils.TitanGraphBuildingUtils.java

/** Inserts a single-valued vertex property into a JSON object
 * @param f/*  w  ww. j  a va  2s . co  m*/
 * @param vp
 * @param o
 * @return
 */
protected static Object jsonNodeToObject(final JsonNode j) {
    return Patterns.match().<Object>andReturn().when(() -> null == j, () -> j)
            .when(() -> j.isTextual(), () -> j.asText()).when(() -> j.isDouble(), () -> j.asDouble())
            .when(() -> j.isIntegralNumber(), () -> j.asLong()).when(() -> j.isBoolean(), () -> j.asBoolean())
            .otherwise(__ -> null);
}

From source file:com.forgerock.wisdom.oauth2.info.internal.StandardIntrospectionService.java

@Override
public TokenInfo introspect(final String token) {

    try {/*from  w w  w . j a  v  a  2 s  . c  om*/
        HttpURLConnection connection = (HttpURLConnection) new URL(baseUrl).openConnection();
        connection.getOutputStream().write(format("token=%s", token).getBytes());
        connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setDoOutput(true);
        if (bearerToken != null) {
            connection.addRequestProperty("Authorization", format("Bearer %s", bearerToken));
        }
        int code = connection.getResponseCode();
        if (code != 200) {
            return TokenInfo.INVALID;
        }

        try (InputStream stream = connection.getInputStream()) {
            JsonNode node = mapper.readTree(stream);
            if (node.get("active").asBoolean()) {

                JsonNode exp = node.get("exp");
                long expiresIn = 0;
                if (exp != null) {
                    expiresIn = exp.asLong() - System.currentTimeMillis();
                }

                JsonNode scope = node.get("scope");
                String[] scopes = null;
                if (scope != null) {
                    scopes = scope.asText().split(" ");
                }

                return new TokenInfo(true, expiresIn, scopes);
            }
        }

    } catch (IOException e) {
        // Ignored
    }

    return TokenInfo.INVALID;
}

From source file:com.spotify.ffwd.json.JsonObjectMapperDecoder.java

private long decodeTtl(JsonNode tree, String name) {
    final JsonNode n = tree.get(name);

    if (n == null)
        return 0;

    return n.asLong();
}

From source file:org.jasig.portlet.survey.service.dto.ResponseAnswerDtoDeserializer.java

@Override
public ResponseAnswerDTO deserialize(JsonParser parser, DeserializationContext context)
        throws IOException, JsonProcessingException {
    log.debug("deserializing responseAnswer JSON");
    JsonNode node = parser.getCodec().readTree(parser);
    ResponseAnswerDTO dto = new ResponseAnswerDTO();

    JsonNode questionNode = node.get("question");
    log.debug(questionNode.toString());//from   w w w  .  j a v a2s  . c o m
    if (questionNode != null && questionNode.canConvertToLong()) {
        Long questionId = questionNode.asLong();
        dto.setQuestion(questionId);
    } else {
        throw new IllegalArgumentException("ResponseAnswer Json missing/bad question field");
    }

    JsonNode answerNode = node.get("answer");
    if (answerNode == null) {
        throw new IllegalArgumentException("ResponseAnswer Json missing answer field");
    }
    if (answerNode.canConvertToLong()) {
        dto.addAnswerId(answerNode.asLong());
    } else if (answerNode.isObject()) {
        for (Iterator<Entry<String, JsonNode>> fields = answerNode.fields(); fields.hasNext();) {
            Entry<String, JsonNode> field = fields.next();
            Long answerId = Long.parseLong(field.getKey());
            assert (field.getValue().isBoolean());
            boolean answerSelected = field.getValue().asBoolean(false);
            if (answerSelected) {
                dto.addAnswerId(answerId);
            }
        }
    } else {
        throw new IllegalArgumentException("ResponseAnswer Json bad answer argument field");
    }

    return dto;
}

From source file:com.spotify.ffwd.json.JsonObjectMapperDecoder.java

private Date decodeTime(JsonNode tree, String name) {
    final JsonNode n = tree.get(name);

    if (n == null)
        return null;

    final long time = n.asLong();
    return new Date(time);
}

From source file:com.cloudmine.api.persistance.CMJacksonModule.java

public CMJacksonModule() {
    super("CustomModule", new Version(1, 0, 0, null));
    addSerializer(new JsonSerializer<Date>() {

        @Override// ww w .  ja  v  a 2  s .  co  m
        public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider)
                throws IOException, JsonProcessingException {
            jgen.writeStartObject();
            jgen.writeRaw(JsonUtilities.convertDateToUnwrappedJsonClass(value));
            jgen.writeEndObject();
        }

        @Override
        public Class<Date> handledType() {
            return Date.class;
        }
    });

    addDeserializer(Date.class, new JsonDeserializer<Date>() {
        @Override
        public Date deserialize(JsonParser jp, DeserializationContext ctxt)
                throws IOException, JsonProcessingException {
            ObjectMapper mapper = (ObjectMapper) jp.getCodec();
            ObjectNode root = (ObjectNode) mapper.readTree(jp);
            JsonNode classNode = root.get(JsonUtilities.CLASS_KEY);
            boolean isDate = classNode != null && JsonUtilities.DATE_CLASS.equals(classNode.asText());
            if (isDate) {
                JsonNode timeNode = root.get(JsonUtilities.TIME_KEY);
                if (timeNode != null) {
                    Long seconds = timeNode.asLong();
                    Date date = new Date(seconds * 1000);
                    return date;
                }
            }
            return null;
        }
    });
    addSerializer(new JsonSerializer<SimpleCMObject>() {

        @Override
        public void serialize(SimpleCMObject value, JsonGenerator jgen, SerializerProvider provider)
                throws IOException {
            jgen.writeStartObject();
            String json = null;
            try {
                json = value.asUnkeyedObject();
            } catch (ConversionException e) {
                LOG.error("Error while serializing, sending empty json", e);
                json = JsonUtilities.EMPTY_JSON;
            }
            jgen.writeRaw(JsonUtilities.unwrap(json));
            jgen.writeEndObject();
        }

        @Override
        public Class<SimpleCMObject> handledType() {
            return SimpleCMObject.class;
        }
    });

    addSerializer(jsonSerializerForType(CMFile.class));
    addSerializer(jsonSerializerForType(CMSessionToken.class));
    addSerializer(jsonSerializerForType(CMType.class));
    addSerializer(jsonSerializerForType(TransportableString.class));
    addSerializer(jsonSerializerForType(ResponseBase.class));

}

From source file:io.appform.jsonrules.expressions.numeric.NumericJsonPathBasedExpression.java

@Override
protected final boolean evaluate(ExpressionEvaluationContext context, String path, JsonNode evaluatedNode) {
    if (null == evaluatedNode || !evaluatedNode.isNumber()) {
        return false;
    }/*  www  .  j  a  v a2 s.  c  om*/
    int comparisonResult = 0;
    if (evaluatedNode.isIntegralNumber()) {
        comparisonResult = Long.compare(evaluatedNode.asLong(), value.longValue());
    } else if (evaluatedNode.isFloatingPointNumber()) {
        comparisonResult = Double.compare(evaluatedNode.asDouble(), value.doubleValue());
    }
    return evaluate(context, comparisonResult);
}

From source file:org.springframework.social.twitter.api.impl.TweetDeserializer.java

public Tweet deserialize(JsonNode node) throws IOException, JsonProcessingException {
    final long id = node.path("id").asLong();
    final String text = node.path("text").asText();
    if (id <= 0 || text == null || text.isEmpty()) {
        return null;
    }//from  www.j  a va2 s.  c om
    JsonNode fromUserNode = node.get("user");
    String dateFormat = TIMELINE_DATE_FORMAT;
    String fromScreenName = fromUserNode.get("screen_name").asText();
    long fromId = fromUserNode.get("id").asLong();
    String fromImageUrl = fromUserNode.get("profile_image_url").asText();
    Date createdAt = toDate(node.get("created_at").asText(), new SimpleDateFormat(dateFormat, Locale.ENGLISH));
    String source = node.get("source").asText();
    JsonNode toUserIdNode = node.get("in_reply_to_user_id");
    Long toUserId = toUserIdNode != null ? toUserIdNode.asLong() : null;
    String languageCode = node.get("lang").asText();
    Tweet tweet = new Tweet(id, text, createdAt, fromScreenName, fromImageUrl, toUserId, fromId, languageCode,
            source);
    JsonNode inReplyToStatusIdNode = node.get("in_reply_to_status_id");
    Long inReplyToStatusId = inReplyToStatusIdNode != null && !inReplyToStatusIdNode.isNull()
            ? inReplyToStatusIdNode.asLong()
            : null;
    tweet.setInReplyToStatusId(inReplyToStatusId);
    JsonNode inReplyToUserIdNode = node.get("in_reply_to_user_id");
    Long inReplyUsersId = inReplyToUserIdNode != null && !inReplyToUserIdNode.isNull()
            ? inReplyToUserIdNode.asLong()
            : null;
    tweet.setInReplyToUserId(inReplyUsersId);
    tweet.setInReplyToScreenName(node.path("in_reply_to_screen_name").asText());
    JsonNode retweetCountNode = node.get("retweet_count");
    Integer retweetCount = retweetCountNode != null && !retweetCountNode.isNull() ? retweetCountNode.asInt()
            : null;
    tweet.setRetweetCount(retweetCount);
    JsonNode retweetedNode = node.get("retweeted");
    JsonNode retweetedStatusNode = node.get("retweeted_status");
    boolean retweeted = retweetedNode != null && !retweetedNode.isNull() ? retweetedNode.asBoolean() : false;
    tweet.setRetweeted(retweeted);
    Tweet retweetedStatus = retweetedStatusNode != null ? this.deserialize(retweetedStatusNode) : null;
    tweet.setRetweetedStatus(retweetedStatus);
    JsonNode favoritedNode = node.get("favorited");
    boolean favorited = favoritedNode != null && !favoritedNode.isNull() ? favoritedNode.asBoolean() : false;
    tweet.setFavorited(favorited);
    JsonNode favoriteCountNode = node.get("favorite_count");
    Integer favoriteCount = favoriteCountNode != null && !favoriteCountNode.isNull() ? favoriteCountNode.asInt()
            : null;
    tweet.setFavoriteCount(favoriteCount);
    Entities entities = toEntities(node.get("entities"), text);
    tweet.setEntities(entities);
    TwitterProfile user = toProfile(fromUserNode);
    tweet.setUser(user);
    JsonNode coordinatesNode = node.get("coordinates");
    Coordinates coordinates = toCoordinates(coordinatesNode);
    tweet.setCoordinates(coordinates);
    JsonNode placeNode = node.get("place");
    Place place = toPlace(placeNode);
    tweet.setPlace(place);
    return tweet;
}

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

/**
 * Parse a single tweet.//from  w  w  w  .j  a v a  2s . co m
 */
private static Tweet parseSingleTweet(JsonNode objectRoot) throws JsonDeserializerException {
    // Basic sanity check
    if (!objectRoot.isObject()) {
        throw new JsonDeserializerException("Tweet JsonNode is not an object");
    }
    JsonNode node;
    Tweet tweet = new Tweet();

    // When was this tweet created?
    node = objectRoot.path("created_at");
    if (node.isMissingNode() || !node.isTextual()) {
        throw new JsonDeserializerException("'created_at' missing or invalid");
    }
    try {
        tweet.setCreatedAt(mDateFormat.parse(node.textValue()));
    } catch (ParseException e) {
        throw new JsonDeserializerException("Invalid date specified in 'created_at'", e);
    }

    // Who sent it? (user handle)
    node = objectRoot.path("from_user");
    if (node.isMissingNode() || !node.isTextual()) {
        throw new JsonDeserializerException("'from_user' missing or invalid");
    }
    tweet.setFromUser(node.textValue());

    // Who sent it? (user id)
    node = objectRoot.path("from_user_id");
    if (node.isMissingNode() || !node.canConvertToLong()) {
        throw new JsonDeserializerException("'from_user_id' missing or invalid");
    }
    tweet.setFromUserId(node.asLong());

    // Tweet id
    node = objectRoot.path("id");
    if (node.isMissingNode() || !node.canConvertToLong()) {
        throw new JsonDeserializerException("'id' missing or invalid");
    }
    tweet.setId(node.asLong());

    // Profile image url - prefer https over http
    node = objectRoot.path("profile_image_url_https");
    if (node.isMissingNode() || !node.isTextual()) {
        // Fall back to http
        node = objectRoot.path("profile_image_url");
        if (node.isMissingNode() || !node.isTextual()) {
            throw new JsonDeserializerException("'profile_image_url' missing or invalid");
        }
    }
    tweet.setProfileImageUrl(node.textValue());

    // Finally: tweet contents!
    node = objectRoot.path("text");
    if (node.isMissingNode() || !node.isTextual()) {
        throw new JsonDeserializerException("'text' missing or invalid");
    }
    tweet.setText(node.textValue());

    // FIXME: entities

    // Optional fields
    // Who sent it? (display name - yes, apparently this is OPTIONAL!)
    tweet.setFromUserName(objectRoot.path("from_user_name").textValue());

    // Free-form location
    tweet.setLocation(objectRoot.path("location").textValue());

    // FIXME: geo

    // End of tweet :-)
    return tweet;
}