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

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#isInt() . 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: UtilsValidator.java    From SkaETL with Apache License 2.0 6 votes vote down vote up
public static <T> T get(JsonNode jsonValue, String key) {
    if (!jsonValue.hasNonNull(key)) {
        return null;
    }
    JsonNode jsonNode = JSONUtils.getInstance().at(jsonValue, key);
    switch (jsonNode.getNodeType()) {
        case BOOLEAN:
            return (T) Boolean.valueOf(jsonNode.asBoolean());
        case NUMBER:
            if (jsonNode.isInt()) {
                return (T) Integer.valueOf(jsonNode.asInt());
            }
            if (jsonNode.isDouble()) {
                return (T) Double.valueOf(jsonNode.asDouble());
            }

        case STRING:
            return (T) jsonNode.asText();
        default:
            throw new IllegalArgumentException(jsonNode.getNodeType() + " type is not yet supported");

    }


}
 
Example 3
Source File: TestVariableResolver.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * @see org.mvel2.integration.VariableResolver#getValue()
 */
@Override
public Object getValue() {
    JsonNode varNode = node.get(fieldName);
    if (varNode.isObject()) {
        return varNode;
    } else if (varNode.isArray()) {
        List<Object> rval = new ArrayList<>();
        for (int idx = 0; idx < varNode.size(); idx++) {
            JsonNode idxNode = varNode.get(idx);
            rval.add(idxNode);
        }
        return rval;
    } else if (varNode.isNull()) {
        return null;
    } else if (varNode.isBoolean()) {
        return varNode.asBoolean();
    } else if (varNode.isTextual()) {
        return varNode.asText();
    } else if (varNode.isInt()) {
        return varNode.asInt();
    } else if (varNode.isDouble()) {
        return varNode.asDouble();
    }
    return varNode;
}
 
Example 4
Source File: StandardCommunity.java    From batfish with Apache License 2.0 6 votes vote down vote up
@JsonCreator
private static StandardCommunity create(@Nullable JsonNode value) {
  // Keep this creator backwards compatible with previous communities implementation
  checkArgument(value != null && !value.isNull(), "Standard community string must not be null");
  if (value.isTextual()) {
    return parse(value.textValue());
  } else if (value.isInt() || value.isLong()) {
    return StandardCommunity.of(value.longValue());
  } else if (value.isArray()
      && value.has(0)
      && value.get(0).textValue().equalsIgnoreCase("standard")) {
    return parse(value.get(1).textValue());
  } else {
    throw new IllegalArgumentException(
        String.format("Invalid standard community value: %s", value));
  }
}
 
Example 5
Source File: JsonNodeAssertions.java    From ts-reaktive with MIT License 5 votes vote down vote up
/**
 * Asserts that the current JsonNode is an array, where at least one element is equal to [expected].
 */
public JsonNodeAssertions isArrayWithInt(int expected) {
    isNotNull();
    if(!actual.isArray()){
        failWithMessage("Expected an array, but was <%s>", actual);
    }
    for (int i = 0; i < actual.size(); i++) {
        JsonNode elem = actual.get(i);
        if (elem.isInt() && elem.asInt() == expected) {
            return this;
        }
    }
    failWithMessage("Expected array to contain int <%s>, but was <%s>", expected, actual);
    return this;
}
 
Example 6
Source File: IntOrString.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public IntOrString deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    ObjectCodec oc = jsonParser.getCodec();
    JsonNode node = oc.readTree(jsonParser);
    IntOrString intOrString;
    if (node.isInt()) {
        intOrString = new IntOrString(node.asInt());
    } else {
        intOrString = new IntOrString(node.asText());
    }
    return intOrString;
}
 
Example 7
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 8
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 9
Source File: JsonDeserializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private EdmPrimitiveTypeKind guessPrimitiveTypeKind(final JsonNode node) {
  return node.isShort() ? EdmPrimitiveTypeKind.Int16 :
    node.isInt() ? EdmPrimitiveTypeKind.Int32 :
      node.isLong() ? EdmPrimitiveTypeKind.Int64 :
        node.isBoolean() ? EdmPrimitiveTypeKind.Boolean :
          node.isFloat() ? EdmPrimitiveTypeKind.Single :
            node.isDouble() ? EdmPrimitiveTypeKind.Double :
              node.isBigDecimal() ? EdmPrimitiveTypeKind.Decimal :
                EdmPrimitiveTypeKind.String;
}
 
Example 10
Source File: ZeroCodeAssertionsProcessorImpl.java    From zerocode with Apache License 2.0 5 votes vote down vote up
private Object convertJsonTypeToJavaType(JsonNode jsonNode) {
    if (jsonNode.isValueNode()) {
        if (jsonNode.isInt()) {
            return jsonNode.asInt();

        } else if (jsonNode.isTextual()) {
            return jsonNode.asText();

        } else if (jsonNode.isBoolean()) {
            return jsonNode.asBoolean();

        } else if (jsonNode.isLong()) {
            return jsonNode.asLong();

        } else if (jsonNode.isDouble()) {
            return jsonNode.asDouble();

        } else if (jsonNode.isNull()) {
            return null;

        } else {
            throw new RuntimeException(format("Oops! Unsupported JSON primitive to Java : %s by the framework", jsonNode.getClass().getName()));
        }
    } else {
        throw new RuntimeException(format("Unsupported JSON Type: %s", jsonNode.getClass().getName()));
    }
}
 
Example 11
Source File: HdfsWritableAvroTest.java    From pxf with Apache License 2.0 5 votes vote down vote up
private Integer getIntegerFromJsonNode(JsonNode node) {
    JsonNode typeInt = node.get("type_int");
    // an Avro int type: '{"type_int": 7}'
    if (typeInt.isInt()) {
        return typeInt.asInt();
    }

    // an Avro enum type: '{"type_int": {"int": 7}}'
    return typeInt.get("int").asInt();
}
 
Example 12
Source File: BaseParser.java    From cwlexec with Apache License 2.0 5 votes vote down vote up
protected static Long processLongField(String key, JsonNode longNode) throws CWLException {
    Long longVal = null;
    if (longNode != null) {
        if (longNode.isLong()) {
            longVal = Long.valueOf(longNode.asLong());
        } else if (longNode.isInt()) {
            longVal = Long.valueOf(longNode.asInt());
        } else {
            throw new CWLException(ResourceLoader.getMessage(CWL_PARSER_INVALID_TYPE, key, "long"), 251);
        }
    }
    return longVal;
}
 
Example 13
Source File: BaseParser.java    From cwlexec with Apache License 2.0 5 votes vote down vote up
protected static Integer processIntegerField(String key, JsonNode integerNode) throws CWLException {
    Integer integer = null;
    if (integerNode != null) {
        if (integerNode.isInt()) {
            integer = Integer.valueOf(integerNode.asInt());
        } else {
            throw new CWLException(ResourceLoader.getMessage(CWL_PARSER_INVALID_TYPE, key, CWLTypeSymbol.INT),
                    251);
        }
    }
    return integer;
}
 
Example 14
Source File: Assertion.java    From batfish with Apache License 2.0 5 votes vote down vote up
@JsonCreator
public Assertion(
    @JsonProperty(PROP_TYPE) AssertionType assertionType,
    @JsonProperty(PROP_EXPECT) JsonNode expect) {
  switch (assertionType) {
    case countequals:
    case countlessthan:
    case countmorethan:
      if (!expect.isInt()) {
        throw new IllegalArgumentException(
            String.format(
                "Value '%s' of assertion type '%s' is not an integer", expect, assertionType));
      }
      break;
    case equals:
      if (!expect.isArray()) {
        throw new IllegalArgumentException(
            String.format(
                "Value '%s' of assertion type '%s' is not a list", expect, assertionType));
      }
      break;
    default:
      throw new IllegalArgumentException("Unhandled assertion type: " + assertionType);
  }
  _assertionType = assertionType;
  _expect = expect;
}
 
Example 15
Source File: NetFlowV9FieldTypeRegistry.java    From graylog-plugin-netflow with Apache License 2.0 4 votes vote down vote up
private static Map<Integer, NetFlowV9FieldType> parseYaml(InputStream inputStream, ObjectMapper yamlMapper) throws IOException {
    final JsonNode node = yamlMapper.readValue(inputStream, JsonNode.class);
    final ImmutableMap.Builder<Integer, NetFlowV9FieldType> mapBuilder = ImmutableMap.builder();
    final Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
    while (fields.hasNext()) {
        final Map.Entry<String, JsonNode> field = fields.next();

        final Integer id;
        try {
            id = Integer.parseInt(field.getKey());
        } catch (NumberFormatException e) {
            LOG.debug("Skipping record with invalid id: {}", field.getKey(), e);
            continue;
        }

        final JsonNode value = field.getValue();

        if (!value.isArray()) {
            LOG.debug("Skipping invalid record: {}", field);
            continue;
        }

        if (value.size() == 1 && ":skip".equals(value.get(0).asText())) {
            LOG.debug("Skipping record: {}", field);
            continue;
        }

        if (value.size() != 2) {
            LOG.debug("Skipping incomplete record: {}", field);
            continue;
        }

        final JsonNode typeNode = value.get(0);
        final NetFlowV9FieldType.ValueType type;
        if (typeNode.isTextual()) {
            type = symbolToValueType(typeNode.asText());
        } else if (typeNode.isInt()) {
            type = intToValueType(typeNode.asInt());
        } else {
            LOG.debug("Skipping invalid record type: {}", field);
            continue;
        }

        final JsonNode nameNode = value.get(1);
        if (!nameNode.isTextual()) {
            LOG.debug("Skipping invalid record type: {}", field);
            continue;
        }

        final String symbol = nameNode.asText();
        final String name = rubySymbolToString(symbol);

        mapBuilder.put(id, NetFlowV9FieldType.create(id, type, name));
    }

    return mapBuilder.build();
}
 
Example 16
Source File: AssertInputCase.java    From tasmo with Apache License 2.0 4 votes vote down vote up
public void assertViewElementExists(List<ModelPathStep> path, int pathIndex, ObjectNode viewNode,
        Map<String, String> expectedFieldValues, List<AssertionResult> resultAccumulator) {

    if (viewNode == null) {
        resultAccumulator.add(new AssertionResult(false, "Supplied view node is null"));
    } else if (pathIndex == path.size() - 1) {
        resultAccumulator.add(assertLeafNodeFields(viewNode, expectedFieldValues));
    } else {
        ModelPathStep step = path.get(pathIndex);
        String refField = step.getRefFieldName();
        if (refField == null) {
            throw new IllegalArgumentException("Malformed model path - ref field not present in mid-path element");
        }

        if (ModelPathStepType.backRefs.equals(step.getStepType())) {
            refField = "all_" + refField;
        } else if (ModelPathStepType.latest_backRef.equals(step.getStepType())) {
            refField = "latest_" + refField;
        } else if (ModelPathStepType.count.equals(step.getStepType())) {
            refField = "count_" + refField;
        }

        JsonNode nextNode = viewNode.get(refField);
        if (nextNode == null) {
            resultAccumulator.add(new AssertionResult(false, "No view data exists for path element " + step));
        } else if (nextNode.isArray()) { //handles refs and all_backrefs
            ArrayNode arrayNode = (ArrayNode) nextNode;
            if (arrayNode.size() == 0) {
                resultAccumulator.add(new AssertionResult(false, "Empty array element in view data for path element " + step));
            } else {
                for (Iterator<JsonNode> iter = arrayNode.elements(); iter.hasNext();) {
                    JsonNode element = iter.next();
                    if (element.isObject()) {
                        assertViewElementExists(path, pathIndex + 1, (ObjectNode) element, expectedFieldValues, resultAccumulator);
                    } else {
                        resultAccumulator.add(new AssertionResult(false, "Array element view data for path element " + step + " was not an object"));
                    }
                }
            }
        } else if (nextNode.isObject()) { //handles ref and latest_backref
            assertViewElementExists(path, pathIndex + 1, (ObjectNode) nextNode, expectedFieldValues, resultAccumulator);
        } else if (nextNode.isInt()) { //handles count
            resultAccumulator.add(assertCountField((IntNode) nextNode, refField, maxFanOut));
        } else {
            resultAccumulator.add(new AssertionResult(false, "Element view data for path element " + step + " was an unexpected type: " + nextNode));
        }
    }
}
 
Example 17
Source File: AssertInputCase.java    From tasmo with Apache License 2.0 4 votes vote down vote up
public void assertViewElementExists(List<ModelPathStep> path, int pathIndex, ObjectNode viewNode,
        Map<String, String> expectedFieldValues, List<AssertionResult> resultAccumulator) {

    if (viewNode == null) {
        resultAccumulator.add(new AssertionResult(false, "Supplied view node is null"));
    } else if (pathIndex == path.size() - 1) {
        resultAccumulator.add(assertLeafNodeFields(viewNode, expectedFieldValues));
    } else {
        ModelPathStep step = path.get(pathIndex);
        String refField = step.getRefFieldName();
        if (refField == null) {
            throw new IllegalArgumentException("Malformed model path - ref field not present in mid-path element");
        }

        if (ModelPathStepType.backRefs.equals(step.getStepType())) {
            refField = "all_" + refField;
        } else if (ModelPathStepType.latest_backRef.equals(step.getStepType())) {
            refField = "latest_" + refField;
        } else if (ModelPathStepType.count.equals(step.getStepType())) {
            refField = "count_" + refField;
        }

        JsonNode nextNode = viewNode.get(refField);
        if (nextNode == null) {
            resultAccumulator.add(new AssertionResult(false, "No view data exists for path element " + step));
        } else if (nextNode.isArray()) { //handles refs and all_backrefs
            ArrayNode arrayNode = (ArrayNode) nextNode;
            if (arrayNode.size() == 0) {
                resultAccumulator.add(new AssertionResult(false, "Empty array element in view data for path element " + step));
            } else {
                for (Iterator<JsonNode> iter = arrayNode.elements(); iter.hasNext();) {
                    JsonNode element = iter.next();
                    if (element.isObject()) {
                        assertViewElementExists(path, pathIndex + 1, (ObjectNode) element, expectedFieldValues, resultAccumulator);
                    } else {
                        resultAccumulator.add(new AssertionResult(false, "Array element view data for path element " + step + " was not an object"));
                    }
                }
            }
        } else if (nextNode.isObject()) { //handles ref and latest_backref
            assertViewElementExists(path, pathIndex + 1, (ObjectNode) nextNode, expectedFieldValues, resultAccumulator);
        } else if (nextNode.isInt()) { //handles count
            resultAccumulator.add(assertCountField((IntNode) nextNode, refField, maxFanOut));
        } else {
            resultAccumulator.add(new AssertionResult(false, "Element view data for path element " + step + " was an unexpected type: " + nextNode));
        }
    }
}
 
Example 18
Source File: V201909JsonSchemaTest.java    From json-schema-validator with Apache License 2.0 4 votes vote down vote up
private void runTestFile(String testCaseFile) throws Exception {
    final URI testCaseFileUri = URI.create("classpath:" + testCaseFile);
    InputStream in = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream(testCaseFile);
    ArrayNode testCases = mapper.readValue(in, ArrayNode.class);

    for (int j = 0; j < testCases.size(); j++) {
        try {
            JsonNode testCase = testCases.get(j);
            SchemaValidatorsConfig config = new SchemaValidatorsConfig();

            ArrayNode testNodes = (ArrayNode) testCase.get("tests");
            for (int i = 0; i < testNodes.size(); i++) {
                JsonNode test = testNodes.get(i);
                JsonNode node = test.get("data");
                JsonNode typeLooseNode = test.get("isTypeLoose");
                // Configure the schemaValidator to set typeLoose's value based on the test file,
                // if test file do not contains typeLoose flag, use default value: true.
                config.setTypeLoose((typeLooseNode == null) ? false : typeLooseNode.asBoolean());
                JsonSchema schema = validatorFactory.getSchema(testCaseFileUri, testCase.get("schema"), config);
                List<ValidationMessage> errors = new ArrayList<ValidationMessage>();

                errors.addAll(schema.validate(node));

                if (test.get("valid").asBoolean()) {
                    if (!errors.isEmpty()) {
                        System.out.println("---- test case failed ----");
                        System.out.println("schema: " + schema.toString());
                        System.out.println("data: " + test.get("data"));
                    }
                    assertEquals(0, errors.size());
                } else {
                    if (errors.isEmpty()) {
                        System.out.println("---- test case failed ----");
                        System.out.println("schema: " + schema);
                        System.out.println("data: " + test.get("data"));
                    } else {
                        JsonNode errorCount = test.get("errorCount");
                        if (errorCount != null && errorCount.isInt() && errors.size() != errorCount.asInt()) {
                            System.out.println("---- test case failed ----");
                            System.out.println("schema: " + schema);
                            System.out.println("data: " + test.get("data"));
                            System.out.println("errors: " + errors);
                            assertEquals("expected error count", errorCount.asInt(), errors.size());
                        }
                    }
                    assertEquals(false, errors.isEmpty());
                }
            }
        } catch (JsonSchemaException e) {
            throw new IllegalStateException(String.format("Current schema should not be invalid: %s", testCaseFile), e);
        }
    }
}
 
Example 19
Source File: RestDMLServiceImpl.java    From sql-layer with GNU Affero General Public License v3.0 4 votes vote down vote up
protected void callDefaultProcedure(PrintWriter writer, HttpServletRequest request, String jsonpArgName,
                                    JDBCCallableStatement call, Map<String,List<String>> queryParams, String jsonParams) throws SQLException {
    if (queryParams != null) {
        for (Map.Entry<String,List<String>> entry : queryParams.entrySet()) {
            if (jsonpArgName.equals(entry.getKey()))
                continue;
            if (entry.getValue().size() != 1)
                throw new WrongExpressionArityException(1, entry.getValue().size());
            call.setString(entry.getKey(), entry.getValue().get(0));
        }
    }
    if (jsonParams != null) {
        JsonNode parsed;
        try {
            parsed = jsonParser(jsonParams).readValueAsTree();
        }
        catch (IOException ex) {
            throw new AkibanInternalException("Error reading from string", ex);
        }
        if (parsed.isObject()) {
            Iterator<String> iter = parsed.fieldNames();
            while (iter.hasNext()) {
                String field = iter.next();
                JsonNode value = parsed.get(field);
                if (value.isBigDecimal()) {
                    call.setBigDecimal(field, value.decimalValue());
                }
                else if (value.isBoolean()) {
                    call.setBoolean(field, value.asBoolean());
                }
                else if (value.isDouble()) {
                    call.setDouble(field, value.asDouble());
                }
                else if (value.isInt()) {
                    call.setInt(field, value.asInt());
                }
                else if (value.isLong()) {
                    call.setLong(field, value.asLong());
                }
                else {
                    call.setString(field, value.textValue());
                }
            }
        }
        else {
            throw new InvalidArgumentTypeException("JSON must be object or array");
        }
    }
    boolean results = call.execute();
    AkibanAppender appender = AkibanAppender.of(writer);
    appender.append('{');
    boolean first = true;
    JDBCParameterMetaData md = (JDBCParameterMetaData)call.getParameterMetaData();
    for (int i = 1; i <= md.getParameterCount(); i++) {
        String name;
        switch (md.getParameterMode(i)) {
        case ParameterMetaData.parameterModeOut:
        case ParameterMetaData.parameterModeInOut:
            name = md.getParameterName(i);
            if (name == null)
                name = String.format("arg%d", i);
            if (first)
                first = false;
            else
                appender.append(',');
            appender.append('"');
            Quote.DOUBLE_QUOTE.append(appender, name);
            appender.append("\":");
            call.formatAsJson(i, appender, options);
            break;
        }
    }
    int nresults = 0;
    while(results) {
        beginResultSetArray(appender, first, nresults++);
        first = false;
        collectResults((JDBCResultSet) call.getResultSet(), appender, options);
        endResultSetArray(appender);
        results = call.getMoreResults();
    }
    appender.append('}');
}
 
Example 20
Source File: JsonQLDataSource.java    From jasperreports with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected Object getConvertedValue(JRJsonNode node, JRField jrField) throws JRException {
    JsonNode dataNode = node.getDataNode();
    Class<?> valueClass = jrField.getValueClass();

    if (log.isDebugEnabled()) {
        log.debug("attempting to convert: " + dataNode + " to class: " + valueClass);
    }

    if (Object.class.equals(valueClass)) {
        return dataNode;
    }

    Object result = null;

    if (!dataNode.isNull())  {
        try {
            if (Boolean.class.equals(valueClass) && dataNode.isBoolean()) {
                result = dataNode.booleanValue();

            } else if (BigDecimal.class.equals(valueClass) && dataNode.isBigDecimal()) {
                result = dataNode.decimalValue();

            } else if (BigInteger.class.equals(valueClass) && dataNode.isBigInteger()) {
                result = dataNode.bigIntegerValue();

            } else if (Double.class.equals(valueClass) && dataNode.isDouble()) {
                result = dataNode.doubleValue();

            } else if (Integer.class.equals(valueClass) && dataNode.isInt()) {
                result = dataNode.intValue();

            } else if (Number.class.isAssignableFrom(valueClass) && dataNode.isNumber()) {
                result = convertNumber(dataNode.numberValue(), valueClass);

            } else {
                result = convertStringValue(dataNode.asText(), valueClass);
            }

            if (result == null) {
                throw new JRException(EXCEPTION_MESSAGE_KEY_CANNOT_CONVERT_FIELD_TYPE,
                        new Object[]{jrField.getName(), valueClass.getName()});
            }

        } catch (Exception e) {
            throw new JRException(EXCEPTION_MESSAGE_KEY_JSON_FIELD_VALUE_NOT_RETRIEVED,
                    new Object[]{jrField.getName(), valueClass.getName()}, e);
        }
    }

    return result;
}