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

The following examples show how to use org.elasticsearch.common.xcontent.XContentBuilder#startObject() . 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: GetFieldMappingsResponse.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    for (Map.Entry<String, ImmutableMap<String, ImmutableMap<String, FieldMappingMetaData>>> indexEntry : mappings.entrySet()) {
        builder.startObject(indexEntry.getKey(), XContentBuilder.FieldCaseConversion.NONE);
        builder.startObject("mappings");
        for (Map.Entry<String, ImmutableMap<String, FieldMappingMetaData>> typeEntry : indexEntry.getValue().entrySet()) {
            builder.startObject(typeEntry.getKey(), XContentBuilder.FieldCaseConversion.NONE);
            for (Map.Entry<String, FieldMappingMetaData> fieldEntry : typeEntry.getValue().entrySet()) {
                builder.startObject(fieldEntry.getKey());
                fieldEntry.getValue().toXContent(builder, params);
                builder.endObject();
            }
            builder.endObject();
        }
        builder.endObject();
        builder.endObject();
    }
    return builder;
}
 
Example 2
Source File: ResponseUtil.java    From elasticsearch-auth with Apache License 2.0 6 votes vote down vote up
public static void send(final RestRequest request,
        final RestChannel channel, final RestStatus status,
        final String... args) {
    try {
        final XContentBuilder builder = JsonXContent.contentBuilder();
        builder.startObject();
        builder.field("status", status.getStatus());
        for (int i = 0; i < args.length; i += 2) {
            builder.field(args[i], args[i + 1]);
        }
        builder.endObject();
        channel.sendResponse(new BytesRestResponse(status, builder));
    } catch (final IOException e) {
        logger.error("Failed to send a response.", e);
        try {
            channel.sendResponse(new BytesRestResponse(channel, e));
        } catch (final IOException e1) {
            logger.error("Failed to send a failure response.", e1);
        }
    }
}
 
Example 3
Source File: RestHighLevelClientCase.java    From skywalking with Apache License 2.0 6 votes vote down vote up
private void index(RestHighLevelClient client, String indexName) throws IOException {
    XContentBuilder builder = XContentFactory.jsonBuilder();
    builder.startObject();
    {
        builder.field("author", "Marker");
        builder.field("title", "Java programing.");
    }
    builder.endObject();
    IndexRequest indexRequest = new IndexRequest(indexName, "_doc", "1").source(builder);

    IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
    if (indexResponse.status().getStatus() >= 400) {
        String message = "elasticsearch index data fail.";
        logger.error(message);
        throw new RuntimeException(message);
    }
}
 
Example 4
Source File: Search.java    From elasticsearch-rest-command with The Unlicense 6 votes vote down vote up
public void buildDelete(XContentBuilder builder,
		DeleteByQueryResponse response) throws IOException {

	builder.startObject();
	builder.startObject("_indices");
	for (IndexDeleteByQueryResponse indexDeleteByQueryResponse : response
			.getIndices().values()) {
		builder.startObject(indexDeleteByQueryResponse.getIndex(),
				XContentBuilder.FieldCaseConversion.NONE);

		builder.startObject("_shards");
		builder.field("total", indexDeleteByQueryResponse.getTotalShards());
		builder.field("successful",
				indexDeleteByQueryResponse.getSuccessfulShards());
		builder.field("failed",
				indexDeleteByQueryResponse.getFailedShards());
		builder.endObject();

		builder.endObject();
	}
	builder.endObject();
	builder.endObject();
}
 
Example 5
Source File: UsersPrivilegesMetaDataTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
public void testXContent() throws IOException {
    XContentBuilder builder = XContentFactory.jsonBuilder();

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

    usersPrivilegesMetaData.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
    UsersPrivilegesMetaData usersPrivilegesMetaData2 = UsersPrivilegesMetaData.fromXContent(parser);
    assertEquals(usersPrivilegesMetaData, usersPrivilegesMetaData2);

    // a metadata custom must consume its surrounded END_OBJECT token, no token must be left
    assertThat(parser.nextToken(), nullValue());
}
 
Example 6
Source File: AnalyzeResponse.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    if (tokens != null) {
        builder.startArray(Fields.TOKENS);
        for (AnalyzeToken token : tokens) {
            token.toXContent(builder, params);
        }
        builder.endArray();
    }

    if (detail != null) {
        builder.startObject(Fields.DETAIL);
        detail.toXContent(builder, params);
        builder.endObject();
    }
    return builder;
}
 
Example 7
Source File: ClusterStatsIndices.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private void addDoubleMinMax(XContentBuilderString field, double min, double max, double avg, XContentBuilder builder) throws IOException {
    builder.startObject(field);
    builder.field(Fields.MIN, min);
    builder.field(Fields.MAX, max);
    builder.field(Fields.AVG, avg);
    builder.endObject();
}
 
Example 8
Source File: VertexiumQueryStringQueryBuilder.java    From vertexium with Apache License 2.0 5 votes vote down vote up
@Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject("vertexium_query_string");
    super.doXContent(builder, params);

    builder.startArray("authorizations");
    for (String authorization : authorizations) {
        builder.value(authorization);
    }
    builder.endArray();

    builder.endObject();
}
 
Example 9
Source File: ElasticsearchException.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Renders a cause exception as xcontent
 */
protected void causeToXContent(XContentBuilder builder, Params params) throws IOException {
    final Throwable cause = getCause();
    if (cause != null && params.paramAsBoolean(REST_EXCEPTION_SKIP_CAUSE, REST_EXCEPTION_SKIP_CAUSE_DEFAULT) == false) {
        builder.field("caused_by");
        builder.startObject();
        toXContent(builder, params, cause);
        builder.endObject();
    }
}
 
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: DefaultShardOperationFailedException.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    builder.field("shard", shardId());
    builder.field("index", index());
    builder.field("status", status.name());
    if (reason != null) {
        builder.startObject("reason");
        ElasticsearchException.generateThrowableXContent(builder, params, cause);
        builder.endObject();
    }
    return builder;
}
 
Example 12
Source File: SettingsContentBuilder.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void createDefaultAnalyzerSettings(XContentBuilder contentBuilder) throws IOException {
  contentBuilder.startObject(FieldConstants.DEFAULT_ANALYZER);
  contentBuilder.field("type", "custom");
  contentBuilder.array(FILTER, "lowercase", "asciifolding", DEFAULT_STEMMER);
  contentBuilder.field("tokenizer", "standard");
  contentBuilder.field("char_filter", "html_strip");
  contentBuilder.endObject();
}
 
Example 13
Source File: HttpInfo.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject(Fields.HTTP);
    builder.array(Fields.BOUND_ADDRESS, (Object[]) address.boundAddresses());
    builder.field(Fields.PUBLISH_ADDRESS, address.publishAddress().toString());
    builder.humanReadableField(Fields.MAX_CONTENT_LENGTH_IN_BYTES, Fields.MAX_CONTENT_LENGTH, maxContentLength());
    builder.endObject();
    return builder;
}
 
Example 14
Source File: ClearFilterJoinCacheResponse.java    From siren-join with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
  builder.field("cluster_name", getClusterName().value());

  builder.startObject("nodes");
  for (ClearFilterJoinCacheNodeResponse node : this) {
    builder.startObject(node.getNode().getName(), XContentBuilder.FieldCaseConversion.NONE);
    builder.field("timestamp", node.getTimestamp());
    builder.endObject();
  }
  builder.endObject();

  return builder;
}
 
Example 15
Source File: Decision.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();
    builder.field("decider", label);
    builder.field("decision", type);
    String explanation = getExplanation();
    builder.field("explanation", explanation != null ? explanation : "none");
    builder.endObject();
    return builder;
}
 
Example 16
Source File: XContentTestUtils.java    From crate with Apache License 2.0 5 votes vote down vote up
public static Map<String, Object> convertToMap(ToXContent part) throws IOException {
    XContentBuilder builder = XContentFactory.jsonBuilder();
    builder.startObject();
    part.toXContent(builder, EMPTY_PARAMS);
    builder.endObject();
    return XContentHelper.convertToMap(BytesReference.bytes(builder), false, builder.contentType()).v2();
}
 
Example 17
Source File: CancelAllocationCommand.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void toXContent(CancelAllocationCommand command, XContentBuilder builder, ToXContent.Params params, String objectName) throws IOException {
    if (objectName == null) {
        builder.startObject();
    } else {
        builder.startObject(objectName);
    }
    builder.field("index", command.shardId().index().name());
    builder.field("shard", command.shardId().id());
    builder.field("node", command.node());
    builder.field("allow_primary", command.allowPrimary());
    builder.endObject();
}
 
Example 18
Source File: SnapshotIndexStatus.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(getIndex(), XContentBuilder.FieldCaseConversion.NONE);
    shardsStats.toXContent(builder, params);
    stats.toXContent(builder, params);
    builder.startObject(Fields.SHARDS);
    for (SnapshotIndexShardStatus shard : indexShards.values()) {
        shard.toXContent(builder, params);
    }
    builder.endObject();
    builder.endObject();
    return builder;
}
 
Example 19
Source File: MatchAllQueryBuilder.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void doXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject(MatchAllQueryParser.NAME);
    if (boost != -1) {
        builder.field("boost", boost);
    }
    builder.endObject();
}
 
Example 20
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());
}