Search in sources :

Example 1 with RestStatus

use of org.elasticsearch.rest.RestStatus in project elasticsearch by elastic.

the class RestGetFieldMappingAction method prepareRequest.

@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
    final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
    final String[] types = request.paramAsStringArrayOrEmptyIfAll("type");
    final String[] fields = Strings.splitStringByCommaToArray(request.param("fields"));
    GetFieldMappingsRequest getMappingsRequest = new GetFieldMappingsRequest();
    getMappingsRequest.indices(indices).types(types).fields(fields).includeDefaults(request.paramAsBoolean("include_defaults", false));
    getMappingsRequest.indicesOptions(IndicesOptions.fromRequest(request, getMappingsRequest.indicesOptions()));
    getMappingsRequest.local(request.paramAsBoolean("local", getMappingsRequest.local()));
    return channel -> client.admin().indices().getFieldMappings(getMappingsRequest, new RestBuilderListener<GetFieldMappingsResponse>(channel) {

        @Override
        public RestResponse buildResponse(GetFieldMappingsResponse response, XContentBuilder builder) throws Exception {
            Map<String, Map<String, Map<String, FieldMappingMetaData>>> mappingsByIndex = response.mappings();
            boolean isPossibleSingleFieldRequest = indices.length == 1 && types.length == 1 && fields.length == 1;
            if (isPossibleSingleFieldRequest && isFieldMappingMissingField(mappingsByIndex)) {
                return new BytesRestResponse(OK, builder.startObject().endObject());
            }
            RestStatus status = OK;
            if (mappingsByIndex.isEmpty() && fields.length > 0) {
                status = NOT_FOUND;
            }
            builder.startObject();
            response.toXContent(builder, request);
            builder.endObject();
            return new BytesRestResponse(status, builder);
        }
    });
}
Also used : BaseRestHandler(org.elasticsearch.rest.BaseRestHandler) FieldMappingMetaData(org.elasticsearch.action.admin.indices.mapping.get.GetFieldMappingsResponse.FieldMappingMetaData) GET(org.elasticsearch.rest.RestRequest.Method.GET) RestResponse(org.elasticsearch.rest.RestResponse) RestBuilderListener(org.elasticsearch.rest.action.RestBuilderListener) GetFieldMappingsResponse(org.elasticsearch.action.admin.indices.mapping.get.GetFieldMappingsResponse) 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) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) GetFieldMappingsRequest(org.elasticsearch.action.admin.indices.mapping.get.GetFieldMappingsRequest) Settings(org.elasticsearch.common.settings.Settings) RestStatus(org.elasticsearch.rest.RestStatus) Map(java.util.Map) IndicesOptions(org.elasticsearch.action.support.IndicesOptions) RestRequest(org.elasticsearch.rest.RestRequest) OK(org.elasticsearch.rest.RestStatus.OK) NodeClient(org.elasticsearch.client.node.NodeClient) RestResponse(org.elasticsearch.rest.RestResponse) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) GetFieldMappingsRequest(org.elasticsearch.action.admin.indices.mapping.get.GetFieldMappingsRequest) GetFieldMappingsResponse(org.elasticsearch.action.admin.indices.mapping.get.GetFieldMappingsResponse) IOException(java.io.IOException) RestStatus(org.elasticsearch.rest.RestStatus) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) Map(java.util.Map) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder)

Example 2 with RestStatus

use of org.elasticsearch.rest.RestStatus in project elasticsearch by elastic.

the class RestGetIndexTemplateAction method prepareRequest.

@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
    final String[] names = Strings.splitStringByCommaToArray(request.param("name"));
    final GetIndexTemplatesRequest getIndexTemplatesRequest = new GetIndexTemplatesRequest(names);
    getIndexTemplatesRequest.local(request.paramAsBoolean("local", getIndexTemplatesRequest.local()));
    getIndexTemplatesRequest.masterNodeTimeout(request.paramAsTime("master_timeout", getIndexTemplatesRequest.masterNodeTimeout()));
    final boolean implicitAll = getIndexTemplatesRequest.names().length == 0;
    return channel -> client.admin().indices().getTemplates(getIndexTemplatesRequest, new RestToXContentListener<GetIndexTemplatesResponse>(channel) {

        @Override
        protected RestStatus getStatus(final GetIndexTemplatesResponse response) {
            final boolean templateExists = response.getIndexTemplates().isEmpty() == false;
            return (templateExists || implicitAll) ? OK : NOT_FOUND;
        }
    });
}
Also used : BaseRestHandler(org.elasticsearch.rest.BaseRestHandler) GET(org.elasticsearch.rest.RestRequest.Method.GET) RestToXContentListener(org.elasticsearch.rest.action.RestToXContentListener) Set(java.util.Set) IOException(java.io.IOException) NOT_FOUND(org.elasticsearch.rest.RestStatus.NOT_FOUND) RestController(org.elasticsearch.rest.RestController) Strings(org.elasticsearch.common.Strings) GetIndexTemplatesResponse(org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesResponse) GetIndexTemplatesRequest(org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesRequest) Settings(org.elasticsearch.common.settings.Settings) RestStatus(org.elasticsearch.rest.RestStatus) RestRequest(org.elasticsearch.rest.RestRequest) OK(org.elasticsearch.rest.RestStatus.OK) NodeClient(org.elasticsearch.client.node.NodeClient) HEAD(org.elasticsearch.rest.RestRequest.Method.HEAD) RestStatus(org.elasticsearch.rest.RestStatus) GetIndexTemplatesResponse(org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesResponse) GetIndexTemplatesRequest(org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesRequest)

Example 3 with RestStatus

use of org.elasticsearch.rest.RestStatus in project elasticsearch by elastic.

the class BulkItemResponse method fromXContent.

/**
     * Reads a {@link BulkItemResponse} from a {@link XContentParser}.
     *
     * @param parser the {@link XContentParser}
     * @param id the id to assign to the parsed {@link BulkItemResponse}. It is usually the index of
     *           the item in the {@link BulkResponse#getItems} array.
     */
public static BulkItemResponse fromXContent(XContentParser parser, int id) throws IOException {
    ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.currentToken(), parser::getTokenLocation);
    XContentParser.Token token = parser.nextToken();
    ensureExpectedToken(XContentParser.Token.FIELD_NAME, token, parser::getTokenLocation);
    String currentFieldName = parser.currentName();
    token = parser.nextToken();
    final OpType opType = OpType.fromString(currentFieldName);
    ensureExpectedToken(XContentParser.Token.START_OBJECT, token, parser::getTokenLocation);
    DocWriteResponse.Builder builder = null;
    CheckedConsumer<XContentParser, IOException> itemParser = null;
    if (opType == OpType.INDEX || opType == OpType.CREATE) {
        final IndexResponse.Builder indexResponseBuilder = new IndexResponse.Builder();
        builder = indexResponseBuilder;
        itemParser = (indexParser) -> IndexResponse.parseXContentFields(indexParser, indexResponseBuilder);
    } else if (opType == OpType.UPDATE) {
        final UpdateResponse.Builder updateResponseBuilder = new UpdateResponse.Builder();
        builder = updateResponseBuilder;
        itemParser = (updateParser) -> UpdateResponse.parseXContentFields(updateParser, updateResponseBuilder);
    } else if (opType == OpType.DELETE) {
        final DeleteResponse.Builder deleteResponseBuilder = new DeleteResponse.Builder();
        builder = deleteResponseBuilder;
        itemParser = (deleteParser) -> DeleteResponse.parseXContentFields(deleteParser, deleteResponseBuilder);
    } else {
        throwUnknownField(currentFieldName, parser.getTokenLocation());
    }
    RestStatus status = null;
    ElasticsearchException exception = null;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        }
        if (ERROR.equals(currentFieldName)) {
            if (token == XContentParser.Token.START_OBJECT) {
                exception = ElasticsearchException.fromXContent(parser);
            }
        } else if (STATUS.equals(currentFieldName)) {
            if (token == XContentParser.Token.VALUE_NUMBER) {
                status = RestStatus.fromCode(parser.intValue());
            }
        } else {
            itemParser.accept(parser);
        }
    }
    ensureExpectedToken(XContentParser.Token.END_OBJECT, token, parser::getTokenLocation);
    token = parser.nextToken();
    ensureExpectedToken(XContentParser.Token.END_OBJECT, token, parser::getTokenLocation);
    BulkItemResponse bulkItemResponse;
    if (exception != null) {
        Failure failure = new Failure(builder.getShardId().getIndexName(), builder.getType(), builder.getId(), exception, status);
        bulkItemResponse = new BulkItemResponse(id, opType, failure);
    } else {
        bulkItemResponse = new BulkItemResponse(id, opType, builder.build());
    }
    return bulkItemResponse;
}
Also used : ElasticsearchException(org.elasticsearch.ElasticsearchException) StreamOutput(org.elasticsearch.common.io.stream.StreamOutput) XContentParserUtils.throwUnknownField(org.elasticsearch.common.xcontent.XContentParserUtils.throwUnknownField) Streamable(org.elasticsearch.common.io.stream.Streamable) ToXContent(org.elasticsearch.common.xcontent.ToXContent) CheckedConsumer(org.elasticsearch.common.CheckedConsumer) IOException(java.io.IOException) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) DocWriteResponse(org.elasticsearch.action.DocWriteResponse) XContentParserUtils.ensureExpectedToken(org.elasticsearch.common.xcontent.XContentParserUtils.ensureExpectedToken) StatusToXContentObject(org.elasticsearch.common.xcontent.StatusToXContentObject) Strings(org.elasticsearch.common.Strings) XContentParser(org.elasticsearch.common.xcontent.XContentParser) ExceptionsHelper(org.elasticsearch.ExceptionsHelper) OpType(org.elasticsearch.action.DocWriteRequest.OpType) Version(org.elasticsearch.Version) UpdateResponse(org.elasticsearch.action.update.UpdateResponse) StreamInput(org.elasticsearch.common.io.stream.StreamInput) RestStatus(org.elasticsearch.rest.RestStatus) IndexResponse(org.elasticsearch.action.index.IndexResponse) DeleteResponse(org.elasticsearch.action.delete.DeleteResponse) Writeable(org.elasticsearch.common.io.stream.Writeable) DocWriteResponse(org.elasticsearch.action.DocWriteResponse) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) IOException(java.io.IOException) ElasticsearchException(org.elasticsearch.ElasticsearchException) UpdateResponse(org.elasticsearch.action.update.UpdateResponse) DeleteResponse(org.elasticsearch.action.delete.DeleteResponse) RestStatus(org.elasticsearch.rest.RestStatus) IndexResponse(org.elasticsearch.action.index.IndexResponse) OpType(org.elasticsearch.action.DocWriteRequest.OpType) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Example 4 with RestStatus

use of org.elasticsearch.rest.RestStatus in project elasticsearch by elastic.

the class RestGetAction method prepareRequest.

@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
    final GetRequest getRequest = new GetRequest(request.param("index"), request.param("type"), request.param("id"));
    getRequest.operationThreaded(true);
    getRequest.refresh(request.paramAsBoolean("refresh", getRequest.refresh()));
    getRequest.routing(request.param("routing"));
    getRequest.parent(request.param("parent"));
    getRequest.preference(request.param("preference"));
    getRequest.realtime(request.paramAsBoolean("realtime", getRequest.realtime()));
    if (request.param("fields") != null) {
        throw new IllegalArgumentException("the parameter [fields] is no longer supported, " + "please use [stored_fields] to retrieve stored fields or [_source] to load the field from _source");
    }
    final String fieldsParam = request.param("stored_fields");
    if (fieldsParam != null) {
        final String[] fields = Strings.splitStringByCommaToArray(fieldsParam);
        if (fields != null) {
            getRequest.storedFields(fields);
        }
    }
    getRequest.version(RestActions.parseVersion(request));
    getRequest.versionType(VersionType.fromString(request.param("version_type"), getRequest.versionType()));
    getRequest.fetchSourceContext(FetchSourceContext.parseFromRestRequest(request));
    return channel -> client.get(getRequest, new RestToXContentListener<GetResponse>(channel) {

        @Override
        protected RestStatus getStatus(final GetResponse response) {
            return response.isExists() ? OK : NOT_FOUND;
        }
    });
}
Also used : BaseRestHandler(org.elasticsearch.rest.BaseRestHandler) GetResponse(org.elasticsearch.action.get.GetResponse) GetRequest(org.elasticsearch.action.get.GetRequest) GET(org.elasticsearch.rest.RestRequest.Method.GET) RestToXContentListener(org.elasticsearch.rest.action.RestToXContentListener) IOException(java.io.IOException) NOT_FOUND(org.elasticsearch.rest.RestStatus.NOT_FOUND) RestController(org.elasticsearch.rest.RestController) VersionType(org.elasticsearch.index.VersionType) Strings(org.elasticsearch.common.Strings) RestActions(org.elasticsearch.rest.action.RestActions) Settings(org.elasticsearch.common.settings.Settings) RestStatus(org.elasticsearch.rest.RestStatus) RestRequest(org.elasticsearch.rest.RestRequest) OK(org.elasticsearch.rest.RestStatus.OK) NodeClient(org.elasticsearch.client.node.NodeClient) HEAD(org.elasticsearch.rest.RestRequest.Method.HEAD) FetchSourceContext(org.elasticsearch.search.fetch.subphase.FetchSourceContext) RestStatus(org.elasticsearch.rest.RestStatus) GetRequest(org.elasticsearch.action.get.GetRequest) GetResponse(org.elasticsearch.action.get.GetResponse)

Example 5 with RestStatus

use of org.elasticsearch.rest.RestStatus in project elasticsearch by elastic.

the class RemoteScrollableHitSourceTests method testWrapExceptionToPreserveStatus.

public void testWrapExceptionToPreserveStatus() throws IOException {
    Exception cause = new Exception();
    // Successfully get the status without a body
    RestStatus status = randomFrom(RestStatus.values());
    ElasticsearchStatusException wrapped = RemoteScrollableHitSource.wrapExceptionToPreserveStatus(status.getStatus(), null, cause);
    assertEquals(status, wrapped.status());
    assertEquals(cause, wrapped.getCause());
    assertEquals("No error body.", wrapped.getMessage());
    // Successfully get the status without a body
    HttpEntity okEntity = new StringEntity("test body", ContentType.TEXT_PLAIN);
    wrapped = RemoteScrollableHitSource.wrapExceptionToPreserveStatus(status.getStatus(), okEntity, cause);
    assertEquals(status, wrapped.status());
    assertEquals(cause, wrapped.getCause());
    assertEquals("body=test body", wrapped.getMessage());
    // Successfully get the status with a broken body
    IOException badEntityException = new IOException();
    HttpEntity badEntity = mock(HttpEntity.class);
    when(badEntity.getContent()).thenThrow(badEntityException);
    wrapped = RemoteScrollableHitSource.wrapExceptionToPreserveStatus(status.getStatus(), badEntity, cause);
    assertEquals(status, wrapped.status());
    assertEquals(cause, wrapped.getCause());
    assertEquals("Failed to extract body.", wrapped.getMessage());
    assertEquals(badEntityException, wrapped.getSuppressed()[0]);
    // Fail to get the status without a body
    int notAnHttpStatus = -1;
    assertNull(RestStatus.fromCode(notAnHttpStatus));
    wrapped = RemoteScrollableHitSource.wrapExceptionToPreserveStatus(notAnHttpStatus, null, cause);
    assertEquals(RestStatus.INTERNAL_SERVER_ERROR, wrapped.status());
    assertEquals(cause, wrapped.getCause());
    assertEquals("Couldn't extract status [" + notAnHttpStatus + "]. No error body.", wrapped.getMessage());
    // Fail to get the status without a body
    wrapped = RemoteScrollableHitSource.wrapExceptionToPreserveStatus(notAnHttpStatus, okEntity, cause);
    assertEquals(RestStatus.INTERNAL_SERVER_ERROR, wrapped.status());
    assertEquals(cause, wrapped.getCause());
    assertEquals("Couldn't extract status [" + notAnHttpStatus + "]. body=test body", wrapped.getMessage());
    // Fail to get the status with a broken body
    wrapped = RemoteScrollableHitSource.wrapExceptionToPreserveStatus(notAnHttpStatus, badEntity, cause);
    assertEquals(RestStatus.INTERNAL_SERVER_ERROR, wrapped.status());
    assertEquals(cause, wrapped.getCause());
    assertEquals("Couldn't extract status [" + notAnHttpStatus + "]. Failed to extract body.", wrapped.getMessage());
    assertEquals(badEntityException, wrapped.getSuppressed()[0]);
}
Also used : StringEntity(org.apache.http.entity.StringEntity) RestStatus(org.elasticsearch.rest.RestStatus) HttpEntity(org.apache.http.HttpEntity) IOException(java.io.IOException) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException) ContentTooLongException(org.apache.http.ContentTooLongException) ParsingException(org.elasticsearch.common.ParsingException) IOException(java.io.IOException) EsRejectedExecutionException(org.elasticsearch.common.util.concurrent.EsRejectedExecutionException) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException)

Aggregations

RestStatus (org.elasticsearch.rest.RestStatus)22 IOException (java.io.IOException)15 ElasticsearchException (org.elasticsearch.ElasticsearchException)11 MainResponse (org.elasticsearch.action.main.MainResponse)11 XContentBuilder (org.elasticsearch.common.xcontent.XContentBuilder)10 HttpHost (org.apache.http.HttpHost)8 HttpResponse (org.apache.http.HttpResponse)8 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)8 Version (org.elasticsearch.Version)8 HttpEntity (org.apache.http.HttpEntity)7 StringEntity (org.apache.http.entity.StringEntity)7 Build (org.elasticsearch.Build)7 ClusterName (org.elasticsearch.cluster.ClusterName)7 Collections (java.util.Collections)6 List (java.util.List)6 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 ActionListener (org.elasticsearch.action.ActionListener)6 ActionRequestValidationException (org.elasticsearch.action.ActionRequestValidationException)6 XContentParser (org.elasticsearch.common.xcontent.XContentParser)6 JsonParseException (com.fasterxml.jackson.core.JsonParseException)5