Java Code Examples for org.codehaus.jackson.JsonNode#isObject()

The following examples show how to use org.codehaus.jackson.JsonNode#isObject() . 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: InjectConfigTest.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
public static JsonNode merge(JsonNode mainNode, JsonNode updateNode)
{
  Iterator<String> fieldNames = updateNode.getFieldNames();
  while (fieldNames.hasNext()) {
    String fieldName = fieldNames.next();
    JsonNode jsonNode = mainNode.get(fieldName);
    // if field doesn't exist or is an embedded object
    if (jsonNode != null && jsonNode.isObject()) {
      merge(jsonNode, updateNode.get(fieldName));
    } else {
      if (mainNode instanceof ObjectNode) {
        // Overwrite field
        JsonNode value = updateNode.get(fieldName);
        ((ObjectNode)mainNode).put(fieldName, value);
      }
    }
  }
  return mainNode;
}
 
Example 2
Source File: JsonCredentialStore.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Instantiate a new keystore using the file at the provided path
 */
public JsonCredentialStore(Path path, KeyToStringCodec codec) throws IOException {
  credentials =  new HashMap<>();

  FileSystem fs = path.getFileSystem(new Configuration());
  try (InputStream in = fs.open(path)) {
    ObjectMapper jsonParser = defaultMapper;
    JsonNode tree = jsonParser.readTree(in);
    if (!tree.isObject()) {
      throw new IllegalArgumentException("Json in " + path.toString() + " is not an object!");
    }

    Iterator<Map.Entry<String, JsonNode>> it = tree.getFields();
    while (it.hasNext()) {
      Map.Entry<String, JsonNode> field = it.next();
      String keyId = field.getKey();
      byte[] key = codec.decodeKey(field.getValue().getTextValue());

      credentials.put(keyId, key);
    }
  }

  log.info("Initialized keystore from {} with {} keys", path.toString(), credentials.size());
}
 
Example 3
Source File: JsonRestSourceHandler.java    From ingestion with Apache License 2.0 6 votes vote down vote up
@Override public List<Event> getEvents(String body, Map<String, String> headers) {

        List<Event> events = new ArrayList<Event>(0);
        ObjectMapper mapper = new ObjectMapper();
        try {
            JsonNode jsonNode = mapper.readTree(body);
            if (jsonNode.isObject()) {
                events.add(buildSingleEvent(headers, findValue(jsonNode, path)));
            }
            if (jsonNode.isArray()) {
                final Iterator<JsonNode> elements = jsonNode.getElements();
                JsonNode element;
                while (elements.hasNext()) {
                    element = elements.next();
                    events.add(buildSingleEvent(headers, findValue(element, path)));
                }
                
            }

        } catch (Exception e) {
            LOG.warn("An error ocurred while response parsing. Then content is not valid: " + body);
        }

        return events;

    }
 
Example 4
Source File: SchemaValidator.java    From avro-util with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * validation logic taken out of class {@link Schema} with adaptations
 * @param schema schema (type) of a field
 * @param defaultValue default value provided for said field in the parent schema
 * @throws SchemaParseException is name is invalid
 */
private static boolean isValidDefault(Schema schema, JsonNode defaultValue) {
  if (defaultValue == null) {
    return false;
  }
  switch (schema.getType()) {
    case STRING:
    case BYTES:
    case ENUM:
    case FIXED:
      return defaultValue.isTextual();
    case INT:
    case LONG:
    case FLOAT:
    case DOUBLE:
      return defaultValue.isNumber();
    case BOOLEAN:
      return defaultValue.isBoolean();
    case NULL:
      return defaultValue.isNull();
    case ARRAY:
      if (!defaultValue.isArray()) {
        return false;
      }
      for (JsonNode element : defaultValue) {
        if (!isValidDefault(schema.getElementType(), element)) {
          return false;
        }
      }
      return true;
    case MAP:
      if (!defaultValue.isObject()) {
        return false;
      }
      for (JsonNode value : defaultValue) {
        if (!isValidDefault(schema.getValueType(), value)) {
          return false;
        }
      }
      return true;
    case UNION: // union default: first branch
      return isValidDefault(schema.getTypes().get(0), defaultValue);
    case RECORD:
      if (!defaultValue.isObject()) {
        return false;
      }
      for (Schema.Field field : schema.getFields()) {
        if (!isValidDefault(
              field.schema(),
              defaultValue.get(field.name()) != null ? defaultValue.get(field.name()) : field.defaultValue()
        )) {
          return false;
        }
      }
      return true;
    default:
      return false;
  }
}
 
Example 5
Source File: GenericServiceAPIResponseEntityDeserializer.java    From Eagle with Apache License 2.0 4 votes vote down vote up
@Override
public GenericServiceAPIResponseEntity deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    GenericServiceAPIResponseEntity entity = new GenericServiceAPIResponseEntity();
    ObjectCodec objectCodec = jp.getCodec();

    JsonNode rootNode = jp.getCodec().readTree(jp);
    if(rootNode.isObject()){
        Iterator<Map.Entry<String,JsonNode>> fields = rootNode.getFields();
        JsonNode objNode = null;
        while(fields.hasNext()){
            Map.Entry<String,JsonNode> field = fields.next();
            if (META_FIELD.equals(field.getKey()) && field.getValue() != null)
                entity.setMeta(objectCodec.readValue(field.getValue().traverse(), Map.class));
            else if(SUCCESS_FIELD.equals(field.getKey()) && field.getValue() != null){
                entity.setSuccess(field.getValue().getValueAsBoolean(false));
            }else if(EXCEPTION_FIELD.equals(field.getKey()) && field.getValue() != null){
                entity.setException(field.getValue().getTextValue());
            }else if(TYPE_FIELD.endsWith(field.getKey())  && field.getValue() != null){
                try {
                    entity.setType(Class.forName(field.getValue().getTextValue()));
                } catch (ClassNotFoundException e) {
                    throw new IOException(e);
                }
            }else if(OBJ_FIELD.equals(field.getKey()) && field.getValue() != null){
                objNode = field.getValue();
            }
        }

        if(objNode!=null) {
            JavaType collectionType=null;
            if (entity.getType() != null) {
                collectionType = TypeFactory.defaultInstance().constructCollectionType(LinkedList.class, entity.getType());
            }else{
                collectionType = TypeFactory.defaultInstance().constructCollectionType(LinkedList.class, Map.class);
            }
            List obj = objectCodec.readValue(objNode.traverse(), collectionType);
            entity.setObj(obj);
        }
    }else{
        throw new IOException("root node is not object");
    }
    return entity;
}
 
Example 6
Source File: AbstractSiteToSiteReportingTask.java    From nifi with Apache License 2.0 4 votes vote down vote up
protected Object getRawNodeValue(final JsonNode fieldNode, final DataType dataType) throws IOException {
    if (fieldNode == null || fieldNode.isNull()) {
        return null;
    }

    if (fieldNode.isNumber()) {
        return fieldNode.getNumberValue();
    }

    if (fieldNode.isBinary()) {
        return fieldNode.getBinaryValue();
    }

    if (fieldNode.isBoolean()) {
        return fieldNode.getBooleanValue();
    }

    if (fieldNode.isTextual()) {
        return fieldNode.getTextValue();
    }

    if (fieldNode.isArray()) {
        final ArrayNode arrayNode = (ArrayNode) fieldNode;
        final int numElements = arrayNode.size();
        final Object[] arrayElements = new Object[numElements];
        int count = 0;

        final DataType elementDataType;
        if (dataType != null && dataType.getFieldType() == RecordFieldType.ARRAY) {
            final ArrayDataType arrayDataType = (ArrayDataType) dataType;
            elementDataType = arrayDataType.getElementType();
        } else {
            elementDataType = null;
        }

        for (final JsonNode node : arrayNode) {
            final Object value = getRawNodeValue(node, elementDataType);
            arrayElements[count++] = value;
        }

        return arrayElements;
    }

    if (fieldNode.isObject()) {
        RecordSchema childSchema;
        if (dataType != null && RecordFieldType.RECORD == dataType.getFieldType()) {
            final RecordDataType recordDataType = (RecordDataType) dataType;
            childSchema = recordDataType.getChildSchema();
        } else {
            childSchema = null;
        }

        if (childSchema == null) {
            childSchema = new SimpleRecordSchema(Collections.emptyList());
        }

        final Iterator<String> fieldNames = fieldNode.getFieldNames();
        final Map<String, Object> childValues = new HashMap<>();
        while (fieldNames.hasNext()) {
            final String childFieldName = fieldNames.next();
            final Object childValue = getRawNodeValue(fieldNode.get(childFieldName), dataType);
            childValues.put(childFieldName, childValue);
        }

        final MapRecord record = new MapRecord(childSchema, childValues);
        return record;
    }

    return null;
}
 
Example 7
Source File: JsonSchemaInference.java    From nifi with Apache License 2.0 4 votes vote down vote up
protected DataType getDataType(final JsonNode jsonNode) {
    if (jsonNode.isTextual()) {
        final String text = jsonNode.getTextValue();
        if (text == null) {
            return RecordFieldType.STRING.getDataType();
        }

        final Optional<DataType> timeDataType = timeValueInference.getDataType(text);
        return timeDataType.orElse(RecordFieldType.STRING.getDataType());
    }

    if (jsonNode.isObject()) {
        final RecordSchema schema = createSchema(jsonNode);
        return RecordFieldType.RECORD.getRecordDataType(schema);
    }

    if (jsonNode.isIntegralNumber()) {
        if (jsonNode.isBigInteger()) {
            return RecordFieldType.BIGINT.getDataType();
        }
        return RecordFieldType.LONG.getDataType();
    }

    if (jsonNode.isBigDecimal()) {
        final DecimalNode decimalNode = (DecimalNode) jsonNode;
        final BigDecimal value = decimalNode.getDecimalValue();
        return RecordFieldType.DECIMAL.getDecimalDataType(value.precision(), value.scale());
    }

    if (jsonNode.isFloatingPointNumber()) {
        return RecordFieldType.DOUBLE.getDataType();
    }
    if (jsonNode.isBinary()) {
        return RecordFieldType.ARRAY.getArrayDataType(RecordFieldType.BYTE.getDataType());
    }
    if (jsonNode.isBoolean()) {
        return RecordFieldType.BOOLEAN.getDataType();
    }

    return null;
}
 
Example 8
Source File: JsonSchemaInference.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
protected boolean isObject(final JsonNode value) {
    return value.isObject();
}