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;
}
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;
}
});
}
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());
}
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());
}
}
});
}
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);
}
Aggregations