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

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#fieldNames() . 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: CayenneExpParser.java    From agrest with Apache License 2.0 6 votes vote down vote up
private CayenneExp fromJsonObject(JsonNode node) {
    // 'exp' key is required; 'params' key is optional
    JsonNode expNode = node.get(JSON_KEY_EXP);
    if (expNode == null) {
        throw new AgException(Status.BAD_REQUEST, "'exp' key is missing in 'cayenneExp' map");
    }

    JsonNode paramsNode = node.get(JSON_KEY_PARAMS);
    if (paramsNode != null) {

        Map<String, Object> paramsMap = new HashMap<>();

        Iterator<String> it = paramsNode.fieldNames();
        while (it.hasNext()) {
            String key = it.next();
            JsonNode valueNode = paramsNode.get(key);
            Object val = extractValue(valueNode);
            paramsMap.put(key, val);
        }

        return new CayenneExp(expNode.asText(), paramsMap);
    }

    return new CayenneExp(expNode.asText());
}
 
Example 2
Source File: MaprElasticSearchServiceBuilder.java    From mapr-music with Apache License 2.0 6 votes vote down vote up
/**
 * Only specified fields will be sent to the ElasticSearch.
 *
 * @param original all the changes.
 * @return changes for the specified fields.
 */
private JsonNode copyOnlyAllowedFields(JsonNode original) {

    ObjectNode allowed = null;
    Iterator<String> fieldNamesIterator = original.fieldNames();
    while (fieldNamesIterator.hasNext()) {

        String fieldName = fieldNamesIterator.next();
        if (!fields.contains(fieldName)) {
            continue;
        }

        if (allowed == null) {
            allowed = mapper.createObjectNode();
        }

        allowed.set(fieldName, original.get(fieldName));
    }

    return allowed;
}
 
Example 3
Source File: ResponseReader.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
/**
 * Reads a {@link APIResponses} OpenAPI node.
 * 
 * @param node json object
 * @return APIResponses model
 */
public static APIResponses readResponses(final JsonNode node) {
    if (node == null || !node.isObject()) {
        return null;
    }
    IoLogging.log.jsonList("APIResponse");
    APIResponses model = new APIResponsesImpl();
    model.setDefaultValue(readResponse(node.get(ResponseConstant.PROP_DEFAULT)));
    for (Iterator<String> fieldNames = node.fieldNames(); fieldNames.hasNext();) {
        String fieldName = fieldNames.next();
        if (ResponseConstant.PROP_DEFAULT.equals(fieldName)) {
            continue;
        }
        model.addAPIResponse(fieldName, readResponse(node.get(fieldName)));
    }
    return model;
}
 
Example 4
Source File: JacksonDeserializer.java    From hawkular-alerts with Apache License 2.0 5 votes vote down vote up
public static Map<String, String> deserializeMap(JsonNode mapNode) {
    Map<String, String> map = new HashMap<>();
    Iterator<String> fieldNames = mapNode.fieldNames();
    while (fieldNames.hasNext()) {
        String field = fieldNames.next();
        map.put(field, mapNode.get(field).asText());
    }
    return map;
}
 
Example 5
Source File: ExampleReader.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Reads the {@link Example} OpenAPI nodes.
 *
 * @param node map of json nodes
 * @return Map of Example model
 */
public static Map<String, Example> readExamples(final JsonNode node) {
    if (node == null || !node.isObject()) {
        return null;
    }
    Map<String, Example> examples = new LinkedHashMap<>();
    for (Iterator<String> fieldNames = node.fieldNames(); fieldNames.hasNext();) {
        String fieldName = fieldNames.next();
        JsonNode childNode = node.get(fieldName);
        examples.put(fieldName, readExample(childNode));
    }

    return examples;
}
 
Example 6
Source File: Environment.java    From event-streams-samples with Apache License 2.0 5 votes vote down vote up
private static JsonNode parseVcapServices(String vcapServices) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode vcapServicesJson = mapper.readValue(vcapServices, JsonNode.class);

    // when running in CloudFoundry VCAP_SERVICES is wrapped into a bigger JSON object
    // so it needs to be extracted. We attempt to read the "instance_id" field to identify
    // if it has been wrapped
    if (vcapServicesJson.get("instance_id") != null) {
        return vcapServicesJson;
    } else {
        String vcapKey = null;
        Iterator<String> it = vcapServicesJson.fieldNames();
        // Find the Event Streams service bound to this application.
        while (it.hasNext() && vcapKey == null) {
            String potentialKey = it.next();
            if (potentialKey.startsWith(SERVICE_NAME)) {
                logger.warn("Using the '{}' key from VCAP_SERVICES.", potentialKey);
                vcapKey = potentialKey;
            }
        }

        if (vcapKey == null) {
            throw new IllegalSaslStateException("No Event Streams service bound");
        } else {
            return vcapServicesJson.get(vcapKey).get(0).get("credentials");
        }
    }
}
 
Example 7
Source File: JsonHelper.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
/**
 * returns the object associated with the given key, ignoring case
 * if object cannot be found, returns null
 *
 * @param node
 * @param key
 * @return value for given key
 */
public static JsonNode getNode(JsonNode node, String key) {

    Iterator<String> fieldNames = node.fieldNames();

    while (fieldNames.hasNext()) {
        String fieldName = fieldNames.next();
        if (fieldName.equalsIgnoreCase(key)) {
            return node.get(fieldName);
        }
    }

    return null;
}
 
Example 8
Source File: JsonDefinitionColumnVisibilityManagement.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] translateVisibility(final Object visibilityObject, final String fieldName) {
  if (visibilityObject == null) {
    return null;
  }
  try {
    final JsonNode attributeMap = mapper.readTree(visibilityObject.toString());
    final JsonNode field = attributeMap.get(fieldName);
    if ((field != null) && field.isValueNode()) {
      return validate(field.textValue());
    }
    final Iterator<String> attNameIt = attributeMap.fieldNames();
    while (attNameIt.hasNext()) {
      final String attName = attNameIt.next();
      if (fieldName.matches(attName)) {
        final JsonNode attNode = attributeMap.get(attName);
        if (attNode == null) {
          LOGGER.error(
              "Cannot parse visibility expression, JsonNode for attribute "
                  + attName
                  + " was null");
          return null;
        }
        return validate(attNode.textValue());
      }
    }
  } catch (IOException | NullPointerException e) {
    LOGGER.error("Cannot parse visibility expression " + visibilityObject.toString(), e);
  }
  return null;
}
 
Example 9
Source File: RequestBodyReader.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Reads the {@link RequestBody} OpenAPI nodes.
 * 
 * @param node json map of Request Bodies
 * @return Map of RequestBody model
 */
public static Map<String, RequestBody> readRequestBodies(final JsonNode node) {
    if (node == null || !node.isObject()) {
        return null;
    }
    IoLogging.log.jsonMap("RequestBody");
    Map<String, RequestBody> requestBodies = new LinkedHashMap<>();
    for (Iterator<String> fieldNames = node.fieldNames(); fieldNames.hasNext();) {
        String fieldName = fieldNames.next();
        JsonNode childNode = node.get(fieldName);
        requestBodies.put(fieldName, readRequestBody(childNode));
    }
    return requestBodies;
}
 
Example 10
Source File: StaticTests.java    From jslt with Apache License 2.0 5 votes vote down vote up
@Test
public void testObjectKeyOrder() {
  Expression expr = Parser.compileString("{\"a\":1, \"b\":2}");
  JsonNode actual = expr.apply(null);

  Iterator<String> it = actual.fieldNames();
  assertEquals("a", it.next());
  assertEquals("b", it.next());
}
 
Example 11
Source File: DynamoDocumentStoreTemplate.java    From Cheddar with Apache License 2.0 5 votes vote down vote up
public JsonNode merge(final JsonNode newNode, final JsonNode oldNode) {
    final Set<String> allFieldNames = new HashSet<>();
    final Iterator<String> newNodeFieldNames = oldNode.fieldNames();
    while (newNodeFieldNames.hasNext()) {
        allFieldNames.add(newNodeFieldNames.next());
    }
    final Iterator<String> oldNodeFieldNames = oldNode.fieldNames();
    while (oldNodeFieldNames.hasNext()) {
        allFieldNames.add(oldNodeFieldNames.next());
    }
    final JsonNode mergedNode = newNode.deepCopy();
    for (final String fieldName : allFieldNames) {
        final JsonNode newNodeValue = newNode.get(fieldName);
        final JsonNode oldNodeValue = oldNode.get(fieldName);
        if (newNodeValue == null && oldNodeValue == null) {
            logger.trace("Skipping (both null): " + fieldName);
        } else if (newNodeValue == null && oldNodeValue != null) {
            logger.trace("Using old (new is null): " + fieldName);
            ((ObjectNode) mergedNode).set(fieldName, oldNodeValue);
        } else if (newNodeValue != null && oldNodeValue == null) {
            logger.trace("Using new (old is null): " + fieldName);
            ((ObjectNode) mergedNode).set(fieldName, newNodeValue);
        } else {
            logger.trace("Using new: " + fieldName);
            if (oldNodeValue.isObject()) {
                ((ObjectNode) mergedNode).set(fieldName, merge(newNodeValue, oldNodeValue));
            } else {
                ((ObjectNode) mergedNode).set(fieldName, newNodeValue);
            }
        }
    }
    return mergedNode;
}
 
Example 12
Source File: ProductService.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * get the white list
 */
@Override
public Map<String, Object> getWhiteList(){
    String content;
    try {
        content = productdao.getWhiteListContent();
    } catch (DataException e1) {
        logger.warn(e1.getMessage());
        content =null;
    }
    if(!StringUtils.isEmpty(content)) {
        try {
            Map<String, Object> json = new HashMap<String, Object>();
            JsonNode node = new ObjectMapper().readTree(content);
            Iterator<String> names = node.fieldNames();
            for (Iterator<String> iter = names; iter.hasNext();) {
                String locale = (String) iter.next();
                json.put(locale, node.get(locale).asText());
            }
            return json;
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }else {
        return null;
    }
}
 
Example 13
Source File: LinkReader.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Reads the {@link Link} OpenAPI nodes.
 * 
 * @param node the json node
 * @return Map of Link model
 */
public static Map<String, Link> readLinks(final JsonNode node) {
    if (node == null || !node.isObject()) {
        return null;
    }
    IoLogging.log.jsonNodeMap("Link");
    Map<String, Link> links = new LinkedHashMap<>();
    for (Iterator<String> fieldNames = node.fieldNames(); fieldNames.hasNext();) {
        String fieldName = fieldNames.next();
        JsonNode childNode = node.get(fieldName);
        links.put(fieldName, readLink(childNode));
    }

    return links;
}
 
Example 14
Source File: LinkReader.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Reads the map of {@link Link} parameters.
 * 
 * @param node the json node
 * @return map of parameters
 */
private static Map<String, Object> readLinkParameters(final JsonNode node) {
    if (node == null || !node.isObject()) {
        return null;
    }
    Map<String, Object> rval = new LinkedHashMap<>();
    for (Iterator<String> fieldNames = node.fieldNames(); fieldNames.hasNext();) {
        String fieldName = fieldNames.next();
        Object value = readObject(node.get(fieldName));
        rval.put(fieldName, value);
    }
    return rval;
}
 
Example 15
Source File: JsonUtil.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Reads a map of strings.
 * 
 * @param node json map
 * @return a String-String map
 */
public static Optional<Map<String, String>> readStringMap(JsonNode node) {
    if (node != null && node.isObject()) {
        Map<String, String> rval = new LinkedHashMap<>();
        for (Iterator<String> fieldNames = node.fieldNames(); fieldNames.hasNext();) {
            String fieldName = fieldNames.next();
            String value = JsonUtil.stringProperty(node, fieldName);
            rval.put(fieldName, value);
        }
        return Optional.of(rval);
    }
    return Optional.empty();
}
 
Example 16
Source File: EncryptedPayloadTest.java    From orion with Apache License 2.0 5 votes vote down vote up
@Test
void serializationToJsonWithoutEncryptedKeyOwners() throws Exception {
  final EncryptedKey encryptedKey = new EncryptedKey("Encrypted key fakery".getBytes(UTF_8));
  final EncryptedPayload payload = new EncryptedPayload(
      Box.KeyPair.random().publicKey(),
      "fake nonce".getBytes(UTF_8),
      new EncryptedKey[] {encryptedKey},
      "fake ciphertext".getBytes(UTF_8),
      "fake group".getBytes(UTF_8));
  final byte[] serialized = Serializer.serialize(HttpContentType.JSON, payload);
  final ObjectMapper mapper = new ObjectMapper();
  final JsonNode jsonNode = mapper.readTree(serialized);
  jsonNode.fieldNames();
}
 
Example 17
Source File: Flattener.java    From foxtrot with Apache License 2.0 4 votes vote down vote up
@Override
public void visit(TrendResponse trendResponse) {
    List<FieldHeader> headers = Lists.newArrayListWithCapacity(3);
    JsonNode root = objectMapper.valueToTree(trendResponse.getTrends());
    if(null == root || !root.isObject()) {
        return;
    }
    List<String> types = Lists.newArrayList();
    List<Map<String, Object>> rows = Lists.newArrayList();
    Iterator<String> typeNameIt = root.fieldNames();
    Map<String, Map<String, Object>> representation = Maps.newTreeMap();
    int typeNameMaxLength = 0;
    while (typeNameIt.hasNext()) {
        String typeName = typeNameIt.next();
        types.add(typeName);
        typeNameMaxLength = Math.max(typeNameMaxLength, typeName.length());
        for(JsonNode dataNode : root.get(typeName)) {
            final String time = Long.toString(dataNode.get("period")
                                                      .asLong());
            if(!representation.containsKey(time)) {
                representation.put(time, Maps.newHashMap());
            }
            representation.get(time)
                    .put(typeName, dataNode.get(COUNT)
                            .asLong());
        }
    }

    headers.add(new FieldHeader("time", 20));
    for(String type : types) {
        headers.add(new FieldHeader(type, 20));
    }
    for(Map.Entry<String, Map<String, Object>> element : representation.entrySet()) {
        Map<String, Object> row = Maps.newTreeMap();
        row.put("time", element.getKey());
        for(Map.Entry<String, Object> data : element.getValue()
                .entrySet()) {
            row.put(data.getKey(), data.getValue());
        }
        rows.add(row);
    }
    flatRepresentation = new FlatRepresentation("trend", new ArrayList<>(headers), rows);
}
 
Example 18
Source File: SchemaSetLoader.java    From curator with Apache License 2.0 4 votes vote down vote up
private void readNode(ImmutableList.Builder<Schema> builder, JsonNode node, SchemaValidatorMapper schemaValidatorMapper)
{
    String name = getText(node, "name", null);
    String path = getText(node, "path", null);
    boolean isRegex = getBoolean(node, "isRegex");
    if ( name == null )
    {
        throw new RuntimeException("name is required at: " + node);
    }
    if ( path == null )
    {
        throw new RuntimeException("path is required at: " + node);
    }

    SchemaBuilder schemaBuilder = isRegex ? Schema.builder(Pattern.compile(path)) : Schema.builder(path);

    String schemaValidatorName = getText(node, "schemaValidator", null);
    if ( schemaValidatorName != null )
    {
        if ( schemaValidatorMapper == null )
        {
            throw new RuntimeException("No SchemaValidatorMapper provided but needed at: " + node);
        }
        schemaBuilder.dataValidator(schemaValidatorMapper.getSchemaValidator(schemaValidatorName));
    }

    Map<String, String> metadata = Maps.newHashMap();
    if ( node.has("metadata") )
    {
        JsonNode metadataNode = node.get("metadata");
        Iterator<String> fieldNameIterator = metadataNode.fieldNames();
        while ( fieldNameIterator.hasNext() )
        {
            String fieldName = fieldNameIterator.next();
            metadata.put(fieldName, getText(metadataNode, fieldName, ""));
        }
    }

    Schema schema = schemaBuilder.name(name)
        .documentation(getText(node, "documentation", ""))
        .ephemeral(getAllowance(node, "ephemeral"))
        .sequential(getAllowance(node, "sequential"))
        .watched(getAllowance(node, "watched"))
        .canBeDeleted(getBoolean(node, "canBeDeleted"))
        .metadata(metadata)
        .build();
    builder.add(schema);
}
 
Example 19
Source File: AIROptionsParser.java    From vscode-as3mxml with Apache License 2.0 4 votes vote down vote up
protected void parseSigningOptions(JsonNode signingOptions, boolean debug, List<String> result)
{
	if(signingOptions.has(AIRSigningOptions.DEBUG) && debug)
	{
		parseSigningOptions(signingOptions.get(AIRSigningOptions.DEBUG), debug, result);
		return;
	}
	if(signingOptions.has(AIRSigningOptions.RELEASE) && !debug)
	{
		parseSigningOptions(signingOptions.get(AIRSigningOptions.RELEASE), debug, result);
		return;
	}

	if(signingOptions.has(AIRSigningOptions.PROVISIONING_PROFILE))
	{
		setPathValueWithoutAssignment(AIRSigningOptions.PROVISIONING_PROFILE, signingOptions.get(AIRSigningOptions.PROVISIONING_PROFILE).asText(), result);
	}
	if(signingOptions.has(AIRSigningOptions.ALIAS))
	{
		setValueWithoutAssignment(AIRSigningOptions.ALIAS, signingOptions.get(AIRSigningOptions.ALIAS).asText(), result);
	}
	if(signingOptions.has(AIRSigningOptions.STORETYPE))
	{
		setValueWithoutAssignment(AIRSigningOptions.STORETYPE, signingOptions.get(AIRSigningOptions.STORETYPE).asText(), result);
	}
	if(signingOptions.has(AIRSigningOptions.KEYSTORE))
	{
		setPathValueWithoutAssignment(AIRSigningOptions.KEYSTORE, signingOptions.get(AIRSigningOptions.KEYSTORE).asText(), result);
	}
	if(signingOptions.has(AIRSigningOptions.PROVIDER_NAME))
	{
		setValueWithoutAssignment(AIRSigningOptions.PROVIDER_NAME, signingOptions.get(AIRSigningOptions.PROVIDER_NAME).asText(), result);
	}
	if(signingOptions.has(AIRSigningOptions.TSA))
	{
		setValueWithoutAssignment(AIRSigningOptions.TSA, signingOptions.get(AIRSigningOptions.TSA).asText(), result);
	}
	Iterator<String> fieldNames = signingOptions.fieldNames();
	while(fieldNames.hasNext())
	{
		String fieldName = fieldNames.next();
		switch(fieldName)
		{
			case AIRSigningOptions.ALIAS:
			case AIRSigningOptions.STORETYPE:
			case AIRSigningOptions.KEYSTORE:
			case AIRSigningOptions.PROVIDER_NAME:
			case AIRSigningOptions.TSA:
			case AIRSigningOptions.PROVISIONING_PROFILE:
			{
				break;
			}
			default:
			{
				throw new Error("Unknown Adobe AIR signing option: " + fieldName);
			}
		}
	}
}
 
Example 20
Source File: JsonODataErrorDeserializer.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
protected ODataError doDeserialize(final JsonParser parser) throws IOException {

    final ODataError error = new ODataError();

    final ObjectNode tree = parser.getCodec().readTree(parser);
    if (tree.has(Constants.JSON_ERROR)) {
      final JsonNode errorNode = tree.get(Constants.JSON_ERROR);

      if (errorNode.has(Constants.ERROR_CODE)) {
        error.setCode(errorNode.get(Constants.ERROR_CODE).textValue());
      }
      if (errorNode.has(Constants.ERROR_MESSAGE)) {
        final JsonNode message = errorNode.get(Constants.ERROR_MESSAGE);
        if (message.isValueNode()) {
          error.setMessage(message.textValue());
        } else if (message.isObject()) {
          error.setMessage(message.get(Constants.VALUE).asText());
        }
      }
      if (errorNode.has(Constants.ERROR_TARGET)) {
        error.setTarget(errorNode.get(Constants.ERROR_TARGET).textValue());
      }
      if (errorNode.hasNonNull(Constants.ERROR_DETAILS)) {
        List<ODataErrorDetail> details = new ArrayList<>();
        JsonODataErrorDetailDeserializer detailDeserializer = new JsonODataErrorDetailDeserializer(serverMode);
        for (JsonNode jsonNode : errorNode.get(Constants.ERROR_DETAILS)) {
          details.add(detailDeserializer.doDeserialize(jsonNode.traverse(parser.getCodec()))
              .getPayload());
        }

        error.setDetails(details);
      }
      if (errorNode.hasNonNull(Constants.ERROR_INNERERROR)) {
        HashMap<String, String> innerErrorMap = new HashMap<>();
        final JsonNode innerError = errorNode.get(Constants.ERROR_INNERERROR);
        for (final Iterator<String> itor = innerError.fieldNames(); itor.hasNext();) {
          final String keyTmp = itor.next();
          final String val = innerError.get(keyTmp).toString();
          innerErrorMap.put(keyTmp, val);
        }
        error.setInnerError(innerErrorMap);
      }
    }

    return error;
  }