Search in sources :

Example 11 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 12 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 13 with RestStatus

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

the class SQLExceptions method createSQLActionException.

/**
     * Create a {@link SQLActionException} out of a {@link Throwable}.
     * If concrete {@link ElasticsearchException} is found, first transform it
     * to a {@link CrateException}
     */
public static SQLActionException createSQLActionException(Throwable e) {
    if (e instanceof SQLActionException) {
        return (SQLActionException) e;
    }
    e = esToCrateException(e);
    int errorCode = 5000;
    RestStatus restStatus = RestStatus.INTERNAL_SERVER_ERROR;
    if (e instanceof CrateException) {
        CrateException crateException = (CrateException) e;
        if (e instanceof ValidationException) {
            errorCode = 4000 + crateException.errorCode();
            restStatus = RestStatus.BAD_REQUEST;
        } else if (e instanceof ReadOnlyException) {
            errorCode = 4030 + crateException.errorCode();
            restStatus = RestStatus.FORBIDDEN;
        } else if (e instanceof ResourceUnknownException) {
            errorCode = 4040 + crateException.errorCode();
            restStatus = RestStatus.NOT_FOUND;
        } else if (e instanceof ConflictException) {
            errorCode = 4090 + crateException.errorCode();
            restStatus = RestStatus.CONFLICT;
        } else if (e instanceof UnhandledServerException) {
            errorCode = 5000 + crateException.errorCode();
        }
    } else if (e instanceof ParsingException) {
        errorCode = 4000;
        restStatus = RestStatus.BAD_REQUEST;
    } else if (e instanceof MapperParsingException) {
        errorCode = 4000;
        restStatus = RestStatus.BAD_REQUEST;
    }
    String message = e.getMessage();
    if (message == null) {
        if (e instanceof CrateException && e.getCause() != null) {
            // use cause because it contains a more meaningful error in most cases
            e = e.getCause();
        }
        StackTraceElement[] stackTraceElements = e.getStackTrace();
        if (stackTraceElements.length > 0) {
            message = String.format(Locale.ENGLISH, "%s in %s", e.getClass().getSimpleName(), stackTraceElements[0]);
        } else {
            message = "Error in " + e.getClass().getSimpleName();
        }
    } else {
        message = e.getClass().getSimpleName() + ": " + message;
    }
    return new SQLActionException(message, errorCode, restStatus, e.getStackTrace());
}
Also used : SQLActionException(io.crate.action.sql.SQLActionException) MapperParsingException(org.elasticsearch.index.mapper.MapperParsingException) RestStatus(org.elasticsearch.rest.RestStatus) ParsingException(io.crate.sql.parser.ParsingException) MapperParsingException(org.elasticsearch.index.mapper.MapperParsingException)

Example 14 with RestStatus

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

the class ReplicationOperation method performOnReplica.

private void performOnReplica(final ShardRouting shard, final ReplicaRequest replicaRequest) {
    if (logger.isTraceEnabled()) {
        logger.trace("[{}] sending op [{}] to replica {} for request [{}]", shard.shardId(), opType, shard, replicaRequest);
    }
    totalShards.incrementAndGet();
    pendingActions.incrementAndGet();
    replicasProxy.performOn(shard, replicaRequest, new ActionListener<ReplicaResponse>() {

        @Override
        public void onResponse(ReplicaResponse response) {
            successfulShards.incrementAndGet();
            primary.updateLocalCheckpointForShard(response.allocationId(), response.localCheckpoint());
            decPendingAndFinishIfNeeded();
        }

        @Override
        public void onFailure(Exception replicaException) {
            logger.trace((org.apache.logging.log4j.util.Supplier<?>) () -> new ParameterizedMessage("[{}] failure while performing [{}] on replica {}, request [{}]", shard.shardId(), opType, shard, replicaRequest), replicaException);
            if (TransportActions.isShardNotAvailableException(replicaException)) {
                decPendingAndFinishIfNeeded();
            } else {
                RestStatus restStatus = ExceptionsHelper.status(replicaException);
                shardReplicaFailures.add(new ReplicationResponse.ShardInfo.Failure(shard.shardId(), shard.currentNodeId(), replicaException, restStatus, false));
                String message = String.format(Locale.ROOT, "failed to perform %s on replica %s", opType, shard);
                replicasProxy.failShardIfNeeded(shard, replicaRequest.primaryTerm(), message, replicaException, ReplicationOperation.this::decPendingAndFinishIfNeeded, ReplicationOperation.this::onPrimaryDemoted, throwable -> decPendingAndFinishIfNeeded());
            }
        }
    });
}
Also used : ElasticsearchException(org.elasticsearch.ElasticsearchException) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) ShardId(org.elasticsearch.index.shard.ShardId) Nullable(org.elasticsearch.common.Nullable) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) Supplier(java.util.function.Supplier) TransportActions(org.elasticsearch.action.support.TransportActions) ArrayList(java.util.ArrayList) ClusterState(org.elasticsearch.cluster.ClusterState) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Locale(java.util.Locale) VersionConflictEngineException(org.elasticsearch.index.engine.VersionConflictEngineException) Set(java.util.Set) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) Sets(org.elasticsearch.common.util.set.Sets) UnavailableShardsException(org.elasticsearch.action.UnavailableShardsException) ActiveShardCount(org.elasticsearch.action.support.ActiveShardCount) Objects(java.util.Objects) Consumer(java.util.function.Consumer) ExceptionsHelper(org.elasticsearch.ExceptionsHelper) List(java.util.List) Logger(org.apache.logging.log4j.Logger) IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) StreamInput(org.elasticsearch.common.io.stream.StreamInput) RestStatus(org.elasticsearch.rest.RestStatus) AllocationId(org.elasticsearch.cluster.routing.AllocationId) Collections(java.util.Collections) ActionListener(org.elasticsearch.action.ActionListener) ElasticsearchException(org.elasticsearch.ElasticsearchException) VersionConflictEngineException(org.elasticsearch.index.engine.VersionConflictEngineException) IOException(java.io.IOException) UnavailableShardsException(org.elasticsearch.action.UnavailableShardsException) RestStatus(org.elasticsearch.rest.RestStatus) Supplier(java.util.function.Supplier) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage)

Example 15 with RestStatus

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

the class RestMainAction method convertMainResponse.

static BytesRestResponse convertMainResponse(MainResponse response, RestRequest request, XContentBuilder builder) throws IOException {
    RestStatus status = response.isAvailable() ? RestStatus.OK : RestStatus.SERVICE_UNAVAILABLE;
    // Default to pretty printing, but allow ?pretty=false to disable
    if (request.hasParam("pretty") == false) {
        builder.prettyPrint().lfAtEnd();
    }
    response.toXContent(builder, request);
    return new BytesRestResponse(status, builder);
}
Also used : RestStatus(org.elasticsearch.rest.RestStatus) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse)

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