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

The following examples show how to use com.fasterxml.jackson.databind.node.ObjectNode#with() . 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: JsonActivationDao.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
@Override
public void setBindingStatus(BindingKey key, boolean active) {
    writeLock().lock();
    try {
        ObjectNode node = getConfiguration()
                .with(JsonConstants.ACTIVATION)
                .with(JsonConstants.BINDINGS);
        if (key instanceof PathBindingKey) {
            node = node.with(JsonConstants.BY_PATH);
        } else if (key instanceof MediaTypeBindingKey) {
            node = node.with(JsonConstants.BY_MEDIA_TYPE);
        }
        node.put(key.getKeyAsString(), active);
    } finally {
        writeLock().unlock();
    }
    configuration().scheduleWrite();
}
 
Example 2
Source File: SchemaBuilderTest.java    From jsonschema-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiTypeSchemaGeneration() throws Exception {
    SchemaBuilder instance = SchemaBuilder.forMultipleTypes(this.config, this.typeContext);

    ObjectNode result = this.config.createObjectNode();
    result.put("openapi", "3.0.0");
    result.with("info")
            .put("title", "Test API")
            .put("version", "0.1.0");
    ObjectNode testPath = result.with("paths")
            .with("/test");
    ObjectNode testPathPost = testPath.with("post");
    testPathPost.with("requestBody")
            .with("content").with("application/json")
            .set("schema", instance.createSchemaReference(TestClass1.class));
    testPathPost.with("responses").with("200")
            .put("description", "succesful POST")
            .with("content").with("application/json")
            .set("schema", instance.createSchemaReference(TestClass2.class));
    ObjectNode testPathPut = testPath.with("put");
    testPathPut.with("requestBody")
            .with("content").with("application/json")
            .set("schema", instance.createSchemaReference(TestClass3.class));
    testPathPut.with("responses").with("201")
            .put("description", "succesful PUT")
            .with("content").with("application/json")
            .set("schema", instance.createSchemaReference(TestClass3.class));

    result.with("components")
            .set("schemas", instance.collectDefinitions("components/schemas"));

    JSONAssert.assertEquals('\n' + result.toString() + '\n',
            TestUtils.loadResource(this.getClass(), "openapi.json"), result.toString(), JSONCompareMode.STRICT);
}
 
Example 3
Source File: ElasticsearchAggregate.java    From Quicksql with MIT License 5 votes vote down vote up
@Override public void implement(Implementor implementor) {
  implementor.visitChild(0, getInput());
  List<String> inputFields = fieldNames(getInput().getRowType());
  for (int group : groupSet) {
    implementor.addGroupBy(inputFields.get(group));
  }

  final ObjectMapper mapper = implementor.elasticsearchTable.mapper;

  for (AggregateCall aggCall : aggCalls) {
    final List<String> names = new ArrayList<>();
    for (int i : aggCall.getArgList()) {
      names.add(inputFields.get(i));
    }

    final ObjectNode aggregation = mapper.createObjectNode();
    final ObjectNode field = aggregation.with(toElasticAggregate(aggCall));

    final String name = names.isEmpty() ? ElasticsearchConstants.ID : names.get(0);
    field.put("field", name);
    if (aggCall.getAggregation().getKind() == SqlKind.ANY_VALUE) {
      field.put("size", 1);
    }

    implementor.addAggregation(aggCall.getName(), aggregation.toString());
  }
}
 
Example 4
Source File: OpenApiDefinition.java    From java-crud-api with MIT License 5 votes vote down vote up
public void set(String path, Object value)
{
    String[] parts = path.replaceAll("\\|$|^\\|", "").split("\\|");
    ObjectNode current = root;
    for (int i=0;i<parts.length-1;i++) {
        String part = parts[i];
        current = current.with(part);
    }
    if (value instanceof Boolean) {
        current.put(parts[parts.length - 1], (Boolean) value);
    } else {
        current.put(parts[parts.length - 1], value.toString());
    }
}
 
Example 5
Source File: MysqlUserMetadataService.java    From metacat with Apache License 2.0 5 votes vote down vote up
@Override
public void populateOwnerIfMissing(final HasDefinitionMetadata holder, final String owner) {
    ObjectNode definitionMetadata = holder.getDefinitionMetadata();
    if (definitionMetadata == null) {
        definitionMetadata = metacatJson.emptyObjectNode();
        holder.setDefinitionMetadata(definitionMetadata);
    }
    final ObjectNode ownerNode = definitionMetadata.with(NAME_OWNER);
    final JsonNode userId = ownerNode.get(NAME_USERID);
    if (userId == null || Strings.isNullOrEmpty(userId.textValue())) {
        ownerNode.put(NAME_USERID, owner);
    }
}
 
Example 6
Source File: JsonFormatter.java    From parsec-libraries with Apache License 2.0 5 votes vote down vote up
@Override
public String format(ParsecServletRequestWrapper req, ParsecServletResponseWrapper resp,
                     Map<String, Object> additionalArgs) {
    try {
        ObjectNode root = _OBJECT_MAPPER.createObjectNode();
        root.put("time", (System.currentTimeMillis() / 1000L));
        ObjectNode reqNode = root.with("request");
        fillRequestNode(req, reqNode);
        ObjectNode respNode = root.with("response");
        fillResponseNode(resp, respNode);
        return _OBJECT_MAPPER.writeValueAsString(root);
    } catch(IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 7
Source File: QueryBuilders.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Override
ObjectNode toJson(ObjectMapper mapper) {
  ObjectNode result = mapper.createObjectNode();
  ObjectNode bool = result.with("bool");
  writeJsonArray("must", mustClauses, bool, mapper);
  writeJsonArray("filter", filterClauses, bool, mapper);
  writeJsonArray("must_not", mustNotClauses, bool, mapper);
  writeJsonArray("should", shouldClauses, bool, mapper);
  return result;
}
 
Example 8
Source File: JsonSubTypesResolver.java    From jsonschema-generator with Apache License 2.0 4 votes vote down vote up
/**
 * Create the custom schema definition for the given subtype, considering the {@link JsonTypeInfo#include()} setting.
 *
 * @param javaType targeted subtype
 * @param typeInfoAnnotation annotation for looking up the type identifier and determining the kind of inclusion/serialization
 * @param attributesToInclude optional: additional attributes to include on the actual/contained schema definition
 * @param context generation context
 * @return created custom definition (or {@code null} if no supported subtype resolution scenario could be detected
 */
private ObjectNode createSubtypeDefinition(ResolvedType javaType, JsonTypeInfo typeInfoAnnotation, ObjectNode attributesToInclude,
        SchemaGenerationContext context) {
    final String typeIdentifier = this.getTypeIdentifier(javaType, typeInfoAnnotation);
    if (typeIdentifier == null) {
        return null;
    }
    final ObjectNode definition = context.getGeneratorConfig().createObjectNode();
    switch (typeInfoAnnotation.include()) {
    case WRAPPER_ARRAY:
        definition.put(context.getKeyword(SchemaKeyword.TAG_TYPE), context.getKeyword(SchemaKeyword.TAG_TYPE_ARRAY));
        ArrayNode itemsArray = definition.withArray(context.getKeyword(SchemaKeyword.TAG_ITEMS));
        itemsArray.addObject()
                .put(context.getKeyword(SchemaKeyword.TAG_TYPE), context.getKeyword(SchemaKeyword.TAG_TYPE_STRING))
                .put(context.getKeyword(SchemaKeyword.TAG_CONST), typeIdentifier);
        if (attributesToInclude == null || attributesToInclude.isEmpty()) {
            itemsArray.add(context.createStandardDefinitionReference(javaType, this));
        } else {
            itemsArray.addObject()
                    .withArray(context.getKeyword(SchemaKeyword.TAG_ALLOF))
                    .add(context.createStandardDefinitionReference(javaType, this))
                    .add(attributesToInclude);
        }
        break;
    case WRAPPER_OBJECT:
        definition.put(context.getKeyword(SchemaKeyword.TAG_TYPE), context.getKeyword(SchemaKeyword.TAG_TYPE_OBJECT));
        ObjectNode propertiesNode = definition.with(context.getKeyword(SchemaKeyword.TAG_PROPERTIES));
        if (attributesToInclude == null || attributesToInclude.isEmpty()) {
            propertiesNode.set(typeIdentifier, context.createStandardDefinitionReference(javaType, this));
        } else {
            propertiesNode.with(typeIdentifier)
                    .withArray(context.getKeyword(SchemaKeyword.TAG_ALLOF))
                    .add(context.createStandardDefinitionReference(javaType, this))
                    .add(attributesToInclude);
        }
        break;
    case PROPERTY:
    case EXISTING_PROPERTY:
        final String propertyName = Optional.ofNullable(typeInfoAnnotation.property())
                .filter(name -> !name.isEmpty())
                .orElseGet(() -> typeInfoAnnotation.use().getDefaultPropertyName());
        ObjectNode additionalPart = definition.withArray(context.getKeyword(SchemaKeyword.TAG_ALLOF))
                .add(context.createStandardDefinitionReference(javaType, this))
                .addObject();
        if (attributesToInclude != null && !attributesToInclude.isEmpty()) {
            additionalPart.setAll(attributesToInclude);
        }
        additionalPart.put(context.getKeyword(SchemaKeyword.TAG_TYPE), context.getKeyword(SchemaKeyword.TAG_TYPE_OBJECT))
                .with(context.getKeyword(SchemaKeyword.TAG_PROPERTIES))
                .with(propertyName)
                .put(context.getKeyword(SchemaKeyword.TAG_CONST), typeIdentifier);
        break;
    default:
        return null;
    }
    return definition;
}
 
Example 9
Source File: ElasticsearchRel.java    From Quicksql with MIT License 4 votes vote down vote up
private String aggregate(List<Pair<String, Class>> fields, ObjectMapper mapper) throws IOException {
    if (aggregations.isEmpty()) {
        throw new IllegalArgumentException("Missing Aggregations");
    }

    if (! groupBy.isEmpty() && offset != null) {
        String message = "Currently ES doesn't support generic pagination "
            + "with aggregations. You can still use LIMIT keyword (without OFFSET). "
            + "For more details see https://github.com/elastic/elasticsearch/issues/4915";
        throw new IllegalStateException(message);
    }

    final ObjectNode query = mapper.createObjectNode();
    // manually parse into JSON from previously concatenated strings
    for (String op : list) {
        query.setAll((ObjectNode) mapper.readTree(op));
    }

    // remove / override attributes which are not applicable to aggregations
    query.put("_source", false);
    query.put("size", 0);
    query.remove("script_fields");

    // allows to detect aggregation for count(*)
    final Predicate<Entry<String, String>> isCountStar = e -> e.getValue()
        .contains("\"" + ElasticsearchConstants.ID + "\"");

    // list of expressions which are count(*)
    final Set<String> countAll = aggregations.stream()
        .filter(isCountStar)
        .map(Map.Entry::getKey).collect(Collectors.toSet());

    // due to ES aggregation format. fields in "order by" clause should go first
    // if "order by" is missing. order in "group by" is un-important
    final Set<String> orderedGroupBy = new LinkedHashSet<>();
    orderedGroupBy.addAll(sort.stream().map(Map.Entry::getKey).collect(Collectors.toList()));
    orderedGroupBy.addAll(groupBy);

    // construct nested aggregations node(s)
    ObjectNode parent = query.with("aggregations");
    for (String name : orderedGroupBy) {
        final String aggName = "g_" + name;

        final ObjectNode section = parent.with(aggName);
        final ObjectNode terms = section.with("terms");
        terms.put("field", name);
        terms.set("missing", ElasticsearchJson.MISSING_VALUE); // expose missing terms

        if (fetch != null) {
            terms.put("size", fetch);
        }

        sort.stream().filter(e -> e.getKey().equals(name)).findAny().ifPresent(s -> {
            terms.with("order").put("_key", s.getValue().isDescending() ? "desc" : "asc");
        });

        parent = section.with("aggregations");
    }

    // simple version for queries like "select count(*), max(col1) from table" (no GROUP BY cols)
    if (! groupBy.isEmpty() || ! aggregations.stream().allMatch(isCountStar)) {
        for (Map.Entry<String, String> aggregation : aggregations) {
            JsonNode value = mapper.readTree(aggregation.getValue());
            parent.set(aggregation.getKey(), value);
        }
    }

    // cleanup query. remove empty AGGREGATIONS element (if empty)
    JsonNode agg = query;
    while (agg.has("aggregations") && agg.get("aggregations").elements().hasNext()) {
        agg = agg.get("aggregations");
    }
    ((ObjectNode) agg).remove("aggregations");

    return query.toString();
}