Java Code Examples for com.fasterxml.jackson.databind.JsonNode#asLong()

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#asLong() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: QConfigAdminClient.java    From qconfig with MIT License 6 votes vote down vote up
@Override
protected Snapshot<String> parse(Response response) throws Exception {
    int code = Integer.parseInt(response.getHeader(Constants.CODE));
    logger.debug("response code is {}", code);
    String message = response.getResponseBody(Constants.UTF_8.name());
    logger.debug("response message is {}", message);
    if (code == ApiResponseCode.OK_CODE) {
        JsonNode jsonNode = objectMapper.readTree(message);
        JsonNode profileNode = jsonNode.get("profile");
        JsonNode versionNode = jsonNode.get("version");
        JsonNode contentNode = jsonNode.get("content");
        JsonNode statusNode = jsonNode.get("statuscode");
        if (profileNode != null
                && versionNode != null
                && contentNode != null
                && statusNode != null) {
            return new Snapshot<String>(profileNode.asText(), versionNode.asLong(), contentNode.asText(), StatusType.codeOf(statusNode.asInt()));
        }
    }
    return null;
}
 
Example 2
Source File: JsonSerializable.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
static Object getValue(JsonNode value) {
    if (value.isValueNode()) {
        switch (value.getNodeType()) {
            case BOOLEAN:
                return value.asBoolean();
            case NUMBER:
                if (value.isInt()) {
                    return value.asInt();
                } else if (value.isLong()) {
                    return value.asLong();
                } else if (value.isDouble()) {
                    return value.asDouble();
                }
            case STRING :
                return value.asText();
        }
    }
    return value;
}
 
Example 3
Source File: VirtualNetworkWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a virtual network link from the JSON input stream.
 *
 * @param networkId network identifier
 * @param stream    virtual link JSON stream
 * @return status of the request - CREATED if the JSON is correct,
 * BAD_REQUEST if the JSON is invalid
 * @onos.rsModel VirtualLink
 */
@POST
@Path("{networkId}/links")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createVirtualLink(@PathParam("networkId") long networkId,
                                  InputStream stream) {
    try {
        ObjectNode jsonTree = readTreeFromStream(mapper(), stream);
        JsonNode specifiedNetworkId = jsonTree.get("networkId");
        if (specifiedNetworkId == null || specifiedNetworkId.asLong() != (networkId)) {
            throw new IllegalArgumentException(INVALID_FIELD + "networkId");
        }
        final VirtualLink vlinkReq = codec(VirtualLink.class).decode(jsonTree, this);
        vnetAdminService.createVirtualLink(vlinkReq.networkId(),
                                           vlinkReq.src(), vlinkReq.dst());
        UriBuilder locationBuilder = uriInfo.getBaseUriBuilder()
                .path("vnets").path(specifiedNetworkId.asText())
                .path("links");
        return Response
                .created(locationBuilder.build())
                .build();
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 4
Source File: JsonMultilangSerializer.java    From streamline with Apache License 2.0 5 votes vote down vote up
@Override
public Long connect(Map<String, Object> conf, ShellContext context, List<String> outputStreams)
        throws IOException, NoOutputException {
    ConnectMsg connectMsg = new ConnectMsg();
    connectMsg.setPidDir(context.getPidDir());
    connectMsg.setConf(conf);
    connectMsg.setOutputStreams(outputStreams);
    connectMsg.setContext(context);
    writeConnectMsg(connectMsg);

    JsonNode node = readMessage();
    JsonNode pidNode = node.get("pid");
    Long pid = pidNode.asLong();
    return pid;
}
 
Example 5
Source File: JsonNodeSupport.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public static Long getLong(JsonNode json, String field) {
    JsonNode value = json.get(field);
    if( value==null ) {
        return null;
    }
    if( value.isNull() ) {
        return null;
    }
    return value.asLong();
}
 
Example 6
Source File: JsonNodeSupport.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public static Long removeLong(ObjectNode json, String field) {
    JsonNode value = json.remove(field);
    if( value==null ) {
        return null;
    }
    if( value.isNull() ) {
        return null;
    }
    return value.asLong();
}
 
Example 7
Source File: OAuthRefreshTokenProcessor.java    From syndesis with Apache License 2.0 5 votes vote down vote up
void processRefreshTokenResponse(final HttpEntity entity) throws IOException, JsonProcessingException {
    final JsonNode body = JSON.readTree(entity.getContent());

    if (body == null) {
        LOG.error("Received empty body while attempting to refresh access token via: {}", authorizationEndpoint);
        return;
    }

    final JsonNode accessToken = body.get("access_token");
    if (isPresentAndHasValue(accessToken)) {
        final String accessTokenValue = accessToken.asText();
        isFirstTime.set(Boolean.FALSE);
        LOG.info("Successful access token refresh");

        Long expiresInSeconds = null;
        if (expiresInOverride != null) {
            expiresInSeconds = expiresInOverride;
        } else {
            final JsonNode expiresIn = body.get("expires_in");
            if (isPresentAndHasValue(expiresIn)) {
                expiresInSeconds = expiresIn.asLong();
            }
        }

        long accessTokenExpiresAt = 0;
        if (expiresInSeconds != null) {
            accessTokenExpiresAt = now() + expiresInSeconds * 1000;
        }

        final JsonNode refreshToken = body.get("refresh_token");
        String refreshTokenValue = null;
        if (isPresentAndHasValue(refreshToken)) {
            refreshTokenValue = refreshToken.asText();

            lastRefreshTokenTried.compareAndSet(refreshTokenValue, null);
        }

        state.update(accessTokenValue, accessTokenExpiresAt, refreshTokenValue);
    }
}
 
Example 8
Source File: JsonObjectMapperDecoder.java    From ffwd with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 9
Source File: DataSetDeserializer.java    From Sparkplug with Eclipse Public License 1.0 5 votes vote down vote up
private Value<?> getValueFromNode(JsonNode nodeValue, DataSetDataType type) {
	switch (type) {
		case Boolean:
			return new Value<Boolean>(type, (boolean)nodeValue.asBoolean());
		case DateTime:
			return new Value<Date>(type, new Date(nodeValue.asLong()));
		case Double:
			return new Value<Double>(type, nodeValue.asDouble());
		case Float:
			return new Value<Float>(type, (float)nodeValue.asDouble());
		case Int16:
		case UInt8:
			return new Value<Byte>(type, (byte)nodeValue.asInt());
		case UInt16:
		case Int32:
			return new Value<Integer>(type, nodeValue.asInt());
		case UInt32:
		case Int64:
			return new Value<Long>(type, (long)nodeValue.asLong());
		case Text:
		case String:
			return new Value<String>(type, nodeValue.asText());
		case UInt64:
			return new Value<BigInteger>(type, BigInteger.valueOf(nodeValue.asLong()));
		case Unknown:
		default:
			return null;
	}
}
 
Example 10
Source File: SendAmountActivity.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
private Long getOldFeeRate(final ObjectNode mTx) {
    final JsonNode previousTransaction = mTx.get("previous_transaction");
    if (previousTransaction != null) {
        final JsonNode oldFeeRate = previousTransaction.get("fee_rate");
        if (oldFeeRate != null && (oldFeeRate.isLong() || oldFeeRate.isInt())) {
            return oldFeeRate.asLong();
        }
    }
    return null;
}
 
Example 11
Source File: VirtualNetworkWebResource.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a virtual network host from the JSON input stream.
 *
 * @param networkId network identifier
 * @param stream    virtual host JSON stream
 * @return status of the request - CREATED if the JSON is correct,
 * BAD_REQUEST if the JSON is invalid
 * @onos.rsModel VirtualHostPut
 */
@POST
@Path("{networkId}/hosts")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createVirtualHost(@PathParam("networkId") long networkId,
                                  InputStream stream) {
    try {
        ObjectNode jsonTree = readTreeFromStream(mapper(), stream);
        JsonNode specifiedNetworkId = jsonTree.get("networkId");
        if (specifiedNetworkId == null || specifiedNetworkId.asLong() != (networkId)) {
            throw new IllegalArgumentException(INVALID_FIELD + "networkId");
        }
        final VirtualHost vhostReq = codec(VirtualHost.class).decode(jsonTree, this);
        vnetAdminService.createVirtualHost(vhostReq.networkId(), vhostReq.id(),
                                           vhostReq.mac(), vhostReq.vlan(),
                                           vhostReq.location(), vhostReq.ipAddresses());
        UriBuilder locationBuilder = uriInfo.getBaseUriBuilder()
                .path("vnets").path(specifiedNetworkId.asText())
                .path("hosts");
        return Response
                .created(locationBuilder.build())
                .build();
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 12
Source File: JsonUtil.java    From iceberg with Apache License 2.0 5 votes vote down vote up
public static long getLong(String property, JsonNode node) {
  Preconditions.checkArgument(node.has(property), "Cannot parse missing long %s", property);
  JsonNode pNode = node.get(property);
  Preconditions.checkArgument(pNode != null && !pNode.isNull() && pNode.isNumber(),
      "Cannot parse %s from non-numeric value: %s", property, pNode);
  return pNode.asLong();
}
 
Example 13
Source File: JsonUtil.java    From iceberg with Apache License 2.0 5 votes vote down vote up
public static long getLong(String property, JsonNode node) {
  Preconditions.checkArgument(node.has(property), "Cannot parse missing int %s", property);
  JsonNode pNode = node.get(property);
  Preconditions.checkArgument(pNode != null && !pNode.isNull() && pNode.isNumber(),
      "Cannot parse %s from non-numeric value: %s", property, pNode);
  return pNode.asLong();
}
 
Example 14
Source File: ReadJsonTestTweetsBuilder.java    From kite with Apache License 2.0 5 votes vote down vote up
private void tryAddLong(Record doc, String solr_field, JsonNode node) {
  if (node == null)
    return;
  Long val = node.asLong();
  if (val == null) {
    return;
  }
  doc.put(solr_field, val);
}
 
Example 15
Source File: ColumnType.java    From ovsdb with Eclipse Public License 1.0 5 votes vote down vote up
static long maxFromJson(final JsonNode json) {
    final JsonNode maxNode = json.get("max");
    if (maxNode != null) {
        if (maxNode.isLong()) {
            return maxNode.asLong();
        }
        if (maxNode.isTextual() && "unlimited".equals(maxNode.asText())) {
            return Long.MAX_VALUE;
        }
    }
    return 1;
}
 
Example 16
Source File: GeneralUtils.java    From template-compiler with Apache License 2.0 5 votes vote down vote up
/**
 * Determines the boolean value of a node based on its type.
 */
public static boolean isTruthy(JsonNode node) {
  if (node.isTextual()) {
    return !node.asText().equals("");
  }
  if (node.isNumber() || node.isBoolean()) {
    return node.asLong() != 0;
  }
  if (node.isMissingNode() || node.isNull()) {
    return false;
  }
  return node.size() != 0;
}
 
Example 17
Source File: PartitionData.java    From presto with Apache License 2.0 5 votes vote down vote up
public static Object getValue(JsonNode partitionValue, Type type)
{
    if (partitionValue.isNull()) {
        return null;
    }
    switch (type.typeId()) {
        case BOOLEAN:
            return partitionValue.asBoolean();
        case INTEGER:
        case DATE:
            return partitionValue.asInt();
        case LONG:
        case TIMESTAMP:
            return partitionValue.asLong();
        case FLOAT:
            return partitionValue.floatValue();
        case DOUBLE:
            return partitionValue.doubleValue();
        case STRING:
        case UUID:
            return partitionValue.asText();
        case FIXED:
        case BINARY:
            try {
                return partitionValue.binaryValue();
            }
            catch (IOException e) {
                throw new UncheckedIOException("Failed during JSON conversion of " + partitionValue, e);
            }
        case DECIMAL:
            return partitionValue.decimalValue();
    }
    throw new UnsupportedOperationException("Type not supported as partition column: " + type);
}
 
Example 18
Source File: ExclusiveMaximumValidator.java    From json-schema-validator with Apache License 2.0 4 votes vote down vote up
public ExclusiveMaximumValidator(String schemaPath, final JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext) {
    super(schemaPath, schemaNode, parentSchema, ValidatorTypeCode.EXCLUSIVE_MAXIMUM, validationContext);

    if (!schemaNode.isNumber()) {
        throw new JsonSchemaException("exclusiveMaximum value is not a number");
    }

    parseErrorCode(getValidatorType().getErrorCodeKey());

    final String maximumText = schemaNode.asText();
    if ((schemaNode.isLong() || schemaNode.isInt()) && (JsonType.INTEGER.toString().equals(getNodeFieldType()))) {
        // "integer", and within long range
        final long lm = schemaNode.asLong();
        typedMaximum = new ThresholdMixin() {
            @Override
            public boolean crossesThreshold(JsonNode node) {
                if (node.isBigInteger()) {
                    //node.isBigInteger is not trustable, the type BigInteger doesn't mean it is a big number.
                    int compare = node.bigIntegerValue().compareTo(new BigInteger(schemaNode.asText()));
                    return compare > 0 || compare == 0;

                } else if (node.isTextual()) {
                    BigDecimal max = new BigDecimal(maximumText);
                    BigDecimal value = new BigDecimal(node.asText());
                    int compare = value.compareTo(max);
                    return compare > 0 || compare == 0;
                }
                long val = node.asLong();
                return lm < val || lm == val;
            }

            @Override
            public String thresholdValue() {
                return String.valueOf(lm);
            }
        };
    } else {
        typedMaximum = new ThresholdMixin() {
            @Override
            public boolean crossesThreshold(JsonNode node) {
                if (schemaNode.isDouble() && schemaNode.doubleValue() == Double.POSITIVE_INFINITY) {
                    return false;
                }
                if (schemaNode.isDouble() && schemaNode.doubleValue() == Double.NEGATIVE_INFINITY) {
                    return true;
                }
                if (node.isDouble() && node.doubleValue() == Double.NEGATIVE_INFINITY) {
                    return false;
                }
                if (node.isDouble() && node.doubleValue() == Double.POSITIVE_INFINITY) {
                    return true;
                }
                final BigDecimal max = new BigDecimal(maximumText);
                BigDecimal value = new BigDecimal(node.asText());
                int compare = value.compareTo(max);
                return compare > 0 || compare == 0;
            }

            @Override
            public String thresholdValue() {
                return maximumText;
            }
        };
    }
}
 
Example 19
Source File: MinimumValidator.java    From json-schema-validator with Apache License 2.0 4 votes vote down vote up
public MinimumValidator(String schemaPath, final JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext) {
    super(schemaPath, schemaNode, parentSchema, ValidatorTypeCode.MINIMUM, validationContext);

    if (!schemaNode.isNumber()) {
        throw new JsonSchemaException("minimum value is not a number");
    }

    JsonNode exclusiveMinimumNode = getParentSchema().getSchemaNode().get(PROPERTY_EXCLUSIVE_MINIMUM);
    if (exclusiveMinimumNode != null && exclusiveMinimumNode.isBoolean()) {
        excludeEqual = exclusiveMinimumNode.booleanValue();
    }

    parseErrorCode(getValidatorType().getErrorCodeKey());

    final String minimumText = schemaNode.asText();
    if ((schemaNode.isLong() || schemaNode.isInt()) && JsonType.INTEGER.toString().equals(getNodeFieldType())) {
        // "integer", and within long range
        final long lmin = schemaNode.asLong();
        typedMinimum = new ThresholdMixin() {
            @Override
            public boolean crossesThreshold(JsonNode node) {
                if (node.isBigInteger()) {
                    //node.isBigInteger is not trustable, the type BigInteger doesn't mean it is a big number.
                    int compare = node.bigIntegerValue().compareTo(new BigInteger(minimumText));
                    return compare < 0 || (excludeEqual && compare == 0);

                } else if (node.isTextual()) {
                    BigDecimal min = new BigDecimal(minimumText);
                    BigDecimal value = new BigDecimal(node.asText());
                    int compare = value.compareTo(min);
                    return compare < 0 || (excludeEqual && compare == 0);

                }
                long val = node.asLong();
                return lmin > val || (excludeEqual && lmin == val);
            }

            @Override
            public String thresholdValue() {
                return String.valueOf(lmin);
            }
        };

    } else {
        typedMinimum = new ThresholdMixin() {
            @Override
            public boolean crossesThreshold(JsonNode node) {
                // jackson's BIG_DECIMAL parsing is limited. see https://github.com/FasterXML/jackson-databind/issues/1770
                if (schemaNode.isDouble() && schemaNode.doubleValue() == Double.NEGATIVE_INFINITY) {
                    return false;
                }
                if (schemaNode.isDouble() && schemaNode.doubleValue() == Double.POSITIVE_INFINITY) {
                    return true;
                }
                if (node.isDouble() && node.doubleValue() == Double.NEGATIVE_INFINITY) {
                    return true;
                }
                if (node.isDouble() && node.doubleValue() == Double.POSITIVE_INFINITY) {
                    return false;
                }
                final BigDecimal min = new BigDecimal(minimumText);
                BigDecimal value = new BigDecimal(node.asText());
                int compare = value.compareTo(min);
                return compare < 0 || (excludeEqual && compare == 0);
            }

            @Override
            public String thresholdValue() {
                return minimumText;
            }
        };
    }
}
 
Example 20
Source File: JsonResolver.java    From pxf with Apache License 2.0 3 votes vote down vote up
/**
 * Determines whether or not a {@link JsonNode} contains a valid numeric type.
 * When val is not a valid numeric type, the default is always returned
 * when calling {@link JsonNode#asLong()}. If not a numeric type, error out.
 *
 * @param type is used to report which numeric type is being validated
 * @param val  is the {@link JsonNode} that we are validating
 * @throws BadRecordException when there is a data mismatch (non-numeric data)
 */
private static void validateNumber(DataType type, JsonNode val) throws BadRecordException {
    // to validate if val is of numeric type:
    // if val is not a number, 0 will be returned by val.asLong(0)
    // we need to check with another default in case val is actually 0
    if (val.asLong(0) == 0 && val.asLong(1) == 1) {
        throw new BadRecordException(String.format("invalid %s input value '%s'", type, val));
    }
}