Search in sources :

Example 66 with XContentBuilder

use of org.elasticsearch.common.xcontent.XContentBuilder in project elasticsearch by elastic.

the class RestExplainAction method prepareRequest.

@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
    final ExplainRequest explainRequest = new ExplainRequest(request.param("index"), request.param("type"), request.param("id"));
    explainRequest.parent(request.param("parent"));
    explainRequest.routing(request.param("routing"));
    explainRequest.preference(request.param("preference"));
    String queryString = request.param("q");
    request.withContentOrSourceParamParserOrNull(parser -> {
        if (parser != null) {
            explainRequest.query(RestActions.getQueryContent(parser));
        } else if (queryString != null) {
            QueryBuilder query = RestActions.urlParamsToQueryBuilder(request);
            explainRequest.query(query);
        }
    });
    if (request.param("fields") != null) {
        throw new IllegalArgumentException("The parameter [fields] is no longer supported, " + "please use [stored_fields] to retrieve stored fields");
    }
    String sField = request.param("stored_fields");
    if (sField != null) {
        String[] sFields = Strings.splitStringByCommaToArray(sField);
        if (sFields != null) {
            explainRequest.storedFields(sFields);
        }
    }
    explainRequest.fetchSourceContext(FetchSourceContext.parseFromRestRequest(request));
    return channel -> client.explain(explainRequest, new RestBuilderListener<ExplainResponse>(channel) {

        @Override
        public RestResponse buildResponse(ExplainResponse response, XContentBuilder builder) throws Exception {
            builder.startObject();
            builder.field(Fields._INDEX, response.getIndex()).field(Fields._TYPE, response.getType()).field(Fields._ID, response.getId()).field(Fields.MATCHED, response.isMatch());
            if (response.hasExplanation()) {
                builder.startObject(Fields.EXPLANATION);
                buildExplanation(builder, response.getExplanation());
                builder.endObject();
            }
            GetResult getResult = response.getGetResult();
            if (getResult != null) {
                builder.startObject(Fields.GET);
                response.getGetResult().toXContentEmbedded(builder, request);
                builder.endObject();
            }
            builder.endObject();
            return new BytesRestResponse(response.isExists() ? OK : NOT_FOUND, builder);
        }

        private void buildExplanation(XContentBuilder builder, Explanation explanation) throws IOException {
            builder.field(Fields.VALUE, explanation.getValue());
            builder.field(Fields.DESCRIPTION, explanation.getDescription());
            Explanation[] innerExps = explanation.getDetails();
            if (innerExps != null) {
                builder.startArray(Fields.DETAILS);
                for (Explanation exp : innerExps) {
                    builder.startObject();
                    buildExplanation(builder, exp);
                    builder.endObject();
                }
                builder.endArray();
            }
        }
    });
}
Also used : BaseRestHandler(org.elasticsearch.rest.BaseRestHandler) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) Explanation(org.apache.lucene.search.Explanation) GET(org.elasticsearch.rest.RestRequest.Method.GET) ExplainRequest(org.elasticsearch.action.explain.ExplainRequest) ExplainResponse(org.elasticsearch.action.explain.ExplainResponse) RestResponse(org.elasticsearch.rest.RestResponse) GetResult(org.elasticsearch.index.get.GetResult) RestBuilderListener(org.elasticsearch.rest.action.RestBuilderListener) IOException(java.io.IOException) NOT_FOUND(org.elasticsearch.rest.RestStatus.NOT_FOUND) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) RestController(org.elasticsearch.rest.RestController) Strings(org.elasticsearch.common.Strings) RestActions(org.elasticsearch.rest.action.RestActions) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) POST(org.elasticsearch.rest.RestRequest.Method.POST) Settings(org.elasticsearch.common.settings.Settings) RestRequest(org.elasticsearch.rest.RestRequest) OK(org.elasticsearch.rest.RestStatus.OK) NodeClient(org.elasticsearch.client.node.NodeClient) FetchSourceContext(org.elasticsearch.search.fetch.subphase.FetchSourceContext) GetResult(org.elasticsearch.index.get.GetResult) RestResponse(org.elasticsearch.rest.RestResponse) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) Explanation(org.apache.lucene.search.Explanation) ExplainResponse(org.elasticsearch.action.explain.ExplainResponse) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) IOException(java.io.IOException) ExplainRequest(org.elasticsearch.action.explain.ExplainRequest) IOException(java.io.IOException) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder)

Example 67 with XContentBuilder

use of org.elasticsearch.common.xcontent.XContentBuilder in project elasticsearch by elastic.

the class ElasticsearchExceptionTests method testFromXContentWithHeadersAndMetadata.

public void testFromXContentWithHeadersAndMetadata() throws IOException {
    RoutingMissingException routing = new RoutingMissingException("_test", "_type", "_id");
    ElasticsearchException baz = new ElasticsearchException("baz", routing);
    baz.addHeader("baz_0", "baz0");
    baz.addMetadata("es.baz_1", "baz1");
    baz.addHeader("baz_2", "baz2");
    baz.addMetadata("es.baz_3", "baz3");
    ElasticsearchException bar = new ElasticsearchException("bar", baz);
    bar.addMetadata("es.bar_0", "bar0");
    bar.addHeader("bar_1", "bar1");
    bar.addMetadata("es.bar_2", "bar2");
    ElasticsearchException foo = new ElasticsearchException("foo", bar);
    foo.addMetadata("es.foo_0", "foo0");
    foo.addHeader("foo_1", "foo1");
    final XContent xContent = randomFrom(XContentType.values()).xContent();
    XContentBuilder builder = XContentBuilder.builder(xContent).startObject().value(foo).endObject();
    ElasticsearchException parsed;
    try (XContentParser parser = createParser(builder)) {
        assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
        parsed = ElasticsearchException.fromXContent(parser);
        assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken());
        assertNull(parser.nextToken());
    }
    assertNotNull(parsed);
    assertEquals(parsed.getMessage(), "Elasticsearch exception [type=exception, reason=foo]");
    assertThat(parsed.getHeaderKeys(), hasSize(1));
    assertThat(parsed.getHeader("foo_1"), hasItem("foo1"));
    assertThat(parsed.getMetadataKeys(), hasSize(1));
    assertThat(parsed.getMetadata("es.foo_0"), hasItem("foo0"));
    ElasticsearchException cause = (ElasticsearchException) parsed.getCause();
    assertEquals(cause.getMessage(), "Elasticsearch exception [type=exception, reason=bar]");
    assertThat(cause.getHeaderKeys(), hasSize(1));
    assertThat(cause.getHeader("bar_1"), hasItem("bar1"));
    assertThat(cause.getMetadataKeys(), hasSize(2));
    assertThat(cause.getMetadata("es.bar_0"), hasItem("bar0"));
    assertThat(cause.getMetadata("es.bar_2"), hasItem("bar2"));
    cause = (ElasticsearchException) cause.getCause();
    assertEquals(cause.getMessage(), "Elasticsearch exception [type=exception, reason=baz]");
    assertThat(cause.getHeaderKeys(), hasSize(2));
    assertThat(cause.getHeader("baz_0"), hasItem("baz0"));
    assertThat(cause.getHeader("baz_2"), hasItem("baz2"));
    assertThat(cause.getMetadataKeys(), hasSize(2));
    assertThat(cause.getMetadata("es.baz_1"), hasItem("baz1"));
    assertThat(cause.getMetadata("es.baz_3"), hasItem("baz3"));
    cause = (ElasticsearchException) cause.getCause();
    assertEquals(cause.getMessage(), "Elasticsearch exception [type=routing_missing_exception, reason=routing is required for [_test]/[_type]/[_id]]");
    assertThat(cause.getHeaderKeys(), hasSize(0));
    assertThat(cause.getMetadataKeys(), hasSize(2));
    assertThat(cause.getMetadata("es.index"), hasItem("_test"));
    assertThat(cause.getMetadata("es.index_uuid"), hasItem("_na_"));
}
Also used : XContent(org.elasticsearch.common.xcontent.XContent) ToXContent(org.elasticsearch.common.xcontent.ToXContent) RoutingMissingException(org.elasticsearch.action.RoutingMissingException) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Example 68 with XContentBuilder

use of org.elasticsearch.common.xcontent.XContentBuilder in project elasticsearch by elastic.

the class ElasticsearchExceptionTests method testFromXContent.

public void testFromXContent() throws IOException {
    final XContent xContent = randomFrom(XContentType.values()).xContent();
    XContentBuilder builder = XContentBuilder.builder(xContent).startObject().field("type", "foo").field("reason", "something went wrong").field("stack_trace", "...").endObject();
    ElasticsearchException parsed;
    try (XContentParser parser = createParser(xContent, builder.bytes())) {
        assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
        parsed = ElasticsearchException.fromXContent(parser);
        assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken());
        assertNull(parser.nextToken());
    }
    assertNotNull(parsed);
    assertEquals(parsed.getMessage(), "Elasticsearch exception [type=foo, reason=something went wrong, stack_trace=...]");
}
Also used : XContent(org.elasticsearch.common.xcontent.XContent) ToXContent(org.elasticsearch.common.xcontent.ToXContent) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Example 69 with XContentBuilder

use of org.elasticsearch.common.xcontent.XContentBuilder in project elasticsearch by elastic.

the class ElasticsearchExceptionTests method testFromXContentWithIgnoredMetadataAndHeaders.

/**
     * Test that some values like arrays of numbers are ignored when parsing back
     * an exception.
     */
public void testFromXContentWithIgnoredMetadataAndHeaders() throws IOException {
    final XContent xContent = randomFrom(XContentType.values()).xContent();
    // The exception content to parse is built using a XContentBuilder
    // because the current Java API does not allow to add metadata/headers
    // of other types than list of strings.
    BytesReference originalBytes;
    try (XContentBuilder builder = XContentBuilder.builder(xContent)) {
        builder.startObject().field("metadata_int", 1).array("metadata_array_of_ints", new int[] { 8, 13, 21 }).field("reason", "Custom reason").array("metadata_array_of_boolean", new boolean[] { false, false }).startArray("metadata_array_of_objects").startObject().field("object_array_one", "value_one").endObject().startObject().field("object_array_two", "value_two").endObject().endArray().field("type", "custom_exception").field("metadata_long", 1L).array("metadata_array_of_longs", new long[] { 2L, 3L, 5L }).field("metadata_other", "some metadata").startObject("header").field("header_string", "some header").array("header_array_of_strings", new String[] { "foo", "bar", "baz" }).endObject().startObject("metadata_object").field("object_field", "value").endObject().endObject();
        originalBytes = builder.bytes();
    }
    ElasticsearchException parsedException;
    try (XContentParser parser = createParser(xContent, originalBytes)) {
        assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
        parsedException = ElasticsearchException.fromXContent(parser);
        assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken());
        assertNull(parser.nextToken());
    }
    assertNotNull(parsedException);
    assertEquals("Elasticsearch exception [type=custom_exception, reason=Custom reason]", parsedException.getMessage());
    assertEquals(2, parsedException.getHeaderKeys().size());
    assertThat(parsedException.getHeader("header_string"), hasItem("some header"));
    assertThat(parsedException.getHeader("header_array_of_strings"), hasItems("foo", "bar", "baz"));
    assertEquals(1, parsedException.getMetadataKeys().size());
    assertThat(parsedException.getMetadata("es.metadata_other"), hasItem("some metadata"));
}
Also used : BytesReference(org.elasticsearch.common.bytes.BytesReference) XContent(org.elasticsearch.common.xcontent.XContent) ToXContent(org.elasticsearch.common.xcontent.ToXContent) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Example 70 with XContentBuilder

use of org.elasticsearch.common.xcontent.XContentBuilder in project elasticsearch by elastic.

the class DocWriteResponseTests method testToXContentDoesntIncludeForcedRefreshUnlessForced.

/**
     * Tests that {@link DocWriteResponse#toXContent(XContentBuilder, ToXContent.Params)} doesn't include {@code forced_refresh} unless it
     * is true. We can't assert this in the yaml tests because "not found" is also "false" there....
     */
public void testToXContentDoesntIncludeForcedRefreshUnlessForced() throws IOException {
    DocWriteResponse response = new DocWriteResponse(new ShardId("index", "uuid", 0), "type", "id", SequenceNumbersService.UNASSIGNED_SEQ_NO, 0, Result.CREATED) {
    };
    response.setShardInfo(new ShardInfo(1, 1));
    response.setForcedRefresh(false);
    try (XContentBuilder builder = JsonXContent.contentBuilder()) {
        response.toXContent(builder, ToXContent.EMPTY_PARAMS);
        try (XContentParser parser = createParser(JsonXContent.jsonXContent, builder.bytes())) {
            assertThat(parser.map(), not(hasKey("forced_refresh")));
        }
    }
    response.setForcedRefresh(true);
    try (XContentBuilder builder = JsonXContent.contentBuilder()) {
        response.toXContent(builder, ToXContent.EMPTY_PARAMS);
        try (XContentParser parser = createParser(JsonXContent.jsonXContent, builder.bytes())) {
            assertThat(parser.map(), hasEntry("forced_refresh", true));
        }
    }
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) XContentParser(org.elasticsearch.common.xcontent.XContentParser) ShardInfo(org.elasticsearch.action.support.replication.ReplicationResponse.ShardInfo)

Aggregations

XContentBuilder (org.elasticsearch.common.xcontent.XContentBuilder)619 IOException (java.io.IOException)127 XContentParser (org.elasticsearch.common.xcontent.XContentParser)122 Settings (org.elasticsearch.common.settings.Settings)60 ArrayList (java.util.ArrayList)59 SearchResponse (org.elasticsearch.action.search.SearchResponse)56 Matchers.containsString (org.hamcrest.Matchers.containsString)53 HashMap (java.util.HashMap)47 CompressedXContent (org.elasticsearch.common.compress.CompressedXContent)43 Map (java.util.Map)41 RestRequest (org.elasticsearch.rest.RestRequest)37 IndexRequestBuilder (org.elasticsearch.action.index.IndexRequestBuilder)36 BytesRestResponse (org.elasticsearch.rest.BytesRestResponse)35 Test (org.junit.Test)34 RestController (org.elasticsearch.rest.RestController)33 NodeClient (org.elasticsearch.client.node.NodeClient)32 BaseRestHandler (org.elasticsearch.rest.BaseRestHandler)32 ElasticsearchAssertions.assertSearchResponse (org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse)32 GeoPoint (org.elasticsearch.common.geo.GeoPoint)31 CrateUnitTest (io.crate.test.integration.CrateUnitTest)28