Java Code Examples for com.fasterxml.jackson.databind.node.ObjectNode#setAll()
The following examples show how to use
com.fasterxml.jackson.databind.node.ObjectNode#setAll() .
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: AbstrDockerCmdExec.java From docker-java with Apache License 2.0 | 7 votes |
@Nonnull protected String registryConfigs(@Nonnull AuthConfigurations authConfigs) { try { final String json; final RemoteApiVersion apiVersion = dockerClientConfig.getApiVersion(); ObjectMapper objectMapper = dockerClientConfig.getObjectMapper(); if (apiVersion.equals(UNKNOWN_VERSION)) { ObjectNode rootNode = objectMapper.valueToTree(authConfigs.getConfigs()); // all registries final ObjectNode authNodes = objectMapper.valueToTree(authConfigs); // wrapped in "configs":{} rootNode.setAll(authNodes); // merge 2 variants json = rootNode.toString(); } else if (apiVersion.isGreaterOrEqual(VERSION_1_19)) { json = objectMapper.writeValueAsString(authConfigs.getConfigs()); } else { json = objectMapper.writeValueAsString(authConfigs); } return BaseEncoding.base64Url().encode(json.getBytes()); } catch (IOException e) { throw new RuntimeException(e); } }
Example 2
Source File: QLearningExpander.java From samantha with MIT License | 6 votes |
public List<ObjectNode> expand(List<ObjectNode> initialResult, RequestContext requestContext) { List<ObjectNode> expandedResult = new ArrayList<>(); for (ObjectNode input : initialResult) { if (sampleRate == null || new Random().nextDouble() <= sampleRate) { List<ObjectNode> newStates = transitioner.transition(input, input); ObjectNode reqBody = Json.newObject(); SamanthaConfigService configService = injector.instanceOf(SamanthaConfigService.class); double qvalue = input.get(rewardAttr).asDouble(); double delayedReward = 0.0; reqBody.setAll(input); for (ObjectNode newState : newStates) { reqBody.setAll(newState); RequestContext pseudoReq = new RequestContext(reqBody, requestContext.getEngineName()); Recommender recommender = configService.getRecommender(recommenderName, pseudoReq); RankedResult rankedResult = recommender.recommend(pseudoReq); if (rankedResult.getLimit() > 0) { delayedReward += rankedResult.getRankingList().get(0).getScore(); } } input.put(delayedRewardAttr, qvalue + decay * delayedReward); expandedResult.add(input); } } return expandedResult; }
Example 3
Source File: LossAvailabilityStatCurrentCodec.java From onos with Apache License 2.0 | 5 votes |
@Override public ObjectNode encode(LossAvailabilityStatCurrent laCurrent, CodecContext context) { checkNotNull(laCurrent, "LA current cannot be null"); ObjectNode result = context.mapper().createObjectNode() .put("startTime", laCurrent.startTime().toString()) .put("elapsedTime", laCurrent.elapsedTime().toString()); ObjectNode resultAbstract = new LossAvailabilityStatCodec().encode(laCurrent, context); result.setAll(resultAbstract); return result; }
Example 4
Source File: VirtualLinkCodec.java From onos with Apache License 2.0 | 5 votes |
@Override public ObjectNode encode(VirtualLink vLink, CodecContext context) { checkNotNull(vLink, NULL_OBJECT_MSG); ObjectNode result = context.mapper().createObjectNode() .put(NETWORK_ID, vLink.networkId().toString()); JsonCodec<Link> codec = context.codec(Link.class); ObjectNode linkResult = codec.encode(vLink, context); result.setAll(linkResult); return result; }
Example 5
Source File: ProcessInstanceMigrationDocumentConverter.java From flowable-engine with Apache License 2.0 | 5 votes |
@Override protected ObjectNode convertMappingInfoToJson(ActivityMigrationMapping.ManyToOneMapping mapping, ObjectMapper objectMapper) { ObjectNode mappingNode = objectMapper.createObjectNode(); JsonNode fromActivityIdsNode = objectMapper.valueToTree(mapping.getFromActivityIds()); mappingNode.set(FROM_ACTIVITY_IDS_JSON_PROPERTY, fromActivityIdsNode); mappingNode.put(TO_ACTIVITY_ID_JSON_PROPERTY, mapping.getToActivityId()); mappingNode.setAll(convertAdditionalMappingInfoToJson(mapping, objectMapper)); return mappingNode; }
Example 6
Source File: DelayMeasurementStatHistoryCodec.java From onos with Apache License 2.0 | 5 votes |
@Override public ObjectNode encode(DelayMeasurementStatHistory dmHistory, CodecContext context) { checkNotNull(dmHistory, "DM history cannot be null"); ObjectNode result = context.mapper().createObjectNode() .put("historyId", String.valueOf(dmHistory.historyStatsId())) .put("endTime", dmHistory.endTime().toString()); ObjectNode resultAbstract = new DelayMeasurementStatCodec().encode(dmHistory, context); result.setAll(resultAbstract); return result; }
Example 7
Source File: OffPolicyLearningExpander.java From samantha with MIT License | 5 votes |
public List<ObjectNode> expand(List<ObjectNode> initialResult, RequestContext requestContext) { List<ObjectNode> expandedResult = new ArrayList<>(); for (ObjectNode input : initialResult) { if (sampleRate == null || new Random().nextDouble() <= sampleRate) { ObjectNode reqBody = Json.newObject(); reqBody.setAll(input); RequestContext pseudoReq = new RequestContext(reqBody, requestContext.getEngineName()); SamanthaConfigService configService = injector.instanceOf(SamanthaConfigService.class); Recommender recommender = configService.getRecommender(recommenderName, pseudoReq); RankedResult rankedResult = recommender.recommend(pseudoReq); if (rankedResult.getLimit() > 0) { String itemKey = FeatureExtractorUtilities.composeConcatenatedKey(input, itemAttrs); for (Prediction prediction : rankedResult.getRankingList()) { String recKey = FeatureExtractorUtilities.composeConcatenatedKey( prediction.getEntity(), itemAttrs ); if (itemKey.equals(recKey)) { expandedResult.add(input); } } } } } return expandedResult; }
Example 8
Source File: OntologyRest.java From mobi with GNU Affero General Public License v3.0 | 5 votes |
/** * Combines multiple JSONObjects into a single JSONObject. * * @param objects the JSONObjects to combine. * @return a JSONObject which has the combined key-value pairs from all of the provided JSONObjects. */ private ObjectNode combineJsonObjects(ObjectNode... objects) { ObjectNode objectNode = mapper.createObjectNode(); if (objects.length == 0) { return objectNode; } for (ObjectNode each : objects) { objectNode.setAll(each); } return objectNode; }
Example 9
Source File: EtcdUtil.java From etcd4j with Apache License 2.0 | 5 votes |
/** * Recursively, flatten all json keys and transform data types * @param node original json * @param currentPath auxiliary variable used for recursion, initially empty string * @return flattened json using dot notation */ @SuppressWarnings("unchecked") private static ObjectNode flattenJson(JsonNode node, String currentPath) { ObjectNode transformed = JsonNodeFactory.instance.objectNode(); Iterator<Map.Entry<String, JsonNode>> fields = node.fields(); while (fields.hasNext()) { Map.Entry<String, JsonNode> next = fields.next(); if (next.getValue().isValueNode()) { String path = currentPath + "." + next.getKey(); String strValue = next.getValue().asText(); if (NumberUtils.isCreatable(strValue)) { Class numberType = numberType(strValue); if (numberType.isAssignableFrom(Integer.class)) { transformed.put(path.substring(1), Integer.valueOf(strValue)); } else if (numberType.isAssignableFrom(Long.class)) { transformed.put(path.substring(1), Long.valueOf(strValue)); } else if (numberType.isAssignableFrom(Float.class)) { transformed.put(path.substring(1), Float.valueOf(strValue)); } else if (numberType.isAssignableFrom(Double.class)) { transformed.put(path.substring(1), Double.valueOf(strValue)); } } else if (booleanType(strValue)) { transformed.put(path.substring(1), Boolean.valueOf(strValue)); } else if (arrayType(strValue)) { transformed.putArray(path.substring(1)); } else { transformed.set(path.substring(1), next.getValue()); } } else { transformed.setAll(flattenJson(next.getValue(), currentPath + "." + next.getKey())); } } return transformed; }
Example 10
Source File: PubsubMessageToObjectNode.java From gcp-ingestion with Mozilla Public License 2.0 | 5 votes |
/** * Recursively descend into a map type field, expanding to the key/value struct required in * BigQuery schemas. */ private void expandMapType(String jsonFieldName, ObjectNode value, Field field, ObjectNode parent, ObjectNode additionalProperties) { final ObjectNode props = additionalProperties == null ? null : Json.createObjectNode(); final Optional<Field> valueFieldOption; if (field.getSubFields().size() == 2) { valueFieldOption = Optional.of(field.getSubFields().get(1)); } else { valueFieldOption = Optional.empty(); if (props != null) { props.setAll(value); } } final ArrayNode unmapped = Json.createArrayNode(); value.fields().forEachRemaining(e -> { ObjectNode kv = Json.createObjectNode(); valueFieldOption .ifPresent(valueField -> processField(e.getKey(), valueField, e.getValue(), kv, props)); // add key after processField so it can't be dropped due to e.getKey() matching // FieldName.KEY when e.getValue() is null or empty or can't be coerced unmapped.add(kv.put(FieldName.KEY, e.getKey())); }); if (!Json.isNullOrEmpty(props)) { additionalProperties.set(jsonFieldName, props); } parent.set(field.getName(), unmapped); }
Example 11
Source File: TopicStreamWriter.java From ksql-fork-with-deep-learning-function with Apache License 2.0 | 5 votes |
@Override String print(ConsumerRecord<String, Bytes> record) throws IOException { JsonNode jsonNode = objectMapper.readTree(record.value().toString()); ObjectNode objectNode = objectMapper.createObjectNode(); objectNode.put(SchemaUtil.ROWTIME_NAME, record.timestamp()); objectNode.put(SchemaUtil.ROWKEY_NAME, (record.key() != null) ? record.key() : "null"); objectNode.setAll((ObjectNode) jsonNode); StringWriter stringWriter = new StringWriter(); objectMapper.writeValue(stringWriter, objectNode); return stringWriter.toString() + "\n"; }
Example 12
Source File: LossAvailabilityStatHistoryCodec.java From onos with Apache License 2.0 | 5 votes |
@Override public ObjectNode encode(LossAvailabilityStatHistory laHistory, CodecContext context) { checkNotNull(laHistory, "LA history cannot be null"); ObjectNode result = context.mapper().createObjectNode() .put("historyId", String.valueOf(laHistory.historyStatsId())) .put("endTime", laHistory.endTime().toString()); ObjectNode resultAbstract = new LossAvailabilityStatCodec().encode(laHistory, context); result.setAll(resultAbstract); return result; }
Example 13
Source File: ElasticsearchRel.java From Quicksql with MIT License | 5 votes |
public String convert(RelNode input, List<Pair<String, Class>> fields) throws IOException { ((ElasticsearchRel) input).implement(this); ObjectMapper mapper = new ObjectMapper(); if (! aggregations.isEmpty()) { return aggregate(fields, mapper); } final ObjectNode query = mapper.createObjectNode(); // manually parse from previously concatenated string for (String op : list) { query.setAll((ObjectNode) mapper.readTree(op)); } if (! sort.isEmpty()) { ArrayNode sortNode = query.withArray("sort"); sort.forEach(e -> sortNode.add( mapper.createObjectNode().put(e.getKey(), e.getValue().isDescending() ? "desc" : "asc")) ); } if (offset != null) { query.put("from", offset); } if (fetch != null) { query.put("size", fetch); } return query.toString(); }
Example 14
Source File: Commons.java From olingo-odata4 with Apache License 2.0 | 5 votes |
public static InputStream getLinksAsJSON(final String entitySetName, final Map.Entry<String, Collection<String>> link) throws IOException { final ObjectNode links = new ObjectNode(JsonNodeFactory.instance); links.put( Constants.get(ConstantKey.JSON_ODATAMETADATA_NAME), Constants.get(ConstantKey.ODATA_METADATA_PREFIX) + entitySetName + "/$links/" + link.getKey()); final ArrayNode uris = new ArrayNode(JsonNodeFactory.instance); for (String uri : link.getValue()) { final String absoluteURI; if (URI.create(uri).isAbsolute()) { absoluteURI = uri; } else { absoluteURI = Constants.get(ConstantKey.DEFAULT_SERVICE_URL) + uri; } uris.add(new ObjectNode(JsonNodeFactory.instance).put("url", absoluteURI)); } if (uris.size() == 1) { links.setAll((ObjectNode) uris.get(0)); } else { links.set("value", uris); } return IOUtils.toInputStream(links.toString(), Constants.ENCODING); }
Example 15
Source File: LossMeasurementStatHistoryCodec.java From onos with Apache License 2.0 | 5 votes |
@Override public ObjectNode encode(LossMeasurementStatHistory lmHistory, CodecContext context) { checkNotNull(lmHistory, "LM history cannot be null"); ObjectNode result = context.mapper().createObjectNode() .put("historyId", String.valueOf(lmHistory.historyStatsId())) .put("endTime", lmHistory.endTime().toString()); ObjectNode resultAbstract = new LossMeasurementStatCodec().encode(lmHistory, context); result.setAll(resultAbstract); return result; }
Example 16
Source File: RubiconBidder.java From prebid-server-java with Apache License 2.0 | 4 votes |
private JsonNode makeTarget(Imp imp, ExtImpRubicon rubiconImpExt, Site site, App app, boolean useFirstPartyData) { final ObjectNode inventory = rubiconImpExt.getInventory(); final ObjectNode inventoryNode = inventory == null ? mapper.mapper().createObjectNode() : inventory; if (useFirstPartyData) { final ExtImpContext context = extImpContext(imp); // copy OPENRTB.site.ext.data.* to every impression – XAPI.imp[].ext.rp.target.* final ObjectNode siteExt = site != null ? site.getExt() : null; if (siteExt != null) { populateObjectNode(inventoryNode, getDataNode(siteExt)); } // copy OPENRTB.app.ext.data.* to every impression – XAPI.imp[].ext.rp.target.* final ObjectNode appExt = app != null ? app.getExt() : null; if (appExt != null) { populateObjectNode(inventoryNode, getDataNode(appExt)); } // copy OPENRTB.imp[].ext.context.data.* to XAPI.imp[].ext.rp.target.* final ObjectNode contextDataNode = context != null ? context.getData() : null; if (contextDataNode != null) { inventoryNode.setAll(contextDataNode); // copy OPENRTB.imp[].ext.context.data.adslot to XAPI.imp[].ext.rp.target.dfp_ad_unit_code without // leading slash final JsonNode adSlotNode = contextDataNode.get("adslot"); if (adSlotNode != null && adSlotNode.isTextual()) { final String adSlot = adSlotNode.textValue(); final String adUnitCode = adSlot.indexOf('/') == 0 ? adSlot.substring(1) : adSlot; inventoryNode.put("dfp_ad_unit_code", adUnitCode); } } // copy OPENRTB.imp[].ext.context.keywords to XAPI.imp[].ext.rp.target.keywords final String keywords = context != null ? context.getKeywords() : null; if (StringUtils.isNotBlank(keywords)) { inventoryNode.put("keywords", keywords); } // copy OPENRTB.imp[].ext.context.search to XAPI.imp[].ext.rp.target.search // copy OPENRTB.site.search to every impression XAPI.imp[].ext.rp.target.search // imp-specific values should take precedence over global values final String contextSearch = context != null ? context.getSearch() : null; final String siteSearch = site != null ? site.getSearch() : null; final String search = ObjectUtils.defaultIfNull(contextSearch, siteSearch); if (StringUtils.isNotBlank(search)) { inventoryNode.put("search", search); } } return inventoryNode.size() > 0 ? inventoryNode : null; }
Example 17
Source File: RubiconBidder.java From prebid-server-java with Apache License 2.0 | 4 votes |
private static void populateObjectNode(ObjectNode objectNode, JsonNode data) { if (data != null && !data.isNull()) { objectNode.setAll((ObjectNode) data); } }
Example 18
Source File: ElasticsearchTable.java From calcite with Apache License 2.0 | 4 votes |
/** * Executes a "find" operation on the underlying index. * * @param ops List of operations represented as Json strings. * @param fields List of fields to project; or null to return map * @param sort list of fields to sort and their direction (asc/desc) * @param aggregations aggregation functions * @return Enumerator of results */ private Enumerable<Object> find(List<String> ops, List<Map.Entry<String, Class>> fields, List<Map.Entry<String, RelFieldCollation.Direction>> sort, List<String> groupBy, List<Map.Entry<String, String>> aggregations, Map<String, String> mappings, Long offset, Long fetch) throws IOException { if (!aggregations.isEmpty() || !groupBy.isEmpty()) { // process aggregations separately return aggregate(ops, fields, sort, groupBy, aggregations, mappings, offset, fetch); } final ObjectNode query = mapper.createObjectNode(); // manually parse from previously concatenated string for (String op: ops) { query.setAll((ObjectNode) mapper.readTree(op)); } if (!sort.isEmpty()) { ArrayNode sortNode = query.withArray("sort"); sort.forEach(e -> sortNode.add( mapper.createObjectNode().put(e.getKey(), e.getValue().isDescending() ? "desc" : "asc"))); } if (offset != null) { query.put("from", offset); } if (fetch != null) { query.put("size", fetch); } final Function1<ElasticsearchJson.SearchHit, Object> getter = ElasticsearchEnumerators.getter(fields, ImmutableMap.copyOf(mappings)); Iterable<ElasticsearchJson.SearchHit> iter; if (offset == null) { // apply scrolling when there is no offsets iter = () -> new Scrolling(transport).query(query); } else { final ElasticsearchJson.Result search = transport.search().apply(query); iter = () -> search.searchHits().hits().iterator(); } return Linq4j.asEnumerable(iter).select(getter); }
Example 19
Source File: SchemaGenerationContextImpl.java From jsonschema-generator with Apache License 2.0 | 4 votes |
/** * Preparation Step: combine the collected attributes and the javaType's definition in the given targetNode. * * @param <M> type of target scope, i.e. either a field or method * @param scope field's type or method return value's type that should be represented by the given targetNode * @param targetNode node in the JSON schema that should represent the associated javaType and include the separately collected attributes * @param isNullable whether the field/method's return value the javaType refers to is allowed to be null in the declaringType * @param forceInlineDefinition whether to generate an inline definition without registering it in this context * @param collectedAttributes separately collected attribute for the field/method in their respective declaring type * @param ignoredDefinitionProvider first custom definition provider to ignore * @see #populateField(FieldScope, Map, Set) * @see #collectMethod(MethodScope, Map, Set) */ private <M extends MemberScope<?, ?>> void populateMemberSchema(M scope, ObjectNode targetNode, boolean isNullable, boolean forceInlineDefinition, ObjectNode collectedAttributes, CustomPropertyDefinitionProvider<M> ignoredDefinitionProvider) { final CustomDefinition customDefinition = this.generatorConfig.getCustomDefinition(scope, this, ignoredDefinitionProvider); if (customDefinition != null && customDefinition.isMeantToBeInline()) { targetNode.setAll(customDefinition.getValue()); if (customDefinition.shouldIncludeAttributes()) { AttributeCollector.mergeMissingAttributes(targetNode, collectedAttributes); Set<String> allowedSchemaTypes = this.collectAllowedSchemaTypes(targetNode); ObjectNode typeAttributes = AttributeCollector.collectTypeAttributes(scope, this, allowedSchemaTypes); AttributeCollector.mergeMissingAttributes(targetNode, typeAttributes); } if (isNullable) { this.makeNullable(targetNode); } } else { // create an "allOf" wrapper for the attributes related to this particular field and its general type final ObjectNode referenceContainer; if (customDefinition != null && !customDefinition.shouldIncludeAttributes() || collectedAttributes == null || collectedAttributes.size() == 0) { // no need for the allOf, can use the sub-schema instance directly as reference referenceContainer = targetNode; } else if (customDefinition == null && scope.isContainerType()) { // same as above, but the collected attributes should be applied also for containers/arrays referenceContainer = targetNode; AttributeCollector.mergeMissingAttributes(targetNode, collectedAttributes); } else { // avoid mixing potential "$ref" element with contextual attributes by introducing an "allOf" wrapper // this is only relevant for DRAFT_7 and is being cleaned-up afterwards for newer DRAFT versions referenceContainer = this.generatorConfig.createObjectNode(); targetNode.set(this.getKeyword(SchemaKeyword.TAG_ALLOF), this.generatorConfig.createArrayNode() .add(referenceContainer) .add(collectedAttributes)); } // only add reference for separate definition if it is not a fixed type that should be in-lined try { this.traverseGenericType(scope, referenceContainer, isNullable, forceInlineDefinition, null); } catch (UnsupportedOperationException ex) { logger.warn("Skipping type definition due to error", ex); } } }
Example 20
Source File: SchemaGenerationContextImpl.java From jsonschema-generator with Apache License 2.0 | 4 votes |
/** * Preparation Step: add the given targetType. Also catering for forced inline-definitions and ignoring custom definitions * * @param scope targeted scope to add * @param targetNode node in the JSON schema that should represent the targetType * @param isNullable whether the field/method's return value is allowed to be null in the declaringType in this particular scenario * @param forceInlineDefinition whether to generate an inline definition without registering it in this context * @param ignoredDefinitionProvider first custom definition provider to ignore */ private void traverseGenericType(TypeScope scope, ObjectNode targetNode, boolean isNullable, boolean forceInlineDefinition, CustomDefinitionProviderV2 ignoredDefinitionProvider) { ResolvedType targetType = scope.getType(); if (!forceInlineDefinition && this.containsDefinition(targetType, ignoredDefinitionProvider)) { logger.debug("adding reference to existing definition of {}", targetType); this.addReference(targetType, targetNode, ignoredDefinitionProvider, isNullable); // nothing more to be done return; } final ObjectNode definition; final boolean includeTypeAttributes; final CustomDefinition customDefinition = this.generatorConfig.getCustomDefinition(targetType, this, ignoredDefinitionProvider); if (customDefinition != null && (customDefinition.isMeantToBeInline() || forceInlineDefinition)) { includeTypeAttributes = customDefinition.shouldIncludeAttributes(); if (targetNode == null) { logger.debug("storing configured custom inline type for {} as definition (since it is the main schema \"#\")", targetType); definition = customDefinition.getValue(); this.putDefinition(targetType, definition, ignoredDefinitionProvider); // targetNode will be populated at the end, in buildDefinitionsAndResolveReferences() } else { logger.debug("directly applying configured custom inline type for {}", targetType); targetNode.setAll(customDefinition.getValue()); definition = targetNode; } if (isNullable) { this.makeNullable(definition); } } else { boolean isContainerType = this.typeContext.isContainerType(targetType); if (forceInlineDefinition || isContainerType && targetNode != null && customDefinition == null) { // always inline array types definition = targetNode; } else { definition = this.generatorConfig.createObjectNode(); this.putDefinition(targetType, definition, ignoredDefinitionProvider); if (targetNode != null) { // targetNode is only null for the main class for which the schema is being generated this.addReference(targetType, targetNode, ignoredDefinitionProvider, isNullable); } } if (customDefinition != null) { logger.debug("applying configured custom definition for {}", targetType); definition.setAll(customDefinition.getValue()); includeTypeAttributes = customDefinition.shouldIncludeAttributes(); } else if (isContainerType) { logger.debug("generating array definition for {}", targetType); this.generateArrayDefinition(scope, definition, isNullable); includeTypeAttributes = true; } else { logger.debug("generating definition for {}", targetType); includeTypeAttributes = !this.addSubtypeReferencesInDefinition(targetType, definition); } } if (includeTypeAttributes) { Set<String> allowedSchemaTypes = this.collectAllowedSchemaTypes(definition); ObjectNode typeAttributes = AttributeCollector.collectTypeAttributes(scope, this, allowedSchemaTypes); // ensure no existing attributes in the 'definition' are replaced, by way of first overriding any conflicts the other way around typeAttributes.setAll(definition); // apply merged attributes definition.setAll(typeAttributes); } // apply overrides as the very last step this.generatorConfig.getTypeAttributeOverrides() .forEach(override -> override.overrideTypeAttributes(definition, scope, this)); }