getNamedXContents() {
+ return namedXContents;
+ }
+
public Suggesters getSuggesters() {
return new Suggesters(suggesters);
}
@@ -618,8 +625,12 @@ public class SearchModule {
}
private void registerScoreFunction(ScoreFunctionSpec> scoreFunction) {
- scoreFunctionParserRegistry.register(scoreFunction.getParser(), scoreFunction.getName());
- namedWriteables.add(new Entry(ScoreFunctionBuilder.class, scoreFunction.getName().getPreferredName(), scoreFunction.getReader()));
+ namedWriteables.add(new NamedWriteableRegistry.Entry(
+ ScoreFunctionBuilder.class, scoreFunction.getName().getPreferredName(), scoreFunction.getReader()));
+ // TODO remove funky contexts
+ namedXContents.add(new NamedXContentRegistry.Entry(
+ ScoreFunctionBuilder.class, scoreFunction.getName(),
+ (XContentParser p, Object c) -> scoreFunction.getParser().fromXContent((QueryParseContext) c)));
}
private void registerValueFormats() {
@@ -742,7 +753,7 @@ public class SearchModule {
registerQuery(
new QuerySpec<>(SpanMultiTermQueryBuilder.NAME, SpanMultiTermQueryBuilder::new, SpanMultiTermQueryBuilder::fromXContent));
registerQuery(new QuerySpec<>(FunctionScoreQueryBuilder.NAME, FunctionScoreQueryBuilder::new,
- c -> FunctionScoreQueryBuilder.fromXContent(scoreFunctionParserRegistry, c)));
+ FunctionScoreQueryBuilder::fromXContent));
registerQuery(
new QuerySpec<>(SimpleQueryStringBuilder.NAME, SimpleQueryStringBuilder::new, SimpleQueryStringBuilder::fromXContent));
registerQuery(new QuerySpec<>(TypeQueryBuilder.NAME, TypeQueryBuilder::new, TypeQueryBuilder::fromXContent));
diff --git a/core/src/main/java/org/elasticsearch/search/internal/AliasFilter.java b/core/src/main/java/org/elasticsearch/search/internal/AliasFilter.java
index fd684380526..8d55dfbab07 100644
--- a/core/src/main/java/org/elasticsearch/search/internal/AliasFilter.java
+++ b/core/src/main/java/org/elasticsearch/search/internal/AliasFilter.java
@@ -25,6 +25,8 @@ import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
+import org.elasticsearch.common.xcontent.XContentFactory;
+import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryRewriteContext;
@@ -62,7 +64,14 @@ public final class AliasFilter implements Writeable {
if (reparseAliases) {
// we are processing a filter received from a 5.0 node - we need to reparse this on the executing node
final IndexMetaData indexMetaData = context.getIndexSettings().getIndexMetaData();
- return ShardSearchRequest.parseAliasFilter(context::newParseContext, indexMetaData, aliases);
+ /* Being static, parseAliasFilter doesn't have access to whatever guts it needs to parse a query. Instead of passing in a bunch
+ * of dependencies we pass in a function that can perform the parsing. */
+ ShardSearchRequest.FilterParser filterParser = bytes -> {
+ try (XContentParser parser = XContentFactory.xContent(bytes).createParser(context.getXContentRegistry(), bytes)) {
+ return context.newParseContext(parser).parseInnerQueryBuilder();
+ }
+ };
+ return ShardSearchRequest.parseAliasFilter(filterParser, indexMetaData, aliases);
}
return filter;
}
diff --git a/core/src/main/java/org/elasticsearch/search/internal/ShardSearchRequest.java b/core/src/main/java/org/elasticsearch/search/internal/ShardSearchRequest.java
index cc7dc3eb5fb..f021d7730cf 100644
--- a/core/src/main/java/org/elasticsearch/search/internal/ShardSearchRequest.java
+++ b/core/src/main/java/org/elasticsearch/search/internal/ShardSearchRequest.java
@@ -24,12 +24,9 @@ import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.collect.ImmutableOpenMap;
-import org.elasticsearch.common.xcontent.XContentFactory;
-import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
-import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.indices.AliasFilterParsingException;
@@ -91,13 +88,17 @@ public interface ShardSearchRequest {
*/
void rewrite(QueryShardContext context) throws IOException;
+ @FunctionalInterface
+ public interface FilterParser {
+ QueryBuilder parse(byte[] bytes) throws IOException;
+ }
/**
* Returns the filter associated with listed filtering aliases.
*
* The list of filtering aliases should be obtained by calling MetaData.filteringAliases.
* Returns null if no filtering is required.
*/
- static QueryBuilder parseAliasFilter(Function contextFactory,
+ static QueryBuilder parseAliasFilter(FilterParser filterParser,
IndexMetaData metaData, String... aliasNames) {
if (aliasNames == null || aliasNames.length == 0) {
return null;
@@ -109,10 +110,7 @@ public interface ShardSearchRequest {
return null;
}
try {
- byte[] filterSource = alias.filter().uncompressed();
- try (XContentParser parser = XContentFactory.xContent(filterSource).createParser(filterSource)) {
- return contextFactory.apply(parser).parseInnerQueryBuilder();
- }
+ return filterParser.parse(alias.filter().uncompressed());
} catch (IOException ex) {
throw new AliasFilterParsingException(index, alias.getAlias(), "Invalid alias filter", ex);
}
@@ -128,19 +126,19 @@ public interface ShardSearchRequest {
// we need to bench here a bit, to see maybe it makes sense to use OrFilter
BoolQueryBuilder combined = new BoolQueryBuilder();
for (String aliasName : aliasNames) {
- AliasMetaData alias = aliases.get(aliasName);
- if (alias == null) {
- // This shouldn't happen unless alias disappeared after filteringAliases was called.
- throw new InvalidAliasNameException(index, aliasNames[0],
- "Unknown alias name was passed to alias Filter");
- }
- QueryBuilder parsedFilter = parserFunction.apply(alias);
- if (parsedFilter != null) {
- combined.should(parsedFilter);
- } else {
- // The filter might be null only if filter was removed after filteringAliases was called
- return null;
- }
+ AliasMetaData alias = aliases.get(aliasName);
+ if (alias == null) {
+ // This shouldn't happen unless alias disappeared after filteringAliases was called.
+ throw new InvalidAliasNameException(index, aliasNames[0],
+ "Unknown alias name was passed to alias Filter");
+ }
+ QueryBuilder parsedFilter = parserFunction.apply(alias);
+ if (parsedFilter != null) {
+ combined.should(parsedFilter);
+ } else {
+ // The filter might be null only if filter was removed after filteringAliases was called
+ return null;
+ }
}
return combined;
}
diff --git a/core/src/main/java/org/elasticsearch/search/sort/GeoDistanceSortBuilder.java b/core/src/main/java/org/elasticsearch/search/sort/GeoDistanceSortBuilder.java
index 9defd05f471..37e660d2a31 100644
--- a/core/src/main/java/org/elasticsearch/search/sort/GeoDistanceSortBuilder.java
+++ b/core/src/main/java/org/elasticsearch/search/sort/GeoDistanceSortBuilder.java
@@ -74,10 +74,8 @@ public class GeoDistanceSortBuilder extends SortBuilder
private static final ParseField UNIT_FIELD = new ParseField("unit");
private static final ParseField DISTANCE_TYPE_FIELD = new ParseField("distance_type");
private static final ParseField VALIDATION_METHOD_FIELD = new ParseField("validation_method");
- private static final ParseField IGNORE_MALFORMED_FIELD = new ParseField("ignore_malformed")
- .withAllDeprecated("use validation_method instead");
- private static final ParseField COERCE_FIELD = new ParseField("coerce", "normalize")
- .withAllDeprecated("use validation_method instead");
+ private static final ParseField IGNORE_MALFORMED_FIELD = new ParseField("ignore_malformed").withAllDeprecated("validation_method");
+ private static final ParseField COERCE_FIELD = new ParseField("coerce", "normalize").withAllDeprecated("validation_method");
private static final ParseField SORTMODE_FIELD = new ParseField("mode", "sort_mode");
private final String fieldName;
diff --git a/core/src/main/java/org/elasticsearch/search/suggest/SuggestionBuilder.java b/core/src/main/java/org/elasticsearch/search/suggest/SuggestionBuilder.java
index ca1d7a2306f..0028767c36f 100644
--- a/core/src/main/java/org/elasticsearch/search/suggest/SuggestionBuilder.java
+++ b/core/src/main/java/org/elasticsearch/search/suggest/SuggestionBuilder.java
@@ -21,7 +21,6 @@ package org.elasticsearch.search.suggest;
import org.apache.lucene.analysis.Analyzer;
import org.elasticsearch.ElasticsearchParseException;
-import org.elasticsearch.action.support.ToXContentToBytes;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.ParsingException;
@@ -29,6 +28,7 @@ import org.elasticsearch.common.io.stream.NamedWriteable;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.lucene.BytesRefs;
+import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.mapper.MappedFieldType;
@@ -43,7 +43,7 @@ import java.util.Objects;
/**
* Base class for the different suggestion implementations.
*/
-public abstract class SuggestionBuilder> extends ToXContentToBytes implements NamedWriteable {
+public abstract class SuggestionBuilder> implements NamedWriteable, ToXContent {
protected final String field;
protected String text;
diff --git a/core/src/main/java/org/elasticsearch/search/suggest/completion/CompletionSuggestionBuilder.java b/core/src/main/java/org/elasticsearch/search/suggest/completion/CompletionSuggestionBuilder.java
index 09382d9aaff..0fd3726384f 100644
--- a/core/src/main/java/org/elasticsearch/search/suggest/completion/CompletionSuggestionBuilder.java
+++ b/core/src/main/java/org/elasticsearch/search/suggest/completion/CompletionSuggestionBuilder.java
@@ -42,7 +42,6 @@ import org.elasticsearch.search.suggest.completion.context.ContextMapping;
import org.elasticsearch.search.suggest.completion.context.ContextMappings;
import java.io.IOException;
-import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -233,10 +232,7 @@ public class CompletionSuggestionBuilder extends SuggestionBuilder {
QueryShardContext shardContext = suggestion.getShardContext();
final ExecutableScript executable = collateScript.apply(vars);
final BytesReference querySource = (BytesReference) executable.run();
- try (XContentParser parser = XContentFactory.xContent(querySource).createParser(querySource)) {
+ try (XContentParser parser = XContentFactory.xContent(querySource).createParser(shardContext.getXContentRegistry(),
+ querySource)) {
QueryBuilder innerQueryBuilder = shardContext.newParseContext(parser).parseInnerQueryBuilder();
final ParsedQuery parsedQuery = shardContext.toQuery(innerQueryBuilder);
collateMatch = Lucene.exists(searcher, parsedQuery.query());
diff --git a/core/src/test/java/org/elasticsearch/ElasticsearchExceptionTests.java b/core/src/test/java/org/elasticsearch/ElasticsearchExceptionTests.java
index f172945d84f..c5d9d31c1eb 100644
--- a/core/src/test/java/org/elasticsearch/ElasticsearchExceptionTests.java
+++ b/core/src/test/java/org/elasticsearch/ElasticsearchExceptionTests.java
@@ -106,7 +106,7 @@ public class ElasticsearchExceptionTests extends ESTestCase {
assertExceptionAsJson(e, false, equalTo(expectedJson));
ElasticsearchException parsed;
- try (XContentParser parser = XContentType.JSON.xContent().createParser(expectedJson)) {
+ try (XContentParser parser = createParser(XContentType.JSON.xContent(), expectedJson)) {
assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
parsed = ElasticsearchException.fromXContent(parser);
assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken());
@@ -142,7 +142,7 @@ public class ElasticsearchExceptionTests extends ESTestCase {
.endObject();
ElasticsearchException parsed;
- try (XContentParser parser = xContent.createParser(builder.bytes())) {
+ 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());
@@ -163,7 +163,7 @@ public class ElasticsearchExceptionTests extends ESTestCase {
XContentBuilder builder = XContentBuilder.builder(xContent).startObject().value(e).endObject();
ElasticsearchException parsed;
- try (XContentParser parser = xContent.createParser(builder.bytes())) {
+ try (XContentParser parser = createParser(builder)) {
assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
parsed = ElasticsearchException.fromXContent(parser);
assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken());
@@ -206,7 +206,7 @@ public class ElasticsearchExceptionTests extends ESTestCase {
XContentBuilder builder = XContentBuilder.builder(xContent).startObject().value(foo).endObject();
ElasticsearchException parsed;
- try (XContentParser parser = xContent.createParser(builder.bytes())) {
+ try (XContentParser parser = createParser(builder)) {
assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
parsed = ElasticsearchException.fromXContent(parser);
assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken());
diff --git a/core/src/test/java/org/elasticsearch/ExceptionSerializationTests.java b/core/src/test/java/org/elasticsearch/ExceptionSerializationTests.java
index 202224872b4..786426822dc 100644
--- a/core/src/test/java/org/elasticsearch/ExceptionSerializationTests.java
+++ b/core/src/test/java/org/elasticsearch/ExceptionSerializationTests.java
@@ -779,6 +779,7 @@ public class ExceptionSerializationTests extends ESTestCase {
ids.put(145, org.elasticsearch.ElasticsearchStatusException.class);
ids.put(146, org.elasticsearch.tasks.TaskCancelledException.class);
ids.put(147, org.elasticsearch.env.ShardLockObtainFailedException.class);
+ ids.put(148, org.elasticsearch.common.xcontent.NamedXContentRegistry.UnknownNamedObjectException.class);
Map, Integer> reverse = new HashMap<>();
for (Map.Entry> entry : ids.entrySet()) {
diff --git a/core/src/test/java/org/elasticsearch/action/DocWriteResponseTests.java b/core/src/test/java/org/elasticsearch/action/DocWriteResponseTests.java
index 017ba128d50..0f6332006d9 100644
--- a/core/src/test/java/org/elasticsearch/action/DocWriteResponseTests.java
+++ b/core/src/test/java/org/elasticsearch/action/DocWriteResponseTests.java
@@ -30,13 +30,14 @@ import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.test.ESTestCase;
import java.io.IOException;
+import java.net.URISyntaxException;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.not;
public class DocWriteResponseTests extends ESTestCase {
- public void testGetLocation() {
+ public void testGetLocation() throws URISyntaxException {
DocWriteResponse response =
new DocWriteResponse(
new ShardId("index", "uuid", 0),
@@ -51,6 +52,35 @@ public class DocWriteResponseTests extends ESTestCase {
assertEquals("/index/type/id?routing=test_routing", response.getLocation("test_routing"));
}
+ public void testGetLocationNonAscii() throws URISyntaxException {
+ DocWriteResponse response =
+ new DocWriteResponse(
+ new ShardId("index", "uuid", 0),
+ "type",
+ "❤",
+ SequenceNumbersService.UNASSIGNED_SEQ_NO,
+ 0,
+ Result.CREATED) {
+ };
+ assertEquals("/index/type/%E2%9D%A4", response.getLocation(null));
+ assertEquals("/index/type/%E2%9D%A4?routing=%C3%A4", response.getLocation("%C3%A4"));
+ }
+
+ public void testInvalidGetLocation() {
+ String invalidPath = "!^*$(@!^!#@";
+ DocWriteResponse invalid =
+ new DocWriteResponse(
+ new ShardId("index", "uuid", 0),
+ "type",
+ invalidPath,
+ SequenceNumbersService.UNASSIGNED_SEQ_NO,
+ 0,
+ Result.CREATED) {
+ };
+ Throwable exception = expectThrows(URISyntaxException.class, () -> invalid.getLocation(null));
+ assertTrue(exception.getMessage().contains(invalidPath));
+ }
+
/**
* 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....
diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplainIT.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplainIT.java
index 33f683b458c..f6ba7d9f022 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplainIT.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplainIT.java
@@ -135,13 +135,15 @@ public final class ClusterAllocationExplainIT extends ESIntegTestCase {
assertEquals(d.type(), Decision.Type.NO);
if (noAttrNode.equals(nodeName)) {
- assertThat(d.toString(), containsString("node does not match [index.routing.allocation.include] filters [foo:\"bar\"]"));
+ assertThat(d.toString(), containsString("node does not match index setting [index.routing.allocation.include] " +
+ "filters [foo:\"bar\"]"));
assertNull(storeStatus);
assertEquals("the shard cannot be assigned because one or more allocation decider returns a 'NO' decision",
explanation.getFinalExplanation());
assertEquals(ClusterAllocationExplanation.FinalDecision.NO, finalDecision);
} else if (barAttrNode.equals(nodeName)) {
- assertThat(d.toString(), containsString("node does not match [index.routing.allocation.include] filters [foo:\"bar\"]"));
+ assertThat(d.toString(), containsString("node does not match index setting [index.routing.allocation.include] " +
+ "filters [foo:\"bar\"]"));
barAttrWeight = weight;
assertNull(storeStatus);
assertEquals("the shard cannot be assigned because one or more allocation decider returns a 'NO' decision",
diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteRequestTests.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteRequestTests.java
index e1205840976..bc52bdc22be 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteRequestTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteRequestTests.java
@@ -179,7 +179,7 @@ public class ClusterRerouteRequestTests extends ESTestCase {
return RestClusterRerouteAction.createRequest(restRequest, allocationCommandRegistry, ParseFieldMatcher.STRICT);
}
- private static RestRequest toRestRequest(ClusterRerouteRequest original) throws IOException {
+ private RestRequest toRestRequest(ClusterRerouteRequest original) throws IOException {
Map params = new HashMap<>();
XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values()));
boolean hasBody = false;
@@ -209,7 +209,7 @@ public class ClusterRerouteRequestTests extends ESTestCase {
}
builder.endObject();
- FakeRestRequest.Builder requestBuilder = new FakeRestRequest.Builder();
+ FakeRestRequest.Builder requestBuilder = new FakeRestRequest.Builder(xContentRegistry());
requestBuilder.withParams(params);
if (hasBody) {
requestBuilder.withContent(builder.bytes());
diff --git a/core/src/test/java/org/elasticsearch/action/admin/indices/rollover/RolloverRequestTests.java b/core/src/test/java/org/elasticsearch/action/admin/indices/rollover/RolloverRequestTests.java
index 999d16fdcb5..17321daf9af 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/indices/rollover/RolloverRequestTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/indices/rollover/RolloverRequestTests.java
@@ -23,7 +23,6 @@ import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
-import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.test.ESTestCase;
import java.util.Set;
@@ -36,12 +35,12 @@ public class RolloverRequestTests extends ESTestCase {
final RolloverRequest request = new RolloverRequest(randomAsciiOfLength(10), randomAsciiOfLength(10));
final XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
- .startObject("conditions")
- .field("max_age", "10d")
- .field("max_docs", 100)
- .endObject()
+ .startObject("conditions")
+ .field("max_age", "10d")
+ .field("max_docs", 100)
+ .endObject()
.endObject();
- RolloverRequest.PARSER.parse(XContentHelper.createParser(builder.bytes()), request, () -> ParseFieldMatcher.EMPTY);
+ RolloverRequest.PARSER.parse(createParser(builder), request, () -> ParseFieldMatcher.EMPTY);
Set conditions = request.getConditions();
assertThat(conditions.size(), equalTo(2));
for (Condition condition : conditions) {
@@ -61,28 +60,28 @@ public class RolloverRequestTests extends ESTestCase {
final RolloverRequest request = new RolloverRequest(randomAsciiOfLength(10), randomAsciiOfLength(10));
final XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
- .startObject("conditions")
- .field("max_age", "10d")
- .field("max_docs", 100)
- .endObject()
- .startObject("mappings")
- .startObject("type1")
- .startObject("properties")
- .startObject("field1")
- .field("type", "string")
- .field("index", "not_analyzed")
+ .startObject("conditions")
+ .field("max_age", "10d")
+ .field("max_docs", 100)
+ .endObject()
+ .startObject("mappings")
+ .startObject("type1")
+ .startObject("properties")
+ .startObject("field1")
+ .field("type", "string")
+ .field("index", "not_analyzed")
+ .endObject()
.endObject()
.endObject()
.endObject()
- .endObject()
- .startObject("settings")
- .field("number_of_shards", 10)
- .endObject()
- .startObject("aliases")
- .startObject("alias1").endObject()
- .endObject()
+ .startObject("settings")
+ .field("number_of_shards", 10)
+ .endObject()
+ .startObject("aliases")
+ .startObject("alias1").endObject()
+ .endObject()
.endObject();
- RolloverRequest.PARSER.parse(XContentHelper.createParser(builder.bytes()), request, () -> ParseFieldMatcher.EMPTY);
+ RolloverRequest.PARSER.parse(createParser(builder), request, () -> ParseFieldMatcher.EMPTY);
Set conditions = request.getConditions();
assertThat(conditions.size(), equalTo(2));
assertThat(request.getCreateIndexRequest().mappings().size(), equalTo(1));
diff --git a/core/src/test/java/org/elasticsearch/action/admin/indices/template/BWCTemplateTests.java b/core/src/test/java/org/elasticsearch/action/admin/indices/template/BWCTemplateTests.java
index 69c6731aa15..7ea103313fe 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/indices/template/BWCTemplateTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/indices/template/BWCTemplateTests.java
@@ -42,12 +42,14 @@ public class BWCTemplateTests extends ESSingleNodeTestCase {
client().prepareIndex("packetbeat-foo", "doc", "1").setSource("message", "foo").get();
client().prepareIndex("filebeat-foo", "doc", "1").setSource("message", "foo").get();
client().prepareIndex("winlogbeat-foo", "doc", "1").setSource("message", "foo").get();
+ assertWarnings("Deprecated field [template] used, replaced by [index_patterns]");
}
public void testLogstashTemplatesBWC() throws Exception {
String ls5x = copyToStringFromClasspath("/org/elasticsearch/action/admin/indices/template/logstash-5.0.template.json");
client().admin().indices().preparePutTemplate("logstash-5x").setSource(ls5x).get();
client().prepareIndex("logstash-foo", "doc", "1").setSource("message", "foo").get();
+ assertWarnings("Deprecated field [template] used, replaced by [index_patterns]");
}
}
diff --git a/core/src/test/java/org/elasticsearch/action/admin/indices/template/put/MetaDataIndexTemplateServiceTests.java b/core/src/test/java/org/elasticsearch/action/admin/indices/template/put/MetaDataIndexTemplateServiceTests.java
index 9779ce83a65..48598ecb2ec 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/indices/template/put/MetaDataIndexTemplateServiceTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/indices/template/put/MetaDataIndexTemplateServiceTests.java
@@ -28,6 +28,7 @@ import org.elasticsearch.cluster.metadata.MetaDataIndexTemplateService.PutReques
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.settings.IndexScopedSettings;
import org.elasticsearch.common.settings.Settings;
+import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.mapper.MapperParsingException;
import org.elasticsearch.indices.IndicesService;
@@ -58,7 +59,7 @@ public class MetaDataIndexTemplateServiceTests extends ESSingleNodeTestCase {
map.put("index.shard.check_on_startup", "blargh");
request.settings(Settings.builder().put(map).build());
- List throwables = putTemplate(request);
+ List throwables = putTemplate(xContentRegistry(), request);
assertEquals(throwables.size(), 1);
assertThat(throwables.get(0), instanceOf(InvalidIndexTemplateException.class));
assertThat(throwables.get(0).getMessage(),
@@ -76,7 +77,7 @@ public class MetaDataIndexTemplateServiceTests extends ESSingleNodeTestCase {
map.put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, "0");
request.settings(Settings.builder().put(map).build());
- List throwables = putTemplate(request);
+ List throwables = putTemplate(xContentRegistry(), request);
assertEquals(throwables.size(), 1);
assertThat(throwables.get(0), instanceOf(InvalidIndexTemplateException.class));
assertThat(throwables.get(0).getMessage(), containsString("name must not contain a space"));
@@ -90,7 +91,7 @@ public class MetaDataIndexTemplateServiceTests extends ESSingleNodeTestCase {
request.patterns(Arrays.asList("foo", "foobar"));
request.aliases(Collections.singleton(new Alias("foobar")));
- List errors = putTemplate(request);
+ List errors = putTemplate(xContentRegistry(), request);
assertThat(errors.size(), equalTo(1));
assertThat(errors.get(0), instanceOf(IllegalArgumentException.class));
assertThat(errors.get(0).getMessage(), equalTo("Alias [foobar] cannot be the same as any pattern in [foo, foobar]"));
@@ -158,17 +159,17 @@ public class MetaDataIndexTemplateServiceTests extends ESSingleNodeTestCase {
}
- private static List putTemplate(PutRequest request) {
+ private static List putTemplate(NamedXContentRegistry xContentRegistry, PutRequest request) {
MetaDataCreateIndexService createIndexService = new MetaDataCreateIndexService(
Settings.EMPTY,
null,
null,
null,
null,
- null, null, null);
+ null, null, null, xContentRegistry);
MetaDataIndexTemplateService service = new MetaDataIndexTemplateService(Settings.EMPTY, null, createIndexService,
new AliasValidator(Settings.EMPTY), null,
- new IndexScopedSettings(Settings.EMPTY, IndexScopedSettings.BUILT_IN_INDEX_SETTINGS));
+ new IndexScopedSettings(Settings.EMPTY, IndexScopedSettings.BUILT_IN_INDEX_SETTINGS), xContentRegistry);
final List throwables = new ArrayList<>();
service.putTemplate(request, new MetaDataIndexTemplateService.PutListener() {
@@ -196,10 +197,11 @@ public class MetaDataIndexTemplateServiceTests extends ESSingleNodeTestCase {
null,
null,
null,
- null);
+ null,
+ xContentRegistry());
MetaDataIndexTemplateService service = new MetaDataIndexTemplateService(
Settings.EMPTY, clusterService, createIndexService, new AliasValidator(Settings.EMPTY), indicesService,
- new IndexScopedSettings(Settings.EMPTY, IndexScopedSettings.BUILT_IN_INDEX_SETTINGS));
+ new IndexScopedSettings(Settings.EMPTY, IndexScopedSettings.BUILT_IN_INDEX_SETTINGS), xContentRegistry());
final List throwables = new ArrayList<>();
final CountDownLatch latch = new CountDownLatch(1);
diff --git a/core/src/test/java/org/elasticsearch/action/get/GetResponseTests.java b/core/src/test/java/org/elasticsearch/action/get/GetResponseTests.java
new file mode 100644
index 00000000000..0fb347dd3d9
--- /dev/null
+++ b/core/src/test/java/org/elasticsearch/action/get/GetResponseTests.java
@@ -0,0 +1,92 @@
+/*
+ * Licensed to Elasticsearch under one or more contributor
+ * license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright
+ * ownership. Elasticsearch licenses this file to you under
+ * the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.elasticsearch.action.get;
+
+import org.elasticsearch.common.Strings;
+import org.elasticsearch.common.bytes.BytesArray;
+import org.elasticsearch.common.bytes.BytesReference;
+import org.elasticsearch.common.collect.Tuple;
+import org.elasticsearch.common.xcontent.XContentParser;
+import org.elasticsearch.common.xcontent.XContentType;
+import org.elasticsearch.index.get.GetField;
+import org.elasticsearch.index.get.GetResult;
+import org.elasticsearch.test.ESTestCase;
+
+import java.io.IOException;
+import java.util.Collections;
+
+import static org.elasticsearch.common.xcontent.XContentHelper.toXContent;
+import static org.elasticsearch.index.get.GetResultTests.copyGetResult;
+import static org.elasticsearch.index.get.GetResultTests.mutateGetResult;
+import static org.elasticsearch.index.get.GetResultTests.randomGetResult;
+import static org.elasticsearch.test.EqualsHashCodeTestUtils.checkEqualsAndHashCode;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertToXContentEquivalent;
+
+public class GetResponseTests extends ESTestCase {
+
+ public void testToAndFromXContent() throws Exception {
+ XContentType xContentType = randomFrom(XContentType.values());
+ Tuple tuple = randomGetResult(xContentType);
+ GetResponse getResponse = new GetResponse(tuple.v1());
+ GetResponse expectedGetResponse = new GetResponse(tuple.v2());
+ BytesReference originalBytes = toXContent(getResponse, xContentType, false);
+ //test that we can parse what we print out
+ GetResponse parsedGetResponse;
+ try (XContentParser parser = createParser(xContentType.xContent(), originalBytes)) {
+ parsedGetResponse = GetResponse.fromXContent(parser);
+ assertNull(parser.nextToken());
+ }
+ assertEquals(expectedGetResponse, parsedGetResponse);
+ //print the parsed object out and test that the output is the same as the original output
+ BytesReference finalBytes = toXContent(parsedGetResponse, xContentType, false);
+ assertToXContentEquivalent(originalBytes, finalBytes, xContentType);
+ //check that the source stays unchanged, no shuffling of keys nor anything like that
+ assertEquals(expectedGetResponse.getSourceAsString(), parsedGetResponse.getSourceAsString());
+
+ }
+
+ public void testToXContent() throws IOException {
+ {
+ GetResponse getResponse = new GetResponse(new GetResult("index", "type", "id", 1, true, new BytesArray("{ \"field1\" : " +
+ "\"value1\", \"field2\":\"value2\"}"), Collections.singletonMap("field1", new GetField("field1",
+ Collections.singletonList("value1")))));
+ String output = Strings.toString(getResponse, false);
+ assertEquals("{\"_index\":\"index\",\"_type\":\"type\",\"_id\":\"id\",\"_version\":1,\"found\":true,\"_source\":{ \"field1\" " +
+ ": \"value1\", \"field2\":\"value2\"},\"fields\":{\"field1\":[\"value1\"]}}", output);
+ }
+ {
+ GetResponse getResponse = new GetResponse(new GetResult("index", "type", "id", 1, false, null, null));
+ String output = Strings.toString(getResponse, false);
+ assertEquals("{\"_index\":\"index\",\"_type\":\"type\",\"_id\":\"id\",\"found\":false}", output);
+ }
+ }
+
+ public void testEqualsAndHashcode() {
+ checkEqualsAndHashCode(new GetResponse(randomGetResult(XContentType.JSON).v1()), GetResponseTests::copyGetResponse,
+ GetResponseTests::mutateGetResponse);
+ }
+ private static GetResponse copyGetResponse(GetResponse getResponse) {
+ return new GetResponse(copyGetResult(getResponse.getResult));
+ }
+
+ private static GetResponse mutateGetResponse(GetResponse getResponse) {
+ return new GetResponse(mutateGetResult(getResponse.getResult));
+ }
+}
diff --git a/core/src/test/java/org/elasticsearch/action/search/MultiSearchRequestTests.java b/core/src/test/java/org/elasticsearch/action/search/MultiSearchRequestTests.java
index d5b17861e0f..e42c56046e6 100644
--- a/core/src/test/java/org/elasticsearch/action/search/MultiSearchRequestTests.java
+++ b/core/src/test/java/org/elasticsearch/action/search/MultiSearchRequestTests.java
@@ -167,7 +167,7 @@ public class MultiSearchRequestTests extends ESTestCase {
private MultiSearchRequest parseMultiSearchRequest(String sample) throws IOException {
byte[] data = StreamsUtils.copyToBytesFromClasspath(sample);
- RestRequest restRequest = new FakeRestRequest.Builder().withContent(new BytesArray(data)).build();
+ RestRequest restRequest = new FakeRestRequest.Builder(xContentRegistry()).withContent(new BytesArray(data)).build();
return RestMultiSearchAction.parseRequest(restRequest, true, parsers(), ParseFieldMatcher.EMPTY);
}
diff --git a/core/src/test/java/org/elasticsearch/action/support/replication/ReplicationResponseTests.java b/core/src/test/java/org/elasticsearch/action/support/replication/ReplicationResponseTests.java
index 7d82b744133..ca8f0a4c6b2 100644
--- a/core/src/test/java/org/elasticsearch/action/support/replication/ReplicationResponseTests.java
+++ b/core/src/test/java/org/elasticsearch/action/support/replication/ReplicationResponseTests.java
@@ -21,9 +21,8 @@ package org.elasticsearch.action.support.replication;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.RoutingMissingException;
-import org.elasticsearch.common.xcontent.ToXContent;
-import org.elasticsearch.common.xcontent.XContent;
-import org.elasticsearch.common.xcontent.XContentBuilder;
+import org.elasticsearch.common.bytes.BytesReference;
+import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.Index;
@@ -117,97 +116,175 @@ public class ReplicationResponseTests extends ESTestCase {
}
public void testShardInfoToXContent() throws IOException {
- ReplicationResponse.ShardInfo shardInfo = new ReplicationResponse.ShardInfo(5, 3);
+ final XContentType xContentType = randomFrom(XContentType.values());
- final XContent xContent = randomFrom(XContentType.values()).xContent();
- try (XContentBuilder builder = XContentBuilder.builder(xContent)) {
- builder.startObject();
- shardInfo.toXContent(builder, ToXContent.EMPTY_PARAMS);
- builder.endObject();
+ final ReplicationResponse.ShardInfo shardInfo = new ReplicationResponse.ShardInfo(5, 3);
+ final BytesReference shardInfoBytes = XContentHelper.toXContent(shardInfo, xContentType, true);
- // Expected JSON is {"_shards":{"total":5,"successful":3,"failed":0}}
- try (XContentParser parser = xContent.createParser(builder.bytes())) {
- assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
- assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
- assertEquals("_shards", parser.currentName());
- assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
- assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
- assertEquals("total", parser.currentName());
- assertEquals(XContentParser.Token.VALUE_NUMBER, parser.nextToken());
- assertEquals(shardInfo.getTotal(), parser.intValue());
- assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
- assertEquals("successful", parser.currentName());
- assertEquals(XContentParser.Token.VALUE_NUMBER, parser.nextToken());
- assertEquals(shardInfo.getSuccessful(), parser.intValue());
- assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
- assertEquals("failed", parser.currentName());
- assertEquals(XContentParser.Token.VALUE_NUMBER, parser.nextToken());
- assertEquals(shardInfo.getFailed(), parser.intValue());
- assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
- assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
- assertNull(parser.nextToken());
- }
+ // Expected JSON is {"_shards":{"total":5,"successful":3,"failed":0}}
+ try (XContentParser parser = createParser(xContentType.xContent(), shardInfoBytes)) {
+ assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
+ assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
+ assertEquals("_shards", parser.currentName());
+ assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
+ assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
+ assertEquals("total", parser.currentName());
+ assertEquals(XContentParser.Token.VALUE_NUMBER, parser.nextToken());
+ assertEquals(shardInfo.getTotal(), parser.intValue());
+ assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
+ assertEquals("successful", parser.currentName());
+ assertEquals(XContentParser.Token.VALUE_NUMBER, parser.nextToken());
+ assertEquals(shardInfo.getSuccessful(), parser.intValue());
+ assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
+ assertEquals("failed", parser.currentName());
+ assertEquals(XContentParser.Token.VALUE_NUMBER, parser.nextToken());
+ assertEquals(shardInfo.getFailed(), parser.intValue());
+ assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
+ assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
+ assertNull(parser.nextToken());
}
}
- public void testRandomShardInfoToXContent() throws IOException {
+ public void testShardInfoToAndFromXContent() throws IOException {
+ final XContentType xContentType = randomFrom(XContentType.values());
+
+ final ReplicationResponse.ShardInfo shardInfo = new ReplicationResponse.ShardInfo(randomIntBetween(1, 5), randomIntBetween(1, 5));
+ final BytesReference shardInfoBytes = XContentHelper.toXContent(shardInfo, xContentType, true);
+
+ ReplicationResponse.ShardInfo parsedShardInfo;
+ try (XContentParser parser = createParser(xContentType.xContent(), shardInfoBytes)) {
+ // Move to the start object that was manually added when building the object
+ assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
+ parsedShardInfo = ReplicationResponse.ShardInfo.fromXContent(parser);
+ assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
+ assertNull(parser.nextToken());
+ }
+ // We can use assertEquals because the shardInfo doesn't have a failure (and exceptions)
+ assertEquals(shardInfo, parsedShardInfo);
+
+ BytesReference parsedShardInfoBytes = XContentHelper.toXContent(parsedShardInfo, xContentType, true);
+ assertEquals(shardInfoBytes, parsedShardInfoBytes);
+ }
+
+ public void testShardInfoWithFailureToXContent() throws IOException {
+ final XContentType xContentType = randomFrom(XContentType.values());
+
final ReplicationResponse.ShardInfo shardInfo = randomShardInfo();
+ final BytesReference shardInfoBytes = XContentHelper.toXContent(shardInfo, xContentType, true);
- final XContent xContent = randomFrom(XContentType.values()).xContent();
- try (XContentBuilder builder = XContentBuilder.builder(xContent)) {
- builder.startObject();
- shardInfo.toXContent(builder, ToXContent.EMPTY_PARAMS);
- builder.endObject();
+ try (XContentParser parser = createParser(xContentType.xContent(), shardInfoBytes)) {
+ assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
+ assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
+ assertEquals("_shards", parser.currentName());
+ assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
+ assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
+ assertEquals("total", parser.currentName());
+ assertEquals(XContentParser.Token.VALUE_NUMBER, parser.nextToken());
+ assertEquals(shardInfo.getTotal(), parser.intValue());
+ assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
+ assertEquals("successful", parser.currentName());
+ assertEquals(XContentParser.Token.VALUE_NUMBER, parser.nextToken());
+ assertEquals(shardInfo.getSuccessful(), parser.intValue());
+ assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
+ assertEquals("failed", parser.currentName());
+ assertEquals(XContentParser.Token.VALUE_NUMBER, parser.nextToken());
+ assertEquals(shardInfo.getFailed(), parser.intValue());
- try (XContentParser parser = xContent.createParser(builder.bytes())) {
- assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
+ if (shardInfo.getFailures() != null && shardInfo.getFailures().length > 0) {
assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
- assertEquals("_shards", parser.currentName());
- assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
- assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
- assertEquals("total", parser.currentName());
- assertEquals(XContentParser.Token.VALUE_NUMBER, parser.nextToken());
- assertEquals(shardInfo.getTotal(), parser.intValue());
- assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
- assertEquals("successful", parser.currentName());
- assertEquals(XContentParser.Token.VALUE_NUMBER, parser.nextToken());
- assertEquals(shardInfo.getSuccessful(), parser.intValue());
- assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
- assertEquals("failed", parser.currentName());
- assertEquals(XContentParser.Token.VALUE_NUMBER, parser.nextToken());
- assertEquals(shardInfo.getFailed(), parser.intValue());
+ assertEquals("failures", parser.currentName());
+ assertEquals(XContentParser.Token.START_ARRAY, parser.nextToken());
- if (shardInfo.getFailures() != null && shardInfo.getFailures().length > 0) {
- assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
- assertEquals("failures", parser.currentName());
- assertEquals(XContentParser.Token.START_ARRAY, parser.nextToken());
-
- for (int i = 0; i < shardInfo.getFailures().length; i++) {
- assertFailure(parser, shardInfo.getFailures()[i]);
- }
- assertEquals(XContentParser.Token.END_ARRAY, parser.nextToken());
+ for (int i = 0; i < shardInfo.getFailures().length; i++) {
+ assertFailure(parser, shardInfo.getFailures()[i]);
}
-
- assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
- assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
- assertNull(parser.nextToken());
+ assertEquals(XContentParser.Token.END_ARRAY, parser.nextToken());
}
+
+ assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
+ assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
+ assertNull(parser.nextToken());
+ }
+ }
+
+ public void testRandomShardInfoFromXContent() throws IOException {
+ final XContentType xContentType = randomFrom(XContentType.values());
+
+ final ReplicationResponse.ShardInfo shardInfo = randomShardInfo();
+ final BytesReference shardInfoBytes = XContentHelper.toXContent(shardInfo, xContentType, true);
+
+ ReplicationResponse.ShardInfo parsedShardInfo;
+ try (XContentParser parser = createParser(xContentType.xContent(), shardInfoBytes)) {
+ // Move to the start object that was manually added when building the object
+ assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
+ parsedShardInfo = ReplicationResponse.ShardInfo.fromXContent(parser);
+ assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
+ assertNull(parser.nextToken());
+ }
+
+ // We can't use assertEquals to compare the original ShardInfo with the parsed ShardInfo
+ // because it may include random failures with exceptions, and exception types are not
+ // preserved during ToXContent->FromXContent process.
+ assertNotNull(parsedShardInfo);
+ assertEquals(shardInfo.getTotal(), parsedShardInfo.getTotal());
+ assertEquals(shardInfo.getSuccessful(), parsedShardInfo.getSuccessful());
+ assertEquals(shardInfo.getFailed(), parsedShardInfo.getFailed());
+ assertEquals(shardInfo.getFailures().length, parsedShardInfo.getFailures().length);
+
+ for (int i = 0; i < shardInfo.getFailures().length; i++) {
+ ReplicationResponse.ShardInfo.Failure parsedFailure = parsedShardInfo.getFailures()[i];
+ ReplicationResponse.ShardInfo.Failure failure = shardInfo.getFailures()[i];
+
+ assertEquals(failure.index(), parsedFailure.index());
+ assertEquals(failure.shardId(), parsedFailure.shardId());
+ assertEquals(failure.nodeId(), parsedFailure.nodeId());
+ assertEquals(failure.status(), parsedFailure.status());
+ assertEquals(failure.primary(), parsedFailure.primary());
+
+ Throwable cause = failure.getCause();
+ String expectedMessage = "Elasticsearch exception [type=" + ElasticsearchException.getExceptionName(cause)
+ + ", reason=" + cause.getMessage() + "]";
+ assertEquals(expectedMessage, parsedFailure.getCause().getMessage());
}
}
public void testRandomFailureToXContent() throws IOException {
- ReplicationResponse.ShardInfo.Failure shardInfoFailure = randomFailure();
+ final XContentType xContentType = randomFrom(XContentType.values());
- final XContent xContent = randomFrom(XContentType.values()).xContent();
- try (XContentBuilder builder = XContentBuilder.builder(xContent)) {
- shardInfoFailure.toXContent(builder, ToXContent.EMPTY_PARAMS);
+ final ReplicationResponse.ShardInfo.Failure shardInfoFailure = randomFailure();
+ final BytesReference shardInfoBytes = XContentHelper.toXContent(shardInfoFailure, xContentType, false);
- try (XContentParser parser = xContent.createParser(builder.bytes())) {
- assertFailure(parser, shardInfoFailure);
- }
+ try (XContentParser parser = createParser(xContentType.xContent(), shardInfoBytes)) {
+ assertFailure(parser, shardInfoFailure);
}
}
+ public void testRandomFailureToAndFromXContent() throws IOException {
+ final XContentType xContentType = randomFrom(XContentType.values());
+
+ final ReplicationResponse.ShardInfo.Failure shardInfoFailure = randomFailure();
+ final BytesReference shardInfoBytes = XContentHelper.toXContent(shardInfoFailure, xContentType, false);
+
+ ReplicationResponse.ShardInfo.Failure parsedFailure;
+ try (XContentParser parser = createParser(xContentType.xContent(), shardInfoBytes)) {
+ // Move to the first start object
+ assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
+ parsedFailure = ReplicationResponse.ShardInfo.Failure.fromXContent(parser);
+ assertNull(parser.nextToken());
+ }
+
+ assertEquals(shardInfoFailure.index(), parsedFailure.index());
+ assertEquals(shardInfoFailure.shardId(), parsedFailure.shardId());
+ assertEquals(shardInfoFailure.nodeId(), parsedFailure.nodeId());
+ assertEquals(shardInfoFailure.status(), parsedFailure.status());
+ assertEquals(shardInfoFailure.primary(), parsedFailure.primary());
+
+ Throwable cause = shardInfoFailure.getCause();
+ String expectedMessage = "Elasticsearch exception [type=" + ElasticsearchException.getExceptionName(cause)
+ + ", reason=" + cause.getMessage() + "]";
+ assertEquals(expectedMessage, parsedFailure.getCause().getMessage());
+ }
+
private static void assertFailure(XContentParser parser, ReplicationResponse.ShardInfo.Failure failure) throws IOException {
assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
diff --git a/core/src/test/java/org/elasticsearch/action/support/replication/TransportReplicationActionTests.java b/core/src/test/java/org/elasticsearch/action/support/replication/TransportReplicationActionTests.java
index f05b931e782..0e01c131aa3 100644
--- a/core/src/test/java/org/elasticsearch/action/support/replication/TransportReplicationActionTests.java
+++ b/core/src/test/java/org/elasticsearch/action/support/replication/TransportReplicationActionTests.java
@@ -360,8 +360,8 @@ public class TransportReplicationActionTests extends ESTestCase {
public void testClosedIndexOnReroute() throws InterruptedException {
final String index = "test";
// no replicas in oder to skip the replication part
- setState(clusterService,
- new ClusterStateChanges().closeIndices(state(index, true, ShardRoutingState.UNASSIGNED), new CloseIndexRequest(index)));
+ setState(clusterService, new ClusterStateChanges(xContentRegistry()).closeIndices(state(index, true, ShardRoutingState.UNASSIGNED),
+ new CloseIndexRequest(index)));
logger.debug("--> using initial state:\n{}", clusterService.state());
Request request = new Request(new ShardId("test", "_na_", 0)).timeout("1ms");
PlainActionFuture listener = new PlainActionFuture<>();
diff --git a/core/src/test/java/org/elasticsearch/action/update/UpdateRequestTests.java b/core/src/test/java/org/elasticsearch/action/update/UpdateRequestTests.java
index 8c342265a28..be95f8dc581 100644
--- a/core/src/test/java/org/elasticsearch/action/update/UpdateRequestTests.java
+++ b/core/src/test/java/org/elasticsearch/action/update/UpdateRequestTests.java
@@ -26,6 +26,7 @@ import org.elasticsearch.common.io.stream.Streamable;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentHelper;
+import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.get.GetResult;
import org.elasticsearch.index.shard.ShardId;
@@ -56,10 +57,10 @@ public class UpdateRequestTests extends ESTestCase {
public void testUpdateRequest() throws Exception {
UpdateRequest request = new UpdateRequest("test", "type", "1");
// simple script
- request.fromXContent(XContentHelper.createParser(XContentFactory.jsonBuilder()
+ request.fromXContent(createParser(XContentFactory.jsonBuilder()
.startObject()
.field("script", "script1")
- .endObject().bytes()));
+ .endObject()));
Script script = request.script();
assertThat(script, notNullValue());
assertThat(script.getIdOrCode(), equalTo("script1"));
@@ -69,9 +70,9 @@ public class UpdateRequestTests extends ESTestCase {
assertThat(params, equalTo(Collections.emptyMap()));
// simple verbose script
- request.fromXContent(XContentHelper.createParser(XContentFactory.jsonBuilder().startObject()
+ request.fromXContent(createParser(XContentFactory.jsonBuilder().startObject()
.startObject("script").field("inline", "script1").endObject()
- .endObject().bytes()));
+ .endObject()));
script = request.script();
assertThat(script, notNullValue());
assertThat(script.getIdOrCode(), equalTo("script1"));
@@ -82,13 +83,13 @@ public class UpdateRequestTests extends ESTestCase {
// script with params
request = new UpdateRequest("test", "type", "1");
- request.fromXContent(XContentHelper.createParser(XContentFactory.jsonBuilder().startObject()
+ request.fromXContent(createParser(XContentFactory.jsonBuilder().startObject()
.startObject("script")
.field("inline", "script1")
.startObject("params")
.field("param1", "value1")
.endObject()
- .endObject().endObject().bytes()));
+ .endObject().endObject()));
script = request.script();
assertThat(script, notNullValue());
assertThat(script.getIdOrCode(), equalTo("script1"));
@@ -100,7 +101,7 @@ public class UpdateRequestTests extends ESTestCase {
assertThat(params.get("param1").toString(), equalTo("value1"));
request = new UpdateRequest("test", "type", "1");
- request.fromXContent(XContentHelper.createParser(XContentFactory.jsonBuilder()
+ request.fromXContent(createParser(XContentFactory.jsonBuilder()
.startObject()
.startObject("script")
.startObject("params")
@@ -108,7 +109,7 @@ public class UpdateRequestTests extends ESTestCase {
.endObject()
.field("inline", "script1")
.endObject()
- .endObject().bytes()));
+ .endObject()));
script = request.script();
assertThat(script, notNullValue());
assertThat(script.getIdOrCode(), equalTo("script1"));
@@ -121,7 +122,7 @@ public class UpdateRequestTests extends ESTestCase {
// script with params and upsert
request = new UpdateRequest("test", "type", "1");
- request.fromXContent(XContentHelper.createParser(XContentFactory.jsonBuilder().startObject()
+ request.fromXContent(createParser(XContentFactory.jsonBuilder().startObject()
.startObject("script")
.startObject("params")
.field("param1", "value1")
@@ -133,7 +134,7 @@ public class UpdateRequestTests extends ESTestCase {
.startObject("compound")
.field("field2", "value2")
.endObject()
- .endObject().endObject().bytes()));
+ .endObject().endObject()));
script = request.script();
assertThat(script, notNullValue());
assertThat(script.getIdOrCode(), equalTo("script1"));
@@ -148,7 +149,7 @@ public class UpdateRequestTests extends ESTestCase {
assertThat(((Map) upsertDoc.get("compound")).get("field2").toString(), equalTo("value2"));
request = new UpdateRequest("test", "type", "1");
- request.fromXContent(XContentHelper.createParser(XContentFactory.jsonBuilder().startObject()
+ request.fromXContent(createParser(XContentFactory.jsonBuilder().startObject()
.startObject("upsert")
.field("field1", "value1")
.startObject("compound")
@@ -160,7 +161,7 @@ public class UpdateRequestTests extends ESTestCase {
.field("param1", "value1")
.endObject()
.field("inline", "script1")
- .endObject().endObject().bytes()));
+ .endObject().endObject()));
script = request.script();
assertThat(script, notNullValue());
assertThat(script.getIdOrCode(), equalTo("script1"));
@@ -176,7 +177,7 @@ public class UpdateRequestTests extends ESTestCase {
// script with doc
request = new UpdateRequest("test", "type", "1");
- request.fromXContent(XContentHelper.createParser(XContentFactory.jsonBuilder()
+ request.fromXContent(createParser(XContentFactory.jsonBuilder()
.startObject()
.startObject("doc")
.field("field1", "value1")
@@ -184,7 +185,7 @@ public class UpdateRequestTests extends ESTestCase {
.field("field2", "value2")
.endObject()
.endObject()
- .endObject().bytes()));
+ .endObject()));
Map doc = request.doc().sourceAsMap();
assertThat(doc.get("field1").toString(), equalTo("value1"));
assertThat(((Map) doc.get("compound")).get("field2").toString(), equalTo("value2"));
@@ -192,54 +193,54 @@ public class UpdateRequestTests extends ESTestCase {
// Related to issue 15338
public void testFieldsParsing() throws Exception {
- UpdateRequest request = new UpdateRequest("test", "type1", "1")
- .fromXContent(XContentHelper.createParser(new BytesArray("{\"doc\": {\"field1\": \"value1\"}, \"fields\": \"_source\"}")));
+ UpdateRequest request = new UpdateRequest("test", "type1", "1").fromXContent(
+ createParser(JsonXContent.jsonXContent, new BytesArray("{\"doc\": {\"field1\": \"value1\"}, \"fields\": \"_source\"}")));
assertThat(request.doc().sourceAsMap().get("field1").toString(), equalTo("value1"));
assertThat(request.fields(), arrayContaining("_source"));
- request = new UpdateRequest("test", "type2", "2").fromXContent(
- XContentHelper.createParser(new BytesArray("{\"doc\": {\"field2\": \"value2\"}, \"fields\": [\"field1\", \"field2\"]}")));
+ request = new UpdateRequest("test", "type2", "2").fromXContent(createParser(JsonXContent.jsonXContent,
+ new BytesArray("{\"doc\": {\"field2\": \"value2\"}, \"fields\": [\"field1\", \"field2\"]}")));
assertThat(request.doc().sourceAsMap().get("field2").toString(), equalTo("value2"));
assertThat(request.fields(), arrayContaining("field1", "field2"));
}
public void testFetchSourceParsing() throws Exception {
UpdateRequest request = new UpdateRequest("test", "type1", "1");
- request.fromXContent(XContentHelper.createParser(XContentFactory.jsonBuilder()
+ request.fromXContent(createParser(XContentFactory.jsonBuilder()
.startObject()
.field("_source", true)
- .endObject().bytes()));
+ .endObject()));
assertThat(request.fetchSource(), notNullValue());
assertThat(request.fetchSource().includes().length, equalTo(0));
assertThat(request.fetchSource().excludes().length, equalTo(0));
assertThat(request.fetchSource().fetchSource(), equalTo(true));
- request.fromXContent(XContentHelper.createParser(XContentFactory.jsonBuilder()
+ request.fromXContent(createParser(XContentFactory.jsonBuilder()
.startObject()
.field("_source", false)
- .endObject().bytes()));
+ .endObject()));
assertThat(request.fetchSource(), notNullValue());
assertThat(request.fetchSource().includes().length, equalTo(0));
assertThat(request.fetchSource().excludes().length, equalTo(0));
assertThat(request.fetchSource().fetchSource(), equalTo(false));
- request.fromXContent(XContentHelper.createParser(XContentFactory.jsonBuilder()
+ request.fromXContent(createParser(XContentFactory.jsonBuilder()
.startObject()
.field("_source", "path.inner.*")
- .endObject().bytes()));
+ .endObject()));
assertThat(request.fetchSource(), notNullValue());
assertThat(request.fetchSource().fetchSource(), equalTo(true));
assertThat(request.fetchSource().includes().length, equalTo(1));
assertThat(request.fetchSource().excludes().length, equalTo(0));
assertThat(request.fetchSource().includes()[0], equalTo("path.inner.*"));
- request.fromXContent(XContentHelper.createParser(XContentFactory.jsonBuilder()
+ request.fromXContent(createParser(XContentFactory.jsonBuilder()
.startObject()
.startObject("_source")
.field("includes", "path.inner.*")
.field("excludes", "another.inner.*")
.endObject()
- .endObject().bytes()));
+ .endObject()));
assertThat(request.fetchSource(), notNullValue());
assertThat(request.fetchSource().fetchSource(), equalTo(true));
assertThat(request.fetchSource().includes().length, equalTo(1));
diff --git a/core/src/test/java/org/elasticsearch/bootstrap/ElasticsearchCliTests.java b/core/src/test/java/org/elasticsearch/bootstrap/ElasticsearchCliTests.java
index 9a1417bdfa6..c31bbe8c74f 100644
--- a/core/src/test/java/org/elasticsearch/bootstrap/ElasticsearchCliTests.java
+++ b/core/src/test/java/org/elasticsearch/bootstrap/ElasticsearchCliTests.java
@@ -25,6 +25,7 @@ import org.elasticsearch.cli.ExitCodes;
import org.elasticsearch.monitor.jvm.JvmInfo;
import java.nio.file.Path;
+import java.util.Map;
import java.util.function.Consumer;
import static org.hamcrest.CoreMatchers.containsString;
@@ -152,9 +153,9 @@ public class ElasticsearchCliTests extends ESElasticsearchCliTestCase {
true,
output -> {},
(foreground, pidFile, quiet, esSettings) -> {
- assertThat(esSettings.size(), equalTo(2));
- assertThat(esSettings, hasEntry("foo", "bar"));
- assertThat(esSettings, hasEntry("baz", "qux"));
+ Map settings = esSettings.getAsMap();
+ assertThat(settings, hasEntry("foo", "bar"));
+ assertThat(settings, hasEntry("baz", "qux"));
},
"-Efoo=bar", "-E", "baz=qux"
);
diff --git a/core/src/test/java/org/elasticsearch/cluster/action/shard/ShardStateActionTests.java b/core/src/test/java/org/elasticsearch/cluster/action/shard/ShardStateActionTests.java
index ce6704cef82..e0add08b074 100644
--- a/core/src/test/java/org/elasticsearch/cluster/action/shard/ShardStateActionTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/action/shard/ShardStateActionTests.java
@@ -54,6 +54,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.LongConsumer;
+import java.util.function.Predicate;
import static org.elasticsearch.test.ClusterServiceUtils.createClusterService;
import static org.elasticsearch.test.ClusterServiceUtils.setState;
@@ -88,9 +89,9 @@ public class ShardStateActionTests extends ESTestCase {
}
@Override
- protected void waitForNewMasterAndRetry(String actionName, ClusterStateObserver observer, ShardEntry shardEntry, Listener listener) {
+ protected void waitForNewMasterAndRetry(String actionName, ClusterStateObserver observer, ShardEntry shardEntry, Listener listener, Predicate changePredicate) {
onBeforeWaitForNewMasterAndRetry.run();
- super.waitForNewMasterAndRetry(actionName, observer, shardEntry, listener);
+ super.waitForNewMasterAndRetry(actionName, observer, shardEntry, listener, changePredicate);
onAfterWaitForNewMasterAndRetry.run();
}
}
diff --git a/core/src/test/java/org/elasticsearch/cluster/metadata/MetaDataIndexAliasesServiceTests.java b/core/src/test/java/org/elasticsearch/cluster/metadata/MetaDataIndexAliasesServiceTests.java
index 8a342057dab..3b894eb8d7c 100644
--- a/core/src/test/java/org/elasticsearch/cluster/metadata/MetaDataIndexAliasesServiceTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/metadata/MetaDataIndexAliasesServiceTests.java
@@ -41,7 +41,7 @@ public class MetaDataIndexAliasesServiceTests extends ESTestCase {
private final AliasValidator aliasValidator = new AliasValidator(Settings.EMPTY);
private final MetaDataDeleteIndexService deleteIndexService = mock(MetaDataDeleteIndexService.class);
private final MetaDataIndexAliasesService service = new MetaDataIndexAliasesService(Settings.EMPTY, null, null, aliasValidator,
- deleteIndexService);
+ deleteIndexService, xContentRegistry());
public MetaDataIndexAliasesServiceTests() {
// Mock any deletes so we don't need to worry about how MetaDataDeleteIndexService does its job
diff --git a/core/src/test/java/org/elasticsearch/cluster/metadata/MetaDataIndexUpgradeServiceTests.java b/core/src/test/java/org/elasticsearch/cluster/metadata/MetaDataIndexUpgradeServiceTests.java
index a1dfdbc74f9..88e2835b5ab 100644
--- a/core/src/test/java/org/elasticsearch/cluster/metadata/MetaDataIndexUpgradeServiceTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/metadata/MetaDataIndexUpgradeServiceTests.java
@@ -30,7 +30,8 @@ import java.util.Collections;
public class MetaDataIndexUpgradeServiceTests extends ESTestCase {
public void testArchiveBrokenIndexSettings() {
- MetaDataIndexUpgradeService service = new MetaDataIndexUpgradeService(Settings.EMPTY, new MapperRegistry(Collections.emptyMap(), Collections.emptyMap()), IndexScopedSettings.DEFAULT_SCOPED_SETTINGS);
+ MetaDataIndexUpgradeService service = new MetaDataIndexUpgradeService(Settings.EMPTY, xContentRegistry(),
+ new MapperRegistry(Collections.emptyMap(), Collections.emptyMap()), IndexScopedSettings.DEFAULT_SCOPED_SETTINGS);
IndexMetaData src = newIndexMeta("foo", Settings.EMPTY);
IndexMetaData indexMetaData = service.archiveBrokenIndexSettings(src);
assertSame(indexMetaData, src);
@@ -56,8 +57,8 @@ public class MetaDataIndexUpgradeServiceTests extends ESTestCase {
}
public void testUpgrade() {
- MetaDataIndexUpgradeService service = new MetaDataIndexUpgradeService(Settings.EMPTY, new MapperRegistry(Collections.emptyMap(),
- Collections.emptyMap()), IndexScopedSettings.DEFAULT_SCOPED_SETTINGS);
+ MetaDataIndexUpgradeService service = new MetaDataIndexUpgradeService(Settings.EMPTY, xContentRegistry(),
+ new MapperRegistry(Collections.emptyMap(), Collections.emptyMap()), IndexScopedSettings.DEFAULT_SCOPED_SETTINGS);
IndexMetaData src = newIndexMeta("foo", Settings.builder().put("index.refresh_interval", "-200").build());
assertFalse(service.isUpgraded(src));
src = service.upgradeIndexMetaData(src, Version.CURRENT.minimumIndexCompatibilityVersion());
@@ -68,8 +69,8 @@ public class MetaDataIndexUpgradeServiceTests extends ESTestCase {
}
public void testIsUpgraded() {
- MetaDataIndexUpgradeService service = new MetaDataIndexUpgradeService(Settings.EMPTY, new MapperRegistry(Collections.emptyMap(),
- Collections.emptyMap()), IndexScopedSettings.DEFAULT_SCOPED_SETTINGS);
+ MetaDataIndexUpgradeService service = new MetaDataIndexUpgradeService(Settings.EMPTY, xContentRegistry(),
+ new MapperRegistry(Collections.emptyMap(), Collections.emptyMap()), IndexScopedSettings.DEFAULT_SCOPED_SETTINGS);
IndexMetaData src = newIndexMeta("foo", Settings.builder().put("index.refresh_interval", "-200").build());
assertFalse(service.isUpgraded(src));
Version version = VersionUtils.randomVersionBetween(random(), VersionUtils.getFirstVersion(), VersionUtils.getPreviousVersion());
@@ -80,8 +81,8 @@ public class MetaDataIndexUpgradeServiceTests extends ESTestCase {
}
public void testFailUpgrade() {
- MetaDataIndexUpgradeService service = new MetaDataIndexUpgradeService(Settings.EMPTY, new MapperRegistry(Collections.emptyMap(),
- Collections.emptyMap()), IndexScopedSettings.DEFAULT_SCOPED_SETTINGS);
+ MetaDataIndexUpgradeService service = new MetaDataIndexUpgradeService(Settings.EMPTY, xContentRegistry(),
+ new MapperRegistry(Collections.emptyMap(), Collections.emptyMap()), IndexScopedSettings.DEFAULT_SCOPED_SETTINGS);
final IndexMetaData metaData = newIndexMeta("foo", Settings.builder()
.put(IndexMetaData.SETTING_VERSION_UPGRADED, Version.V_5_0_0_beta1)
.put(IndexMetaData.SETTING_VERSION_CREATED, Version.fromString("2.4.0"))
diff --git a/core/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDeciderTests.java b/core/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDeciderTests.java
index 3aba43f366a..d005b05737d 100644
--- a/core/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDeciderTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDeciderTests.java
@@ -786,8 +786,9 @@ public class DiskThresholdDeciderTests extends ESAllocationTestCase {
} catch (IllegalArgumentException e) {
assertThat("can't be allocated because there isn't enough room: " + e.getMessage(),
e.getMessage(),
- containsString("the node is above the low watermark [cluster.routing.allocation.disk.watermark.low=0.7], using " +
- "more disk space than the maximum allowed [70.0%], actual free: [26.0%]"));
+ containsString("the node is above the low watermark cluster setting " +
+ "[cluster.routing.allocation.disk.watermark.low=0.7], using more disk space than the maximum " +
+ "allowed [70.0%], actual free: [26.0%]"));
}
}
@@ -858,7 +859,7 @@ public class DiskThresholdDeciderTests extends ESAllocationTestCase {
Decision decision = diskThresholdDecider.canRemain(firstRouting, firstRoutingNode, routingAllocation);
assertThat(decision.type(), equalTo(Decision.Type.NO));
assertThat(((Decision.Single) decision).getExplanation(), containsString(
- "the shard cannot remain on this node because it is above the high watermark " +
+ "the shard cannot remain on this node because it is above the high watermark cluster setting " +
"[cluster.routing.allocation.disk.watermark.high=70%] and there is less than the required [30.0%] free disk on node, " +
"actual free: [20.0%]"));
@@ -890,12 +891,12 @@ public class DiskThresholdDeciderTests extends ESAllocationTestCase {
assertThat(decision.type(), equalTo(Decision.Type.NO));
if (fooRouting.recoverySource().getType() == RecoverySource.Type.EMPTY_STORE) {
assertThat(((Decision.Single) decision).getExplanation(), containsString(
- "the node is above the high watermark [cluster.routing.allocation.disk.watermark.high=70%], using more disk space than " +
- "the maximum allowed [70.0%], actual free: [20.0%]"));
+ "the node is above the high watermark cluster setting [cluster.routing.allocation.disk.watermark.high=70%], using " +
+ "more disk space than the maximum allowed [70.0%], actual free: [20.0%]"));
} else {
assertThat(((Decision.Single) decision).getExplanation(), containsString(
- "the node is above the low watermark [cluster.routing.allocation.disk.watermark.low=60%], using more disk space than " +
- "the maximum allowed [60.0%], actual free: [20.0%]"));
+ "the node is above the low watermark cluster setting [cluster.routing.allocation.disk.watermark.low=60%], using more " +
+ "disk space than the maximum allowed [60.0%], actual free: [20.0%]"));
}
// Creating AllocationService instance and the services it depends on...
diff --git a/core/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDeciderUnitTests.java b/core/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDeciderUnitTests.java
index 659c3b25833..7379ee78d03 100644
--- a/core/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDeciderUnitTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDeciderUnitTests.java
@@ -106,8 +106,8 @@ public class DiskThresholdDeciderUnitTests extends ESAllocationTestCase {
decision = decider.canAllocate(test_0, new RoutingNode("node_1", node_1), allocation);
assertEquals(mostAvailableUsage.toString(), Decision.Type.NO, decision.type());
assertThat(((Decision.Single) decision).getExplanation(), containsString(
- "the node is above the high watermark [cluster.routing.allocation.disk.watermark.high=90%], using more disk space than " +
- "the maximum allowed [90.0%]"));
+ "the node is above the high watermark cluster setting [cluster.routing.allocation.disk.watermark.high=90%], using more " +
+ "disk space than the maximum allowed [90.0%]"));
}
public void testCanRemainUsesLeastAvailableSpace() {
@@ -181,8 +181,8 @@ public class DiskThresholdDeciderUnitTests extends ESAllocationTestCase {
decision = decider.canRemain(test_1, new RoutingNode("node_1", node_1), allocation);
assertEquals(Decision.Type.NO, decision.type());
assertThat(((Decision.Single) decision).getExplanation(), containsString("the shard cannot remain on this node because it is " +
- "above the high watermark [cluster.routing.allocation.disk.watermark.high=90%] and there is less than the required [10.0%] " +
- "free disk on node, actual free: [9.0%]"));
+ "above the high watermark cluster setting [cluster.routing.allocation.disk.watermark.high=90%] and there is less than " +
+ "the required [10.0%] free disk on node, actual free: [9.0%]"));
try {
decider.canRemain(test_0, new RoutingNode("node_1", node_1), allocation);
fail("not allocated on this node");
diff --git a/core/src/test/java/org/elasticsearch/common/ParseFieldTests.java b/core/src/test/java/org/elasticsearch/common/ParseFieldTests.java
index 1f348000ee4..59b37f9e9e6 100644
--- a/core/src/test/java/org/elasticsearch/common/ParseFieldTests.java
+++ b/core/src/test/java/org/elasticsearch/common/ParseFieldTests.java
@@ -20,77 +20,45 @@ package org.elasticsearch.common;
import org.elasticsearch.test.ESTestCase;
-import static org.hamcrest.CoreMatchers.containsString;
+import java.io.IOException;
+
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.hamcrest.collection.IsArrayContainingInAnyOrder.arrayContainingInAnyOrder;
public class ParseFieldTests extends ESTestCase {
- public void testParse() {
+ public void testParse() throws IOException {
String name = "foo_bar";
ParseField field = new ParseField(name);
String[] deprecated = new String[]{"barFoo", "bar_foo", "Foobar"};
ParseField withDeprecations = field.withDeprecation(deprecated);
assertThat(field, not(sameInstance(withDeprecations)));
- assertThat(field.match(name, false), is(true));
- assertThat(field.match("foo bar", false), is(false));
+ assertThat(field.match(name), is(true));
+ assertThat(field.match("foo bar"), is(false));
for (String deprecatedName : deprecated) {
- assertThat(field.match(deprecatedName, false), is(false));
+ assertThat(field.match(deprecatedName), is(false));
}
- assertThat(withDeprecations.match(name, false), is(true));
- assertThat(withDeprecations.match("foo bar", false), is(false));
+ assertThat(withDeprecations.match(name), is(true));
+ assertThat(withDeprecations.match("foo bar"), is(false));
for (String deprecatedName : deprecated) {
- assertThat(withDeprecations.match(deprecatedName, false), is(true));
- }
-
- // now with strict mode
- assertThat(field.match(name, true), is(true));
- assertThat(field.match("foo bar", true), is(false));
- for (String deprecatedName : deprecated) {
- assertThat(field.match(deprecatedName, true), is(false));
- }
-
- assertThat(withDeprecations.match(name, true), is(true));
- assertThat(withDeprecations.match("foo bar", true), is(false));
- for (String deprecatedName : deprecated) {
- IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> {
- withDeprecations.match(deprecatedName, true);
- });
- assertThat(e.getMessage(), containsString("used, expected [foo_bar] instead"));
+ assertThat(withDeprecations.match(deprecatedName), is(true));
+ assertWarnings("Deprecated field [" + deprecatedName + "] used, expected [foo_bar] instead");
}
}
- public void testAllDeprecated() {
+ public void testAllDeprecated() throws IOException {
String name = "like_text";
-
- boolean withDeprecatedNames = randomBoolean();
String[] deprecated = new String[]{"text", "same_as_text"};
- String[] allValues;
- if (withDeprecatedNames) {
- String[] newArray = new String[1 + deprecated.length];
- newArray[0] = name;
- System.arraycopy(deprecated, 0, newArray, 1, deprecated.length);
- allValues = newArray;
- } else {
- allValues = new String[] {name};
- }
-
- ParseField field;
- if (withDeprecatedNames) {
- field = new ParseField(name).withDeprecation(deprecated).withAllDeprecated("like");
- } else {
- field = new ParseField(name).withAllDeprecated("like");
- }
-
- // strict mode off
- assertThat(field.match(randomFrom(allValues), false), is(true));
- assertThat(field.match("not a field name", false), is(false));
-
- // now with strict mode
- IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> field.match(randomFrom(allValues), true));
- assertThat(e.getMessage(), containsString(" used, replaced by [like]"));
+ ParseField field = new ParseField(name).withDeprecation(deprecated).withAllDeprecated("like");
+ assertFalse(field.match("not a field name"));
+ assertTrue(field.match("text"));
+ assertWarnings("Deprecated field [text] used, replaced by [like]");
+ assertTrue(field.match("same_as_text"));
+ assertWarnings("Deprecated field [same_as_text] used, replaced by [like]");
+ assertTrue(field.match("like_text"));
+ assertWarnings("Deprecated field [like_text] used, replaced by [like]");
}
public void testGetAllNamesIncludedDeprecated() {
diff --git a/core/src/test/java/org/elasticsearch/common/logging/DeprecationLoggerTests.java b/core/src/test/java/org/elasticsearch/common/logging/DeprecationLoggerTests.java
index f75e73ced2c..d0e1b807baf 100644
--- a/core/src/test/java/org/elasticsearch/common/logging/DeprecationLoggerTests.java
+++ b/core/src/test/java/org/elasticsearch/common/logging/DeprecationLoggerTests.java
@@ -41,6 +41,12 @@ public class DeprecationLoggerTests extends ESTestCase {
private final DeprecationLogger logger = new DeprecationLogger(Loggers.getLogger(getClass()));
+ @Override
+ protected boolean enableWarningsCheck() {
+ //this is a low level test for the deprecation logger, setup and checks are done manually
+ return false;
+ }
+
public void testAddsHeaderWithThreadContext() throws IOException {
String msg = "A simple message [{}]";
String param = randomAsciiOfLengthBetween(1, 5);
@@ -54,7 +60,7 @@ public class DeprecationLoggerTests extends ESTestCase {
Map> responseHeaders = threadContext.getResponseHeaders();
assertEquals(1, responseHeaders.size());
- assertEquals(formatted, responseHeaders.get(DeprecationLogger.DEPRECATION_HEADER).get(0));
+ assertEquals(formatted, responseHeaders.get(DeprecationLogger.WARNING_HEADER).get(0));
}
}
@@ -74,7 +80,7 @@ public class DeprecationLoggerTests extends ESTestCase {
assertEquals(1, responseHeaders.size());
- List responses = responseHeaders.get(DeprecationLogger.DEPRECATION_HEADER);
+ List responses = responseHeaders.get(DeprecationLogger.WARNING_HEADER);
assertEquals(2, responses.size());
assertEquals(formatted, responses.get(0));
@@ -93,7 +99,7 @@ public class DeprecationLoggerTests extends ESTestCase {
logger.deprecated(expected);
Map> responseHeaders = threadContext.getResponseHeaders();
- List responses = responseHeaders.get(DeprecationLogger.DEPRECATION_HEADER);
+ List responses = responseHeaders.get(DeprecationLogger.WARNING_HEADER);
// ensure it works (note: concurrent tests may be adding to it, but in different threads, so it should have no impact)
assertThat(responses, hasSize(atLeast(1)));
@@ -104,7 +110,7 @@ public class DeprecationLoggerTests extends ESTestCase {
logger.deprecated(unexpected);
responseHeaders = threadContext.getResponseHeaders();
- responses = responseHeaders.get(DeprecationLogger.DEPRECATION_HEADER);
+ responses = responseHeaders.get(DeprecationLogger.WARNING_HEADER);
assertThat(responses, hasSize(atLeast(1)));
assertThat(responses, hasItem(expected));
diff --git a/core/src/test/java/org/elasticsearch/common/network/NetworkModuleTests.java b/core/src/test/java/org/elasticsearch/common/network/NetworkModuleTests.java
index 3e29068e672..b1ec686c395 100644
--- a/core/src/test/java/org/elasticsearch/common/network/NetworkModuleTests.java
+++ b/core/src/test/java/org/elasticsearch/common/network/NetworkModuleTests.java
@@ -27,6 +27,7 @@ import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.BoundTransportAddress;
import org.elasticsearch.common.util.BigArrays;
+import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.http.HttpInfo;
import org.elasticsearch.http.HttpServerAdapter;
import org.elasticsearch.http.HttpServerTransport;
@@ -137,6 +138,7 @@ public class NetworkModuleTests extends ModuleTestCase {
BigArrays bigArrays,
CircuitBreakerService circuitBreakerService,
NamedWriteableRegistry namedWriteableRegistry,
+ NamedXContentRegistry xContentRegistry,
NetworkService networkService) {
return Collections.singletonMap("custom", custom);
}
@@ -176,6 +178,7 @@ public class NetworkModuleTests extends ModuleTestCase {
BigArrays bigArrays,
CircuitBreakerService circuitBreakerService,
NamedWriteableRegistry namedWriteableRegistry,
+ NamedXContentRegistry xContentRegistry,
NetworkService networkService) {
Map> supplierMap = new HashMap<>();
supplierMap.put("custom", custom);
@@ -208,6 +211,7 @@ public class NetworkModuleTests extends ModuleTestCase {
BigArrays bigArrays,
CircuitBreakerService circuitBreakerService,
NamedWriteableRegistry namedWriteableRegistry,
+ NamedXContentRegistry xContentRegistry,
NetworkService networkService) {
Map> supplierMap = new HashMap<>();
supplierMap.put("custom", custom);
@@ -252,6 +256,6 @@ public class NetworkModuleTests extends ModuleTestCase {
}
private NetworkModule newNetworkModule(Settings settings, boolean transportClient, NetworkPlugin... plugins) {
- return new NetworkModule(settings, transportClient, Arrays.asList(plugins), null, null, null, null, null);
+ return new NetworkModule(settings, transportClient, Arrays.asList(plugins), null, null, null, null, xContentRegistry(), null);
}
}
diff --git a/core/src/test/java/org/elasticsearch/common/unit/FuzzinessTests.java b/core/src/test/java/org/elasticsearch/common/unit/FuzzinessTests.java
index 3f6f1848fd8..b370250bf9d 100644
--- a/core/src/test/java/org/elasticsearch/common/unit/FuzzinessTests.java
+++ b/core/src/test/java/org/elasticsearch/common/unit/FuzzinessTests.java
@@ -20,9 +20,8 @@ package org.elasticsearch.common.unit;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.StreamInput;
-import org.elasticsearch.common.xcontent.XContent;
+import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
-import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.test.ESTestCase;
import java.io.IOException;
@@ -31,7 +30,6 @@ import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.hamcrest.number.IsCloseTo.closeTo;
public class FuzzinessTests extends ESTestCase {
public void testNumerics() {
@@ -43,12 +41,11 @@ public class FuzzinessTests extends ESTestCase {
final int iters = randomIntBetween(10, 50);
for (int i = 0; i < iters; i++) {
{
- XContent xcontent = XContentType.JSON.xContent();
float floatValue = randomFloat();
- String json = jsonBuilder().startObject()
+ XContentBuilder json = jsonBuilder().startObject()
.field(Fuzziness.X_FIELD_NAME, floatValue)
- .endObject().string();
- XContentParser parser = xcontent.createParser(json);
+ .endObject();
+ XContentParser parser = createParser(json);
assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.VALUE_NUMBER));
@@ -57,17 +54,16 @@ public class FuzzinessTests extends ESTestCase {
assertThat(parser.nextToken(), equalTo(XContentParser.Token.END_OBJECT));
}
{
- XContent xcontent = XContentType.JSON.xContent();
Integer intValue = frequently() ? randomIntBetween(0, 2) : randomIntBetween(0, 100);
Float floatRep = randomFloat();
Number value = intValue;
if (randomBoolean()) {
value = new Float(floatRep += intValue);
}
- String json = jsonBuilder().startObject()
+ XContentBuilder json = jsonBuilder().startObject()
.field(Fuzziness.X_FIELD_NAME, randomBoolean() ? value.toString() : value)
- .endObject().string();
- XContentParser parser = xcontent.createParser(json);
+ .endObject();
+ XContentParser parser = createParser(json);
assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME));
assertThat(parser.nextToken(), anyOf(equalTo(XContentParser.Token.VALUE_NUMBER), equalTo(XContentParser.Token.VALUE_STRING)));
@@ -93,14 +89,15 @@ public class FuzzinessTests extends ESTestCase {
}
}
{
- XContent xcontent = XContentType.JSON.xContent();
- String json = jsonBuilder().startObject()
- .field(Fuzziness.X_FIELD_NAME, randomBoolean() ? "AUTO" : "auto")
- .endObject().string();
+ XContentBuilder json;
if (randomBoolean()) {
- json = Fuzziness.AUTO.toXContent(jsonBuilder().startObject(), null).endObject().string();
+ json = Fuzziness.AUTO.toXContent(jsonBuilder().startObject(), null).endObject();
+ } else {
+ json = jsonBuilder().startObject()
+ .field(Fuzziness.X_FIELD_NAME, randomBoolean() ? "AUTO" : "auto")
+ .endObject();
}
- XContentParser parser = xcontent.createParser(json);
+ XContentParser parser = createParser(json);
assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.VALUE_STRING));
diff --git a/core/src/test/java/org/elasticsearch/common/xcontent/BaseXContentTestCase.java b/core/src/test/java/org/elasticsearch/common/xcontent/BaseXContentTestCase.java
index 1c0a92dbd74..e468751cf4a 100644
--- a/core/src/test/java/org/elasticsearch/common/xcontent/BaseXContentTestCase.java
+++ b/core/src/test/java/org/elasticsearch/common/xcontent/BaseXContentTestCase.java
@@ -21,11 +21,13 @@ package org.elasticsearch.common.xcontent;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
-
import com.fasterxml.jackson.core.JsonParseException;
+
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.Constants;
+import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.cluster.metadata.IndexMetaData;
+import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
@@ -751,7 +753,7 @@ public abstract class BaseXContentTestCase extends ESTestCase {
generator.writeEndObject();
}
- XContentParser parser = xcontentType().xContent().createParser(os.toByteArray());
+ XContentParser parser = xcontentType().xContent().createParser(NamedXContentRegistry.EMPTY, os.toByteArray());
assertEquals(Token.START_OBJECT, parser.nextToken());
assertEquals(Token.FIELD_NAME, parser.nextToken());
assertEquals("bar", parser.currentName());
@@ -785,7 +787,7 @@ public abstract class BaseXContentTestCase extends ESTestCase {
generator.writeRawValue(new BytesArray(rawData));
}
- XContentParser parser = xcontentType().xContent().createParser(os.toByteArray());
+ XContentParser parser = xcontentType().xContent().createParser(NamedXContentRegistry.EMPTY, os.toByteArray());
assertEquals(Token.START_OBJECT, parser.nextToken());
assertEquals(Token.FIELD_NAME, parser.nextToken());
assertEquals("foo", parser.currentName());
@@ -801,7 +803,7 @@ public abstract class BaseXContentTestCase extends ESTestCase {
generator.writeEndObject();
}
- parser = xcontentType().xContent().createParser(os.toByteArray());
+ parser = xcontentType().xContent().createParser(NamedXContentRegistry.EMPTY, os.toByteArray());
assertEquals(Token.START_OBJECT, parser.nextToken());
assertEquals(Token.FIELD_NAME, parser.nextToken());
assertEquals("test", parser.currentName());
@@ -829,7 +831,7 @@ public abstract class BaseXContentTestCase extends ESTestCase {
generator.flush();
byte[] serialized = os.toByteArray();
- XContentParser parser = xcontentType().xContent().createParser(serialized);
+ XContentParser parser = xcontentType().xContent().createParser(NamedXContentRegistry.EMPTY, serialized);
Map map = parser.map();
assertEquals("bar", map.get("foo"));
assertEquals(bigInteger, map.get("bigint"));
@@ -990,17 +992,50 @@ public abstract class BaseXContentTestCase extends ESTestCase {
assumeTrue("Test only makes sense if XContent parser has strict duplicate checks enabled",
XContent.isStrictDuplicateDetectionEnabled());
- BytesReference bytes = builder()
+ XContentBuilder builder = builder()
.startObject()
.field("key", 1)
.field("key", 2)
- .endObject()
- .bytes();
+ .endObject();
- JsonParseException pex = expectThrows(JsonParseException.class, () -> createParser(xcontentType().xContent(), bytes).map());
+ JsonParseException pex = expectThrows(JsonParseException.class, () -> createParser(builder).map());
assertThat(pex.getMessage(), startsWith("Duplicate field 'key'"));
}
+ public void testNamedObject() throws IOException {
+ Object test1 = new Object();
+ Object test2 = new Object();
+ NamedXContentRegistry registry = new NamedXContentRegistry(Arrays.asList(
+ new NamedXContentRegistry.Entry(Object.class, new ParseField("test1"), p -> test1),
+ new NamedXContentRegistry.Entry(Object.class, new ParseField("test2", "deprecated"), p -> test2),
+ new NamedXContentRegistry.Entry(Object.class, new ParseField("str"), p -> p.text())));
+ XContentBuilder b = XContentBuilder.builder(xcontentType().xContent());
+ b.value("test");
+ XContentParser p = xcontentType().xContent().createParser(registry, b.bytes());
+ assertEquals(test1, p.namedObject(Object.class, "test1", null));
+ assertEquals(test2, p.namedObject(Object.class, "test2", null));
+ assertEquals(test2, p.namedObject(Object.class, "deprecated", null));
+ assertWarnings("Deprecated field [deprecated] used, expected [test2] instead");
+ {
+ p.nextToken();
+ assertEquals("test", p.namedObject(Object.class, "str", null));
+ NamedXContentRegistry.UnknownNamedObjectException e = expectThrows(NamedXContentRegistry.UnknownNamedObjectException.class,
+ () -> p.namedObject(Object.class, "unknown", null));
+ assertEquals("Unknown Object [unknown]", e.getMessage());
+ assertEquals("java.lang.Object", e.getCategoryClass());
+ assertEquals("unknown", e.getName());
+ }
+ {
+ Exception e = expectThrows(ElasticsearchException.class, () -> p.namedObject(String.class, "doesn't matter", null));
+ assertEquals("Unknown namedObject category [java.lang.String]", e.getMessage());
+ }
+ {
+ XContentParser emptyRegistryParser = xcontentType().xContent().createParser(NamedXContentRegistry.EMPTY, new byte[] {});
+ Exception e = expectThrows(ElasticsearchException.class,
+ () -> emptyRegistryParser.namedObject(String.class, "doesn't matter", null));
+ assertEquals("namedObject is not supported for this parser", e.getMessage());
+ }
+ }
private static void expectUnclosedException(ThrowingRunnable runnable) {
IllegalStateException e = expectThrows(IllegalStateException.class, runnable);
diff --git a/core/src/test/java/org/elasticsearch/common/xcontent/ObjectParserTests.java b/core/src/test/java/org/elasticsearch/common/xcontent/ObjectParserTests.java
index 46c0ba35723..3c1bc509328 100644
--- a/core/src/test/java/org/elasticsearch/common/xcontent/ObjectParserTests.java
+++ b/core/src/test/java/org/elasticsearch/common/xcontent/ObjectParserTests.java
@@ -180,8 +180,8 @@ public class ObjectParserTests extends ESTestCase {
}
}
}
- XContentParser parser = XContentType.JSON.xContent()
- .createParser("{\"url\" : { \"host\": \"http://foobar\", \"port\" : 80}, \"name\" : \"foobarbaz\"}");
+ XContentParser parser = createParser(JsonXContent.jsonXContent,
+ "{\"url\" : { \"host\": \"http://foobar\", \"port\" : 80}, \"name\" : \"foobarbaz\"}");
ObjectParser objectParser = new ObjectParser<>("foo");
objectParser.declareString(Foo::setName, new ParseField("name"));
objectParser.declareObjectOrDefault(Foo::setURI, (p, s) -> s.parseURI(p), () -> null, new ParseField("url"));
@@ -218,27 +218,17 @@ public class ObjectParserTests extends ESTestCase {
}
}
- public void testDeprecationFail() throws IOException {
- XContentParser parser = createParser(JsonXContent.jsonXContent, "{\"old_test\" : \"foo\"}");
+ public void testDeprecationWarnings() throws IOException {
class TestStruct {
public String test;
}
ObjectParser objectParser = new ObjectParser<>("foo");
TestStruct s = new TestStruct();
-
+ XContentParser parser = createParser(XContentType.JSON.xContent(), "{\"old_test\" : \"foo\"}");
objectParser.declareField((i, v, c) -> v.test = i.text(), new ParseField("test", "old_test"), ObjectParser.ValueType.STRING);
-
- try {
- objectParser.parse(parser, s, STRICT_PARSING);
- fail("deprecated value");
- } catch (IllegalArgumentException ex) {
- assertEquals(ex.getMessage(), "Deprecated field [old_test] used, expected [test] instead");
-
- }
- assertNull(s.test);
- parser = createParser(JsonXContent.jsonXContent, "{\"old_test\" : \"foo\"}");
objectParser.parse(parser, s, () -> ParseFieldMatcher.EMPTY);
assertEquals("foo", s.test);
+ assertWarnings("Deprecated field [old_test] used, expected [test] instead");
}
public void testFailOnValueType() throws IOException {
diff --git a/core/src/test/java/org/elasticsearch/common/xcontent/UnknownNamedObjectExceptionTests.java b/core/src/test/java/org/elasticsearch/common/xcontent/UnknownNamedObjectExceptionTests.java
new file mode 100644
index 00000000000..5ed3b0cf8c2
--- /dev/null
+++ b/core/src/test/java/org/elasticsearch/common/xcontent/UnknownNamedObjectExceptionTests.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to Elasticsearch under one or more contributor
+ * license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright
+ * ownership. Elasticsearch licenses this file to you under
+ * the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.elasticsearch.common.xcontent;
+
+import org.elasticsearch.common.io.stream.BytesStreamOutput;
+import org.elasticsearch.common.io.stream.StreamInput;
+import org.elasticsearch.common.xcontent.NamedXContentRegistry.UnknownNamedObjectException;
+import org.elasticsearch.rest.RestStatus;
+import org.elasticsearch.test.ESTestCase;
+
+import java.io.IOException;
+
+public class UnknownNamedObjectExceptionTests extends ESTestCase {
+ public void testRoundTrip() throws IOException {
+ XContentLocation location = new XContentLocation(between(1, 1000), between(1, 1000));
+ UnknownNamedObjectException created = new UnknownNamedObjectException(location, UnknownNamedObjectExceptionTests.class,
+ randomAsciiOfLength(5));
+ UnknownNamedObjectException roundTripped;
+
+ try (BytesStreamOutput out = new BytesStreamOutput()) {
+ created.writeTo(out);
+ try (StreamInput in = out.bytes().streamInput()) {
+ roundTripped = new UnknownNamedObjectException(in);
+ }
+ }
+ assertEquals(created.getMessage(), roundTripped.getMessage());
+ assertEquals(created.getLineNumber(), roundTripped.getLineNumber());
+ assertEquals(created.getColumnNumber(), roundTripped.getColumnNumber());
+ assertEquals(created.getCategoryClass(), roundTripped.getCategoryClass());
+ assertEquals(created.getName(), roundTripped.getName());
+ }
+
+ public void testStatusCode() {
+ XContentLocation location = new XContentLocation(between(1, 1000), between(1, 1000));
+ UnknownNamedObjectException e = new UnknownNamedObjectException(location, UnknownNamedObjectExceptionTests.class,
+ randomAsciiOfLength(5));
+ assertEquals(RestStatus.BAD_REQUEST, e.status());
+ }
+}
diff --git a/core/src/test/java/org/elasticsearch/common/xcontent/XContentParserUtilsTests.java b/core/src/test/java/org/elasticsearch/common/xcontent/XContentParserUtilsTests.java
index bec1a0e4fb5..00edb25d5c3 100644
--- a/core/src/test/java/org/elasticsearch/common/xcontent/XContentParserUtilsTests.java
+++ b/core/src/test/java/org/elasticsearch/common/xcontent/XContentParserUtilsTests.java
@@ -20,62 +20,24 @@
package org.elasticsearch.common.xcontent;
import org.elasticsearch.common.ParsingException;
-import org.elasticsearch.common.bytes.BytesReference;
+import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.test.ESTestCase;
-import org.junit.Before;
import java.io.IOException;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.is;
+import static org.elasticsearch.common.xcontent.XContentParserUtils.ensureExpectedToken;
public class XContentParserUtilsTests extends ESTestCase {
-
- private XContentType xContentType;
-
- @Before
- public void setUp() throws Exception {
- super.setUp();
- xContentType = randomFrom(XContentType.values());
- }
-
- public void testEnsureFieldName() throws IOException {
- ParsingException e = expectThrows(ParsingException.class, () -> {
- XContentParser parser = createParser(createBuilder().startObject().endObject().bytes());
+ public void testEnsureExpectedToken() throws IOException {
+ final XContentParser.Token randomToken = randomFrom(XContentParser.Token.values());
+ try (XContentParser parser = createParser(JsonXContent.jsonXContent, "{}")) {
// Parser current token is null
assertNull(parser.currentToken());
- XContentParserUtils.ensureFieldName(parser.currentToken(), parser::getTokenLocation);
- });
- assertThat(e.getMessage(), equalTo("Failed to parse object: expecting token of type [FIELD_NAME] but found [null]"));
-
- e = expectThrows(ParsingException.class, () -> {
- XContentParser parser = createParser(createBuilder().startObject().field("foo", "bar").endObject().bytes());
- // Parser next token is a start object
- XContentParserUtils.ensureFieldName(parser.nextToken(), parser::getTokenLocation);
- });
- assertThat(e.getMessage(), equalTo("Failed to parse object: expecting token of type [FIELD_NAME] but found [START_OBJECT]"));
-
- e = expectThrows(ParsingException.class, () -> {
- XContentParser parser = createParser(createBuilder().startObject().field("foo", "bar").endObject().bytes());
- // Moves to start object
- assertThat(parser.nextToken(), is(XContentParser.Token.START_OBJECT));
- // Expected field name is "foo", not "test"
- XContentParserUtils.ensureFieldName(parser, parser.nextToken(), "test");
- });
- assertThat(e.getMessage(), equalTo("Failed to parse object: expecting field with name [test] but found [foo]"));
-
- // Everything is fine
- final String randomFieldName = randomAsciiOfLength(5);
- XContentParser parser = createParser(createBuilder().startObject().field(randomFieldName, 0).endObject().bytes());
- assertThat(parser.nextToken(), is(XContentParser.Token.START_OBJECT));
- XContentParserUtils.ensureFieldName(parser, parser.nextToken(), randomFieldName);
- }
-
- private XContentBuilder createBuilder() throws IOException {
- return XContentBuilder.builder(xContentType.xContent());
- }
-
- private XContentParser createParser(BytesReference bytes) throws IOException {
- return xContentType.xContent().createParser(bytes);
+ ParsingException e = expectThrows(ParsingException.class,
+ () -> ensureExpectedToken(randomToken, parser.currentToken(), parser::getTokenLocation));
+ assertEquals("Failed to parse object: expecting token of type [" + randomToken + "] but found [null]", e.getMessage());
+ ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser::getTokenLocation);
+ ensureExpectedToken(XContentParser.Token.END_OBJECT, parser.nextToken(), parser::getTokenLocation);
+ }
}
}
diff --git a/core/src/test/java/org/elasticsearch/common/xcontent/support/XContentHelperTests.java b/core/src/test/java/org/elasticsearch/common/xcontent/support/XContentHelperTests.java
index a8091fc1122..2401a3550e9 100644
--- a/core/src/test/java/org/elasticsearch/common/xcontent/support/XContentHelperTests.java
+++ b/core/src/test/java/org/elasticsearch/common/xcontent/support/XContentHelperTests.java
@@ -19,10 +19,16 @@
package org.elasticsearch.common.xcontent.support;
+import org.elasticsearch.common.bytes.BytesReference;
+import org.elasticsearch.common.xcontent.NamedXContentRegistry;
+import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentHelper;
+import org.elasticsearch.common.xcontent.XContentParser;
+import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.test.ESTestCase;
import org.hamcrest.Matchers;
+import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
@@ -61,5 +67,27 @@ public class XContentHelperTests extends ESTestCase {
assertThat(content, Matchers.equalTo(expected));
}
-
+ public void testToXContentWrapInObject() throws IOException {
+ boolean wrapInObject = randomBoolean();
+ XContentType xContentType = randomFrom(XContentType.values());
+ ToXContent toXContent = (builder, params) -> {
+ if (wrapInObject == false) {
+ builder.startObject();
+ }
+ builder.field("field", "value");
+ if (wrapInObject == false) {
+ builder.endObject();
+ }
+ return builder;
+ };
+ BytesReference bytes = XContentHelper.toXContent(toXContent, xContentType, wrapInObject);
+ try (XContentParser parser = xContentType.xContent().createParser(NamedXContentRegistry.EMPTY, bytes)) {
+ assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
+ assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
+ assertTrue(parser.nextToken().isValue());
+ assertEquals("value", parser.text());
+ assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
+ assertNull(parser.nextToken());
+ }
+ }
}
diff --git a/core/src/test/java/org/elasticsearch/discovery/DiscoveryWithServiceDisruptionsIT.java b/core/src/test/java/org/elasticsearch/discovery/DiscoveryWithServiceDisruptionsIT.java
index 90d7e5e5a9e..d5e9ddcde9a 100644
--- a/core/src/test/java/org/elasticsearch/discovery/DiscoveryWithServiceDisruptionsIT.java
+++ b/core/src/test/java/org/elasticsearch/discovery/DiscoveryWithServiceDisruptionsIT.java
@@ -82,8 +82,6 @@ import org.elasticsearch.test.junit.annotations.TestLogging;
import org.elasticsearch.test.transport.MockTransportService;
import org.elasticsearch.transport.ConnectionProfile;
import org.elasticsearch.transport.TcpTransport;
-import org.elasticsearch.transport.Transport;
-import org.elasticsearch.transport.TransportException;
import org.elasticsearch.transport.TransportRequest;
import org.elasticsearch.transport.TransportRequestOptions;
import org.elasticsearch.transport.TransportService;
diff --git a/core/src/test/java/org/elasticsearch/gateway/GatewayMetaStateTests.java b/core/src/test/java/org/elasticsearch/gateway/GatewayMetaStateTests.java
index b106ca64227..f5a5391436a 100644
--- a/core/src/test/java/org/elasticsearch/gateway/GatewayMetaStateTests.java
+++ b/core/src/test/java/org/elasticsearch/gateway/GatewayMetaStateTests.java
@@ -392,7 +392,7 @@ public class GatewayMetaStateTests extends ESAllocationTestCase {
private final boolean upgrade;
public MockMetaDataIndexUpgradeService(boolean upgrade) {
- super(Settings.EMPTY, null, null);
+ super(Settings.EMPTY, null, null, null);
this.upgrade = upgrade;
}
@Override
diff --git a/core/src/test/java/org/elasticsearch/http/HttpServerTests.java b/core/src/test/java/org/elasticsearch/http/HttpServerTests.java
index 2d827ebb6e4..db9eebfe5fc 100644
--- a/core/src/test/java/org/elasticsearch/http/HttpServerTests.java
+++ b/core/src/test/java/org/elasticsearch/http/HttpServerTests.java
@@ -31,6 +31,7 @@ import org.elasticsearch.common.transport.BoundTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.util.concurrent.ThreadContext;
+import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.indices.breaker.CircuitBreakerService;
import org.elasticsearch.indices.breaker.HierarchyCircuitBreakerService;
import org.elasticsearch.rest.AbstractRestChannel;
@@ -192,7 +193,7 @@ public class HttpServerTests extends ESTestCase {
private final BytesReference content;
private TestRestRequest(String path, String content) {
- super(Collections.emptyMap(), path);
+ super(NamedXContentRegistry.EMPTY, Collections.emptyMap(), path);
this.content = new BytesArray(content);
}
diff --git a/core/src/test/java/org/elasticsearch/index/IndexModuleTests.java b/core/src/test/java/org/elasticsearch/index/IndexModuleTests.java
index 6b24c2e356c..e9b52589b9c 100644
--- a/core/src/test/java/org/elasticsearch/index/IndexModuleTests.java
+++ b/core/src/test/java/org/elasticsearch/index/IndexModuleTests.java
@@ -144,8 +144,8 @@ public class IndexModuleTests extends ESTestCase {
}
private IndexService newIndexService(IndexModule module) throws IOException {
- return module.newIndexService(nodeEnvironment, deleter, circuitBreakerService, bigArrays, threadPool, scriptService,
- indicesQueriesRegistry, clusterService, null, indicesQueryCache, mapperRegistry, shardId -> {},
+ return module.newIndexService(nodeEnvironment, xContentRegistry(), deleter, circuitBreakerService, bigArrays, threadPool,
+ scriptService, indicesQueriesRegistry, clusterService, null, indicesQueryCache, mapperRegistry, shardId -> {},
new IndicesFieldDataCache(settings, listener));
}
diff --git a/core/src/test/java/org/elasticsearch/index/analysis/AnalysisRegistryTests.java b/core/src/test/java/org/elasticsearch/index/analysis/AnalysisRegistryTests.java
index 4a5a0b95672..dedd478e3bf 100644
--- a/core/src/test/java/org/elasticsearch/index/analysis/AnalysisRegistryTests.java
+++ b/core/src/test/java/org/elasticsearch/index/analysis/AnalysisRegistryTests.java
@@ -104,7 +104,7 @@ public class AnalysisRegistryTests extends ESTestCase {
assertTrue(e.getMessage().contains("[index.analysis.analyzer.default_index] is not supported"));
}
- public void testBackCompatOverrideDefaultIndexAnalyzer() {
+ public void testBackCompatOverrideDefaultIndexAnalyzer() throws IOException {
Version version = VersionUtils.randomVersionBetween(random(), VersionUtils.getFirstVersion(),
VersionUtils.getPreviousVersion(Version.V_5_0_0_alpha1));
Settings settings = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, version).build();
@@ -113,6 +113,8 @@ public class AnalysisRegistryTests extends ESTestCase {
assertThat(indexAnalyzers.getDefaultIndexAnalyzer().analyzer(), instanceOf(EnglishAnalyzer.class));
assertThat(indexAnalyzers.getDefaultSearchAnalyzer().analyzer(), instanceOf(StandardAnalyzer.class));
assertThat(indexAnalyzers.getDefaultSearchQuoteAnalyzer().analyzer(), instanceOf(StandardAnalyzer.class));
+ assertWarnings("setting [index.analysis.analyzer.default_index] is deprecated, use [index.analysis.analyzer.default] " +
+ "instead for index [index]");
}
public void testOverrideDefaultSearchAnalyzer() {
@@ -125,7 +127,7 @@ public class AnalysisRegistryTests extends ESTestCase {
assertThat(indexAnalyzers.getDefaultSearchQuoteAnalyzer().analyzer(), instanceOf(EnglishAnalyzer.class));
}
- public void testBackCompatOverrideDefaultIndexAndSearchAnalyzer() {
+ public void testBackCompatOverrideDefaultIndexAndSearchAnalyzer() throws IOException {
Version version = VersionUtils.randomVersionBetween(random(), VersionUtils.getFirstVersion(),
VersionUtils.getPreviousVersion(Version.V_5_0_0_alpha1));
Settings settings = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, version).build();
@@ -137,6 +139,8 @@ public class AnalysisRegistryTests extends ESTestCase {
assertThat(indexAnalyzers.getDefaultIndexAnalyzer().analyzer(), instanceOf(EnglishAnalyzer.class));
assertThat(indexAnalyzers.getDefaultSearchAnalyzer().analyzer(), instanceOf(EnglishAnalyzer.class));
assertThat(indexAnalyzers.getDefaultSearchQuoteAnalyzer().analyzer(), instanceOf(EnglishAnalyzer.class));
+ assertWarnings("setting [index.analysis.analyzer.default_index] is deprecated, use [index.analysis.analyzer.default] " +
+ "instead for index [index]");
}
public void testConfigureCamelCaseTokenFilter() throws IOException {
diff --git a/core/src/test/java/org/elasticsearch/index/codec/CodecTests.java b/core/src/test/java/org/elasticsearch/index/codec/CodecTests.java
index ea89acbd8f8..e49e21bd2ff 100644
--- a/core/src/test/java/org/elasticsearch/index/codec/CodecTests.java
+++ b/core/src/test/java/org/elasticsearch/index/codec/CodecTests.java
@@ -89,7 +89,7 @@ public class CodecTests extends ESTestCase {
dir.close();
}
- private static CodecService createCodecService() throws IOException {
+ private CodecService createCodecService() throws IOException {
Settings nodeSettings = Settings.builder()
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir())
.build();
@@ -97,7 +97,8 @@ public class CodecTests extends ESTestCase {
SimilarityService similarityService = new SimilarityService(settings, Collections.emptyMap());
IndexAnalyzers indexAnalyzers = createTestAnalysis(settings, nodeSettings).indexAnalyzers;
MapperRegistry mapperRegistry = new MapperRegistry(Collections.emptyMap(), Collections.emptyMap());
- MapperService service = new MapperService(settings, indexAnalyzers, similarityService, mapperRegistry, () -> null);
+ MapperService service = new MapperService(settings, indexAnalyzers, xContentRegistry(), similarityService, mapperRegistry,
+ () -> null);
return new CodecService(service, ESLoggerFactory.getLogger("test"));
}
diff --git a/core/src/test/java/org/elasticsearch/index/engine/InternalEngineTests.java b/core/src/test/java/org/elasticsearch/index/engine/InternalEngineTests.java
index 523efb6829c..76e1b37e4dc 100644
--- a/core/src/test/java/org/elasticsearch/index/engine/InternalEngineTests.java
+++ b/core/src/test/java/org/elasticsearch/index/engine/InternalEngineTests.java
@@ -85,6 +85,7 @@ import org.elasticsearch.common.lucene.uid.Versions;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.BigArrays;
+import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.VersionType;
@@ -378,7 +379,7 @@ public class InternalEngineTests extends ESTestCase {
};
EngineConfig config = new EngineConfig(openMode, shardId, threadPool, indexSettings, null, store, deletionPolicy,
mergePolicy, iwc.getAnalyzer(), iwc.getSimilarity(), new CodecService(null, logger), listener,
- new TranslogHandler(shardId.getIndexName(), logger), IndexSearcher.getDefaultQueryCache(),
+ new TranslogHandler(xContentRegistry(), shardId.getIndexName(), logger), IndexSearcher.getDefaultQueryCache(),
IndexSearcher.getDefaultQueryCachingPolicy(), translogConfig, TimeValue.timeValueMinutes(5), refreshListener,
maxUnsafeAutoIdTimestamp);
@@ -2305,7 +2306,7 @@ public class InternalEngineTests extends ESTestCase {
public final AtomicInteger recoveredOps = new AtomicInteger(0);
- public TranslogHandler(String indexName, Logger logger) {
+ public TranslogHandler(NamedXContentRegistry xContentRegistry, String indexName, Logger logger) {
super(new ShardId("test", "_na_", 0), null, logger);
Settings settings = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT).build();
Index index = new Index(indexName, "_na_");
@@ -2314,7 +2315,8 @@ public class InternalEngineTests extends ESTestCase {
IndexAnalyzers indexAnalyzers = new IndexAnalyzers(indexSettings, defaultAnalyzer, defaultAnalyzer, defaultAnalyzer, Collections.emptyMap());
SimilarityService similarityService = new SimilarityService(indexSettings, Collections.emptyMap());
MapperRegistry mapperRegistry = new IndicesModule(Collections.emptyList()).getMapperRegistry();
- mapperService = new MapperService(indexSettings, indexAnalyzers, similarityService, mapperRegistry, () -> null);
+ mapperService = new MapperService(indexSettings, indexAnalyzers, xContentRegistry, similarityService, mapperRegistry,
+ () -> null);
}
@Override
diff --git a/core/src/test/java/org/elasticsearch/index/get/GetFieldTests.java b/core/src/test/java/org/elasticsearch/index/get/GetFieldTests.java
new file mode 100644
index 00000000000..1058420afa7
--- /dev/null
+++ b/core/src/test/java/org/elasticsearch/index/get/GetFieldTests.java
@@ -0,0 +1,101 @@
+/*
+ * Licensed to Elasticsearch under one or more contributor
+ * license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright
+ * ownership. Elasticsearch licenses this file to you under
+ * the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.elasticsearch.index.get;
+
+import org.elasticsearch.common.Strings;
+import org.elasticsearch.common.bytes.BytesReference;
+import org.elasticsearch.common.collect.Tuple;
+import org.elasticsearch.common.xcontent.XContentParser;
+import org.elasticsearch.common.xcontent.XContentType;
+import org.elasticsearch.index.mapper.ParentFieldMapper;
+import org.elasticsearch.index.mapper.RoutingFieldMapper;
+import org.elasticsearch.index.mapper.UidFieldMapper;
+import org.elasticsearch.test.ESTestCase;
+import org.elasticsearch.test.RandomObjects;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Supplier;
+
+import static org.elasticsearch.common.xcontent.XContentHelper.toXContent;
+import static org.elasticsearch.test.EqualsHashCodeTestUtils.checkEqualsAndHashCode;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertToXContentEquivalent;
+
+public class GetFieldTests extends ESTestCase {
+
+ public void testToXContent() throws IOException {
+ GetField getField = new GetField("field", Arrays.asList("value1", "value2"));
+ String output = Strings.toString(getField, true);
+ assertEquals("{\"field\":[\"value1\",\"value2\"]}", output);
+ }
+
+ public void testEqualsAndHashcode() {
+ checkEqualsAndHashCode(randomGetField(XContentType.JSON).v1(), GetFieldTests::copyGetField, GetFieldTests::mutateGetField);
+ }
+
+ public void testToAndFromXContent() throws Exception {
+ XContentType xContentType = randomFrom(XContentType.values());
+ Tuple tuple = randomGetField(xContentType);
+ GetField getField = tuple.v1();
+ GetField expectedGetField = tuple.v2();
+ BytesReference originalBytes = toXContent(getField, xContentType, true);
+ //test that we can parse what we print out
+ GetField parsedGetField;
+ try (XContentParser parser = createParser(xContentType.xContent(), originalBytes)) {
+ //we need to move to the next token, the start object one that we manually added is not expected
+ assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
+ assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
+ parsedGetField = GetField.fromXContent(parser);
+ assertEquals(XContentParser.Token.END_ARRAY, parser.currentToken());
+ assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
+ assertNull(parser.nextToken());
+ }
+ assertEquals(expectedGetField, parsedGetField);
+ BytesReference finalBytes = toXContent(parsedGetField, xContentType, true);
+ assertToXContentEquivalent(originalBytes, finalBytes, xContentType);
+ }
+
+ private static GetField copyGetField(GetField getField) {
+ return new GetField(getField.getName(), getField.getValues());
+ }
+
+ private static GetField mutateGetField(GetField getField) {
+ List> mutations = new ArrayList<>();
+ mutations.add(() -> new GetField(randomUnicodeOfCodepointLength(15), getField.getValues()));
+ mutations.add(() -> new GetField(getField.getName(), randomGetField(XContentType.JSON).v1().getValues()));
+ return randomFrom(mutations).get();
+ }
+
+ public static Tuple randomGetField(XContentType xContentType) {
+ if (randomBoolean()) {
+ String fieldName = randomFrom(ParentFieldMapper.NAME, RoutingFieldMapper.NAME, UidFieldMapper.NAME);
+ GetField getField = new GetField(fieldName, Collections.singletonList(randomAsciiOfLengthBetween(3, 10)));
+ return Tuple.tuple(getField, getField);
+ }
+ String fieldName = randomAsciiOfLengthBetween(3, 10);
+ Tuple, List