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

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#intValue() . 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: OpenAPIDeserializer.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
public Integer getInteger(String key, ObjectNode node, boolean required, String location, ParseResult result) {
    Integer value = null;
    JsonNode v = node.get(key);
    if (node == null || v == null) {
        if (required) {
            result.missing(location, key);
            result.invalid();
        }
    }
    else if(v.getNodeType().equals(JsonNodeType.NUMBER)) {
        if (v.isInt()) {
            value = v.intValue();
        }
    }
    else if(!v.isValueNode()) {
        result.invalidType(location, key, "integer", node);
    }
    return value;
}
 
Example 2
Source File: Int32TypeParser.java    From connect-utils with Apache License 2.0 6 votes vote down vote up
@Override
public Object parseJsonNode(JsonNode input, Schema schema) {
  Object result;
  if (input.isNumber()) {
    result = input.intValue();
  } else if (input.isTextual()) {
    result = parseString(input.textValue(), schema);
  } else {
    throw new UnsupportedOperationException(
        String.format(
            "Could not parse '%s' to %s",
            input,
            this.expectedClass().getSimpleName()
        )
    );
  }
  return result;
}
 
Example 3
Source File: VariableContainsExpressionFunction.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
public static boolean arrayNodeContains(ArrayNode arrayNode, Object value) {
    Iterator<JsonNode> iterator = arrayNode.iterator();
    while (iterator.hasNext()) {
        JsonNode jsonNode = iterator.next();
        if (value == null && jsonNode.isNull()) {
            return true;
        } else if (value != null) {
            if (value instanceof String && jsonNode.isTextual() && StringUtils.equals(jsonNode.asText(), (String) value)) {
                return true;
            } else if (value instanceof Number && jsonNode.isLong() && jsonNode.longValue() == ((Number) value).longValue()) {
                return true;
            } else if (value instanceof Number && jsonNode.isDouble() && jsonNode.doubleValue() == ((Number) value).doubleValue()) {
                return true;
            } else if (value instanceof Number && jsonNode.isInt() && jsonNode.intValue() == ((Number) value).intValue()) {
                return true;
            } else if (value instanceof Boolean && jsonNode.isBoolean() && jsonNode.booleanValue() == ((Boolean) value).booleanValue()) {
                return true;
            }
        }
    }   
    return false;
}
 
Example 4
Source File: MultiplyOperator.java    From jslt with Apache License 2.0 6 votes vote down vote up
public JsonNode perform(JsonNode v1, JsonNode v2) {
  if (v1.isTextual() || v2.isTextual()) {
    // if one operand is string: do string multiplication

    String str;
    int num;
    if (v1.isTextual() && !v2.isTextual()) {
      str = v1.asText();
      num = v2.intValue();
    } else if (v2.isTextual()) {
      str = v2.asText();
      num = v1.intValue();
    } else
      throw new JsltException("Can't multiply two strings!");

    StringBuilder buf = new StringBuilder();
    for ( ; num > 0; num--)
      buf.append(str);

    return new TextNode(buf.toString());
  } else
    // do numeric operation
    return super.perform(v1, v2);
}
 
Example 5
Source File: RevisionJsonDeserializer.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
private static void validateRevisionNumber(DeserializationContext ctx, @Nullable JsonNode node,
                                           String type, boolean zeroAllowed) throws JsonMappingException {
    if (node == null) {
        ctx.reportInputMismatch(Revision.class, "missing %s revision number", type);
        // Should never reach here.
        throw new Error();
    }

    if (!node.canConvertToInt() || !zeroAllowed && node.intValue() == 0) {
        ctx.reportInputMismatch(Revision.class,
                                "A %s revision number must be %s integer.",
                                type, zeroAllowed ? "an" : "a non-zero");
        // Should never reach here.
        throw new Error();
    }
}
 
Example 6
Source File: Util.java    From celos with Apache License 2.0 5 votes vote down vote up
public static int getIntProperty(ObjectNode properties, String name) {
    JsonNode node = properties.get(name);
    if (node == null) {
        throw new IllegalArgumentException("Property " + name + " not set.");
    } else if (!node.isInt()) {
        throw new IllegalArgumentException("Property " + name + " is not an integer, but " + node);
    } else {
        return node.intValue();
    }
}
 
Example 7
Source File: BatchRequestBuilder.java    From simple-json-rpc with MIT License 5 votes vote down vote up
@NotNull
private static Object nodeValue(@NotNull JsonNode id) {
    if (id.isLong()) {
        return id.longValue();
    } else if (id.isInt()) {
        return id.intValue();
    } else if (id.isTextual()) {
        return id.textValue();
    }
    throw new IllegalArgumentException("Wrong id=" + id);
}
 
Example 8
Source File: MinPropertiesValidator.java    From json-schema-validator with Apache License 2.0 5 votes vote down vote up
public MinPropertiesValidator(String schemaPath, JsonNode schemaNode, JsonSchema parentSchema,
                              ValidationContext validationContext) {
    super(schemaPath, schemaNode, parentSchema, ValidatorTypeCode.MIN_PROPERTIES, validationContext);
    if (schemaNode.isIntegralNumber()) {
        min = schemaNode.intValue();
    }

    parseErrorCode(getValidatorType().getErrorCodeKey());
}
 
Example 9
Source File: ClassWithInterfaceFieldsRegistry.java    From istio-java-api with Apache License 2.0 5 votes vote down vote up
Object deserialize(JsonNode node, String fieldName, Class targetClass, DeserializationContext ctxt) throws IOException {
    final JsonNode value = node.get(fieldName);
    switch (type()) {
        case "integer":
            return value.intValue();
        case "string":
            return value.textValue();
        case "number":
            return value.doubleValue();
        case "boolean":
            return value.booleanValue();
        default:
            throw new IllegalArgumentException("Unknown simple type '" + type + "'");
    }
}
 
Example 10
Source File: AtlasGraphSONUtility.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
private static Object getTypedValueFromJsonNode(JsonNode node) {
    Object theValue = null;

    if (node != null && !node.isNull()) {
        if (node.isBoolean()) {
            theValue = node.booleanValue();
        } else if (node.isDouble()) {
            theValue = node.doubleValue();
        } else if (node.isFloatingPointNumber()) {
            theValue = node.floatValue();
        } else if (node.isInt()) {
            theValue = node.intValue();
        } else if (node.isLong()) {
            theValue = node.longValue();
        } else if (node.isTextual()) {
            theValue = node.textValue();
        } else if (node.isArray()) {
            // this is an array so just send it back so that it can be
            // reprocessed to its primitive components
            theValue = node;
        } else if (node.isObject()) {
            // this is an object so just send it back so that it can be
            // reprocessed to its primitive components
            theValue = node;
        } else {
            theValue = node.textValue();
        }
    }

    return theValue;
}
 
Example 11
Source File: AtlasGraphSONUtility.java    From atlas with Apache License 2.0 5 votes vote down vote up
private static Object getTypedValueFromJsonNode(JsonNode node) {
    Object theValue = null;

    if (node != null && !node.isNull()) {
        if (node.isBoolean()) {
            theValue = node.booleanValue();
        } else if (node.isDouble()) {
            theValue = node.doubleValue();
        } else if (node.isFloatingPointNumber()) {
            theValue = node.floatValue();
        } else if (node.isInt()) {
            theValue = node.intValue();
        } else if (node.isLong()) {
            theValue = node.longValue();
        } else if (node.isTextual()) {
            theValue = node.textValue();
        } else if (node.isArray()) {
            // this is an array so just send it back so that it can be
            // reprocessed to its primitive components
            theValue = node;
        } else if (node.isObject()) {
            // this is an object so just send it back so that it can be
            // reprocessed to its primitive components
            theValue = node;
        } else {
            theValue = node.textValue();
        }
    }

    return theValue;
}
 
Example 12
Source File: MinItemsValidator.java    From json-schema-validator with Apache License 2.0 5 votes vote down vote up
public MinItemsValidator(String schemaPath, JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext) {
    super(schemaPath, schemaNode, parentSchema, ValidatorTypeCode.MIN_ITEMS, validationContext);
    if (schemaNode.isIntegralNumber()) {
        min = schemaNode.intValue();
    }

    parseErrorCode(getValidatorType().getErrorCodeKey());
}
 
Example 13
Source File: JsonFrameworkDeserializer.java    From zeno with Apache License 2.0 5 votes vote down vote up
@Override
public Integer deserializeInteger(JsonReadGenericRecord record, String fieldName) {
    JsonNode node = record.getNode().isNumber() ? record.getNode() : getJsonNode(record, fieldName);
    if (node == null)
        return null;
    return node.intValue();
}
 
Example 14
Source File: ShortIOProvider.java    From constellation with Apache License 2.0 5 votes vote down vote up
@Override
public void readObject(final int attributeId, final int elementId, final JsonNode jnode, 
        final GraphWriteMethods graph, final Map<Integer, Integer> vertexMap, final Map<Integer, Integer> transactionMap, 
        final GraphByteReader byteReader, final ImmutableObjectCache cache) throws IOException {
    final short attributeValue = (short) jnode.intValue();
    graph.setShortValue(attributeId, elementId, attributeValue);
}
 
Example 15
Source File: IntegerObjectIOProvider.java    From constellation with Apache License 2.0 5 votes vote down vote up
@Override
public void readObject(final int attributeId, final int elementId, final JsonNode jnode, 
        final GraphWriteMethods graph, final Map<Integer, Integer> vertexMap, final Map<Integer, Integer> transactionMap, 
        final GraphByteReader byteReader, final ImmutableObjectCache cache) throws IOException {
    final Integer attributeValue = jnode.isNull() ? null : jnode.intValue();
    graph.setObjectValue(attributeId, elementId, attributeValue);
}
 
Example 16
Source File: ByteIOProvider.java    From constellation with Apache License 2.0 5 votes vote down vote up
@Override
public void readObject(final int attributeId, final int elementId, final JsonNode jnode, 
        final GraphWriteMethods graph, final Map<Integer, Integer> vertexMap, final Map<Integer, Integer> transactionMap, 
        final GraphByteReader byteReader, final ImmutableObjectCache cache) throws IOException {
    final byte attributeValue = (byte) jnode.intValue();
    graph.setByteValue(attributeId, elementId, attributeValue);
}
 
Example 17
Source File: SchemaUpgrade.java    From glowroot with Apache License 2.0 4 votes vote down vote up
private static boolean updateCentralConfigurationPropertiesFile(JsonNode webConfigNode)
        throws IOException {
    String bindAddressText = "";
    JsonNode bindAddressNode = webConfigNode.get("bindAddress");
    if (bindAddressNode != null && !bindAddressNode.asText().equals("0.0.0.0")) {
        bindAddressText = bindAddressNode.asText();
    }
    String portText = "";
    JsonNode portNode = webConfigNode.get("port");
    if (portNode != null && portNode.intValue() != 4000) {
        portText = portNode.asText();
    }
    String httpsText = "";
    JsonNode httpsNode = webConfigNode.get("https");
    if (httpsNode != null && httpsNode.booleanValue()) {
        httpsText = "true";
    }
    String contextPathText = "";
    JsonNode contextPathNode = webConfigNode.get("contextPath");
    if (contextPathNode != null && !contextPathNode.asText().equals("/")) {
        contextPathText = contextPathNode.asText();
    }
    File propFile = new File("glowroot-central.properties");
    if (!propFile.exists()) {
        startupLogger.warn("glowroot-central.properties file does not exist, so not populating"
                + " ui properties");
        return false;
    }
    Properties props = PropertiesFiles.load(propFile);
    StringBuilder sb = new StringBuilder();
    if (!props.containsKey("ui.bindAddress")) {
        sb.append("\n");
        sb.append("# default is ui.bindAddress=0.0.0.0\n");
        sb.append("ui.bindAddress=");
        sb.append(bindAddressText);
        sb.append("\n");
    }
    if (!props.containsKey("ui.port")) {
        sb.append("\n");
        sb.append("# default is ui.port=4000\n");
        sb.append("ui.port=");
        sb.append(portText);
        sb.append("\n");
    }
    if (!props.containsKey("ui.https")) {
        sb.append("\n");
        sb.append("# default is ui.https=false\n");
        sb.append("# set this to \"true\" to serve the UI over HTTPS\n");
        sb.append("# the certificate and private key to be used must be placed in the same"
                + " directory as this properties\n");
        sb.append("# file, with filenames \"ui-cert.pem\" and \"ui-key.pem\", where ui-cert.pem"
                + " is a PEM encoded X.509\n");
        sb.append("# certificate chain, and ui-key.pem is a PEM encoded PKCS#8 private key"
                + " without a passphrase (for\n");
        sb.append("# example, a self signed certificate can be generated at the command line"
                + " meeting the above\n");
        sb.append("# requirements using OpenSSL 1.0.0 or later:\n");
        sb.append("# \"openssl req -new -x509 -nodes -days 365 -out ui-cert.pem -keyout"
                + " ui-key.pem\")\n");
        sb.append("ui.https=");
        sb.append(httpsText);
        sb.append("\n");
    }
    if (!props.containsKey("ui.contextPath")) {
        sb.append("\n");
        sb.append("# default is ui.contextPath=/\n");
        sb.append("# this only needs to be changed if reverse proxying the UI behind a non-root"
                + " context path\n");
        sb.append("ui.contextPath=");
        sb.append(contextPathText);
        sb.append("\n");
    }
    if (sb.length() == 0) {
        // glowroot-central.properties file has been updated
        return false;
    }
    if (props.containsKey("jgroups.configurationFile")) {
        startupLogger.error("When running in a cluster, you must manually upgrade"
                + " the glowroot-central.properties files on each node to add the following"
                + " properties:\n\n" + sb + "\n\n");
        throw new IllegalStateException(
                "Glowroot central could not start, see error message above for instructions");
    }
    try (Writer out = Files.newBufferedWriter(propFile.toPath(), UTF_8, CREATE, APPEND)) {
        out.write(sb.toString());
    }
    return true;
}
 
Example 18
Source File: JsonConvert.java    From DBus with Apache License 2.0 4 votes vote down vote up
@Override
public Object convert(Schema schema, JsonNode value) {
    return (short) value.intValue();
}
 
Example 19
Source File: JsonFileReader.java    From kafka-connect-fs with Apache License 2.0 4 votes vote down vote up
private Object mapValue(Schema schema, JsonNode value) {
    if (value == null) return null;

    switch (value.getNodeType()) {
        case BOOLEAN:
            return value.booleanValue();
        case NUMBER:
            if (value.isShort()) {
                return value.shortValue();
            } else if (value.isInt()) {
                return value.intValue();
            } else if (value.isLong()) {
                return value.longValue();
            } else if (value.isFloat()) {
                return value.floatValue();
            } else if (value.isDouble()) {
                return value.doubleValue();
            } else if (value.isBigInteger()) {
                return value.bigIntegerValue();
            } else {
                return value.numberValue();
            }
        case STRING:
            return value.asText();
        case BINARY:
            try {
                return value.binaryValue();
            } catch (IOException ioe) {
                throw new RuntimeException(ioe);
            }
        case OBJECT:
        case POJO:
            Struct struct = new Struct(schema);
            Iterable<Map.Entry<String, JsonNode>> fields = value::fields;
            StreamSupport.stream(fields.spliterator(), false)
                    .forEach(field -> struct.put(field.getKey(),
                            mapValue(extractSchema(field.getValue()), field.getValue()))
                    );
            return struct;
        case ARRAY:
            Iterable<JsonNode> arrayElements = value::elements;
            return StreamSupport.stream(arrayElements.spliterator(), false)
                    .map(elm -> mapValue(schema, elm))
                    .collect(Collectors.toList());
        case NULL:
        case MISSING:
        default:
            return null;
    }
}
 
Example 20
Source File: RevisionJsonDeserializer.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
@Override
public Revision deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
    final JsonNode node = p.readValueAsTree();
    if (node.isNumber()) {
        validateRevisionNumber(ctx, node, "major", false);
        return new Revision(node.intValue());
    }

    if (node.isTextual()) {
        try {
            return new Revision(node.textValue());
        } catch (IllegalArgumentException e) {
            ctx.reportInputMismatch(Revision.class, e.getMessage());
            // Should never reach here.
            throw new Error();
        }
    }

    if (!node.isObject()) {
        ctx.reportInputMismatch(Revision.class,
                                "A revision must be a non-zero integer or " +
                                "an object that contains \"major\" and \"minor\" properties.");
        // Should never reach here.
        throw new Error();
    }

    final JsonNode majorNode = node.get("major");
    final JsonNode minorNode = node.get("minor");
    final int major;

    validateRevisionNumber(ctx, majorNode, "major", false);
    major = majorNode.intValue();
    if (minorNode != null) {
        validateRevisionNumber(ctx, minorNode, "minor", true);
        if (minorNode.intValue() != 0) {
            ctx.reportInputMismatch(Revision.class,
                                    "A revision must not have a non-zero \"minor\" property.");
        }
    }

    return new Revision(major);
}