Java Code Examples for org.elasticsearch.common.xcontent.XContentBuilder#endObject()

The following examples show how to use org.elasticsearch.common.xcontent.XContentBuilder#endObject() . 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: MergeStats.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject(Fields.MERGES);
    builder.field(Fields.CURRENT, current);
    builder.field(Fields.CURRENT_DOCS, currentNumDocs);
    builder.byteSizeField(Fields.CURRENT_SIZE_IN_BYTES, Fields.CURRENT_SIZE, currentSizeInBytes);
    builder.field(Fields.TOTAL, total);
    builder.timeValueField(Fields.TOTAL_TIME_IN_MILLIS, Fields.TOTAL_TIME, totalTimeInMillis);
    builder.field(Fields.TOTAL_DOCS, totalNumDocs);
    builder.byteSizeField(Fields.TOTAL_SIZE_IN_BYTES, Fields.TOTAL_SIZE, totalSizeInBytes);
    builder.timeValueField(Fields.TOTAL_STOPPED_TIME_IN_MILLIS, Fields.TOTAL_STOPPED_TIME, totalStoppedTimeInMillis);
    builder.timeValueField(Fields.TOTAL_THROTTLED_TIME_IN_MILLIS, Fields.TOTAL_THROTTLED_TIME, totalThrottledTimeInMillis);
    builder.byteSizeField(Fields.TOTAL_THROTTLE_BYTES_PER_SEC_IN_BYTES, Fields.TOTAL_THROTTLE_BYTES_PER_SEC, totalBytesPerSecAutoThrottle);
    builder.endObject();
    return builder;
}
 
Example 2
Source File: UserDefinedFunctionsMetaDataTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
public void testUserDefinedFunctionToXContentWithEmptyMetadata() throws IOException {
    XContentBuilder builder = XContentFactory.jsonBuilder();

    // reflects the logic used to process custom metadata in the cluster state
    builder.startObject();
    UserDefinedFunctionsMetaData functions = UserDefinedFunctionsMetaData.of();
    functions.toXContent(builder, ToXContent.EMPTY_PARAMS);
    builder.endObject();

    XContentParser parser = JsonXContent.JSON_XCONTENT.createParser(
        xContentRegistry(), DeprecationHandler.THROW_UNSUPPORTED_OPERATION, BytesReference.toBytes(BytesReference.bytes(builder)));
    parser.nextToken(); // enter START_OBJECT
    UserDefinedFunctionsMetaData functions2 = UserDefinedFunctionsMetaData.fromXContent(parser);
    assertEquals(functions, functions2);
}
 
Example 3
Source File: UsersMetaDataTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
public void testUsersMetaDataWithoutAttributesToXContent() throws IOException {
    XContentBuilder builder = XContentFactory.jsonBuilder();

    // reflects the logic used to process custom metadata in the cluster state
    builder.startObject();

    UsersMetaData users = new UsersMetaData(UserDefinitions.SINGLE_USER_ONLY);
    users.toXContent(builder, ToXContent.EMPTY_PARAMS);
    builder.endObject();

    XContentParser parser = JsonXContent.JSON_XCONTENT.createParser(
        xContentRegistry(),
        DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
        Strings.toString(builder));
    parser.nextToken(); // start object
    UsersMetaData users2 = UsersMetaData.fromXContent(parser);
    assertEquals(users, users2);

    // a metadata custom must consume the surrounded END_OBJECT token, no token must be left
    assertThat(parser.nextToken(), nullValue());
}
 
Example 4
Source File: SearchShardsRequestBuilder.java    From elasticshell with Apache License 2.0 5 votes vote down vote up
@Override
protected XContentBuilder toXContent(ClusterSearchShardsRequest request, ClusterSearchShardsResponse response, XContentBuilder builder) throws IOException {
    builder.startObject();
    builder.field(Fields.OK, true);
    response.toXContent(builder, ToXContent.EMPTY_PARAMS);
    builder.endObject();
    return builder;
}
 
Example 5
Source File: ClusterStatsNodes.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject(Fields.CPU).field(Fields.PERCENT, cpuPercent).endObject();
    if (count > 0) {
        builder.startObject(Fields.OPEN_FILE_DESCRIPTORS);
        builder.field(Fields.MIN, getMinOpenFileDescriptors());
        builder.field(Fields.MAX, getMaxOpenFileDescriptors());
        builder.field(Fields.AVG, getAvgOpenFileDescriptors());
        builder.endObject();
    }
    return builder;
}
 
Example 6
Source File: SnapshotStatus.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    try {
        XContentBuilder builder = XContentFactory.jsonBuilder().prettyPrint();
        builder.startObject();
        toXContent(builder, EMPTY_PARAMS);
        builder.endObject();
        return builder.string();
    } catch (IOException e) {
        return "{ \"error\" : \"" + e.getMessage() + "\"}";
    }
}
 
Example 7
Source File: ParentFieldMapper.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    if (!active()) {
        return builder;
    }
    boolean includeDefaults = params.paramAsBoolean("include_defaults", false);

    builder.startObject(CONTENT_TYPE);
    builder.field("type", parentType);
    if (includeDefaults || joinFieldHasCustomFieldDataSettings()) {
        builder.field("fielddata", (Map) childJoinFieldType.fieldDataType().getSettings().getAsMap());
    }
    builder.endObject();
    return builder;
}
 
Example 8
Source File: NodesInfoResponse.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    try {
        XContentBuilder builder = XContentFactory.jsonBuilder().prettyPrint();
        builder.startObject();
        toXContent(builder, EMPTY_PARAMS);
        builder.endObject();
        return builder.string();
    } catch (IOException e) {
        return "{ \"error\" : \"" + e.getMessage() + "\"}";
    }
}
 
Example 9
Source File: RestHighLevelClientCase.java    From skywalking with Apache License 2.0 5 votes vote down vote up
private void createIndex(RestHighLevelClient client, String indexName) throws IOException {
    CreateIndexRequest request = new CreateIndexRequest(indexName);

    XContentBuilder builder = XContentFactory.jsonBuilder();
    builder.startObject();
    {
        builder.startObject("properties");
        {
            builder.startObject("author");
            {
                builder.field("type", "keyword");
            }
            builder.endObject();
            builder.startObject("title");
            {
                builder.field("type", "keyword");
            }
            builder.endObject();
        }
        builder.endObject();
    }
    builder.endObject();
    request.mapping(builder);

    request.settings(Settings.builder().put("index.number_of_shards", 1).put("index.number_of_replicas", 0));

    CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
    if (createIndexResponse.isAcknowledged() == false) {
        String message = "elasticsearch create index fail.";
        logger.error(message);
        throw new RuntimeException(message);
    }
}
 
Example 10
Source File: NestedBuilder.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
protected XContentBuilder internalXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject();
    if (path == null) {
        throw new SearchSourceBuilderException("nested path must be set on nested aggregation [" + getName() + "]");
    }
    builder.field("path", path);
    return builder.endObject();
}
 
Example 11
Source File: CoordinateSearchMetadata.java    From siren-join with GNU Affero General Public License v3.0 5 votes vote down vote up
public XContentBuilder toXContent(XContentBuilder builder) throws IOException {
  builder.startObject();

  builder.startObject(Fields.RELATIONS);

  builder.startObject(Fields.FROM);
  this.relations[0].toXContent(builder);
  builder.endObject();

  builder.startObject(Fields.TO);
  this.relations[1].toXContent(builder);
  builder.endObject();

  builder.endObject(); // end relations object

  builder.field(Fields.SIZE, size);
  builder.field(Fields.SIZE_IN_BYTES, sizeInBytes);
  builder.field(Fields.IS_PRUNED, isPruned);
  builder.field(Fields.CACHE_HIT, cacheHit);
  builder.field(Fields.TERMS_ENCODING, termsEncoding.name().toLowerCase(Locale.ROOT));
  if (ordering != null) {
    builder.field(Fields.ORDERING, ordering.name().toLowerCase(Locale.ROOT));
  }
  if (maxTermsPerShard != -1) {
    builder.field(Fields.MAX_TERMS_PER_SHARD, maxTermsPerShard);
  }
  builder.field(Fields.TOOK, tookInMillis);

  builder.endObject();
  return builder;
}
 
Example 12
Source File: DocumentGroup.java    From elasticsearch-carrot2 with Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params)
        throws IOException {
    builder.startObject();
    builder
        .field("id", id)
        .field("score", score)
        .field("label", getLabel())
        .array("phrases", phrases);
    
    if (ungroupedDocuments) {
        builder.field("other_topics", ungroupedDocuments);
    }

    if (documentReferences.length > 0) {
        builder.array("documents", documentReferences);
    }

    if (subgroups.length > 0) {
        builder.startArray("clusters");
        for (DocumentGroup group : subgroups) {
            group.toXContent(builder, params);
        }
        builder.endArray();
    }

    builder.endObject();
    return builder;
}
 
Example 13
Source File: SearchGuardRoles.java    From openshift-elasticsearch-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException{
    try {
        // output keys are names of roles
        for (Roles role : roles.values()) {
            builder.startObject(role.getName());
            if (!role.getCluster().isEmpty()) {
                builder.array(CLUSTER_HEADER, role.getCluster().toArray());
            }
            if(role.getExpire() != null) {
                builder.field(EXPIRES, role.getExpire());
            }
            if(!role.getIndices().isEmpty()) {
                builder.startObject(INDICES_HEADER);
                role.getIndices().sort(new Comparator<Indices>() {
                    @Override
                    public int compare(Indices o1, Indices o2) {
                        return o1.getIndex().compareTo(o2.getIndex());
                    }
                });
                for (Indices index : role.getIndices()) {
                    if(!index.getTypes().isEmpty()) {
                        builder.startObject(index.getIndex());
                        for (Type type : index.getTypes()) {
                            builder.array(type.getType(), type.getActions().toArray());
                        }
                        builder.endObject();
                    }
                }
                builder.endObject();
            }
            builder.endObject();
        }
        return builder;
    } catch (IOException e) {
        throw new RuntimeException("Unable to convert the SearchGuardRoles to JSON", e);
    }
}
 
Example 14
Source File: CoordinateSearchMetadata.java    From siren-join with GNU Affero General Public License v3.0 5 votes vote down vote up
public XContentBuilder toXContent(XContentBuilder builder) throws IOException {
  builder.startObject(Fields.COORDINATE_SEARCH);

  builder.startArray(Fields.ACTIONS);
  for (Action action : this.actions) {
    action.toXContent(builder);
  }
  builder.endArray();

  builder.endObject();
  return builder;
}
 
Example 15
Source File: HistogramBuilder.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
protected XContentBuilder doInternalXContent(XContentBuilder builder, Params params) throws IOException {
    if (interval == null) {
        throw new SearchSourceBuilderException("[interval] must be defined for histogram aggregation [" + getName() + "]");
    }
    builder.field("interval", interval);

    if (order != null) {
        builder.field("order");
        order.toXContent(builder, params);
    }

    if (offset != null) {
        builder.field("offset", offset);
    }

    if (minDocCount != null) {
        builder.field("min_doc_count", minDocCount);
    }

    if (extendedBoundsMin != null || extendedBoundsMax != null) {
        builder.startObject(HistogramParser.EXTENDED_BOUNDS.getPreferredName());
        if (extendedBoundsMin != null) {
            builder.field("min", extendedBoundsMin);
        }
        if (extendedBoundsMax != null) {
            builder.field("max", extendedBoundsMax);
        }
        builder.endObject();
    }
    return builder;
}
 
Example 16
Source File: XContentTestUtilsTests.java    From crate with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public void testInsertRandomXContent() throws IOException {
    XContentBuilder builder = XContentFactory.jsonBuilder();
    builder.startObject();
    {
        builder.startObject("foo");
        {
            builder.field("bar", 1);
        }
        builder.endObject();
        builder.startObject("foo1");
        {
            builder.startObject("foo2");
            {
                builder.field("buzz", 1);
            }
            builder.endObject();
        }
        builder.endObject();
        builder.field("foo3", 2);
        builder.startArray("foo4");
        {
            builder.startObject();
            {
                builder.field("foo5", 1);
            }
            builder.endObject();
        }
        builder.endArray();
    }
    builder.endObject();

    Map<String, Object> resultMap;

    try (XContentParser parser = createParser(XContentType.JSON.xContent(),
            insertRandomFields(builder.contentType(), BytesReference.bytes(builder), null, random()))) {
        resultMap = parser.map();
    }
    assertEquals(5, resultMap.keySet().size());
    assertEquals(2, ((Map<String, Object>) resultMap.get("foo")).keySet().size());
    Map<String, Object> foo1 = (Map<String, Object>) resultMap.get("foo1");
    assertEquals(2, foo1.keySet().size());
    assertEquals(2, ((Map<String, Object>) foo1.get("foo2")).keySet().size());
    List<Object> foo4List = (List<Object>) resultMap.get("foo4");
    assertEquals(1, foo4List.size());
    assertEquals(2, ((Map<String, Object>) foo4List.get(0)).keySet().size());

    Predicate<String> pathsToExclude = path -> path.endsWith("foo1");
    try (XContentParser parser = createParser(XContentType.JSON.xContent(),
            insertRandomFields(builder.contentType(), BytesReference.bytes(builder), pathsToExclude, random()))) {
        resultMap = parser.map();
    }
    assertEquals(5, resultMap.keySet().size());
    assertEquals(2, ((Map<String, Object>) resultMap.get("foo")).keySet().size());
    foo1 = (Map<String, Object>) resultMap.get("foo1");
    assertEquals(1, foo1.keySet().size());
    assertEquals(2, ((Map<String, Object>) foo1.get("foo2")).keySet().size());
    foo4List = (List<Object>) resultMap.get("foo4");
    assertEquals(1, foo4List.size());
    assertEquals(2, ((Map<String, Object>) foo4List.get(0)).keySet().size());

    pathsToExclude = path -> path.contains("foo1");
    try (XContentParser parser = createParser(XContentType.JSON.xContent(),
            insertRandomFields(builder.contentType(), BytesReference.bytes(builder), pathsToExclude, random()))) {
        resultMap = parser.map();
    }
    assertEquals(5, resultMap.keySet().size());
    assertEquals(2, ((Map<String, Object>) resultMap.get("foo")).keySet().size());
    foo1 = (Map<String, Object>) resultMap.get("foo1");
    assertEquals(1, foo1.keySet().size());
    assertEquals(1, ((Map<String, Object>) foo1.get("foo2")).keySet().size());
    foo4List = (List<Object>) resultMap.get("foo4");
    assertEquals(1, foo4List.size());
    assertEquals(2, ((Map<String, Object>) foo4List.get(0)).keySet().size());
}
 
Example 17
Source File: LimitQueryBuilder.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject(LimitQueryParser.NAME);
    builder.field("value", limit);
    builder.endObject();
}
 
Example 18
Source File: TextFieldMapper.java    From crate with Apache License 2.0 4 votes vote down vote up
void doXContent(XContentBuilder builder) throws IOException {
    builder.startObject("index_prefixes");
    builder.field("min_chars", minChars);
    builder.field("max_chars", maxChars);
    builder.endObject();
}
 
Example 19
Source File: ESClient.java    From uavstack with Apache License 2.0 3 votes vote down vote up
private XContentBuilder createMapping(String type, Map<String, Map<String, Object>> properties) throws IOException {

        XContentBuilder mapping;

        mapping = jsonBuilder().startObject().startObject(type);

        mapping = mapping.startObject("properties");

        for (String key : properties.keySet()) {
            mapping = mapping.startObject(key);

            Map<String, Object> fv = properties.get(key);

            for (String field : fv.keySet()) {
                mapping = mapping.field(field, fv.get(field));
            }

            mapping = mapping.endObject();
        }

        mapping = mapping.endObject();

        mapping = mapping.endObject();

        mapping = mapping.endObject();

        return mapping;
    }
 
Example 20
Source File: SnapshotShardFailure.java    From Elasticsearch with Apache License 2.0 2 votes vote down vote up
/**
 * Serializes snapshot failure information into JSON
 *
 * @param snapshotShardFailure snapshot failure information
 * @param builder              XContent builder
 * @param params               additional parameters
 */
public static void toXContent(SnapshotShardFailure snapshotShardFailure, XContentBuilder builder, ToXContent.Params params) throws IOException {
    builder.startObject();
    snapshotShardFailure.toXContent(builder, params);
    builder.endObject();
}