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

The following examples show how to use com.fasterxml.jackson.databind.node.ArrayNode#addAll() . 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: DXJSON.java    From dxWDL with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a JSON array.
 */
public ArrayNode build() {
    ArrayNode output = mapper.createArrayNode();
    ArrayBuilder nextBuilder = this;
    List<ArrayBuilder> builders = Lists.newArrayList();
    // We'll need to process this linked list in the reverse order, so
    // that the first items to be added (which are at the "tail") go
    // into the result list first.
    while (!nextBuilder.isEmpty) {
        builders.add(nextBuilder);
        nextBuilder = nextBuilder.next;
    }
    Collections.reverse(builders);

    for (ArrayBuilder builder : builders) {
        if (builder.value != null) {
            output.add(builder.value);
        }
        if (builder.listValue != null) {
            output.addAll(builder.listValue);
        }
    }
    return output;
}
 
Example 2
Source File: LargeTextNodeRemover.java    From foxtrot with Apache License 2.0 6 votes vote down vote up
private void handleArrayNode(final String table,
                             final String documentId,
                             final String parentKey,
                             ArrayNode arrayNode) {
    if (arrayNode == null || arrayNode.isNull()) {
        return;
    }
    ArrayNode copy = objectMapper.createArrayNode();
    arrayNode.elements()
            .forEachRemaining(node -> {
                boolean copyNode = true;
                if (node.isObject()) {
                    handleObjectNode(table, documentId, (ObjectNode) node);
                } else if (node.isArray()) {
                    handleArrayNode(table, documentId, parentKey, (ArrayNode) node);
                } else if (node.isTextual()) {
                    copyNode = !evaluateForRemoval(table, documentId, parentKey, node);
                }
                if (copyNode) {
                    copy.add(node);
                }
            });
    arrayNode.removeAll();
    arrayNode.addAll(copy);
}
 
Example 3
Source File: PlusOperator.java    From jslt with Apache License 2.0 5 votes vote down vote up
private ArrayNode concatenateArrays(JsonNode v1, JsonNode v2) {
  // .addAll is faster than many .add() calls
  ArrayNode result = NodeUtils.mapper.createArrayNode();
  result.addAll((ArrayNode) v1);
  result.addAll((ArrayNode) v2);
  return result;
}
 
Example 4
Source File: ProductSyncMockUtils.java    From commercetools-sync-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an {@link AttributeDraft} with the supplied {@code attributeName} and {@code references}.
 *
 * @param attributeName the name to set on the {@link AttributeDraft}.
 * @param references    the references to set on the {@link AttributeDraft}.
 * @return an {@link AttributeDraft} with the supplied {@code attributeName} and {@code references}.
 */
@Nonnull
public static AttributeDraft getReferenceSetAttributeDraft(@Nonnull final String attributeName,
                                                           @Nonnull final ObjectNode... references) {
    final ArrayNode referenceSet = JsonNodeFactory.instance.arrayNode();
    referenceSet.addAll(Arrays.asList(references));
    return AttributeDraft.of(attributeName, referenceSet);
}
 
Example 5
Source File: Metrics.java    From open-Autoscaler with Apache License 2.0 5 votes vote down vote up
public String transformOutput() throws JsonParseException, JsonMappingException, IOException{
	String current_json =  BeanValidation.new_mapper.writeValueAsString(this.data);
	JsonNode top = BeanValidation.new_mapper.readTree(current_json);
	JsonObjectComparator comparator = new JsonObjectComparator("timestamp", "long");
	Iterator<JsonNode> elements = top.elements();
	List<JsonNode> elements_sorted = new ArrayList<JsonNode>();
	while(elements.hasNext()){
		elements_sorted.add(elements.next());
	}
	Collections.sort(elements_sorted, comparator);

	ObjectNode jNode = BeanValidation.new_mapper.createObjectNode();

	List<JsonNode> sub_list;
    long last_timestamp;
    int max_len = Integer.parseInt(ConfigManager.get("maxMetricRecord"));
    BeanValidation.logger.info("Current maxMetricRecord returned is " + max_len + " and current number of metric record is " + elements_sorted.size());
    if(elements_sorted.size() > max_len){
    	sub_list = elements_sorted.subList(0, max_len);
    	JsonNode last_metric = elements_sorted.get(max_len-1);
    	last_timestamp = last_metric.get("timestamp").asLong();
    }
    else {
    	sub_list = elements_sorted;
    	last_timestamp = 0;
    }

    JsonNodeFactory factory = JsonNodeFactory.instance;
    ArrayNode aaData = new ArrayNode(factory);
    aaData.addAll(sub_list);
	jNode.set("data", aaData);
    jNode.put("timestamp", last_timestamp);
	return jNode.toString();

}
 
Example 6
Source File: InitializrMetadataV2JsonMapper.java    From initializr with Apache License 2.0 5 votes vote down vote up
protected void singleSelect(ObjectNode parent, SingleSelectCapability capability,
		Function<MetadataElement, ObjectNode> valueMapper) {
	ObjectNode single = nodeFactory.objectNode();
	single.put("type", capability.getType().getName());
	DefaultMetadataElement defaultType = capability.getDefault();
	if (defaultType != null) {
		single.put("default", defaultType.getId());
	}
	ArrayNode values = nodeFactory.arrayNode();
	values.addAll(capability.getContent().stream().map(valueMapper).collect(Collectors.toList()));
	single.set("values", values);
	parent.set(capability.getId(), single);
}
 
Example 7
Source File: JsonUtil.java    From n2o-framework with Apache License 2.0 4 votes vote down vote up
public static void mergeArrays(ArrayNode mainArray, ArrayNode updateArray) {
    mainArray.addAll(updateArray);
}
 
Example 8
Source File: RawMetricResource.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
public Representation doRepresent() {
	
	/**
	 * Fetch data metrics for both HistoricalMetricProvider & TransientMetricProvider
	 */
	String projectId = (String) getRequest().getAttributes().get("projectid");
	String metricId = (String) getRequest().getAttributes().get("metricid");
	
	String start = getQueryValue("startDate");
	String end = getQueryValue("endDate");
	
	QueryBuilder builder = QueryBuilder.start();
	try {
		if (start != null && start != "") {
			builder.and("__datetime").greaterThanEquals(new Date(start).toJavaDate());
		}
		if (end != null && end != "") {
			builder.and("__datetime").lessThanEquals(new Date(end).toJavaDate());
		}
	} catch (ParseException e) {
		e.getStackTrace();
	}
	
	BasicDBObject query = (BasicDBObject) builder.get(); 
	
	ArrayNode results = mapper.createArrayNode();
			
	if (projectId != null && metricId != null) {
		this.db = mongo.getDB(ANALYSIS_SCHEDULING_DATABASE);
		ProjectAnalysisResportory repository = new ProjectAnalysisResportory(this.db);
		Iterable<MetricExecution> listMetricExecutions = repository.getMetricExecutions().findByProjectId(projectId);
		
		List<String> metricExecutions = new ArrayList<>();
		for (MetricExecution metricExecution : listMetricExecutions) {
			metricExecutions.add(metricExecution.getMetricProviderId());
		}

		if (metricExecutions.contains(metricId)) {
			List<IMetricProvider> platformProvider = this.platform.getMetricProviderManager().getMetricProviders();
			for (IMetricProvider iMetricProvider : platformProvider) {
				if (iMetricProvider.getIdentifier().equals(metricId)) {
					Project project = platform.getProjectRepositoryManager().getProjectRepository().getProjects().findOneByShortName(projectId);
					if(iMetricProvider instanceof IHistoricalMetricProvider) {
						results.addAll(getHistoricDocuments(platform.getMetricsRepository(project).getDb().getCollection(((IHistoricalMetricProvider) iMetricProvider).getCollectionName()), query));
					} else if (iMetricProvider instanceof ITransientMetricProvider) {
						results.addAll(getTransientDocuments(((ITransientMetricProvider) iMetricProvider).adapt(platform.getMetricsRepository(project).getDb()).getPongoCollections()));
					}
					break;
				}
			}

		}
	
	}
	
	return Util.createJsonRepresentation(results);
}
 
Example 9
Source File: JacksonRuntime.java    From jmespath-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public JsonNode createArray(Collection<JsonNode> elements) {
  ArrayNode array = JsonNodeFactory.instance.arrayNode();
  array.addAll(elements);
  return array;
}
 
Example 10
Source File: JacksonUtil.java    From endpoints-java with Apache License 2.0 4 votes vote down vote up
/**
 * Safely merge two array nodes. This will append values from the second
 * array into the first array, and return the first array.
 */
public static ArrayNode mergeArray(ArrayNode array1, ArrayNode array2) {
  array1.addAll(array2);
  return array1;
}
 
Example 11
Source File: BeanValidation.java    From open-Autoscaler with Apache License 2.0 4 votes vote down vote up
public static String transformHistory(List<HistoryData> scalinghistory) throws JsonParseException, JsonMappingException, IOException{
	String current_json =  new_mapper.writeValueAsString(scalinghistory);
	JsonNode top = new_mapper.readTree(current_json);
	Iterator<JsonNode> elements = top.elements();
	int instances= -1, adjustment=-1;
	while (elements.hasNext()){
		JsonNode history_data = elements.next();
		Iterator<Entry<String, JsonNode>> history_data_items= history_data.fields();
		while(history_data_items.hasNext()){
			Entry<String, JsonNode> Node = history_data_items.next();
			String nodestring = Node.getKey();
			JsonNode subNode = Node.getValue();
			if(nodestring.equals("status")){
				switch(subNode.asInt()){
					case 1: ((ObjectNode)history_data).put("status", "READY");
       	                    break;
		        	case 2: ((ObjectNode)history_data).put("status", "REALIZING");
		        	        break;
		        	case 3: ((ObjectNode)history_data).put("status", "COMPLETED");
			                break;
			        case -1: ((ObjectNode)history_data).put("status", "FAILED");
			                  break;
			        default: break;
				}
			} else if (nodestring.equals("trigger")){
				Iterator<Entry<String, JsonNode>> trigger_items= subNode.fields();
				while (trigger_items.hasNext()){
					Entry<String, JsonNode> item_node = trigger_items.next();
					String item_name = item_node.getKey();
					JsonNode item_value = item_node.getValue();
					if(item_name.equals("triggerType")){
						switch(item_value.asInt()){
							case 0: ((ObjectNode)subNode).put("triggerType", "MonitorEvent");
    	                            break;
				        	case 1: ((ObjectNode)subNode).put("triggerType", "PolicyChange");
				        	        break;
					        default: break;
						}
					}
				}
			} else if (nodestring.equals("instances")){
				instances = subNode.asInt();
			} else if (nodestring.equals("adjustment")){
				adjustment = subNode.asInt();
			}
		}
		((ObjectNode)history_data).put("instancesBefore", instances - adjustment);
		((ObjectNode)history_data).put("instancesAfter", instances);
		((ObjectNode)history_data).remove("instances");
		((ObjectNode)history_data).remove("adjustment");
	}


	JsonObjectComparator comparator = new JsonObjectComparator("startTime", "long");
	elements = top.elements();
	List<JsonNode> elements_sorted = new ArrayList<JsonNode>();
	while(elements.hasNext()){
		elements_sorted.add(elements.next());
	}
	Collections.sort(elements_sorted, comparator);

	ObjectNode jNode = new_mapper.createObjectNode();


	List<JsonNode> sub_list;
    long last_timestamp;
    int max_len = Integer.parseInt(ConfigManager.get("maxHistoryRecord"));
    logger.info("Current maxHistoryRecord returned is " + max_len + " and current number of history record is " + elements_sorted.size());
    if(elements_sorted.size() > max_len){
    	sub_list = elements_sorted.subList(0, max_len);
    	JsonNode last_history = elements_sorted.get(max_len-1);
    	last_timestamp = last_history.get("startTime").asLong();
    }
    else {
    	sub_list = elements_sorted;
    	last_timestamp = 0;
    }

    JsonNodeFactory factory = JsonNodeFactory.instance;
    ArrayNode aaData = new ArrayNode(factory);
    aaData.addAll(sub_list);
	jNode.set("data", aaData);
    jNode.put("timestamp", last_timestamp);
	return jNode.toString();

}
 
Example 12
Source File: CrdGenerator.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
private <E extends Enum<E>> ArrayNode enumCaseArray(E[] values) {
    ArrayNode arrayNode = nf.arrayNode();
    arrayNode.addAll(Schema.enumCases(values));
    return arrayNode;
}
 
Example 13
Source File: DynamoDBSolWorker.java    From aws-dynamodb-mars-json-demo with Apache License 2.0 4 votes vote down vote up
/**
 * Gets ArrayNode containing JSON representations of images if the manifest ETag does not match the provided old
 * ETag for the provided URL.
 *
 * @param sol
 *            JSON representation of a sol
 * @return ArrayNode containing JSON representation of images
 * @throws IOException
 *             Invalid URL, invalid JSON, or connection error
 */
public static ArrayNode getImages(final JsonNode sol) throws IOException {
    final ArrayNode images = new ArrayNode(JsonNodeFactory.instance);
    if (sol != null) {
        // Check version
        if (!sol.has(VERSION_KEY) || !SUPPORTED_VERSIONS.contains(sol.get(VERSION_KEY).asText())) {
            throw new IllegalArgumentException("Unsupported sol type: " + sol.get(VERSION_KEY));
        }
        // Check for mission name
        if (!sol.has(MISSION_KEY)) {
            throw new IllegalArgumentException("Mission name missing");
        }
        // Check for sol number
        if (!sol.has(SOL_KEY)) {
            throw new IllegalArgumentException("Sol number missing");
        }
        final String mission = sol.get(MISSION_KEY).asText();
        final Integer solNum = sol.get(SOL_KEY).asInt();
        final Iterator<Map.Entry<String, JsonNode>> solIt = sol.fields();
        // Process keys that point to instrument image arrays
        // Rather than hard-coding in the keys for the instruments, use
        // pattern matching to find instrument keys
        while (solIt.hasNext()) {
            final Map.Entry<String, JsonNode> entry = solIt.next();
            final String key = entry.getKey();
            final Matcher matcher = INSTRUMENT_PATTERN.matcher(key);
            if (matcher.matches()) {
                if (matcher.groupCount() == 1) {
                    final String instrument = matcher.group(matcher.groupCount());
                    // Blacklisted instruments do not provide the fields required
                    if (!DO_NOT_PROCESS_INSTRUMENTS.contains(instrument)) {
                        // Process instrument to get images
                        images.addAll(parseInstrumentImages("Sol " + solNum + "->" + key, mission, instrument,
                            entry.getValue()));
                    }
                } else {
                    LOGGER.warning("Unexpected instrument name: Sol" + solNum + "->" + key);
                }
            }
        }
    }
    return images;
}