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();
}
}
});
}
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_"));
}
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=...]");
}
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"));
}
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));
}
}
}
Aggregations