Search in sources :

Example 31 with XContentType

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

the class BytesRestResponseTests method testErrorToAndFromXContent.

public void testErrorToAndFromXContent() throws IOException {
    final boolean detailed = randomBoolean();
    Exception original;
    ElasticsearchException cause = null;
    String reason;
    String type = "exception";
    RestStatus status = RestStatus.INTERNAL_SERVER_ERROR;
    boolean addHeadersOrMetadata = false;
    switch(randomIntBetween(0, 5)) {
        case 0:
            original = new ElasticsearchException("ElasticsearchException without cause");
            if (detailed) {
                addHeadersOrMetadata = randomBoolean();
                reason = "ElasticsearchException without cause";
            } else {
                reason = "ElasticsearchException[ElasticsearchException without cause]";
            }
            break;
        case 1:
            original = new ElasticsearchException("ElasticsearchException with a cause", new FileNotFoundException("missing"));
            if (detailed) {
                addHeadersOrMetadata = randomBoolean();
                type = "exception";
                reason = "ElasticsearchException with a cause";
                cause = new ElasticsearchException("Elasticsearch exception [type=file_not_found_exception, reason=missing]");
            } else {
                reason = "ElasticsearchException[ElasticsearchException with a cause]";
            }
            break;
        case 2:
            original = new ResourceNotFoundException("ElasticsearchException with custom status");
            status = RestStatus.NOT_FOUND;
            if (detailed) {
                addHeadersOrMetadata = randomBoolean();
                type = "resource_not_found_exception";
                reason = "ElasticsearchException with custom status";
            } else {
                reason = "ResourceNotFoundException[ElasticsearchException with custom status]";
            }
            break;
        case 3:
            TransportAddress address = buildNewFakeTransportAddress();
            original = new RemoteTransportException("remote", address, "action", new ResourceAlreadyExistsException("ElasticsearchWrapperException with a cause that has a custom status"));
            status = RestStatus.BAD_REQUEST;
            if (detailed) {
                type = "resource_already_exists_exception";
                reason = "ElasticsearchWrapperException with a cause that has a custom status";
            } else {
                reason = "RemoteTransportException[[remote][" + address.toString() + "][action]]";
            }
            break;
        case 4:
            original = new RemoteTransportException("ElasticsearchWrapperException with a cause that has a special treatment", new IllegalArgumentException("wrong"));
            status = RestStatus.BAD_REQUEST;
            if (detailed) {
                type = "illegal_argument_exception";
                reason = "wrong";
            } else {
                reason = "RemoteTransportException[[ElasticsearchWrapperException with a cause that has a special treatment]]";
            }
            break;
        case 5:
            status = randomFrom(RestStatus.values());
            original = new ElasticsearchStatusException("ElasticsearchStatusException with random status", status);
            if (detailed) {
                addHeadersOrMetadata = randomBoolean();
                type = "status_exception";
                reason = "ElasticsearchStatusException with random status";
            } else {
                reason = "ElasticsearchStatusException[ElasticsearchStatusException with random status]";
            }
            break;
        default:
            throw new UnsupportedOperationException("Failed to generate random exception");
    }
    String message = "Elasticsearch exception [type=" + type + ", reason=" + reason + "]";
    ElasticsearchStatusException expected = new ElasticsearchStatusException(message, status, cause);
    if (addHeadersOrMetadata) {
        ElasticsearchException originalException = ((ElasticsearchException) original);
        if (randomBoolean()) {
            originalException.addHeader("foo", "bar", "baz");
            expected.addHeader("foo", "bar", "baz");
        }
        if (randomBoolean()) {
            originalException.addMetadata("es.metadata_0", "0");
            expected.addMetadata("es.metadata_0", "0");
        }
        if (randomBoolean()) {
            String resourceType = randomAsciiOfLength(5);
            String resourceId = randomAsciiOfLength(5);
            originalException.setResources(resourceType, resourceId);
            expected.setResources(resourceType, resourceId);
        }
        if (randomBoolean()) {
            originalException.setIndex("_index");
            expected.setIndex("_index");
        }
    }
    final XContentType xContentType = randomFrom(XContentType.values());
    Map<String, String> params = Collections.singletonMap("format", xContentType.mediaType());
    RestRequest request = new FakeRestRequest.Builder(xContentRegistry()).withParams(params).build();
    RestChannel channel = detailed ? new DetailedExceptionRestChannel(request) : new SimpleExceptionRestChannel(request);
    BytesRestResponse response = new BytesRestResponse(channel, original);
    ElasticsearchException parsedError;
    try (XContentParser parser = createParser(xContentType.xContent(), response.content())) {
        parsedError = BytesRestResponse.errorFromXContent(parser);
        assertNull(parser.nextToken());
    }
    assertEquals(expected.status(), parsedError.status());
    assertDeepEquals(expected, parsedError);
}
Also used : RemoteTransportException(org.elasticsearch.transport.RemoteTransportException) TransportAddress(org.elasticsearch.common.transport.TransportAddress) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) FileNotFoundException(java.io.FileNotFoundException) ResourceAlreadyExistsException(org.elasticsearch.ResourceAlreadyExistsException) ElasticsearchException(org.elasticsearch.ElasticsearchException) Matchers.containsString(org.hamcrest.Matchers.containsString) ElasticsearchException(org.elasticsearch.ElasticsearchException) ParsingException(org.elasticsearch.common.ParsingException) ResourceAlreadyExistsException(org.elasticsearch.ResourceAlreadyExistsException) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException) ResourceNotFoundException(org.elasticsearch.ResourceNotFoundException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) SearchPhaseExecutionException(org.elasticsearch.action.search.SearchPhaseExecutionException) RemoteTransportException(org.elasticsearch.transport.RemoteTransportException) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException) XContentType(org.elasticsearch.common.xcontent.XContentType) FakeRestRequest(org.elasticsearch.test.rest.FakeRestRequest) ResourceNotFoundException(org.elasticsearch.ResourceNotFoundException) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Example 32 with XContentType

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

the class RestTable method buildResponse.

public static RestResponse buildResponse(Table table, RestChannel channel) throws Exception {
    RestRequest request = channel.request();
    XContentType xContentType = XContentType.fromMediaTypeOrFormat(request.param("format", request.header("Accept")));
    if (xContentType != null) {
        return buildXContentBuilder(table, channel);
    }
    return buildTextPlainResponse(table, channel);
}
Also used : RestRequest(org.elasticsearch.rest.RestRequest) XContentType(org.elasticsearch.common.xcontent.XContentType)

Example 33 with XContentType

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

the class MainResponseTests method testFromXContent.

public void testFromXContent() throws IOException {
    MainResponse mainResponse = createTestItem();
    XContentType xContentType = randomFrom(XContentType.values());
    boolean humanReadable = randomBoolean();
    BytesReference originalBytes = toXContent(mainResponse, xContentType, humanReadable);
    MainResponse parsed;
    try (XContentParser parser = createParser(xContentType.xContent(), originalBytes)) {
        parsed = MainResponse.fromXContent(parser);
        assertNull(parser.nextToken());
    }
    assertEquals(mainResponse.getClusterUuid(), parsed.getClusterUuid());
    assertEquals(mainResponse.getClusterName(), parsed.getClusterName());
    assertEquals(mainResponse.getNodeName(), parsed.getNodeName());
    assertEquals(mainResponse.getBuild(), parsed.getBuild());
    assertEquals(mainResponse.getVersion(), parsed.getVersion());
    // we cannot recreate the "available" flag from xContent, but should be "true" if request came through
    assertEquals(true, parsed.isAvailable());
    assertToXContentEquivalent(originalBytes, toXContent(parsed, xContentType, humanReadable), xContentType);
}
Also used : BytesReference(org.elasticsearch.common.bytes.BytesReference) XContentType(org.elasticsearch.common.xcontent.XContentType) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Example 34 with XContentType

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

the class IndexResponseTests method testToAndFromXContent.

public void testToAndFromXContent() throws IOException {
    final Tuple<IndexResponse, IndexResponse> tuple = randomIndexResponse();
    IndexResponse indexResponse = tuple.v1();
    IndexResponse expectedIndexResponse = tuple.v2();
    boolean humanReadable = randomBoolean();
    XContentType xContentType = randomFrom(XContentType.values());
    BytesReference indexResponseBytes = toXContent(indexResponse, xContentType, humanReadable);
    // Shuffle the XContent fields
    if (randomBoolean()) {
        try (XContentParser parser = createParser(xContentType.xContent(), indexResponseBytes)) {
            indexResponseBytes = shuffleXContent(parser, randomBoolean()).bytes();
        }
    }
    // Parse the XContent bytes to obtain a parsed
    IndexResponse parsedIndexResponse;
    try (XContentParser parser = createParser(xContentType.xContent(), indexResponseBytes)) {
        parsedIndexResponse = IndexResponse.fromXContent(parser);
        assertNull(parser.nextToken());
    }
    // We can't use equals() to compare the original and the parsed index response
    // because the random index response can contain shard failures with exceptions,
    // and those exceptions are not parsed back with the same types.
    assertDocWriteResponse(expectedIndexResponse, parsedIndexResponse);
}
Also used : BytesReference(org.elasticsearch.common.bytes.BytesReference) XContentType(org.elasticsearch.common.xcontent.XContentType) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Example 35 with XContentType

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

the class ShardSearchFailureTests method testFromXContent.

public void testFromXContent() throws IOException {
    ShardSearchFailure response = createTestItem();
    XContentType xContentType = randomFrom(XContentType.values());
    boolean humanReadable = randomBoolean();
    BytesReference originalBytes = toXContent(response, xContentType, humanReadable);
    ShardSearchFailure parsed;
    try (XContentParser parser = createParser(xContentType.xContent(), originalBytes)) {
        assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
        parsed = ShardSearchFailure.fromXContent(parser);
        assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken());
        assertNull(parser.nextToken());
    }
    assertEquals(response.index(), parsed.index());
    assertEquals(response.shard().getNodeId(), parsed.shard().getNodeId());
    assertEquals(response.shardId(), parsed.shardId());
    // we cannot compare the cause, because it will be wrapped in an outer ElasticSearchException
    // best effort: try to check that the original message appears somewhere in the rendered xContent
    String originalMsg = response.getCause().getMessage();
    assertEquals(parsed.getCause().getMessage(), "Elasticsearch exception [type=parsing_exception, reason=" + originalMsg + "]");
    String nestedMsg = response.getCause().getCause().getMessage();
    assertEquals(parsed.getCause().getCause().getMessage(), "Elasticsearch exception [type=illegal_argument_exception, reason=" + nestedMsg + "]");
}
Also used : BytesReference(org.elasticsearch.common.bytes.BytesReference) XContentType(org.elasticsearch.common.xcontent.XContentType) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Aggregations

XContentType (org.elasticsearch.common.xcontent.XContentType)82 BytesReference (org.elasticsearch.common.bytes.BytesReference)48 XContentParser (org.elasticsearch.common.xcontent.XContentParser)42 Map (java.util.Map)19 XContentBuilder (org.elasticsearch.common.xcontent.XContentBuilder)19 HashMap (java.util.HashMap)18 IndexRequest (org.elasticsearch.action.index.IndexRequest)11 DocWriteRequest (org.elasticsearch.action.DocWriteRequest)10 IOException (java.io.IOException)9 BytesRef (org.apache.lucene.util.BytesRef)8 DeleteRequest (org.elasticsearch.action.delete.DeleteRequest)8 Collections.emptyMap (java.util.Collections.emptyMap)6 ElasticsearchException (org.elasticsearch.ElasticsearchException)6 BulkRequest (org.elasticsearch.action.bulk.BulkRequest)6 UpdateRequest (org.elasticsearch.action.update.UpdateRequest)6 Collections.singletonMap (java.util.Collections.singletonMap)5 HttpEntity (org.apache.http.HttpEntity)5 ByteArrayEntity (org.apache.http.entity.ByteArrayEntity)5 GetRequest (org.elasticsearch.action.get.GetRequest)5 WriteRequest (org.elasticsearch.action.support.WriteRequest)5