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

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#booleanValue() . 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: 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 2
Source File: BooleanParser.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.isBoolean()) {
    result = input.booleanValue();
  } 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: YqlFallbackLinker.java    From yql-plus with Apache License 2.0 6 votes vote down vote up
public static Object readProperty(JsonNode node, String property) throws IOException {
    JsonNode result = node.get(property);
    if (result == null) {
        return null;
    }
    switch (result.getNodeType()) {
        case NUMBER:
            return result.numberValue();
        case BOOLEAN:
            return result.booleanValue();
        case NULL:
            return null;
        case STRING:
            return result.asText();
        case BINARY:
            return ByteBuffer.wrap(result.binaryValue());
        case MISSING:
        case OBJECT:
        case POJO:
        case ARRAY:
        default:
            return result;
    }

}
 
Example 4
Source File: JsonNodeLinker.java    From yql-plus with Apache License 2.0 6 votes vote down vote up
public static Object readProperty(JsonNode node, String property) throws IOException {
    JsonNode result = node.get(property);
    if (result == null) {
        return null;
    }
    switch (result.getNodeType()) {
        case NUMBER:
            return result.numberValue();
        case BOOLEAN:
            return result.booleanValue();
        case NULL:
            return null;
        case STRING:
            return result.asText();
        case BINARY:
            return ByteBuffer.wrap(result.binaryValue());
        case MISSING:
        case OBJECT:
        case POJO:
        case ARRAY:
        default:
            return result;
    }

}
 
Example 5
Source File: JsonWrittenEventProvider.java    From tasmo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isDeletion() {
    JsonNode deletion = instanceNode.get(ReservedFields.DELETED);
    if (deletion != null && deletion.isBoolean()) {
        return deletion.booleanValue();
    }

    return false;
}
 
Example 6
Source File: JsonFieldToMapPayloadExtractor.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected Object getPayloadValue(JsonNode event, String definitionName, String definitionType) {
    JsonNode parameterNode = event.get(definitionName);
    Object value = null;

    if (EventPayloadTypes.STRING.equals(definitionType)) {
        value = parameterNode.asText();

    } else if (EventPayloadTypes.BOOLEAN.equals(definitionType)) {
        value = parameterNode.booleanValue();

    } else if (EventPayloadTypes.INTEGER.equals(definitionType)) {
        value = parameterNode.intValue();

    } else if (EventPayloadTypes.DOUBLE.equals(definitionType)) {
        value = parameterNode.doubleValue();

    } else if (EventPayloadTypes.LONG.equals(definitionType)) {
      value = parameterNode.longValue();

    } else if (EventPayloadTypes.JSON.equals(definitionType)) {
        value = parameterNode;

    } else {
        LOGGER.warn("Unsupported payload type: {} ", definitionType);
        value = parameterNode.asText();

    }

    return value;
}
 
Example 7
Source File: RosettaBinder.java    From Rosetta with Apache License 2.0 5 votes vote down vote up
private Object unwrapJsonValue(JsonNode node) {
  if (node.isNull()) {
    return null;
  } else if (node.isBoolean()) {
    return node.booleanValue();
  } else if (node.isBinary()) {
    return ((BinaryNode) node).binaryValue();
  } else if (node.isNumber()) {
    return node.numberValue();
  } else {
    return node.asText();
  }
}
 
Example 8
Source File: UniqueItemsValidator.java    From json-schema-validator with Apache License 2.0 5 votes vote down vote up
public UniqueItemsValidator(String schemaPath, JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext) {
    super(schemaPath, schemaNode, parentSchema, ValidatorTypeCode.UNIQUE_ITEMS, validationContext);
    if (schemaNode.isBoolean()) {
        unique = schemaNode.booleanValue();
    }

    parseErrorCode(getValidatorType().getErrorCodeKey());
}
 
Example 9
Source File: JsonWrittenEventProvider.java    From tasmo with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean getBooleanField(String fieldname) {
    JsonNode value = fieldsNode.get(fieldname);
    if (value instanceof BooleanNode) {
        return value.booleanValue();
    } else {
        return null;
    }
}
 
Example 10
Source File: JsonWrittenEventProvider.java    From tasmo with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean getBooleanField(String fieldname) {
    JsonNode value = fieldsNode.get(fieldname);
    if (value instanceof BooleanNode) {
        return value.booleanValue();
    } else {
        return null;
    }
}
 
Example 11
Source File: RobotsFilter.java    From storm-crawler with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(Map stormConf, JsonNode filterParams) {
    Config conf = new Config();
    conf.putAll(stormConf);
    factory = new ProtocolFactory(conf);
    robots = new HttpRobotRulesParser(conf);

    JsonNode node = filterParams.get("fromCacheOnly");
    if (node != null && node.isBoolean()) {
        fromCacheOnly = node.booleanValue();
    }
}
 
Example 12
Source File: BooleanObjectIOProvider.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 Boolean attributeValue = jnode.isNull() ? null : jnode.booleanValue();
    graph.setObjectValue(attributeId, elementId, attributeValue);
}
 
Example 13
Source File: JsonExampleDeserializer.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
private Example createExample(JsonNode node) {
    if (node instanceof ObjectNode) {
        ObjectExample obj = new ObjectExample();
        ObjectNode on = (ObjectNode) node;
        for (Iterator<Entry<String, JsonNode>> x = on.fields(); x.hasNext(); ) {
            Entry<String, JsonNode> i = x.next();
            String key = i.getKey();
            JsonNode value = i.getValue();
            obj.put(key, createExample(value));
        }
        return obj;
    } else if (node instanceof ArrayNode) {
        ArrayExample arr = new ArrayExample();
        ArrayNode an = (ArrayNode) node;
        for (JsonNode childNode : an) {
            arr.add(createExample(childNode));
        }
        return arr;
    } else if (node instanceof DoubleNode) {
        return new DoubleExample(node.doubleValue());
    } else if (node instanceof IntNode || node instanceof ShortNode) {
        return new IntegerExample(node.intValue());
    } else if (node instanceof FloatNode) {
        return new FloatExample(node.floatValue());
    } else if (node instanceof BigIntegerNode) {
        return new BigIntegerExample(node.bigIntegerValue());
    } else if (node instanceof DecimalNode) {
        return new DecimalExample(node.decimalValue());
    } else if (node instanceof LongNode) {
        return new LongExample(node.longValue());
    } else if (node instanceof BooleanNode) {
        return new BooleanExample(node.booleanValue());
    } else {
        return new StringExample(node.asText());
    }
}
 
Example 14
Source File: DocumentAnalyzer.java    From azure-documentdb-java with MIT License 4 votes vote down vote up
private static PartitionKeyInternal extractPartitionKeyValueInternal(String documentAsString, PartitionKeyDefinition partitionKeyDefinition) {
    JsonNode root;
    try {
        root = objectMapper.readTree(documentAsString);

        Iterator<String> path = partitionKeyDefinition.getPaths().iterator();   
        JsonNode node =  root.path(path.next().substring(1));

        while(path.hasNext() && node != null) {
            node = node.path(path.next());
        }

        Object partitionKeyValue = null;

        if (node != null) {

            switch (node.getNodeType()) {
            case BOOLEAN:
                partitionKeyValue = node.booleanValue();
                break;
            case MISSING:
                partitionKeyValue = Undefined.Value();
                break;
            case NULL:
                partitionKeyValue = JSONObject.NULL;
                break;
            case NUMBER:
                partitionKeyValue = node.numberValue();
                break;
            case STRING:
                partitionKeyValue = node.textValue();
                break;
            default:
                throw new RuntimeException(String.format("undefined json type %s", node.getNodeType()));
            }
        } else {
            partitionKeyValue = Undefined.Value();
        }

        return fromPartitionKeyvalue(partitionKeyValue);

    } catch (Exception e) {
        LOGGER.error("Failed to extract partition key value from document {}", documentAsString, e);
        throw ExceptionUtils.toRuntimeException(e);
    }
}
 
Example 15
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 16
Source File: PropertyDeserializer.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
private static Boolean getBoolean(JsonNode node, PropertyBuilder.PropertyId type) {
    final JsonNode detailNode = getDetailNode(node, type);
    return detailNode == null ? null : detailNode.booleanValue();
}
 
Example 17
Source File: MaximumValidator.java    From json-schema-validator with Apache License 2.0 4 votes vote down vote up
public MaximumValidator(String schemaPath, final JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext) {
    super(schemaPath, schemaNode, parentSchema, ValidatorTypeCode.MAXIMUM, validationContext);

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

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

    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 || (excludeEqual && 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 || (excludeEqual && compare == 0);
                }
                long val = node.asLong();
                return lm < val || (excludeEqual && 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 || (excludeEqual && compare == 0);
            }

            @Override
            public String thresholdValue() {
                return maximumText;
            }
        };
    }
}
 
Example 18
Source File: PatchTestCase.java    From zjsonpatch with Apache License 2.0 4 votes vote down vote up
private static boolean isEnabled(JsonNode node) {
    JsonNode disabled = node.get("disabled");
    return (disabled == null || !disabled.booleanValue());
}
 
Example 19
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;
}
 
Example 20
Source File: JsonDataSource.java    From jasperreports with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public Object getFieldValue(JRField jrField) throws JRException 
{
	if(currentJsonNode == null) {
		return null;
	}
	
	String expression = null;
	if (fieldExpressions.containsKey(jrField.getName()))
	{
		expression = fieldExpressions.get(jrField.getName());
	}
	else
	{
		expression = getFieldExpression(jrField);
		fieldExpressions.put(jrField.getName(), expression);
	}
	if (expression == null || expression.length() == 0)
	{
		return null;
	}

	Object value = null;
	
	Class<?> valueClass = jrField.getValueClass();
	JsonNode selectedObject = getJsonData(currentJsonNode, expression);
	
	if(Object.class != valueClass) 
	{
		boolean hasValue = selectedObject != null 
				&& !selectedObject.isMissingNode() && !selectedObject.isNull();
		if (hasValue) 
		{
			try {
				if (valueClass.equals(String.class)) {
                       if (selectedObject.isArray()) {
                           value = selectedObject.toString();
                       } else {
                           value = selectedObject.asText();
                       }

				} else if (valueClass.equals(Boolean.class)) {
					value = selectedObject.booleanValue();
					
				} else if (Number.class.isAssignableFrom(valueClass)) {
					//FIXME if the json node is a number, avoid converting to string and parsing back the value
						value = convertStringValue(selectedObject.asText(), valueClass);
						
				}
				else if (Date.class.isAssignableFrom(valueClass)) {
						value = convertStringValue(selectedObject.asText(), valueClass);
						
				} else {
					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);
			}
		}
	}
	else
	{
		value = selectedObject;
	}
	
	return value;
}