Java Code Examples for com.fasterxml.jackson.databind.node.ArrayNode#elements()

The following examples show how to use com.fasterxml.jackson.databind.node.ArrayNode#elements() . 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: EnumChecker.java    From qconfig with MIT License 7 votes vote down vote up
public EnumChecker(ObjectNode node) {
    super(node);

    if (isNullable()) {
        enums.add("");
    }

    ArrayNode values = (ArrayNode) node.get(TemplateContants.VALUES);
    Iterator<JsonNode> iterator = values.elements();
    while (iterator.hasNext()) {
        JsonNode next = iterator.next();
        if (next.isTextual()) {
            enums.add(next.asText());
        } else {
            enums.add(next.get(TemplateContants.NAME).asText());
        }
    }

}
 
Example 2
Source File: JsonSchemaHelper.java    From syndesis with Apache License 2.0 6 votes vote down vote up
public static JsonNode sanitize(final JsonNode node) {
    if (node == null) {
        return null;
    }

    if (node.isArray()) {
        ArrayNode arrayNode = (ArrayNode) node;
        Iterator<JsonNode> elements = arrayNode.elements();
        elements.forEachRemaining(JsonSchemaHelper::sanitize);
    } else if (node.isObject()) {
        ObjectNode objectNode = (ObjectNode) node;

        JsonNode formatNode = node.get("format");
        if (formatNode != null &&
                formatNode.isTextual() &&
                !isKnownFormat(formatNode.asText())) {
            objectNode.remove("format");
        }

        Iterator<Map.Entry<String, JsonNode>> fields = objectNode.fields();
        fields.forEachRemaining(field -> sanitize(field.getValue()));
    }

    return node;
}
 
Example 3
Source File: JsonPatchValidator.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Validate the provided jsonNode using Entando criteria
 * @param jsonNode
 */
public void validatePatch(JsonNode jsonNode) {

    // Test if the json node is generically convertible to a Patch
    this.converter.convert(jsonNode);

    // Check if the operations are supported, can't access Spring PatchOperations as they are protected
    ArrayNode opNodes = (ArrayNode) jsonNode;

    for (Iterator<JsonNode> elements = opNodes.elements(); elements.hasNext(); ) {

        JsonNode opNode = elements.next();

        String opType = opNode.get("op").textValue();
        if (!ENTANDO_SUPPORTED_OPERATIONS.contains(opType)) {
            throw new PatchException("Not supported operation type: " + opType);
        }
    }
}
 
Example 4
Source File: SimpleHttpProvider.java    From streams with Apache License 2.0 6 votes vote down vote up
/**
 Override this to change how entity gets converted to objects.
 */
protected List<ObjectNode> parse(JsonNode jsonNode) {

  List<ObjectNode> results = new ArrayList<>();

  if (jsonNode != null && jsonNode instanceof ObjectNode ) {
    results.add((ObjectNode) jsonNode);
  } else if (jsonNode != null && jsonNode instanceof ArrayNode) {
    ArrayNode arrayNode = (ArrayNode) jsonNode;
    Iterator<JsonNode> iterator = arrayNode.elements();
    while (iterator.hasNext()) {
      ObjectNode element = (ObjectNode) iterator.next();

      results.add(element);
    }
  }

  return results;
}
 
Example 5
Source File: Configurations.java    From monasca-common with Apache License 2.0 6 votes vote down vote up
private static void buildConfigFor(String path, Map<String, String> config, JsonNode node) {
  for (Iterator<Map.Entry<String, JsonNode>> i = node.fields(); i.hasNext();) {
    Map.Entry<String, JsonNode> field = i.next();
    if (field.getValue() instanceof ValueNode) {
      ValueNode valueNode = (ValueNode) field.getValue();
      config.put(DOT_JOINER.join(path, field.getKey()), valueNode.asText());
    } else if (field.getValue() instanceof ArrayNode) {
      StringBuilder combinedValue = new StringBuilder();
      ArrayNode arrayNode = (ArrayNode) field.getValue();
      for (Iterator<JsonNode> it = arrayNode.elements(); it.hasNext();) {
        String value = it.next().asText().replaceAll("^\"|\"$", "");
        if (combinedValue.length() > 0)
          combinedValue.append(',');
        combinedValue.append(value);
      }

      config.put(DOT_JOINER.join(path, field.getKey()), combinedValue.toString());
    }

    buildConfigFor(DOT_JOINER.join(path, field.getKey()), config, field.getValue());
  }
}
 
Example 6
Source File: GitHubIdentityProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private String searchEmail(String accessToken) {
	try {
		ArrayNode emails = (ArrayNode) SimpleHttp.doGet(EMAIL_URL, session).header("Authorization", "Bearer " + accessToken).asJson();

		Iterator<JsonNode> loop = emails.elements();
		while (loop.hasNext()) {
			JsonNode mail = loop.next();
			if (mail.get("primary").asBoolean()) {
				return getJsonProperty(mail, "email");
			}
		}
	} catch (Exception e) {
		throw new IdentityBrokerException("Could not obtain user email from github.", e);
	}
	throw new IdentityBrokerException("Primary email from github is not found.");
}
 
Example 7
Source File: StringListMapDeserializer.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
    JsonNode jsonNode = jsonParser.readValueAsTree();
    Iterator<Map.Entry<String, JsonNode>> itr = jsonNode.fields();
    Map<String, List<String>> map = new HashMap<>();
    while (itr.hasNext()) {
        Map.Entry<String, JsonNode> e = itr.next();
        List<String> values = new LinkedList<>();
        if (!e.getValue().isArray()) {
            values.add((e.getValue().isNull()) ? null : e.getValue().asText());
        } else {
            ArrayNode a = (ArrayNode) e.getValue();
            Iterator<JsonNode> vitr = a.elements();
            while (vitr.hasNext()) {
                JsonNode node = vitr.next();
                values.add((node.isNull() ? null : node.asText()));
            }
        }
        map.put(e.getKey(), values);
    }
    return map;
}
 
Example 8
Source File: PerspectiveIOProvider.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, ImmutableObjectCache cache) throws IOException {
    if (!jnode.isNull()) {
        final PerspectiveModel model = new PerspectiveModel();

        final JsonNode root = jnode.get(LIST);
        if (root.isArray()) {
            final ArrayNode rootArray = (ArrayNode) root;
            for (final Iterator<JsonNode> i = rootArray.elements(); i.hasNext();) {
                final JsonNode element = i.next();

                final String label = element.get(LABEL).textValue();
                final int oldRelativeTo = element.get(RELATIVE_TO).intValue();
                final int relativeTo = vertexMap.getOrDefault(oldRelativeTo, Graph.NOT_FOUND);
                final Vector3f eye = readVector(element, EYE);
                final Vector3f centre = readVector(element, CENTRE);
                final Vector3f up = readVector(element, UP);
                final Vector3f rotate = readVector(element, ROTATE);

                // Don't load dud values.
                if (label != null && eye != null && centre != null && up != null && rotate != null) {
                    final Perspective p = new Perspective(label, relativeTo, centre, eye, up, rotate);
                    model.addElement(p);
                }
            }
        }

        graph.setObjectValue(attributeId, elementId, model);
    }
}
 
Example 9
Source File: CommerceUtils.java    From template-compiler with Apache License 2.0 5 votes vote down vote up
/**
   * Format money using CLDR currency formatter
   */
//  public static String getCLDRMoneyString(BigDecimal amount, String currencyCode, CLDR.Locale locale) {
//    return PluginUtils.formatMoney(amount, currencyCode, locale);
//  }

  public static void writeVariantFormat(JsonNode variant, StringBuilder buf) {
    ArrayNode optionValues = (ArrayNode) variant.get("optionValues");
    if (optionValues == null) {
      return;
    }

    Iterator<JsonNode> iterator = optionValues.elements();
    List<String> values = new ArrayList<>();

    while (iterator.hasNext()) {
      JsonNode option = iterator.next();
      values.add(option.get("value").asText());
    }

    int size = values.size();
    for (int i = 0; i < size; i++) {
      if (i > 0) {
        buf.append(" / ");
      }
      buf.append(values.get(i));
    }
  }
 
Example 10
Source File: JsonQueryTest.java    From link-move with Apache License 2.0 5 votes vote down vote up
private List<JsonNode> collectNodes(ArrayNode arrayNode) {

        List<JsonNode> nodes = new ArrayList<>();

        Iterator<JsonNode> iter = arrayNode.elements();
        while (iter.hasNext()) {
            nodes.add(iter.next());
        }
        return nodes;
    }
 
Example 11
Source File: JsonPatchPatchConverter.java    From spring-sync with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a {@link Patch} object given a JsonNode.
 * @param jsonNode a JsonNode containing the JSON Patch
 * @return a {@link Patch}
 */
public Patch convert(JsonNode jsonNode) {
	if (!(jsonNode instanceof ArrayNode)) {
		throw new IllegalArgumentException("JsonNode must be an instance of ArrayNode");
	}
	
	ArrayNode opNodes = (ArrayNode) jsonNode;
	List<PatchOperation> ops = new ArrayList<PatchOperation>(opNodes.size());
	for(Iterator<JsonNode> elements = opNodes.elements(); elements.hasNext(); ) {
		JsonNode opNode = elements.next();
		
		String opType = opNode.get("op").textValue();
		String path = opNode.get("path").textValue();
		
		JsonNode valueNode = opNode.get("value");
		Object value = valueFromJsonNode(path, valueNode);			
		String from = opNode.has("from") ? opNode.get("from").textValue() : null;

		if (opType.equals("test")) {
			ops.add(new TestOperation(path, value));
		} else if (opType.equals("replace")) {
			ops.add(new ReplaceOperation(path, value));
		} else if (opType.equals("remove")) {
			ops.add(new RemoveOperation(path));
		} else if (opType.equals("add")) {
			ops.add(new AddOperation(path, value));
		} else if (opType.equals("copy")) {
			ops.add(new CopyOperation(path, from));
		} else if (opType.equals("move")) {
			ops.add(new MoveOperation(path, from));
		} else {
			throw new PatchException("Unrecognized operation type: " + opType);
		}
	}
	
	return new Patch(ops);
}
 
Example 12
Source File: VbngManager.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Recovers from XOS record. Re-sets up the mapping between private IP
 * address and public IP address, re-calculates intents and re-installs
 * those intents.
 */
private void statusRecovery() {
    log.info("vBNG starts to recover from XOS record......");
    ObjectNode map;
    try {
        RestClient restClient =
                new RestClient(vbngConfigurationService.getXosIpAddress(),
                        vbngConfigurationService.getXosRestPort());
        map = restClient.getRest();
    } catch (Exception e) {
        log.warn("Could not contact XOS {}", e.getMessage());
        return;
    }
    if (map == null) {
        log.info("Stop to recover vBNG status due to the vBNG map "
                + "is null!");
        return;
    }

    log.info("Get record from XOS: {}", map);

    ArrayNode array = (ArrayNode) map.get(VBNG_MAP_NAME);
    Iterator<JsonNode> entries = array.elements();
    while (entries.hasNext()) {
        ObjectNode entry = (ObjectNode) entries.next();

        IpAddress hostIpAdddress =
                IpAddress.valueOf(entry.get("private_ip").asText());
        IpAddress publicIpAddress =
                IpAddress.valueOf(entry.get("routeable_subnet").asText());
        MacAddress macAddress =
                MacAddress.valueOf(entry.get("mac").asText());
        String hostName = entry.get("hostname").asText();

        // Create vBNG
        createVbng(hostIpAdddress, publicIpAddress, macAddress, hostName);

    }
}
 
Example 13
Source File: AddRecordStore.java    From constellation with Apache License 2.0 4 votes vote down vote up
@Override
public void callService(final PluginParameters parameters, final InputStream in, final OutputStream out) throws IOException {
    final String graphId = parameters.getStringValue(GRAPH_ID_PARAMETER_ID);
    final boolean completeWithSchema = parameters.getBooleanValue(COMPLETE_PARAMETER_ID);
    final String arrange = parameters.getStringValue(ARRANGE_PARAMETER_ID);
    final boolean resetView = parameters.getBooleanValue(RESET_PARAMETER_ID);

    final RecordStore rs = new GraphRecordStore();
    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode json = mapper.readTree(in);

    // We want to read a JSON document that looks like:
    //
    // {"columns":["A","B"],"data":[[1,"a"],[2,"b"],[3,"c"]]}
    //
    // which is what is output by pandas.to_json(..., orient="split').
    // (We ignore the index array.)
    if (!json.hasNonNull(COLUMNS) || !json.get(COLUMNS).isArray()) {
        throw new RestServiceException("Could not find columns object containing column names");
    }

    if (!json.hasNonNull("data") || !json.get("data").isArray()) {
        throw new RestServiceException("Could not find data object containing data rows");
    }

    final ArrayNode columns = (ArrayNode) json.get(COLUMNS);
    final String[] headers = new String[columns.size()];
    for (int i = 0; i < headers.length; i++) {
        headers[i] = columns.get(i).asText();
    }

    final ArrayNode data = (ArrayNode) json.get("data");
    for (final Iterator<JsonNode> i = data.elements(); i.hasNext();) {
        final ArrayNode jrow = (ArrayNode) i.next();
        rs.add();
        boolean txFound = false;
        boolean txSourceFound = false;
        for (int ix = 0; ix < headers.length; ix++) {
            final String h = headers[ix];
            final JsonNode jn = jrow.get(ix);
            if (!jn.isNull()) {
                if (jn.getNodeType() == JsonNodeType.ARRAY) {
                    rs.set(h, RestServiceUtilities.toList((ArrayNode) jn));
                } else {
                    rs.set(h, jn.asText());
                }
            }
            txFound |= h.startsWith(GraphRecordStoreUtilities.TRANSACTION);
            txSourceFound |= TX_SOURCE.equals(h);
        }

        if (txFound && !txSourceFound) {
            rs.set(TX_SOURCE, API_SOURCE);
        }
    }

    addToGraph(graphId, rs, completeWithSchema, arrange, resetView);
}
 
Example 14
Source File: SPARQLServiceConverter.java    From hypergraphql with Apache License 2.0 4 votes vote down vote up
private String getSelectNonRoot(ArrayNode jsonQuery, Set<String> input, String rootType) {


        JsonNode firstField = jsonQuery.elements().next();
        String graphID = ((SPARQLEndpointService) schema.getTypes().get(rootType).getFields().get(firstField.get("name").asText()).getService()).getGraph();
        String parentId = firstField.get("parentId").asText();
        String valueSTR = valuesSTR(parentId, input);

        Iterator<JsonNode> queryFieldsIterator = jsonQuery.elements();

        StringBuilder whereClause = new StringBuilder();

        while (queryFieldsIterator.hasNext()) {

            JsonNode field = queryFieldsIterator.next();

            String subquery = getFieldSubquery(field);

            whereClause.append(subquery);
        }

        return selectQuerySTR(valueSTR + (whereClause.toString()), graphID);
    }
 
Example 15
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 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));
        }
    }
}