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

The following examples show how to use com.fasterxml.jackson.databind.node.ObjectNode#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: LogicalFilter3.java    From jolt with Apache License 2.0 6 votes vote down vote up
@Override
public LogicalFilter3 deserialize( JsonParser jp, DeserializationContext ctxt ) throws IOException {

    ObjectCodec objectCodec = jp.getCodec();
    ObjectNode root = jp.readValueAsTree();

    // We assume it is a LogicalFilter
    Iterator<String> iter = root.fieldNames();
    String key = iter.next();

    JsonNode arrayNode = root.iterator().next();
    if ( arrayNode == null || arrayNode.isMissingNode() || ! arrayNode.isArray() ) {
        throw new RuntimeException( "Invalid format of LogicalFilter encountered." );
    }

    // pass in our objectCodec so that the subJsonParser knows about our configured Modules and Annotations
    JsonParser subJsonParser = arrayNode.traverse( objectCodec );
    List<QueryFilter> childrenQueryFilters = subJsonParser.readValueAs( new TypeReference<List<QueryFilter>>() {} );

    return new LogicalFilter3( QueryParam.valueOf( key ), childrenQueryFilters );
}
 
Example 2
Source File: PrintingController.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void removeNulls(JsonNode tree) {
	if (tree instanceof ArrayNode) {
		ArrayNode array = (ArrayNode) tree;
		for (int i = array.size() - 1; i >= 0; i--) {
			if (array.get(i).isNull()) {
				array.remove(i);
			} else {
				removeNulls(array.get(i));
			}
		}
	} else if (tree instanceof ObjectNode) {
		ObjectNode object = (ObjectNode) tree;
		Set<String> nulls = new HashSet<String>();
		for (Iterator<String> it = object.fieldNames(); it.hasNext();) {
			String name = it.next();
			if (object.get(name).isNull()) {
				nulls.add(name);
			} else {
				removeNulls(object.get(name));
			}
		}
		object.remove(nulls);
	}
}
 
Example 3
Source File: ServiceParameters.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link ServiceParameters} instance based on all properties in the given object node. Only numbers, text and boolean values are added, nested object structures are ignored.
 */
public static ServiceParameters fromObjectNode(ObjectNode node) {
    ServiceParameters parameters = new ServiceParameters();

    Iterator<String> ir = node.fieldNames();
    String name = null;
    JsonNode value = null;
    while (ir.hasNext()) {
        name = ir.next();
        value = node.get(name);

        // Depending on the type, extract the raw value object
        if (value != null) {
            if (value.isNumber()) {
                parameters.addParameter(name, value.numberValue());
            } else if (value.isBoolean()) {
                parameters.addParameter(name, value.booleanValue());
            } else if (value.isTextual()) {
                parameters.addParameter(name, value.textValue());
            }
        }
    }
    return parameters;
}
 
Example 4
Source File: ServiceParameters.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link ServiceParameters} instance based on all properties in the given
 * object node. Only numbers, text and boolean values are added, nested object structures
 * are ignored.
 */
public static ServiceParameters fromObjectNode(ObjectNode node) {
	ServiceParameters parameters = new ServiceParameters();
	
	Iterator<String> ir = node.fieldNames();
	String name = null;
	JsonNode value = null; 
	while(ir.hasNext()) {
		name = ir.next();
		value = node.get(name);
		
		// Depending on the type, extract the raw value object
		if(value != null) {
			if(value.isNumber()) {
				parameters.addParameter(name, value.numberValue());
			} else if(value.isBoolean()) {
				parameters.addParameter(name, value.booleanValue());
			} else if(value.isTextual()) {
				parameters.addParameter(name, value.textValue());
			}
		}
	}
  return parameters;
 }
 
Example 5
Source File: JsonCrudService.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
private void replaceRelation(Collection collection, UUID id, ObjectNode data, User user)
  throws IOException, NotFoundException, PermissionFetchingException {

  JsonNode accepted = data.get("accepted");
  if (accepted == null || !accepted.isBoolean()) {
    throw new IOException("Only the property accepted can be updated. It must be a boolean");
  }
  JsonNode rev = data.get("^rev");
  if (rev == null || !rev.isNumber()) {
    throw new IOException("^rev must be a number");
  }

  for (Iterator<String> fieldNames = data.fieldNames(); fieldNames.hasNext(); ) {
    String name = fieldNames.next();
    if (!name.startsWith("^") && !name.startsWith("@") && !name.equals("_id") && !name.equals("accepted")) {
      throw new IOException("Only 'accepted' is a changeable property");
    }
  }

  UpdateRelation updateRelation = new UpdateRelation(id, rev.asInt(), accepted.asBoolean());

  timDbAccess.replaceRelation(collection, updateRelation, user);

}
 
Example 6
Source File: JSONUtilities.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
protected Set<String> retrieveAllLinkNames(final InputStream is) throws IOException {
  final ObjectNode srcNode = (ObjectNode) mapper.readTree(is);
  IOUtils.closeQuietly(is);

  final Set<String> links = new HashSet<String>();

  final Iterator<String> fieldIter = srcNode.fieldNames();

  while (fieldIter.hasNext()) {
    final String field = fieldIter.next();

    if (field.endsWith(Constants.get(ConstantKey.JSON_NAVIGATION_BIND_SUFFIX))
        || field.endsWith(Constants.get(ConstantKey.JSON_NAVIGATION_SUFFIX))
        || field.endsWith(Constants.get(ConstantKey.JSON_MEDIA_SUFFIX))
        || field.endsWith(Constants.get(ConstantKey.JSON_EDITLINK_NAME))) {
      if (field.indexOf('@') > 0) {
        links.add(field.substring(0, field.indexOf('@')));
      } else {
        links.add(field);
      }
    }
  }

  return links;
}
 
Example 7
Source File: InPlaceLeftHandMerger.java    From bootique with Apache License 2.0 6 votes vote down vote up
protected JsonNode mergeObjects(JsonNode target, JsonNode source) {

        ObjectNode targetObject = (ObjectNode) target;
        ObjectNode srcObject = (ObjectNode) source;

        Iterator<String> fieldNames = srcObject.fieldNames();
        while (fieldNames.hasNext()) {

            String fieldName = fieldNames.next();
            JsonNode srcChild = srcObject.get(fieldName);
            JsonNode targetChild = targetObject.get(fieldName);

            targetObject.replace(fieldName, apply(targetChild, srcChild));
        }

        return target;
    }
 
Example 8
Source File: JsonUtils.java    From search-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
public static Map<String, Object> parserMap(ObjectNode node) {
    Map<String, Object> map = new HashMap<String, Object>();
    Iterator<String> iterable = node.fieldNames();
    while (iterable.hasNext()) {
        String key = iterable.next();
        JsonNode jsonNode = node.get(key);
        if (jsonNode.isValueNode()) {
            map.put(key, parserValue(jsonNode));
        } else if (jsonNode.isArray()) {
            map.put(key, parserArrayNode((ArrayNode) jsonNode));
        } else if (jsonNode.isObject()) {
            map.put(key, parserMap((ObjectNode) jsonNode));
        }
    }
    return map;
}
 
Example 9
Source File: JsonEventConventions.java    From tasmo with Apache License 2.0 5 votes vote down vote up
public String getInstanceClassName(ObjectNode eventNode) {
    int idx = 0;
    for (Iterator<String> fieldNames = eventNode.fieldNames(); fieldNames.hasNext();) {
        String fieldName = fieldNames.next();
        if (idx++ < ReservedFields.EVENT_FIELD_COUNT) {
            if (!fieldName.equals(ReservedFields.EVENT_ID)
                && !fieldName.equals(ReservedFields.TENANT_ID)
                && !fieldName.equals(ReservedFields.USER_ID)
                && !fieldName.equals(ReservedFields.ACTOR_ID)
                && !fieldName.equals(ReservedFields.CAUSED_BY)
                && !fieldName.equals(ReservedFields.ACTIVITY_VERB)
                && !fieldName.equals(ReservedFields.EVENT_TYPE)
                && !fieldName.equals(ReservedFields.MODEL_VERSION_ID)
                && !fieldName.equals(ReservedFields.NIL_FIELD)
                && !fieldName.equals(ReservedFields.TRACK_EVENT_PROCESSED_LIFECYCLE)) {
                return fieldName;
            }
        } else {
            Iterator<String> allFields = eventNode.fieldNames();
            List<String> annoying = Lists.newArrayList();
            while (allFields.hasNext()) {
                annoying.add(allFields.next());
            }
            throw new IllegalArgumentException("Supplied event node has an unexpected set of fields: " + Arrays.toString(annoying.toArray()));
        }
    }

    return null;
}
 
Example 10
Source File: JsonUtil.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
public static void merge(ObjectNode mainNode, ObjectNode updateNode) {
    Iterator<String> fieldNames = updateNode.fieldNames();
    while (fieldNames.hasNext()) {
        String fieldName = fieldNames.next();
        JsonNode jsonMainNode = mainNode.get(fieldName);
        JsonNode jsonUpdateNode = updateNode.get(fieldName);
        if (jsonMainNode != null && (jsonMainNode.isObject() && jsonUpdateNode.isObject())) {
            merge((ObjectNode) jsonMainNode, (ObjectNode) jsonUpdateNode);
        } else if (jsonMainNode != null && jsonMainNode.isArray() && jsonUpdateNode.isArray()) {
            mergeArrays((ArrayNode) jsonMainNode, (ArrayNode) jsonUpdateNode);
        } else {
            mainNode.put(fieldName, jsonUpdateNode);
        }
    }
}
 
Example 11
Source File: LocalMaterializationSystemBuilder.java    From tasmo with Apache License 2.0 5 votes vote down vote up
private String getViewClassFromViewModel(ObjectNode viewNode) {
    for (Iterator<String> it = viewNode.fieldNames(); it.hasNext();) {
        String fieldName = it.next();

        JsonNode got = viewNode.get(fieldName);
        if (got != null && !got.isNull() && got.isObject() && got.has(ReservedFields.VIEW_OBJECT_ID)) {
            return fieldName;
        }
    }

    return "";
}
 
Example 12
Source File: PostProcessBenchmarkResults.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
private void removeFields(ObjectNode node, Predicate<String> fieldNamePredicate) {
    List<String> fieldNamesToRemove = new ArrayList<>();
    for (Iterator<String> it = node.fieldNames(); it.hasNext(); ) {
        final String fieldName = it.next();
        if (fieldNamePredicate.test(fieldName)) {
            fieldNamesToRemove.add(fieldName);
        }
    }
    node.remove(fieldNamesToRemove);
}
 
Example 13
Source File: JsonFilterSpecMapper.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
private List<FilterSpec> deserialize(JsonNode jsonNode, ResourceInformation resourceInformation, PathSpec jsonAttributePath, QueryContext queryContext) {
	if (jsonNode instanceof ArrayNode) {
		return deserializeJsonArrayFilter((ArrayNode) jsonNode, resourceInformation, jsonAttributePath, queryContext);
	}
	else if (jsonNode instanceof ObjectNode) {
		ObjectNode objectNode = (ObjectNode) jsonNode;

		List<FilterSpec> filterSpecs = new ArrayList<>();
		Iterator<String> fieldNames = objectNode.fieldNames();
		while (fieldNames.hasNext()) {
			String fieldName = fieldNames.next();
			JsonNode element = objectNode.get(fieldName);
			FilterOperator operator = findOperator(fieldName);
			if (operator != null) {
				filterSpecs.add(deserializeJsonOperatorFilter(operator, element, resourceInformation, jsonAttributePath, queryContext));
			}
			else if (element instanceof ObjectNode) {
				PathSpec nestedAttrPath = jsonAttributePath.append(fieldName);
				filterSpecs.add(FilterSpec.and(deserialize(element, resourceInformation, nestedAttrPath, queryContext)));
			}
			else {
				PathSpec nestedJsonAttrPath = jsonAttributePath.append(fieldName);
				QueryPathSpec resolvedImplPath = pathResolver.resolve(resourceInformation, nestedJsonAttrPath.getElements(), QueryPathResolver.NamingType.JSON, "filter", queryContext);
				Object value = deserializeJsonFilterValue(resourceInformation, nestedJsonAttrPath, element, queryContext);
				filterSpecs.add(new FilterSpec(resolvedImplPath.getAttributePath(), FilterOperator.EQ, value));
			}
		}
		return filterSpecs;
	}
	else {
		throw newParseException(jsonNode);
	}
}
 
Example 14
Source File: OozieExternalService.java    From celos with Apache License 2.0 5 votes vote down vote up
Properties setupDefaultProperties(ObjectNode defaults, ScheduledTime t) {
    Properties props = new Properties();
    ScheduledTimeFormatter formatter = new ScheduledTimeFormatter();
    for (Iterator<String> names = defaults.fieldNames(); names.hasNext();) {
        String name = names.next();
        String value = defaults.get(name).textValue();
        props.setProperty(name, formatter.replaceTimeTokens(value, t));
    }
    return props;
}
 
Example 15
Source File: IdeaJSON.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static NodeModel toNodeModel(ObjectNode idea) {

	// Pull out the style attributes
	String color = null;
	if (idea.has(MAPJS_JSON_ATTRIBUTES_KEY)) {
	    ObjectNode attributes = JsonUtil.optObject(idea, MAPJS_JSON_ATTRIBUTES_KEY);
	    if (attributes.has(MAPJS_JSON_STYLE_KEY)) {
		ObjectNode styles = JsonUtil.optObject(attributes, MAPJS_JSON_STYLE_KEY);
		color = JsonUtil.optString(styles, MAPJS_JSON_BACKGROUND_COLOR_KEY);
	    }
	}
	if (color == null || color.length() == 0) {
	    color = DEFAULT_COLOR;
	}

	String creator = JsonUtil.optString(idea, "creator");
	NodeConceptModel nodeConceptModel = new NodeConceptModel(JsonUtil.optLong(idea, MAPJS_JSON_ID_KEY),
		JsonUtil.optString(idea, MAPJS_JSON_TITLE_KEY), color, creator);
	NodeModel nodeModel = new NodeModel(nodeConceptModel);

	if (idea.has(MAPJS_JSON_IDEAS_KEY)) {
	    ObjectNode ideas = JsonUtil.optObject(idea, MAPJS_JSON_IDEAS_KEY);
	    Iterator<String> keys = ideas.fieldNames();
	    while (keys.hasNext()) {
		String key = keys.next();
		nodeModel.addNode(IdeaJSON.toNodeModel(JsonUtil.optObject(ideas, key)));
	    }
	}

	return nodeModel;
    }
 
Example 16
Source File: JacksonUtil.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
public static ObjectNode mergeObject(ObjectNode object1, ObjectNode object2,
    boolean throwOnConflict) {
  Iterator<String> fieldNames = object2.fieldNames();
  while (fieldNames.hasNext()) {
    String fieldName = fieldNames.next();
    JsonNode child2 = object2.get(fieldName);
    JsonNode child1 = object1.get(fieldName);
    JsonNode merged = (child1 == null) ? child2 : mergeNode(child1, child2, throwOnConflict);
    object1.put(fieldName, merged);
  }
  return object1;
}
 
Example 17
Source File: TestComponentActivityParser.java    From incubator-taverna-language with Apache License 2.0 5 votes vote down vote up
@Test
public void parseSimpleTell() throws Exception {
	WorkflowBundle researchObj = parseWorkflow(WF_SIMPLE_COMPONENT);
	Profile profile = researchObj.getMainProfile();
	assertNotNull("could not find profile in bundle", profile);

	Processor comp = researchObj.getMainWorkflow().getProcessors()
			.getByName("combiner");
	assertNotNull("could not find processor 'combiner'", comp);

	Configuration config = scufl2Tools
			.configurationForActivityBoundToProcessor(comp, profile);

	Activity act = (Activity) config.getConfigures();
	assertEquals(ACTIVITY_URI, act.getType());

	ObjectNode resource = config.getJsonAsObjectNode();
	assertEquals(ACTIVITY_URI.resolve("#Config"), config.getType());

	int length = 0;
	Iterator<?> i = resource.fieldNames();
	while (i.hasNext()) {
		i.next();
		length++;
	}
	assertEquals("must be exactly 4 items in the translated component", 4,
			length);

	assertEquals("http://www.myexperiment.org", resource
			.get("registryBase").textValue());
	assertEquals("SCAPE Utility Components", resource.get("familyName")
			.textValue());
	assertEquals("MeasuresDocCombiner", resource.get("componentName")
			.textValue());
	assertEquals(1, resource.get("componentVersion").asInt());

	assertEquals(2, comp.getInputPorts().size());
	assertEquals(1, comp.getOutputPorts().size());
}
 
Example 18
Source File: KVStoreUtil.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
private static IKVStore readObjectNodeToKVStore(final ObjectNode node) {
	Iterator<String> fieldNameIt = node.fieldNames();
	IKVStore store = new KVStore();

	while (fieldNameIt.hasNext()) {
		String fieldName = fieldNameIt.next();
		JsonNode value = node.get(fieldName);
		switch (value.getNodeType()) {
		case BOOLEAN:
			store.put(fieldName, value.asBoolean());
			break;
		case MISSING:
			store.put(fieldName, null);
			break;
		case NULL:
			store.put(fieldName, null);
			break;
		case NUMBER:
			store.put(fieldName, value.asText());
			break;
		case STRING:
			store.put(fieldName, value.asText());
			break;
		default:
			store.put(fieldName, value.asText());
			break;
		}
	}
	return store;
}
 
Example 19
Source File: KeycloakIdentity.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public KeycloakIdentity(AccessToken accessToken, KeycloakSession keycloakSession) {
    if (accessToken == null) {
        throw new ErrorResponseException("invalid_bearer_token", "Could not obtain bearer access_token from request.", Status.FORBIDDEN);
    }
    if (keycloakSession == null) {
        throw new ErrorResponseException("no_keycloak_session", "No keycloak session", Status.FORBIDDEN);
    }
    this.accessToken = accessToken;
    this.keycloakSession = keycloakSession;
    this.realm = keycloakSession.getContext().getRealm();

    Map<String, Collection<String>> attributes = new HashMap<>();

    try {
        ObjectNode objectNode = JsonSerialization.createObjectNode(this.accessToken);
        Iterator<String> iterator = objectNode.fieldNames();

        while (iterator.hasNext()) {
            String fieldName = iterator.next();
            JsonNode fieldValue = objectNode.get(fieldName);
            List<String> values = new ArrayList<>();

            if (fieldValue.isArray()) {
                Iterator<JsonNode> valueIterator = fieldValue.iterator();

                while (valueIterator.hasNext()) {
                    values.add(valueIterator.next().asText());
                }
            } else {
                String value = fieldValue.asText();

                if (StringUtil.isNullOrEmpty(value)) {
                    continue;
                }

                values.add(value);
            }

            if (!values.isEmpty()) {
                attributes.put(fieldName, values);
            }
        }

        AccessToken.Access realmAccess = accessToken.getRealmAccess();

        if (realmAccess != null) {
            attributes.put("kc.realm.roles", realmAccess.getRoles());
        }

        Map<String, AccessToken.Access> resourceAccess = accessToken.getResourceAccess();

        if (resourceAccess != null) {
            resourceAccess.forEach((clientId, access) -> attributes.put("kc.client." + clientId + ".roles", access.getRoles()));
        }

        ClientModel clientModel = getTargetClient();
        UserModel clientUser = null;

        if (clientModel != null) {
            clientUser = this.keycloakSession.users().getServiceAccount(clientModel);
        }

        UserModel userSession = getUserFromSessionState();

        this.resourceServer = clientUser != null && userSession.getId().equals(clientUser.getId());

        if (resourceServer) {
            this.id = clientModel.getId();
        } else {
            this.id = userSession.getId();
        }
    } catch (Exception e) {
        throw new RuntimeException("Error while reading attributes from security token.", e);
    }

    this.attributes = Attributes.from(attributes);
}
 
Example 20
Source File: AtlasGraphSONUtility.java    From incubator-atlas with Apache License 2.0 4 votes vote down vote up
private static Object getValue(Object value, final boolean includeType) {

        Object returnValue = value;

        // if the includeType is set to true then show the data types of the properties
        if (includeType) {

            // type will be one of: map, list, string, long, int, double, float.
            // in the event of a complex object it will call a toString and store as a
            // string
            String type = determineType(value);

            ObjectNode valueAndType = JSON_NODE_FACTORY.objectNode();
            valueAndType.put(AtlasGraphSONTokens.TYPE, type);

            if (type.equals(AtlasGraphSONTokens.TYPE_LIST)) {

                // values of lists must be accumulated as ObjectNode objects under the value key.
                // will return as a ArrayNode. called recursively to traverse the entire
                // object graph of each item in the array.
                ArrayNode list = (ArrayNode) value;

                // there is a set of values that must be accumulated as an array under a key
                ArrayNode valueArray = valueAndType.putArray(AtlasGraphSONTokens.VALUE);
                for (int ix = 0; ix < list.size(); ix++) {
                    // the value of each item in the array is a node object from an ArrayNode...must
                    // get the value of it.
                    addObject(valueArray, getValue(getTypedValueFromJsonNode(list.get(ix)), includeType));
                }

            } else if (type.equals(AtlasGraphSONTokens.TYPE_MAP)) {

                // maps are converted to a ObjectNode.  called recursively to traverse
                // the entire object graph within the map.
                ObjectNode convertedMap = JSON_NODE_FACTORY.objectNode();
                ObjectNode jsonObject = (ObjectNode) value;
                Iterator<?> keyIterator = jsonObject.fieldNames();
                while (keyIterator.hasNext()) {
                    Object key = keyIterator.next();

                    // no need to getValue() here as this is already a ObjectNode and should have type info
                    convertedMap.put(key.toString(), jsonObject.get(key.toString()));
                }

                valueAndType.put(AtlasGraphSONTokens.VALUE, convertedMap);
            } else {

                // this must be a primitive value or a complex object.  if a complex
                // object it will be handled by a call to toString and stored as a
                // string value
                putObject(valueAndType, AtlasGraphSONTokens.VALUE, value);
            }

            // this goes back as a JSONObject with data type and value
            returnValue = valueAndType;
        }

        return returnValue;
    }