Close xcontent parsers (partial) (#31513)

Partial pass at closing XContentParsers in server.  This mostly involved adding try-with-resources statements around the usage of XContentParsers.
This commit is contained in:
Tom Callahan 2018-06-24 15:39:56 -04:00 committed by GitHub
parent 9efb0fe9ba
commit 629c376f02
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
53 changed files with 1186 additions and 1025 deletions

View File

@ -558,9 +558,10 @@ public class PutIndexTemplateRequest extends MasterNodeRequest<PutIndexTemplateR
builder.startObject("mappings"); builder.startObject("mappings");
for (Map.Entry<String, String> entry : mappings.entrySet()) { for (Map.Entry<String, String> entry : mappings.entrySet()) {
builder.field(entry.getKey()); builder.field(entry.getKey());
XContentParser parser = JsonXContent.jsonXContent.createParser(NamedXContentRegistry.EMPTY, try (XContentParser parser = JsonXContent.jsonXContent.createParser(NamedXContentRegistry.EMPTY,
DeprecationHandler.THROW_UNSUPPORTED_OPERATION, entry.getValue()); DeprecationHandler.THROW_UNSUPPORTED_OPERATION, entry.getValue())) {
builder.copyCurrentStructure(parser); builder.copyCurrentStructure(parser);
}
} }
builder.endObject(); builder.endObject();

View File

@ -58,12 +58,13 @@ public class ClusterUpdateSettingsRequestTests extends ESTestCase {
assertThat(iae.getMessage(), assertThat(iae.getMessage(),
containsString("[cluster_update_settings_request] unknown field [" + unsupportedField + "], parser not found")); containsString("[cluster_update_settings_request] unknown field [" + unsupportedField + "], parser not found"));
} else { } else {
XContentParser parser = createParser(xContentType.xContent(), originalBytes); try (XContentParser parser = createParser(xContentType.xContent(), originalBytes)) {
ClusterUpdateSettingsRequest parsedRequest = ClusterUpdateSettingsRequest.fromXContent(parser); ClusterUpdateSettingsRequest parsedRequest = ClusterUpdateSettingsRequest.fromXContent(parser);
assertNull(parser.nextToken()); assertNull(parser.nextToken());
assertThat(parsedRequest.transientSettings(), equalTo(request.transientSettings())); assertThat(parsedRequest.transientSettings(), equalTo(request.transientSettings()));
assertThat(parsedRequest.persistentSettings(), equalTo(request.persistentSettings())); assertThat(parsedRequest.persistentSettings(), equalTo(request.persistentSettings()));
}
} }
} }

View File

@ -134,11 +134,12 @@ public class CreateIndexRequestTests extends ESTestCase {
for (Map.Entry<String, String> expectedEntry : expected.entrySet()) { for (Map.Entry<String, String> expectedEntry : expected.entrySet()) {
String expectedValue = expectedEntry.getValue(); String expectedValue = expectedEntry.getValue();
String actualValue = actual.get(expectedEntry.getKey()); String actualValue = actual.get(expectedEntry.getKey());
XContentParser expectedJson = JsonXContent.jsonXContent.createParser(NamedXContentRegistry.EMPTY, try (XContentParser expectedJson = JsonXContent.jsonXContent.createParser(NamedXContentRegistry.EMPTY,
LoggingDeprecationHandler.INSTANCE, expectedValue); LoggingDeprecationHandler.INSTANCE, expectedValue);
XContentParser actualJson = JsonXContent.jsonXContent.createParser(NamedXContentRegistry.EMPTY, XContentParser actualJson = JsonXContent.jsonXContent.createParser(NamedXContentRegistry.EMPTY,
LoggingDeprecationHandler.INSTANCE, actualValue); LoggingDeprecationHandler.INSTANCE, actualValue)){
assertEquals(expectedJson.map(), actualJson.map()); assertEquals(expectedJson.map(), actualJson.map());
}
} }
} }

View File

@ -147,9 +147,10 @@ public class PutMappingRequestTests extends ESTestCase {
private void assertMappingsEqual(String expected, String actual) throws IOException { private void assertMappingsEqual(String expected, String actual) throws IOException {
XContentParser expectedJson = createParser(XContentType.JSON.xContent(), expected); try (XContentParser expectedJson = createParser(XContentType.JSON.xContent(), expected);
XContentParser actualJson = createParser(XContentType.JSON.xContent(), actual); XContentParser actualJson = createParser(XContentType.JSON.xContent(), actual)) {
assertEquals(expectedJson.mapOrdered(), actualJson.mapOrdered()); assertEquals(expectedJson.mapOrdered(), actualJson.mapOrdered());
}
} }
/** /**

View File

@ -25,6 +25,7 @@ import org.elasticsearch.action.admin.indices.create.CreateIndexRequestTests;
import org.elasticsearch.common.Strings; import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.RandomCreateIndexGenerator; import org.elasticsearch.index.RandomCreateIndexGenerator;
import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.ESTestCase;
@ -93,7 +94,9 @@ public class ResizeRequestTests extends ESTestCase {
ResizeRequest parsedResizeRequest = new ResizeRequest(resizeRequest.getTargetIndexRequest().index(), ResizeRequest parsedResizeRequest = new ResizeRequest(resizeRequest.getTargetIndexRequest().index(),
resizeRequest.getSourceIndex()); resizeRequest.getSourceIndex());
parsedResizeRequest.fromXContent(createParser(xContentType.xContent(), originalBytes)); try (XContentParser xParser = createParser(xContentType.xContent(), originalBytes)) {
parsedResizeRequest.fromXContent(xParser);
}
assertEquals(resizeRequest.getSourceIndex(), parsedResizeRequest.getSourceIndex()); assertEquals(resizeRequest.getSourceIndex(), parsedResizeRequest.getSourceIndex());
assertEquals(resizeRequest.getTargetIndexRequest().index(), parsedResizeRequest.getTargetIndexRequest().index()); assertEquals(resizeRequest.getTargetIndexRequest().index(), parsedResizeRequest.getTargetIndexRequest().index());

View File

@ -54,9 +54,9 @@ public class MultiGetRequestTests extends ESTestCase {
builder.endArray(); builder.endArray();
} }
builder.endObject(); builder.endObject();
final XContentParser parser = createParser(builder); try (XContentParser parser = createParser(builder)) {
final MultiGetRequest mgr = new MultiGetRequest(); final MultiGetRequest mgr = new MultiGetRequest();
final ParsingException e = expectThrows( final ParsingException e = expectThrows(
ParsingException.class, ParsingException.class,
() -> { () -> {
final String defaultIndex = randomAlphaOfLength(5); final String defaultIndex = randomAlphaOfLength(5);
@ -64,9 +64,10 @@ public class MultiGetRequestTests extends ESTestCase {
final FetchSourceContext fetchSource = FetchSourceContext.FETCH_SOURCE; final FetchSourceContext fetchSource = FetchSourceContext.FETCH_SOURCE;
mgr.add(defaultIndex, defaultType, null, fetchSource, null, parser, true); mgr.add(defaultIndex, defaultType, null, fetchSource, null, parser, true);
}); });
assertThat( assertThat(
e.toString(), e.toString(),
containsString("unknown key [doc] for a START_ARRAY, expected [docs] or [ids]")); containsString("unknown key [doc] for a START_ARRAY, expected [docs] or [ids]"));
}
} }
public void testUnexpectedField() throws IOException { public void testUnexpectedField() throws IOException {
@ -141,16 +142,17 @@ public class MultiGetRequestTests extends ESTestCase {
MultiGetRequest expected = createTestInstance(); MultiGetRequest expected = createTestInstance();
XContentType xContentType = randomFrom(XContentType.values()); XContentType xContentType = randomFrom(XContentType.values());
BytesReference shuffled = toShuffledXContent(expected, xContentType, ToXContent.EMPTY_PARAMS, false); BytesReference shuffled = toShuffledXContent(expected, xContentType, ToXContent.EMPTY_PARAMS, false);
XContentParser parser = createParser(XContentFactory.xContent(xContentType), shuffled); try (XContentParser parser = createParser(XContentFactory.xContent(xContentType), shuffled)) {
MultiGetRequest actual = new MultiGetRequest(); MultiGetRequest actual = new MultiGetRequest();
actual.add(null, null, null, null, null, parser, true); actual.add(null, null, null, null, null, parser, true);
assertThat(parser.nextToken(), nullValue()); assertThat(parser.nextToken(), nullValue());
assertThat(actual.items.size(), equalTo(expected.items.size())); assertThat(actual.items.size(), equalTo(expected.items.size()));
for (int i = 0; i < expected.items.size(); i++) { for (int i = 0; i < expected.items.size(); i++) {
MultiGetRequest.Item expectedItem = expected.items.get(i); MultiGetRequest.Item expectedItem = expected.items.get(i);
MultiGetRequest.Item actualItem = actual.items.get(i); MultiGetRequest.Item actualItem = actual.items.get(i);
assertThat(actualItem, equalTo(expectedItem)); assertThat(actualItem, equalTo(expectedItem));
}
} }
} }
} }

View File

@ -39,10 +39,11 @@ public class MultiGetResponseTests extends ESTestCase {
MultiGetResponse expected = createTestInstance(); MultiGetResponse expected = createTestInstance();
XContentType xContentType = randomFrom(XContentType.values()); XContentType xContentType = randomFrom(XContentType.values());
BytesReference shuffled = toShuffledXContent(expected, xContentType, ToXContent.EMPTY_PARAMS, false); BytesReference shuffled = toShuffledXContent(expected, xContentType, ToXContent.EMPTY_PARAMS, false);
MultiGetResponse parsed;
XContentParser parser = createParser(XContentFactory.xContent(xContentType), shuffled); try (XContentParser parser = createParser(XContentFactory.xContent(xContentType), shuffled)) {
MultiGetResponse parsed = MultiGetResponse.fromXContent(parser); parsed = MultiGetResponse.fromXContent(parser);
assertNull(parser.nextToken()); assertNull(parser.nextToken());
}
assertNotSame(expected, parsed); assertNotSame(expected, parsed);
assertThat(parsed.getResponses().length, equalTo(expected.getResponses().length)); assertThat(parsed.getResponses().length, equalTo(expected.getResponses().length));
@ -60,6 +61,7 @@ public class MultiGetResponseTests extends ESTestCase {
assertThat(actualItem.getResponse(), equalTo(expectedItem.getResponse())); assertThat(actualItem.getResponse(), equalTo(expectedItem.getResponse()));
} }
} }
} }
} }

View File

@ -40,9 +40,11 @@ public class MultiSearchResponseTests extends ESTestCase {
MultiSearchResponse expected = createTestInstance(); MultiSearchResponse expected = createTestInstance();
XContentType xContentType = randomFrom(XContentType.values()); XContentType xContentType = randomFrom(XContentType.values());
BytesReference shuffled = toShuffledXContent(expected, xContentType, ToXContent.EMPTY_PARAMS, false); BytesReference shuffled = toShuffledXContent(expected, xContentType, ToXContent.EMPTY_PARAMS, false);
XContentParser parser = createParser(XContentFactory.xContent(xContentType), shuffled); MultiSearchResponse actual;
MultiSearchResponse actual = MultiSearchResponse.fromXContext(parser); try (XContentParser parser = createParser(XContentFactory.xContent(xContentType), shuffled)) {
assertThat(parser.nextToken(), nullValue()); actual = MultiSearchResponse.fromXContext(parser);
assertThat(parser.nextToken(), nullValue());
}
assertThat(actual.getTook(), equalTo(expected.getTook())); assertThat(actual.getTook(), equalTo(expected.getTook()));
assertThat(actual.getResponses().length, equalTo(expected.getResponses().length)); assertThat(actual.getResponses().length, equalTo(expected.getResponses().length));

View File

@ -181,8 +181,7 @@ public class MetaDataTests extends ESTestCase {
.field("random", "value") .field("random", "value")
.endObject() .endObject()
.endObject()); .endObject());
XContentParser parser = createParser(JsonXContent.jsonXContent, metadata); try (XContentParser parser = createParser(JsonXContent.jsonXContent, metadata)) {
try {
MetaData.Builder.fromXContent(parser); MetaData.Builder.fromXContent(parser);
fail(); fail();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
@ -197,8 +196,7 @@ public class MetaDataTests extends ESTestCase {
.field("random", "value") .field("random", "value")
.endObject() .endObject()
.endObject()); .endObject());
XContentParser parser = createParser(JsonXContent.jsonXContent, metadata); try (XContentParser parser = createParser(JsonXContent.jsonXContent, metadata)) {
try {
IndexMetaData.Builder.fromXContent(parser); IndexMetaData.Builder.fromXContent(parser);
fail(); fail();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
@ -225,9 +223,10 @@ public class MetaDataTests extends ESTestCase {
builder.startObject(); builder.startObject();
originalMeta.toXContent(builder, ToXContent.EMPTY_PARAMS); originalMeta.toXContent(builder, ToXContent.EMPTY_PARAMS);
builder.endObject(); builder.endObject();
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder))) {
final MetaData fromXContentMeta = MetaData.fromXContent(parser); final MetaData fromXContentMeta = MetaData.fromXContent(parser);
assertThat(fromXContentMeta.indexGraveyard(), equalTo(originalMeta.indexGraveyard())); assertThat(fromXContentMeta.indexGraveyard(), equalTo(originalMeta.indexGraveyard()));
}
} }
public void testSerializationWithIndexGraveyard() throws IOException { public void testSerializationWithIndexGraveyard() throws IOException {

View File

@ -50,15 +50,17 @@ abstract class BaseGeoParsingTestCase extends ESTestCase {
public abstract void testParseGeometryCollection() throws IOException; public abstract void testParseGeometryCollection() throws IOException;
protected void assertValidException(XContentBuilder builder, Class expectedException) throws IOException { protected void assertValidException(XContentBuilder builder, Class expectedException) throws IOException {
XContentParser parser = createParser(builder); try (XContentParser parser = createParser(builder)) {
parser.nextToken(); parser.nextToken();
ElasticsearchGeoAssertions.assertValidException(parser, expectedException); ElasticsearchGeoAssertions.assertValidException(parser, expectedException);
}
} }
protected void assertGeometryEquals(Shape expected, XContentBuilder geoJson) throws IOException { protected void assertGeometryEquals(Shape expected, XContentBuilder geoJson) throws IOException {
XContentParser parser = createParser(geoJson); try (XContentParser parser = createParser(geoJson)) {
parser.nextToken(); parser.nextToken();
ElasticsearchGeoAssertions.assertEquals(expected, ShapeParser.parse(parser).build()); ElasticsearchGeoAssertions.assertEquals(expected, ShapeParser.parse(parser).build());
}
} }
protected ShapeCollection<Shape> shapeCollection(Shape... shapes) { protected ShapeCollection<Shape> shapeCollection(Shape... shapes) {

View File

@ -193,18 +193,20 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.startArray().value(50).value(-39).endArray() .startArray().value(50).value(-39).endArray()
.endArray() .endArray()
.endObject(); .endObject();
XContentParser parser = createParser(multilinesGeoJson); try (XContentParser parser = createParser(multilinesGeoJson)) {
parser.nextToken(); parser.nextToken();
ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class); ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class);
}
// test #4: "envelope" with empty coordinates // test #4: "envelope" with empty coordinates
multilinesGeoJson = XContentFactory.jsonBuilder().startObject().field("type", "envelope") multilinesGeoJson = XContentFactory.jsonBuilder().startObject().field("type", "envelope")
.startArray("coordinates") .startArray("coordinates")
.endArray() .endArray()
.endObject(); .endObject();
parser = createParser(multilinesGeoJson); try (XContentParser parser = createParser(multilinesGeoJson)) {
parser.nextToken(); parser.nextToken();
ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class); ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class);
}
} }
@Override @Override
@ -266,9 +268,10 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
Polygon expected = GEOMETRY_FACTORY.createPolygon(shell, null); Polygon expected = GEOMETRY_FACTORY.createPolygon(shell, null);
Mapper.BuilderContext mockBuilderContext = new Mapper.BuilderContext(indexSettings, new ContentPath()); Mapper.BuilderContext mockBuilderContext = new Mapper.BuilderContext(indexSettings, new ContentPath());
final GeoShapeFieldMapper mapperBuilder = new GeoShapeFieldMapper.Builder("test").ignoreZValue(true).build(mockBuilderContext); final GeoShapeFieldMapper mapperBuilder = new GeoShapeFieldMapper.Builder("test").ignoreZValue(true).build(mockBuilderContext);
XContentParser parser = createParser(polygonGeoJson); try (XContentParser parser = createParser(polygonGeoJson)) {
parser.nextToken(); parser.nextToken();
ElasticsearchGeoAssertions.assertEquals(jtsGeom(expected), ShapeParser.parse(parser, mapperBuilder).build()); ElasticsearchGeoAssertions.assertEquals(jtsGeom(expected), ShapeParser.parse(parser, mapperBuilder).build());
}
} }
public void testInvalidDimensionalPolygon() throws IOException { public void testInvalidDimensionalPolygon() throws IOException {
@ -285,9 +288,10 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.endArray() .endArray()
.endArray() .endArray()
.endObject(); .endObject();
XContentParser parser = createParser(polygonGeoJson); try (XContentParser parser = createParser(polygonGeoJson)) {
parser.nextToken(); parser.nextToken();
ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class); ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class);
}
} }
public void testParseInvalidPoint() throws IOException { public void testParseInvalidPoint() throws IOException {
@ -299,9 +303,10 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.startArray().value(-74.011).value(40.753).endArray() .startArray().value(-74.011).value(40.753).endArray()
.endArray() .endArray()
.endObject(); .endObject();
XContentParser parser = createParser(invalidPoint1); try (XContentParser parser = createParser(invalidPoint1)) {
parser.nextToken(); parser.nextToken();
ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class); ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class);
}
// test case 2: create an invalid point object with an empty number of coordinates // test case 2: create an invalid point object with an empty number of coordinates
XContentBuilder invalidPoint2 = XContentFactory.jsonBuilder() XContentBuilder invalidPoint2 = XContentFactory.jsonBuilder()
@ -310,9 +315,10 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.startArray("coordinates") .startArray("coordinates")
.endArray() .endArray()
.endObject(); .endObject();
parser = createParser(invalidPoint2); try (XContentParser parser = createParser(invalidPoint2)) {
parser.nextToken(); parser.nextToken();
ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class); ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class);
}
} }
public void testParseInvalidMultipoint() throws IOException { public void testParseInvalidMultipoint() throws IOException {
@ -322,9 +328,10 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.field("type", "multipoint") .field("type", "multipoint")
.startArray("coordinates").value(-74.011).value(40.753).endArray() .startArray("coordinates").value(-74.011).value(40.753).endArray()
.endObject(); .endObject();
XContentParser parser = createParser(invalidMultipoint1); try (XContentParser parser = createParser(invalidMultipoint1)) {
parser.nextToken(); parser.nextToken();
ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class); ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class);
}
// test case 2: create an invalid multipoint object with null coordinate // test case 2: create an invalid multipoint object with null coordinate
XContentBuilder invalidMultipoint2 = XContentFactory.jsonBuilder() XContentBuilder invalidMultipoint2 = XContentFactory.jsonBuilder()
@ -333,9 +340,10 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.startArray("coordinates") .startArray("coordinates")
.endArray() .endArray()
.endObject(); .endObject();
parser = createParser(invalidMultipoint2); try (XContentParser parser = createParser(invalidMultipoint2)) {
parser.nextToken(); parser.nextToken();
ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class); ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class);
}
// test case 3: create a valid formatted multipoint object with invalid number (0) of coordinates // test case 3: create a valid formatted multipoint object with invalid number (0) of coordinates
XContentBuilder invalidMultipoint3 = XContentFactory.jsonBuilder() XContentBuilder invalidMultipoint3 = XContentFactory.jsonBuilder()
@ -345,9 +353,10 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.startArray().endArray() .startArray().endArray()
.endArray() .endArray()
.endObject(); .endObject();
parser = createParser(invalidMultipoint3); try (XContentParser parser = createParser(invalidMultipoint3)) {
parser.nextToken(); parser.nextToken();
ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class); ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class);
}
} }
public void testParseInvalidMultiPolygon() throws IOException { public void testParseInvalidMultiPolygon() throws IOException {
@ -380,9 +389,10 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.endArray() .endArray()
.endObject()); .endObject());
XContentParser parser = createParser(JsonXContent.jsonXContent, multiPolygonGeoJson); try (XContentParser parser = createParser(JsonXContent.jsonXContent, multiPolygonGeoJson)) {
parser.nextToken(); parser.nextToken();
ElasticsearchGeoAssertions.assertValidException(parser, InvalidShapeException.class); ElasticsearchGeoAssertions.assertValidException(parser, InvalidShapeException.class);
}
} }
public void testParseInvalidDimensionalMultiPolygon() throws IOException { public void testParseInvalidDimensionalMultiPolygon() throws IOException {
@ -419,9 +429,10 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.endArray() .endArray()
.endObject()); .endObject());
XContentParser parser = createParser(JsonXContent.jsonXContent, multiPolygonGeoJson); try (XContentParser parser = createParser(JsonXContent.jsonXContent, multiPolygonGeoJson)) {
parser.nextToken(); parser.nextToken();
ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class); ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class);
}
} }
@ -440,11 +451,12 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.endArray() .endArray()
.endObject()); .endObject());
XContentParser parser = createParser(JsonXContent.jsonXContent, polygonGeoJson); try (XContentParser parser = createParser(JsonXContent.jsonXContent, polygonGeoJson)) {
parser.nextToken(); parser.nextToken();
Shape shape = ShapeParser.parse(parser).build(); Shape shape = ShapeParser.parse(parser).build();
ElasticsearchGeoAssertions.assertPolygon(shape); ElasticsearchGeoAssertions.assertPolygon(shape);
}
// test 2: ccw poly crossing dateline // test 2: ccw poly crossing dateline
polygonGeoJson = Strings.toString(XContentFactory.jsonBuilder().startObject().field("type", "Polygon") polygonGeoJson = Strings.toString(XContentFactory.jsonBuilder().startObject().field("type", "Polygon")
@ -460,11 +472,12 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.endArray() .endArray()
.endObject()); .endObject());
parser = createParser(JsonXContent.jsonXContent, polygonGeoJson); try (XContentParser parser = createParser(JsonXContent.jsonXContent, polygonGeoJson)) {
parser.nextToken(); parser.nextToken();
shape = ShapeParser.parse(parser).build(); Shape shape = ShapeParser.parse(parser).build();
ElasticsearchGeoAssertions.assertMultiPolygon(shape); ElasticsearchGeoAssertions.assertMultiPolygon(shape);
}
// test 3: cw poly not crossing dateline // test 3: cw poly not crossing dateline
polygonGeoJson = Strings.toString(XContentFactory.jsonBuilder().startObject().field("type", "Polygon") polygonGeoJson = Strings.toString(XContentFactory.jsonBuilder().startObject().field("type", "Polygon")
@ -480,11 +493,12 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.endArray() .endArray()
.endObject()); .endObject());
parser = createParser(JsonXContent.jsonXContent, polygonGeoJson); try (XContentParser parser = createParser(JsonXContent.jsonXContent, polygonGeoJson)) {
parser.nextToken(); parser.nextToken();
shape = ShapeParser.parse(parser).build(); Shape shape = ShapeParser.parse(parser).build();
ElasticsearchGeoAssertions.assertPolygon(shape); ElasticsearchGeoAssertions.assertPolygon(shape);
}
// test 4: cw poly crossing dateline // test 4: cw poly crossing dateline
polygonGeoJson = Strings.toString(XContentFactory.jsonBuilder().startObject().field("type", "Polygon") polygonGeoJson = Strings.toString(XContentFactory.jsonBuilder().startObject().field("type", "Polygon")
@ -500,11 +514,12 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.endArray() .endArray()
.endObject()); .endObject());
parser = createParser(JsonXContent.jsonXContent, polygonGeoJson); try (XContentParser parser = createParser(JsonXContent.jsonXContent, polygonGeoJson)) {
parser.nextToken(); parser.nextToken();
shape = ShapeParser.parse(parser).build(); Shape shape = ShapeParser.parse(parser).build();
ElasticsearchGeoAssertions.assertMultiPolygon(shape); ElasticsearchGeoAssertions.assertMultiPolygon(shape);
}
} }
public void testParseOGCPolygonWithHoles() throws IOException { public void testParseOGCPolygonWithHoles() throws IOException {
@ -528,11 +543,12 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.endArray() .endArray()
.endObject()); .endObject());
XContentParser parser = createParser(JsonXContent.jsonXContent, polygonGeoJson); try (XContentParser parser = createParser(JsonXContent.jsonXContent, polygonGeoJson)) {
parser.nextToken(); parser.nextToken();
Shape shape = ShapeParser.parse(parser).build(); Shape shape = ShapeParser.parse(parser).build();
ElasticsearchGeoAssertions.assertPolygon(shape); ElasticsearchGeoAssertions.assertPolygon(shape);
}
// test 2: ccw poly crossing dateline // test 2: ccw poly crossing dateline
polygonGeoJson = Strings.toString(XContentFactory.jsonBuilder().startObject().field("type", "Polygon") polygonGeoJson = Strings.toString(XContentFactory.jsonBuilder().startObject().field("type", "Polygon")
@ -554,11 +570,12 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.endArray() .endArray()
.endObject()); .endObject());
parser = createParser(JsonXContent.jsonXContent, polygonGeoJson); try (XContentParser parser = createParser(JsonXContent.jsonXContent, polygonGeoJson)) {
parser.nextToken(); parser.nextToken();
shape = ShapeParser.parse(parser).build(); Shape shape = ShapeParser.parse(parser).build();
ElasticsearchGeoAssertions.assertMultiPolygon(shape); ElasticsearchGeoAssertions.assertMultiPolygon(shape);
}
// test 3: cw poly not crossing dateline // test 3: cw poly not crossing dateline
polygonGeoJson = Strings.toString(XContentFactory.jsonBuilder().startObject().field("type", "Polygon") polygonGeoJson = Strings.toString(XContentFactory.jsonBuilder().startObject().field("type", "Polygon")
@ -580,11 +597,13 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.endArray() .endArray()
.endObject()); .endObject());
parser = createParser(JsonXContent.jsonXContent, polygonGeoJson); try (XContentParser parser = createParser(JsonXContent.jsonXContent, polygonGeoJson)) {
parser.nextToken(); parser.nextToken();
shape = ShapeParser.parse(parser).build(); Shape shape = ShapeParser.parse(parser).build();
ElasticsearchGeoAssertions.assertPolygon(shape);
}
ElasticsearchGeoAssertions.assertPolygon(shape);
// test 4: cw poly crossing dateline // test 4: cw poly crossing dateline
polygonGeoJson = Strings.toString(XContentFactory.jsonBuilder().startObject().field("type", "Polygon") polygonGeoJson = Strings.toString(XContentFactory.jsonBuilder().startObject().field("type", "Polygon")
@ -606,11 +625,12 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.endArray() .endArray()
.endObject()); .endObject());
parser = createParser(JsonXContent.jsonXContent, polygonGeoJson); try (XContentParser parser = createParser(JsonXContent.jsonXContent, polygonGeoJson)) {
parser.nextToken(); parser.nextToken();
shape = ShapeParser.parse(parser).build(); Shape shape = ShapeParser.parse(parser).build();
ElasticsearchGeoAssertions.assertMultiPolygon(shape); ElasticsearchGeoAssertions.assertMultiPolygon(shape);
}
} }
public void testParseInvalidPolygon() throws IOException { public void testParseInvalidPolygon() throws IOException {
@ -627,9 +647,10 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.endArray() .endArray()
.endArray() .endArray()
.endObject()); .endObject());
XContentParser parser = createParser(JsonXContent.jsonXContent, invalidPoly); try (XContentParser parser = createParser(JsonXContent.jsonXContent, invalidPoly)) {
parser.nextToken(); parser.nextToken();
ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class); ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class);
}
// test case 2: create an invalid polygon with only 1 point // test case 2: create an invalid polygon with only 1 point
invalidPoly = Strings.toString(XContentFactory.jsonBuilder().startObject().field("type", "polygon") invalidPoly = Strings.toString(XContentFactory.jsonBuilder().startObject().field("type", "polygon")
@ -640,9 +661,10 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.endArray() .endArray()
.endObject()); .endObject());
parser = createParser(JsonXContent.jsonXContent, invalidPoly); try (XContentParser parser = createParser(JsonXContent.jsonXContent, invalidPoly)) {
parser.nextToken(); parser.nextToken();
ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class); ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class);
}
// test case 3: create an invalid polygon with 0 points // test case 3: create an invalid polygon with 0 points
invalidPoly = Strings.toString(XContentFactory.jsonBuilder().startObject().field("type", "polygon") invalidPoly = Strings.toString(XContentFactory.jsonBuilder().startObject().field("type", "polygon")
@ -653,9 +675,10 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.endArray() .endArray()
.endObject()); .endObject());
parser = createParser(JsonXContent.jsonXContent, invalidPoly); try (XContentParser parser = createParser(JsonXContent.jsonXContent, invalidPoly)) {
parser.nextToken(); parser.nextToken();
ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class); ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class);
}
// test case 4: create an invalid polygon with null value points // test case 4: create an invalid polygon with null value points
invalidPoly = Strings.toString(XContentFactory.jsonBuilder().startObject().field("type", "polygon") invalidPoly = Strings.toString(XContentFactory.jsonBuilder().startObject().field("type", "polygon")
@ -666,9 +689,10 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.endArray() .endArray()
.endObject()); .endObject());
parser = createParser(JsonXContent.jsonXContent, invalidPoly); try (XContentParser parser = createParser(JsonXContent.jsonXContent, invalidPoly)) {
parser.nextToken(); parser.nextToken();
ElasticsearchGeoAssertions.assertValidException(parser, IllegalArgumentException.class); ElasticsearchGeoAssertions.assertValidException(parser, IllegalArgumentException.class);
}
// test case 5: create an invalid polygon with 1 invalid LinearRing // test case 5: create an invalid polygon with 1 invalid LinearRing
invalidPoly = Strings.toString(XContentFactory.jsonBuilder().startObject().field("type", "polygon") invalidPoly = Strings.toString(XContentFactory.jsonBuilder().startObject().field("type", "polygon")
@ -677,18 +701,20 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.endArray() .endArray()
.endObject()); .endObject());
parser = createParser(JsonXContent.jsonXContent, invalidPoly); try (XContentParser parser = createParser(JsonXContent.jsonXContent, invalidPoly)) {
parser.nextToken(); parser.nextToken();
ElasticsearchGeoAssertions.assertValidException(parser, IllegalArgumentException.class); ElasticsearchGeoAssertions.assertValidException(parser, IllegalArgumentException.class);
}
// test case 6: create an invalid polygon with 0 LinearRings // test case 6: create an invalid polygon with 0 LinearRings
invalidPoly = Strings.toString(XContentFactory.jsonBuilder().startObject().field("type", "polygon") invalidPoly = Strings.toString(XContentFactory.jsonBuilder().startObject().field("type", "polygon")
.startArray("coordinates").endArray() .startArray("coordinates").endArray()
.endObject()); .endObject());
parser = createParser(JsonXContent.jsonXContent, invalidPoly); try (XContentParser parser = createParser(JsonXContent.jsonXContent, invalidPoly)) {
parser.nextToken(); parser.nextToken();
ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class); ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class);
}
// test case 7: create an invalid polygon with 0 LinearRings // test case 7: create an invalid polygon with 0 LinearRings
invalidPoly = Strings.toString(XContentFactory.jsonBuilder().startObject().field("type", "polygon") invalidPoly = Strings.toString(XContentFactory.jsonBuilder().startObject().field("type", "polygon")
@ -697,9 +723,10 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.endArray() .endArray()
.endObject()); .endObject());
parser = createParser(JsonXContent.jsonXContent, invalidPoly); try (XContentParser parser = createParser(JsonXContent.jsonXContent, invalidPoly)) {
parser.nextToken(); parser.nextToken();
ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class); ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class);
}
} }
public void testParsePolygonWithHole() throws IOException { public void testParsePolygonWithHole() throws IOException {
@ -764,9 +791,10 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.endArray() .endArray()
.endObject()); .endObject());
XContentParser parser = createParser(JsonXContent.jsonXContent, polygonGeoJson); try (XContentParser parser = createParser(JsonXContent.jsonXContent, polygonGeoJson)) {
parser.nextToken(); parser.nextToken();
ElasticsearchGeoAssertions.assertValidException(parser, InvalidShapeException.class); ElasticsearchGeoAssertions.assertValidException(parser, InvalidShapeException.class);
}
} }
@Override @Override
@ -980,11 +1008,12 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.endArray() .endArray()
.endObject(); .endObject();
XContentParser parser = createParser(polygonGeoJson); try (XContentParser parser = createParser(polygonGeoJson)) {
parser.nextToken(); parser.nextToken();
Shape shape = ShapeParser.parse(parser).build(); Shape shape = ShapeParser.parse(parser).build();
ElasticsearchGeoAssertions.assertPolygon(shape); ElasticsearchGeoAssertions.assertPolygon(shape);
}
// test 2: valid ccw (right handed system) poly not crossing dateline (with 'ccw' field) // test 2: valid ccw (right handed system) poly not crossing dateline (with 'ccw' field)
polygonGeoJson = XContentFactory.jsonBuilder() polygonGeoJson = XContentFactory.jsonBuilder()
@ -1009,11 +1038,12 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.endArray() .endArray()
.endObject(); .endObject();
parser = createParser(polygonGeoJson); try (XContentParser parser = createParser(polygonGeoJson)) {
parser.nextToken(); parser.nextToken();
shape = ShapeParser.parse(parser).build(); Shape shape = ShapeParser.parse(parser).build();
ElasticsearchGeoAssertions.assertPolygon(shape); ElasticsearchGeoAssertions.assertPolygon(shape);
}
// test 3: valid ccw (right handed system) poly not crossing dateline (with 'counterclockwise' field) // test 3: valid ccw (right handed system) poly not crossing dateline (with 'counterclockwise' field)
polygonGeoJson = XContentFactory.jsonBuilder() polygonGeoJson = XContentFactory.jsonBuilder()
@ -1038,11 +1068,12 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.endArray() .endArray()
.endObject(); .endObject();
parser = createParser(polygonGeoJson); try (XContentParser parser = createParser(polygonGeoJson)) {
parser.nextToken(); parser.nextToken();
shape = ShapeParser.parse(parser).build(); Shape shape = ShapeParser.parse(parser).build();
ElasticsearchGeoAssertions.assertPolygon(shape); ElasticsearchGeoAssertions.assertPolygon(shape);
}
// test 4: valid cw (left handed system) poly crossing dateline (with 'left' field) // test 4: valid cw (left handed system) poly crossing dateline (with 'left' field)
polygonGeoJson = XContentFactory.jsonBuilder() polygonGeoJson = XContentFactory.jsonBuilder()
@ -1067,11 +1098,12 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.endArray() .endArray()
.endObject(); .endObject();
parser = createParser(polygonGeoJson); try (XContentParser parser = createParser(polygonGeoJson)) {
parser.nextToken(); parser.nextToken();
shape = ShapeParser.parse(parser).build(); Shape shape = ShapeParser.parse(parser).build();
ElasticsearchGeoAssertions.assertMultiPolygon(shape); ElasticsearchGeoAssertions.assertMultiPolygon(shape);
}
// test 5: valid cw multipoly (left handed system) poly crossing dateline (with 'cw' field) // test 5: valid cw multipoly (left handed system) poly crossing dateline (with 'cw' field)
polygonGeoJson = XContentFactory.jsonBuilder() polygonGeoJson = XContentFactory.jsonBuilder()
@ -1096,11 +1128,12 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.endArray() .endArray()
.endObject(); .endObject();
parser = createParser(polygonGeoJson); try (XContentParser parser = createParser(polygonGeoJson)) {
parser.nextToken(); parser.nextToken();
shape = ShapeParser.parse(parser).build(); Shape shape = ShapeParser.parse(parser).build();
ElasticsearchGeoAssertions.assertMultiPolygon(shape); ElasticsearchGeoAssertions.assertMultiPolygon(shape);
}
// test 6: valid cw multipoly (left handed system) poly crossing dateline (with 'clockwise' field) // test 6: valid cw multipoly (left handed system) poly crossing dateline (with 'clockwise' field)
polygonGeoJson = XContentFactory.jsonBuilder() polygonGeoJson = XContentFactory.jsonBuilder()
@ -1125,10 +1158,11 @@ public class GeoJsonShapeParserTests extends BaseGeoParsingTestCase {
.endArray() .endArray()
.endObject(); .endObject();
parser = createParser(polygonGeoJson); try (XContentParser parser = createParser(polygonGeoJson)) {
parser.nextToken(); parser.nextToken();
shape = ShapeParser.parse(parser).build(); Shape shape = ShapeParser.parse(parser).build();
ElasticsearchGeoAssertions.assertMultiPolygon(shape); ElasticsearchGeoAssertions.assertMultiPolygon(shape);
}
} }
} }

View File

@ -59,13 +59,14 @@ public class GeoUtilTests extends ESTestCase {
XContentBuilder builder = jsonBuilder().startObject(); XContentBuilder builder = jsonBuilder().startObject();
tokenGenerator.accept(builder); tokenGenerator.accept(builder);
builder.endObject(); builder.endObject();
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder))) {
assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); // { assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); // {
assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); // field name assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); // field name
assertTrue(parser.nextToken().isValue()); // field value assertTrue(parser.nextToken().isValue()); // field value
int precision = GeoUtils.parsePrecision(parser); int precision = GeoUtils.parsePrecision(parser);
assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken()); // } assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken()); // }
assertNull(parser.nextToken()); // no more tokens assertNull(parser.nextToken()); // no more tokens
return precision; return precision;
}
} }
} }

View File

@ -79,12 +79,13 @@ public abstract class AbstractShapeBuilderTestCase<SB extends ShapeBuilder> exte
} }
XContentBuilder builder = testShape.toXContent(contentBuilder, ToXContent.EMPTY_PARAMS); XContentBuilder builder = testShape.toXContent(contentBuilder, ToXContent.EMPTY_PARAMS);
XContentBuilder shuffled = shuffleXContent(builder); XContentBuilder shuffled = shuffleXContent(builder);
XContentParser shapeContentParser = createParser(shuffled); try (XContentParser shapeContentParser = createParser(shuffled)) {
shapeContentParser.nextToken(); shapeContentParser.nextToken();
ShapeBuilder parsedShape = ShapeParser.parse(shapeContentParser); ShapeBuilder parsedShape = ShapeParser.parse(shapeContentParser);
assertNotSame(testShape, parsedShape); assertNotSame(testShape, parsedShape);
assertEquals(testShape, parsedShape); assertEquals(testShape, parsedShape);
assertEquals(testShape.hashCode(), parsedShape.hashCode()); assertEquals(testShape.hashCode(), parsedShape.hashCode());
}
} }
} }

View File

@ -45,13 +45,14 @@ public class FuzzinessTests extends ESTestCase {
XContentBuilder json = jsonBuilder().startObject() XContentBuilder json = jsonBuilder().startObject()
.field(Fuzziness.X_FIELD_NAME, floatValue) .field(Fuzziness.X_FIELD_NAME, floatValue)
.endObject(); .endObject();
XContentParser parser = createParser(json); try (XContentParser parser = createParser(json)) {
assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT)); assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.VALUE_NUMBER)); assertThat(parser.nextToken(), equalTo(XContentParser.Token.VALUE_NUMBER));
Fuzziness fuzziness = Fuzziness.parse(parser); Fuzziness fuzziness = Fuzziness.parse(parser);
assertThat(fuzziness.asFloat(), equalTo(floatValue)); assertThat(fuzziness.asFloat(), equalTo(floatValue));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.END_OBJECT)); assertThat(parser.nextToken(), equalTo(XContentParser.Token.END_OBJECT));
}
} }
{ {
Integer intValue = frequently() ? randomIntBetween(0, 2) : randomIntBetween(0, 100); Integer intValue = frequently() ? randomIntBetween(0, 2) : randomIntBetween(0, 100);
@ -63,28 +64,29 @@ public class FuzzinessTests extends ESTestCase {
XContentBuilder json = jsonBuilder().startObject() XContentBuilder json = jsonBuilder().startObject()
.field(Fuzziness.X_FIELD_NAME, randomBoolean() ? value.toString() : value) .field(Fuzziness.X_FIELD_NAME, randomBoolean() ? value.toString() : value)
.endObject(); .endObject();
XContentParser parser = createParser(json); try (XContentParser parser = createParser(json)) {
assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT)); assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME));
assertThat(parser.nextToken(), anyOf(equalTo(XContentParser.Token.VALUE_NUMBER), equalTo(XContentParser.Token.VALUE_STRING))); assertThat(parser.nextToken(), anyOf(equalTo(XContentParser.Token.VALUE_NUMBER), equalTo(XContentParser.Token.VALUE_STRING)));
Fuzziness fuzziness = Fuzziness.parse(parser); Fuzziness fuzziness = Fuzziness.parse(parser);
if (value.intValue() >= 1) { if (value.intValue() >= 1) {
assertThat(fuzziness.asDistance(), equalTo(Math.min(2, value.intValue()))); assertThat(fuzziness.asDistance(), equalTo(Math.min(2, value.intValue())));
} }
assertThat(parser.nextToken(), equalTo(XContentParser.Token.END_OBJECT)); assertThat(parser.nextToken(), equalTo(XContentParser.Token.END_OBJECT));
if (intValue.equals(value)) { if (intValue.equals(value)) {
switch (intValue) { switch (intValue) {
case 1: case 1:
assertThat(fuzziness, sameInstance(Fuzziness.ONE)); assertThat(fuzziness, sameInstance(Fuzziness.ONE));
break; break;
case 2: case 2:
assertThat(fuzziness, sameInstance(Fuzziness.TWO)); assertThat(fuzziness, sameInstance(Fuzziness.TWO));
break; break;
case 0: case 0:
assertThat(fuzziness, sameInstance(Fuzziness.ZERO)); assertThat(fuzziness, sameInstance(Fuzziness.ZERO));
break; break;
default: default:
break; break;
}
} }
} }
} }
@ -102,15 +104,16 @@ public class FuzzinessTests extends ESTestCase {
.field(Fuzziness.X_FIELD_NAME, auto) .field(Fuzziness.X_FIELD_NAME, auto)
.endObject(); .endObject();
} }
XContentParser parser = createParser(json); try (XContentParser parser = createParser(json)) {
assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT)); assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.VALUE_STRING)); assertThat(parser.nextToken(), equalTo(XContentParser.Token.VALUE_STRING));
Fuzziness fuzziness = Fuzziness.parse(parser); Fuzziness fuzziness = Fuzziness.parse(parser);
if (isDefaultAutoFuzzinessTested) { if (isDefaultAutoFuzzinessTested) {
assertThat(fuzziness, sameInstance(Fuzziness.AUTO)); assertThat(fuzziness, sameInstance(Fuzziness.AUTO));
}
assertThat(parser.nextToken(), equalTo(XContentParser.Token.END_OBJECT));
} }
assertThat(parser.nextToken(), equalTo(XContentParser.Token.END_OBJECT));
} }
} }
@ -152,15 +155,16 @@ public class FuzzinessTests extends ESTestCase {
.field(Fuzziness.X_FIELD_NAME, auto) .field(Fuzziness.X_FIELD_NAME, auto)
.endObject(); .endObject();
XContentParser parser = createParser(json); try (XContentParser parser = createParser(json)) {
assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT)); assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.VALUE_STRING)); assertThat(parser.nextToken(), equalTo(XContentParser.Token.VALUE_STRING));
Fuzziness fuzziness = Fuzziness.parse(parser); Fuzziness fuzziness = Fuzziness.parse(parser);
Fuzziness deserializedFuzziness = doSerializeRoundtrip(fuzziness); Fuzziness deserializedFuzziness = doSerializeRoundtrip(fuzziness);
assertEquals(fuzziness, deserializedFuzziness); assertEquals(fuzziness, deserializedFuzziness);
assertEquals(fuzziness.asString(), deserializedFuzziness.asString()); assertEquals(fuzziness.asString(), deserializedFuzziness.asString());
}
} }
private static Fuzziness doSerializeRoundtrip(Fuzziness in) throws IOException { private static Fuzziness doSerializeRoundtrip(Fuzziness in) throws IOException {

View File

@ -274,14 +274,15 @@ public abstract class BaseXContentTestCase extends ESTestCase {
final byte[] randomBytes = randomBytes(); final byte[] randomBytes = randomBytes();
BytesReference bytes = BytesReference.bytes(builder().startObject().field("binary", randomBytes).endObject()); BytesReference bytes = BytesReference.bytes(builder().startObject().field("binary", randomBytes).endObject());
XContentParser parser = createParser(xcontentType().xContent(), bytes); try (XContentParser parser = createParser(xcontentType().xContent(), bytes)) {
assertSame(parser.nextToken(), Token.START_OBJECT); assertSame(parser.nextToken(), Token.START_OBJECT);
assertSame(parser.nextToken(), Token.FIELD_NAME); assertSame(parser.nextToken(), Token.FIELD_NAME);
assertEquals(parser.currentName(), "binary"); assertEquals(parser.currentName(), "binary");
assertTrue(parser.nextToken().isValue()); assertTrue(parser.nextToken().isValue());
assertArrayEquals(randomBytes, parser.binaryValue()); assertArrayEquals(randomBytes, parser.binaryValue());
assertSame(parser.nextToken(), Token.END_OBJECT); assertSame(parser.nextToken(), Token.END_OBJECT);
assertNull(parser.nextToken()); assertNull(parser.nextToken());
}
} }
public void testBinaryValue() throws Exception { public void testBinaryValue() throws Exception {
@ -290,14 +291,15 @@ public abstract class BaseXContentTestCase extends ESTestCase {
final byte[] randomBytes = randomBytes(); final byte[] randomBytes = randomBytes();
BytesReference bytes = BytesReference.bytes(builder().startObject().field("binary").value(randomBytes).endObject()); BytesReference bytes = BytesReference.bytes(builder().startObject().field("binary").value(randomBytes).endObject());
XContentParser parser = createParser(xcontentType().xContent(), bytes); try (XContentParser parser = createParser(xcontentType().xContent(), bytes)) {
assertSame(parser.nextToken(), Token.START_OBJECT); assertSame(parser.nextToken(), Token.START_OBJECT);
assertSame(parser.nextToken(), Token.FIELD_NAME); assertSame(parser.nextToken(), Token.FIELD_NAME);
assertEquals(parser.currentName(), "binary"); assertEquals(parser.currentName(), "binary");
assertTrue(parser.nextToken().isValue()); assertTrue(parser.nextToken().isValue());
assertArrayEquals(randomBytes, parser.binaryValue()); assertArrayEquals(randomBytes, parser.binaryValue());
assertSame(parser.nextToken(), Token.END_OBJECT); assertSame(parser.nextToken(), Token.END_OBJECT);
assertNull(parser.nextToken()); assertNull(parser.nextToken());
}
} }
public void testBinaryValueWithOffsetLength() throws Exception { public void testBinaryValueWithOffsetLength() throws Exception {
@ -315,14 +317,15 @@ public abstract class BaseXContentTestCase extends ESTestCase {
} }
builder.endObject(); builder.endObject();
XContentParser parser = createParser(xcontentType().xContent(), BytesReference.bytes(builder)); try (XContentParser parser = createParser(xcontentType().xContent(), BytesReference.bytes(builder))) {
assertSame(parser.nextToken(), Token.START_OBJECT); assertSame(parser.nextToken(), Token.START_OBJECT);
assertSame(parser.nextToken(), Token.FIELD_NAME); assertSame(parser.nextToken(), Token.FIELD_NAME);
assertEquals(parser.currentName(), "bin"); assertEquals(parser.currentName(), "bin");
assertTrue(parser.nextToken().isValue()); assertTrue(parser.nextToken().isValue());
assertArrayEquals(Arrays.copyOfRange(randomBytes, offset, offset + length), parser.binaryValue()); assertArrayEquals(Arrays.copyOfRange(randomBytes, offset, offset + length), parser.binaryValue());
assertSame(parser.nextToken(), Token.END_OBJECT); assertSame(parser.nextToken(), Token.END_OBJECT);
assertNull(parser.nextToken()); assertNull(parser.nextToken());
}
} }
public void testBinaryUTF8() throws Exception { public void testBinaryUTF8() throws Exception {
@ -333,14 +336,15 @@ public abstract class BaseXContentTestCase extends ESTestCase {
builder.field("utf8").utf8Value(randomBytesRef.bytes, randomBytesRef.offset, randomBytesRef.length); builder.field("utf8").utf8Value(randomBytesRef.bytes, randomBytesRef.offset, randomBytesRef.length);
builder.endObject(); builder.endObject();
XContentParser parser = createParser(xcontentType().xContent(), BytesReference.bytes(builder)); try (XContentParser parser = createParser(xcontentType().xContent(), BytesReference.bytes(builder))) {
assertSame(parser.nextToken(), Token.START_OBJECT); assertSame(parser.nextToken(), Token.START_OBJECT);
assertSame(parser.nextToken(), Token.FIELD_NAME); assertSame(parser.nextToken(), Token.FIELD_NAME);
assertEquals(parser.currentName(), "utf8"); assertEquals(parser.currentName(), "utf8");
assertTrue(parser.nextToken().isValue()); assertTrue(parser.nextToken().isValue());
assertThat(new BytesRef(parser.charBuffer()).utf8ToString(), equalTo(randomBytesRef.utf8ToString())); assertThat(new BytesRef(parser.charBuffer()).utf8ToString(), equalTo(randomBytesRef.utf8ToString()));
assertSame(parser.nextToken(), Token.END_OBJECT); assertSame(parser.nextToken(), Token.END_OBJECT);
assertNull(parser.nextToken()); assertNull(parser.nextToken());
}
} }
public void testText() throws Exception { public void testText() throws Exception {
@ -351,14 +355,15 @@ public abstract class BaseXContentTestCase extends ESTestCase {
final BytesReference random = new BytesArray(randomBytes()); final BytesReference random = new BytesArray(randomBytes());
XContentBuilder builder = builder().startObject().field("text", new Text(random)).endObject(); XContentBuilder builder = builder().startObject().field("text", new Text(random)).endObject();
XContentParser parser = createParser(xcontentType().xContent(), BytesReference.bytes(builder)); try (XContentParser parser = createParser(xcontentType().xContent(), BytesReference.bytes(builder))) {
assertSame(parser.nextToken(), Token.START_OBJECT); assertSame(parser.nextToken(), Token.START_OBJECT);
assertSame(parser.nextToken(), Token.FIELD_NAME); assertSame(parser.nextToken(), Token.FIELD_NAME);
assertEquals(parser.currentName(), "text"); assertEquals(parser.currentName(), "text");
assertTrue(parser.nextToken().isValue()); assertTrue(parser.nextToken().isValue());
assertThat(new BytesRef(parser.charBuffer()).utf8ToString(), equalTo(random.utf8ToString())); assertThat(new BytesRef(parser.charBuffer()).utf8ToString(), equalTo(random.utf8ToString()));
assertSame(parser.nextToken(), Token.END_OBJECT); assertSame(parser.nextToken(), Token.END_OBJECT);
assertNull(parser.nextToken()); assertNull(parser.nextToken());
}
} }
public void testReadableInstant() throws Exception { public void testReadableInstant() throws Exception {
@ -741,18 +746,19 @@ public abstract class BaseXContentTestCase extends ESTestCase {
generator.writeEndObject(); generator.writeEndObject();
} }
XContentParser parser = xcontentType().xContent() try (XContentParser parser = xcontentType().xContent()
.createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, os.toByteArray()); .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, os.toByteArray())) {
assertEquals(Token.START_OBJECT, parser.nextToken()); assertEquals(Token.START_OBJECT, parser.nextToken());
assertEquals(Token.FIELD_NAME, parser.nextToken()); assertEquals(Token.FIELD_NAME, parser.nextToken());
assertEquals("bar", parser.currentName()); assertEquals("bar", parser.currentName());
assertEquals(Token.START_OBJECT, parser.nextToken()); assertEquals(Token.START_OBJECT, parser.nextToken());
assertEquals(Token.FIELD_NAME, parser.nextToken()); assertEquals(Token.FIELD_NAME, parser.nextToken());
assertEquals("foo", parser.currentName()); assertEquals("foo", parser.currentName());
assertEquals(Token.VALUE_NULL, parser.nextToken()); assertEquals(Token.VALUE_NULL, parser.nextToken());
assertEquals(Token.END_OBJECT, parser.nextToken()); assertEquals(Token.END_OBJECT, parser.nextToken());
assertEquals(Token.END_OBJECT, parser.nextToken()); assertEquals(Token.END_OBJECT, parser.nextToken());
assertNull(parser.nextToken()); assertNull(parser.nextToken());
}
} }
public void testRawValue() throws Exception { public void testRawValue() throws Exception {
@ -776,14 +782,15 @@ public abstract class BaseXContentTestCase extends ESTestCase {
generator.writeRawValue(new BytesArray(rawData).streamInput(), source.type()); generator.writeRawValue(new BytesArray(rawData).streamInput(), source.type());
} }
XContentParser parser = xcontentType().xContent() try (XContentParser parser = xcontentType().xContent()
.createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, os.toByteArray()); .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, os.toByteArray())) {
assertEquals(Token.START_OBJECT, parser.nextToken()); assertEquals(Token.START_OBJECT, parser.nextToken());
assertEquals(Token.FIELD_NAME, parser.nextToken()); assertEquals(Token.FIELD_NAME, parser.nextToken());
assertEquals("foo", parser.currentName()); assertEquals("foo", parser.currentName());
assertEquals(Token.VALUE_NULL, parser.nextToken()); assertEquals(Token.VALUE_NULL, parser.nextToken());
assertEquals(Token.END_OBJECT, parser.nextToken()); assertEquals(Token.END_OBJECT, parser.nextToken());
assertNull(parser.nextToken()); assertNull(parser.nextToken());
}
os = new ByteArrayOutputStream(); os = new ByteArrayOutputStream();
try (XContentGenerator generator = xcontentType().xContent().createGenerator(os)) { try (XContentGenerator generator = xcontentType().xContent().createGenerator(os)) {
@ -793,18 +800,19 @@ public abstract class BaseXContentTestCase extends ESTestCase {
generator.writeEndObject(); generator.writeEndObject();
} }
parser = xcontentType().xContent() try (XContentParser parser = xcontentType().xContent()
.createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, os.toByteArray()); .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, os.toByteArray())) {
assertEquals(Token.START_OBJECT, parser.nextToken()); assertEquals(Token.START_OBJECT, parser.nextToken());
assertEquals(Token.FIELD_NAME, parser.nextToken()); assertEquals(Token.FIELD_NAME, parser.nextToken());
assertEquals("test", parser.currentName()); assertEquals("test", parser.currentName());
assertEquals(Token.START_OBJECT, parser.nextToken()); assertEquals(Token.START_OBJECT, parser.nextToken());
assertEquals(Token.FIELD_NAME, parser.nextToken()); assertEquals(Token.FIELD_NAME, parser.nextToken());
assertEquals("foo", parser.currentName()); assertEquals("foo", parser.currentName());
assertEquals(Token.VALUE_NULL, parser.nextToken()); assertEquals(Token.VALUE_NULL, parser.nextToken());
assertEquals(Token.END_OBJECT, parser.nextToken()); assertEquals(Token.END_OBJECT, parser.nextToken());
assertEquals(Token.END_OBJECT, parser.nextToken()); assertEquals(Token.END_OBJECT, parser.nextToken());
assertNull(parser.nextToken()); assertNull(parser.nextToken());
}
} }
@ -822,11 +830,12 @@ public abstract class BaseXContentTestCase extends ESTestCase {
generator.flush(); generator.flush();
byte[] serialized = os.toByteArray(); byte[] serialized = os.toByteArray();
XContentParser parser = xcontentType().xContent() try (XContentParser parser = xcontentType().xContent()
.createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, serialized); .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, serialized)) {
Map<String, Object> map = parser.map(); Map<String, Object> map = parser.map();
assertEquals("bar", map.get("foo")); assertEquals("bar", map.get("foo"));
assertEquals(bigInteger, map.get("bigint")); assertEquals(bigInteger, map.get("bigint"));
}
} }
public void testEnsureNameNotNull() { public void testEnsureNameNotNull() {
@ -984,44 +993,46 @@ public abstract class BaseXContentTestCase extends ESTestCase {
.field("key", 1) .field("key", 1)
.field("key", 2) .field("key", 2)
.endObject(); .endObject();
try (XContentParser xParser = createParser(builder)) {
JsonParseException pex = expectThrows(JsonParseException.class, () -> createParser(builder).map()); JsonParseException pex = expectThrows(JsonParseException.class, () -> xParser.map());
assertThat(pex.getMessage(), startsWith("Duplicate field 'key'")); assertThat(pex.getMessage(), startsWith("Duplicate field 'key'"));
}
} }
public void testNamedObject() throws IOException { public void testNamedObject() throws IOException {
Object test1 = new Object(); Object test1 = new Object();
Object test2 = new Object(); Object test2 = new Object();
NamedXContentRegistry registry = new NamedXContentRegistry(Arrays.asList( NamedXContentRegistry registry = new NamedXContentRegistry(Arrays.asList(
new NamedXContentRegistry.Entry(Object.class, new ParseField("test1"), p -> test1), 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("test2", "deprecated"), p -> test2),
new NamedXContentRegistry.Entry(Object.class, new ParseField("str"), p -> p.text()))); new NamedXContentRegistry.Entry(Object.class, new ParseField("str"), p -> p.text())));
XContentBuilder b = XContentBuilder.builder(xcontentType().xContent()); XContentBuilder b = XContentBuilder.builder(xcontentType().xContent());
b.value("test"); b.value("test");
XContentParser p = xcontentType().xContent().createParser(registry, LoggingDeprecationHandler.INSTANCE, try (XContentParser p = xcontentType().xContent().createParser(registry, LoggingDeprecationHandler.INSTANCE,
BytesReference.bytes(b).streamInput()); BytesReference.bytes(b).streamInput())) {
assertEquals(test1, p.namedObject(Object.class, "test1", null)); assertEquals(test1, p.namedObject(Object.class, "test1", null));
assertEquals(test2, p.namedObject(Object.class, "test2", null)); assertEquals(test2, p.namedObject(Object.class, "test2", null));
assertEquals(test2, p.namedObject(Object.class, "deprecated", null)); assertEquals(test2, p.namedObject(Object.class, "deprecated", null));
assertWarnings("Deprecated field [deprecated] used, expected [test2] instead"); assertWarnings("Deprecated field [deprecated] used, expected [test2] instead");
{
p.nextToken(); p.nextToken();
assertEquals("test", p.namedObject(Object.class, "str", null)); assertEquals("test", p.namedObject(Object.class, "str", null));
NamedObjectNotFoundException e = expectThrows(NamedObjectNotFoundException.class, {
NamedObjectNotFoundException e = expectThrows(NamedObjectNotFoundException.class,
() -> p.namedObject(Object.class, "unknown", null)); () -> p.namedObject(Object.class, "unknown", null));
assertThat(e.getMessage(), endsWith("unable to parse Object with name [unknown]: parser not found")); assertThat(e.getMessage(), endsWith("unable to parse Object with name [unknown]: parser not found"));
}
{
Exception e = expectThrows(NamedObjectNotFoundException.class, () -> p.namedObject(String.class, "doesn't matter", null));
assertEquals("unknown named object category [java.lang.String]", e.getMessage());
}
} }
{ try (XContentParser emptyRegistryParser = xcontentType().xContent()
Exception e = expectThrows(NamedObjectNotFoundException.class, () -> p.namedObject(String.class, "doesn't matter", null)); .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, new byte[] {})) {
assertEquals("unknown named object category [java.lang.String]", e.getMessage());
}
{
XContentParser emptyRegistryParser = xcontentType().xContent()
.createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, new byte[] {});
Exception e = expectThrows(NamedObjectNotFoundException.class, Exception e = expectThrows(NamedObjectNotFoundException.class,
() -> emptyRegistryParser.namedObject(String.class, "doesn't matter", null)); () -> emptyRegistryParser.namedObject(String.class, "doesn't matter", null));
assertEquals("named objects are not supported for this parser", e.getMessage()); assertEquals("named objects are not supported for this parser", e.getMessage());
} }
} }
private static void expectUnclosedException(ThrowingRunnable runnable) { private static void expectUnclosedException(ThrowingRunnable runnable) {

View File

@ -216,43 +216,44 @@ public class XContentBuilderTests extends ESTestCase {
} }
builder.field("fakefield", terms).endObject().endObject().endObject(); builder.field("fakefield", terms).endObject().endObject().endObject();
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder));
XContentBuilder filterBuilder = null; XContentBuilder filterBuilder = null;
XContentParser.Token token; XContentParser.Token token;
String currentFieldName = null;
assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder))) {
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) { String currentFieldName = null;
currentFieldName = parser.currentName(); assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT));
} else if (token.isValue()) { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if ("test".equals(currentFieldName)) { if (token == XContentParser.Token.FIELD_NAME) {
assertThat(parser.text(), equalTo("test field")); currentFieldName = parser.currentName();
} } else if (token.isValue()) {
} else if (token == XContentParser.Token.START_OBJECT) { if ("test".equals(currentFieldName)) {
if ("filter".equals(currentFieldName)) { assertThat(parser.text(), equalTo("test field"));
filterBuilder = XContentFactory.contentBuilder(parser.contentType()); }
filterBuilder.copyCurrentStructure(parser); } else if (token == XContentParser.Token.START_OBJECT) {
if ("filter".equals(currentFieldName)) {
filterBuilder = XContentFactory.contentBuilder(parser.contentType());
filterBuilder.copyCurrentStructure(parser);
}
} }
} }
} }
assertNotNull(filterBuilder); assertNotNull(filterBuilder);
parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(filterBuilder)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(filterBuilder))) {
assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT)); assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME));
assertThat(parser.currentName(), equalTo("terms")); assertThat(parser.currentName(), equalTo("terms"));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT)); assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME));
assertThat(parser.currentName(), equalTo("fakefield")); assertThat(parser.currentName(), equalTo("fakefield"));
assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_ARRAY)); assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_ARRAY));
int i = 0; int i = 0;
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
assertThat(parser.text(), equalTo(terms.get(i++))); assertThat(parser.text(), equalTo(terms.get(i++)));
} }
assertThat(i, equalTo(terms.size())); assertThat(i, equalTo(terms.size()));
}
} }
public void testHandlingOfPath() throws IOException { public void testHandlingOfPath() throws IOException {

View File

@ -33,9 +33,10 @@ public class CborXContentParserTests extends ESTestCase {
for (int i = 0; i < 2; i++) { for (int i = 0; i < 2; i++) {
// Running this part twice triggers the issue. // Running this part twice triggers the issue.
// See https://github.com/elastic/elasticsearch/issues/8629 // See https://github.com/elastic/elasticsearch/issues/8629
XContentParser parser = createParser(CborXContent.cborXContent, ref); try (XContentParser parser = createParser(CborXContent.cborXContent, ref)) {
while (parser.nextToken() != null) { while (parser.nextToken() != null) {
parser.charBuffer(); parser.charBuffer();
}
} }
} }
} }

View File

@ -62,8 +62,10 @@ public class JsonVsCborTests extends ESTestCase {
xsonGen.close(); xsonGen.close();
jsonGen.close(); jsonGen.close();
try (XContentParser json0sParser = createParser(JsonXContent.jsonXContent, jsonOs.bytes());
verifySameTokens(createParser(JsonXContent.jsonXContent, jsonOs.bytes()), createParser(CborXContent.cborXContent, xsonOs.bytes())); XContentParser xson0sParser = createParser(CborXContent.cborXContent, xsonOs.bytes())) {
verifySameTokens(json0sParser, xson0sParser);
}
} }
private void verifySameTokens(XContentParser parser1, XContentParser parser2) throws IOException { private void verifySameTokens(XContentParser parser1, XContentParser parser2) throws IOException {

View File

@ -63,8 +63,10 @@ public class JsonVsSmileTests extends ESTestCase {
xsonGen.close(); xsonGen.close();
jsonGen.close(); jsonGen.close();
verifySameTokens(createParser(JsonXContent.jsonXContent, jsonOs.bytes()), try (XContentParser jsonParser = createParser(JsonXContent.jsonXContent, jsonOs.bytes());
createParser(SmileXContent.smileXContent, xsonOs.bytes())); XContentParser smileParser = createParser(SmileXContent.smileXContent, xsonOs.bytes())) {
verifySameTokens(jsonParser, smileParser);
}
} }
private void verifySameTokens(XContentParser parser1, XContentParser parser2) throws IOException { private void verifySameTokens(XContentParser parser1, XContentParser parser2) throws IOException {

View File

@ -75,15 +75,15 @@ public abstract class AbstractXContentFilteringTestCase extends AbstractFilterin
} }
static void assertXContentBuilderAsBytes(final XContentBuilder expected, final XContentBuilder actual) { static void assertXContentBuilderAsBytes(final XContentBuilder expected, final XContentBuilder actual) {
try { XContent xContent = XContentFactory.xContent(actual.contentType());
XContent xContent = XContentFactory.xContent(actual.contentType()); try (
XContentParser jsonParser = XContentParser jsonParser =
xContent.createParser(NamedXContentRegistry.EMPTY, xContent.createParser(NamedXContentRegistry.EMPTY,
DeprecationHandler.THROW_UNSUPPORTED_OPERATION, BytesReference.bytes(expected).streamInput()); DeprecationHandler.THROW_UNSUPPORTED_OPERATION, BytesReference.bytes(expected).streamInput());
XContentParser testParser = XContentParser testParser =
xContent.createParser(NamedXContentRegistry.EMPTY, xContent.createParser(NamedXContentRegistry.EMPTY,
DeprecationHandler.THROW_UNSUPPORTED_OPERATION, BytesReference.bytes(actual).streamInput()); DeprecationHandler.THROW_UNSUPPORTED_OPERATION, BytesReference.bytes(actual).streamInput());
) {
while (true) { while (true) {
XContentParser.Token token1 = jsonParser.nextToken(); XContentParser.Token token1 = jsonParser.nextToken();
XContentParser.Token token2 = testParser.nextToken(); XContentParser.Token token2 = testParser.nextToken();

View File

@ -56,9 +56,10 @@ public class IndexTests extends ESTestCase {
final Index original = new Index(name, uuid); final Index original = new Index(name, uuid);
final XContentBuilder builder = JsonXContent.contentBuilder(); final XContentBuilder builder = JsonXContent.contentBuilder();
original.toXContent(builder, ToXContent.EMPTY_PARAMS); original.toXContent(builder, ToXContent.EMPTY_PARAMS);
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder))) {
parser.nextToken(); // the beginning of the parser parser.nextToken(); // the beginning of the parser
assertThat(Index.fromXContent(parser), equalTo(original)); assertThat(Index.fromXContent(parser), equalTo(original));
}
} }
public void testEquals() { public void testEquals() {

View File

@ -28,6 +28,7 @@ import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.xcontent.XContent; import org.elasticsearch.common.xcontent.XContent;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.search.internal.SearchContext; import org.elasticsearch.search.internal.SearchContext;
import org.elasticsearch.test.AbstractQueryTestCase; import org.elasticsearch.test.AbstractQueryTestCase;
@ -169,8 +170,10 @@ public class BoolQueryBuilderTests extends AbstractQueryTestCase<BoolQueryBuilde
public void testEmptyBooleanQuery() throws Exception { public void testEmptyBooleanQuery() throws Exception {
XContentBuilder contentBuilder = XContentFactory.contentBuilder(randomFrom(XContentType.values())); XContentBuilder contentBuilder = XContentFactory.contentBuilder(randomFrom(XContentType.values()));
contentBuilder.startObject().startObject("bool").endObject().endObject(); contentBuilder.startObject().startObject("bool").endObject().endObject();
Query parsedQuery = parseQuery(createParser(contentBuilder)).toQuery(createShardContext()); try (XContentParser xParser = createParser(contentBuilder)) {
assertThat(parsedQuery, Matchers.instanceOf(MatchAllDocsQuery.class)); Query parsedQuery = parseQuery(xParser).toQuery(createShardContext());
assertThat(parsedQuery, Matchers.instanceOf(MatchAllDocsQuery.class));
}
} }
public void testDefaultMinShouldMatch() throws Exception { public void testDefaultMinShouldMatch() throws Exception {

View File

@ -124,11 +124,12 @@ public class InnerHitBuilderTests extends ESTestCase {
innerHit.toXContent(builder, ToXContent.EMPTY_PARAMS); innerHit.toXContent(builder, ToXContent.EMPTY_PARAMS);
//fields is printed out as an object but parsed into a List where order matters, we disable shuffling //fields is printed out as an object but parsed into a List where order matters, we disable shuffling
XContentBuilder shuffled = shuffleXContent(builder, "fields"); XContentBuilder shuffled = shuffleXContent(builder, "fields");
XContentParser parser = createParser(shuffled); try (XContentParser parser = createParser(shuffled)) {
InnerHitBuilder secondInnerHits = InnerHitBuilder.fromXContent(parser); InnerHitBuilder secondInnerHits = InnerHitBuilder.fromXContent(parser);
assertThat(innerHit, not(sameInstance(secondInnerHits))); assertThat(innerHit, not(sameInstance(secondInnerHits)));
assertThat(innerHit, equalTo(secondInnerHits)); assertThat(innerHit, equalTo(secondInnerHits));
assertThat(innerHit.hashCode(), equalTo(secondInnerHits.hashCode())); assertThat(innerHit.hashCode(), equalTo(secondInnerHits.hashCode()));
}
} }
} }

View File

@ -107,16 +107,17 @@ public class GeoPointParsingTests extends ESTestCase {
content.endObject(); content.endObject();
content.endObject(); content.endObject();
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(content)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(content))) {
parser.nextToken(); parser.nextToken();
Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser)); Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser));
assertThat(e.getMessage(), is("field must be either [lat], [lon] or [geohash]")); assertThat(e.getMessage(), is("field must be either [lat], [lon] or [geohash]"));
}
XContentParser parser2 = createParser(JsonXContent.jsonXContent, BytesReference.bytes(content)); try (XContentParser parser2 = createParser(JsonXContent.jsonXContent, BytesReference.bytes(content))) {
parser2.nextToken(); parser2.nextToken();
e = expectThrows(ElasticsearchParseException.class, () -> Exception e = expectThrows(ElasticsearchParseException.class, () ->
GeoUtils.parseGeoPoint(toObject(parser2), randomBoolean())); GeoUtils.parseGeoPoint(toObject(parser2), randomBoolean()));
assertThat(e.getMessage(), is("field must be either [lat], [lon] or [geohash]")); assertThat(e.getMessage(), is("field must be either [lat], [lon] or [geohash]"));
}
} }
public void testInvalidPointLatHashMix() throws IOException { public void testInvalidPointLatHashMix() throws IOException {
@ -125,16 +126,17 @@ public class GeoPointParsingTests extends ESTestCase {
content.field("lat", 0).field("geohash", stringEncode(0d, 0d)); content.field("lat", 0).field("geohash", stringEncode(0d, 0d));
content.endObject(); content.endObject();
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(content)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(content))) {
parser.nextToken(); parser.nextToken();
Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser)); Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser));
assertThat(e.getMessage(), is("field must be either lat/lon or geohash")); assertThat(e.getMessage(), is("field must be either lat/lon or geohash"));
}
XContentParser parser2 = createParser(JsonXContent.jsonXContent, BytesReference.bytes(content)); try (XContentParser parser2 = createParser(JsonXContent.jsonXContent, BytesReference.bytes(content))) {
parser2.nextToken(); parser2.nextToken();
e = expectThrows(ElasticsearchParseException.class, () -> Exception e = expectThrows(ElasticsearchParseException.class, () ->
GeoUtils.parseGeoPoint(toObject(parser2), randomBoolean())); GeoUtils.parseGeoPoint(toObject(parser2), randomBoolean()));
assertThat(e.getMessage(), is("field must be either lat/lon or geohash")); assertThat(e.getMessage(), is("field must be either lat/lon or geohash"));
}
} }
public void testInvalidPointLonHashMix() throws IOException { public void testInvalidPointLonHashMix() throws IOException {
@ -143,17 +145,18 @@ public class GeoPointParsingTests extends ESTestCase {
content.field("lon", 0).field("geohash", stringEncode(0d, 0d)); content.field("lon", 0).field("geohash", stringEncode(0d, 0d));
content.endObject(); content.endObject();
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(content)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(content))) {
parser.nextToken(); parser.nextToken();
Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser)); Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser));
assertThat(e.getMessage(), is("field must be either lat/lon or geohash")); assertThat(e.getMessage(), is("field must be either lat/lon or geohash"));
}
XContentParser parser2 = createParser(JsonXContent.jsonXContent, BytesReference.bytes(content)); try (XContentParser parser2 = createParser(JsonXContent.jsonXContent, BytesReference.bytes(content))) {
parser2.nextToken(); parser2.nextToken();
e = expectThrows(ElasticsearchParseException.class, () -> Exception e = expectThrows(ElasticsearchParseException.class, () ->
GeoUtils.parseGeoPoint(toObject(parser2), randomBoolean())); GeoUtils.parseGeoPoint(toObject(parser2), randomBoolean()));
assertThat(e.getMessage(), is("field must be either lat/lon or geohash")); assertThat(e.getMessage(), is("field must be either lat/lon or geohash"));
}
} }
public void testInvalidField() throws IOException { public void testInvalidField() throws IOException {
@ -162,17 +165,18 @@ public class GeoPointParsingTests extends ESTestCase {
content.field("lon", 0).field("lat", 0).field("test", 0); content.field("lon", 0).field("lat", 0).field("test", 0);
content.endObject(); content.endObject();
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(content)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(content))) {
parser.nextToken(); parser.nextToken();
Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser)); Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser));
assertThat(e.getMessage(), is("field must be either [lat], [lon] or [geohash]")); assertThat(e.getMessage(), is("field must be either [lat], [lon] or [geohash]"));
}
try (XContentParser parser2 = createParser(JsonXContent.jsonXContent, BytesReference.bytes(content))) {
XContentParser parser2 = createParser(JsonXContent.jsonXContent, BytesReference.bytes(content)); parser2.nextToken();
parser2.nextToken(); Exception e = expectThrows(ElasticsearchParseException.class, () ->
e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(toObject(parser2), randomBoolean()));
GeoUtils.parseGeoPoint(toObject(parser2), randomBoolean())); assertThat(e.getMessage(), is("field must be either [lat], [lon] or [geohash]"));
assertThat(e.getMessage(), is("field must be either [lat], [lon] or [geohash]")); }
} }
public void testInvalidGeoHash() throws IOException { public void testInvalidGeoHash() throws IOException {
@ -181,11 +185,12 @@ public class GeoPointParsingTests extends ESTestCase {
content.field("geohash", "!!!!"); content.field("geohash", "!!!!");
content.endObject(); content.endObject();
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(content)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(content))) {
parser.nextToken(); parser.nextToken();
Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser)); Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser));
assertThat(e.getMessage(), is("unsupported symbol [!] in geohash [!!!!]")); assertThat(e.getMessage(), is("unsupported symbol [!] in geohash [!!!!]"));
}
} }
private XContentParser objectLatLon(double lat, double lon) throws IOException { private XContentParser objectLatLon(double lat, double lon) throws IOException {

View File

@ -384,29 +384,33 @@ public class GeoUtilsTests extends ESTestCase {
double lat = randomDouble() * 180 - 90 + randomIntBetween(-1000, 1000) * 180; double lat = randomDouble() * 180 - 90 + randomIntBetween(-1000, 1000) * 180;
double lon = randomDouble() * 360 - 180 + randomIntBetween(-1000, 1000) * 360; double lon = randomDouble() * 360 - 180 + randomIntBetween(-1000, 1000) * 360;
XContentBuilder json = jsonBuilder().startObject().field("lat", lat).field("lon", lon).endObject(); XContentBuilder json = jsonBuilder().startObject().field("lat", lat).field("lon", lon).endObject();
XContentParser parser = createParser(json); try (XContentParser parser = createParser(json)) {
parser.nextToken(); parser.nextToken();
GeoPoint point = GeoUtils.parseGeoPoint(parser); GeoPoint point = GeoUtils.parseGeoPoint(parser);
assertThat(point, equalTo(new GeoPoint(lat, lon))); assertThat(point, equalTo(new GeoPoint(lat, lon)));
}
json = jsonBuilder().startObject().field("lat", String.valueOf(lat)).field("lon", String.valueOf(lon)).endObject(); json = jsonBuilder().startObject().field("lat", String.valueOf(lat)).field("lon", String.valueOf(lon)).endObject();
parser = createParser(json); try (XContentParser parser = createParser(json)) {
parser.nextToken(); parser.nextToken();
point = GeoUtils.parseGeoPoint(parser); GeoPoint point = GeoUtils.parseGeoPoint(parser);
assertThat(point, equalTo(new GeoPoint(lat, lon))); assertThat(point, equalTo(new GeoPoint(lat, lon)));
}
json = jsonBuilder().startObject().startArray("foo").value(lon).value(lat).endArray().endObject(); json = jsonBuilder().startObject().startArray("foo").value(lon).value(lat).endArray().endObject();
parser = createParser(json); try (XContentParser parser = createParser(json)) {
while (parser.currentToken() != Token.START_ARRAY) { while (parser.currentToken() != Token.START_ARRAY) {
parser.nextToken(); parser.nextToken();
}
GeoPoint point = GeoUtils.parseGeoPoint(parser);
assertThat(point, equalTo(new GeoPoint(lat, lon)));
} }
point = GeoUtils.parseGeoPoint(parser);
assertThat(point, equalTo(new GeoPoint(lat, lon)));
json = jsonBuilder().startObject().field("foo", lat + "," + lon).endObject(); json = jsonBuilder().startObject().field("foo", lat + "," + lon).endObject();
parser = createParser(json); try (XContentParser parser = createParser(json)) {
while (parser.currentToken() != Token.VALUE_STRING) { while (parser.currentToken() != Token.VALUE_STRING) {
parser.nextToken(); parser.nextToken();
}
GeoPoint point = GeoUtils.parseGeoPoint(parser);
assertThat(point, equalTo(new GeoPoint(lat, lon)));
} }
point = GeoUtils.parseGeoPoint(parser);
assertThat(point, equalTo(new GeoPoint(lat, lon)));
} }
} }
@ -415,12 +419,13 @@ public class GeoUtilsTests extends ESTestCase {
double lon = randomDouble() * 360 - 180 + randomIntBetween(-1000, 1000) * 360; double lon = randomDouble() * 360 - 180 + randomIntBetween(-1000, 1000) * 360;
double alt = randomDouble() * 1000; double alt = randomDouble() * 1000;
XContentBuilder json = jsonBuilder().startObject().field("foo", lat + "," + lon + "," + alt).endObject(); XContentBuilder json = jsonBuilder().startObject().field("foo", lat + "," + lon + "," + alt).endObject();
XContentParser parser = createParser(json); try (XContentParser parser = createParser(json)) {
while (parser.currentToken() != Token.VALUE_STRING) { while (parser.currentToken() != Token.VALUE_STRING) {
parser.nextToken(); parser.nextToken();
}
Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser, new GeoPoint(), false));
assertThat(e.getMessage(), containsString("but [ignore_z_value] parameter is [false]"));
} }
Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser, new GeoPoint(), false));
assertThat(e.getMessage(), containsString("but [ignore_z_value] parameter is [false]"));
} }
public void testParseGeoPointGeohash() throws IOException { public void testParseGeoPointGeohash() throws IOException {
@ -431,74 +436,82 @@ public class GeoUtilsTests extends ESTestCase {
geohashBuilder.append(BASE_32[randomInt(BASE_32.length - 1)]); geohashBuilder.append(BASE_32[randomInt(BASE_32.length - 1)]);
} }
XContentBuilder json = jsonBuilder().startObject().field("geohash", geohashBuilder.toString()).endObject(); XContentBuilder json = jsonBuilder().startObject().field("geohash", geohashBuilder.toString()).endObject();
XContentParser parser = createParser(json); try (XContentParser parser = createParser(json)) {
parser.nextToken();
GeoPoint point = GeoUtils.parseGeoPoint(parser);
assertThat(point.lat(), allOf(lessThanOrEqualTo(90.0), greaterThanOrEqualTo(-90.0)));
assertThat(point.lon(), allOf(lessThanOrEqualTo(180.0), greaterThanOrEqualTo(-180.0)));
json = jsonBuilder().startObject().field("geohash", geohashBuilder.toString()).endObject();
parser = createParser(json);
while (parser.currentToken() != Token.VALUE_STRING) {
parser.nextToken(); parser.nextToken();
GeoPoint point = GeoUtils.parseGeoPoint(parser);
assertThat(point.lat(), allOf(lessThanOrEqualTo(90.0), greaterThanOrEqualTo(-90.0)));
assertThat(point.lon(), allOf(lessThanOrEqualTo(180.0), greaterThanOrEqualTo(-180.0)));
}
json = jsonBuilder().startObject().field("geohash", geohashBuilder.toString()).endObject();
try (XContentParser parser = createParser(json)) {
while (parser.currentToken() != Token.VALUE_STRING) {
parser.nextToken();
}
GeoPoint point = GeoUtils.parseGeoPoint(parser);
assertThat(point.lat(), allOf(lessThanOrEqualTo(90.0), greaterThanOrEqualTo(-90.0)));
assertThat(point.lon(), allOf(lessThanOrEqualTo(180.0), greaterThanOrEqualTo(-180.0)));
} }
point = GeoUtils.parseGeoPoint(parser);
assertThat(point.lat(), allOf(lessThanOrEqualTo(90.0), greaterThanOrEqualTo(-90.0)));
assertThat(point.lon(), allOf(lessThanOrEqualTo(180.0), greaterThanOrEqualTo(-180.0)));
} }
} }
public void testParseGeoPointGeohashWrongType() throws IOException { public void testParseGeoPointGeohashWrongType() throws IOException {
XContentBuilder json = jsonBuilder().startObject().field("geohash", 1.0).endObject(); XContentBuilder json = jsonBuilder().startObject().field("geohash", 1.0).endObject();
XContentParser parser = createParser(json); try (XContentParser parser = createParser(json)) {
parser.nextToken(); parser.nextToken();
Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser)); Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser));
assertThat(e.getMessage(), containsString("geohash must be a string")); assertThat(e.getMessage(), containsString("geohash must be a string"));
}
} }
public void testParseGeoPointLatNoLon() throws IOException { public void testParseGeoPointLatNoLon() throws IOException {
double lat = 0.0; double lat = 0.0;
XContentBuilder json = jsonBuilder().startObject().field("lat", lat).endObject(); XContentBuilder json = jsonBuilder().startObject().field("lat", lat).endObject();
XContentParser parser = createParser(json); try (XContentParser parser = createParser(json)) {
parser.nextToken(); parser.nextToken();
Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser)); Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser));
assertThat(e.getMessage(), is("field [lon] missing")); assertThat(e.getMessage(), is("field [lon] missing"));
}
} }
public void testParseGeoPointLonNoLat() throws IOException { public void testParseGeoPointLonNoLat() throws IOException {
double lon = 0.0; double lon = 0.0;
XContentBuilder json = jsonBuilder().startObject().field("lon", lon).endObject(); XContentBuilder json = jsonBuilder().startObject().field("lon", lon).endObject();
XContentParser parser = createParser(json); try (XContentParser parser = createParser(json)) {
parser.nextToken(); parser.nextToken();
Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser)); Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser));
assertThat(e.getMessage(), is("field [lat] missing")); assertThat(e.getMessage(), is("field [lat] missing"));
}
} }
public void testParseGeoPointLonWrongType() throws IOException { public void testParseGeoPointLonWrongType() throws IOException {
double lat = 0.0; double lat = 0.0;
XContentBuilder json = jsonBuilder().startObject().field("lat", lat).field("lon", false).endObject(); XContentBuilder json = jsonBuilder().startObject().field("lat", lat).field("lon", false).endObject();
XContentParser parser = createParser(json); try (XContentParser parser = createParser(json)) {
parser.nextToken(); parser.nextToken();
Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser)); Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser));
assertThat(e.getMessage(), is("longitude must be a number")); assertThat(e.getMessage(), is("longitude must be a number"));
}
} }
public void testParseGeoPointLatWrongType() throws IOException { public void testParseGeoPointLatWrongType() throws IOException {
double lon = 0.0; double lon = 0.0;
XContentBuilder json = jsonBuilder().startObject().field("lat", false).field("lon", lon).endObject(); XContentBuilder json = jsonBuilder().startObject().field("lat", false).field("lon", lon).endObject();
XContentParser parser = createParser(json); try (XContentParser parser = createParser(json)) {
parser.nextToken(); parser.nextToken();
Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser)); Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser));
assertThat(e.getMessage(), is("latitude must be a number")); assertThat(e.getMessage(), is("latitude must be a number"));
}
} }
public void testParseGeoPointExtraField() throws IOException { public void testParseGeoPointExtraField() throws IOException {
double lat = 0.0; double lat = 0.0;
double lon = 0.0; double lon = 0.0;
XContentBuilder json = jsonBuilder().startObject().field("lat", lat).field("lon", lon).field("foo", true).endObject(); XContentBuilder json = jsonBuilder().startObject().field("lat", lat).field("lon", lon).field("foo", true).endObject();
XContentParser parser = createParser(json); try (XContentParser parser = createParser(json)) {
parser.nextToken(); parser.nextToken();
Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser)); Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser));
assertThat(e.getMessage(), is("field must be either [lat], [lon] or [geohash]")); assertThat(e.getMessage(), is("field must be either [lat], [lon] or [geohash]"));
}
} }
public void testParseGeoPointLonLatGeoHash() throws IOException { public void testParseGeoPointLonLatGeoHash() throws IOException {
@ -506,10 +519,11 @@ public class GeoUtilsTests extends ESTestCase {
double lon = 0.0; double lon = 0.0;
String geohash = "abcd"; String geohash = "abcd";
XContentBuilder json = jsonBuilder().startObject().field("lat", lat).field("lon", lon).field("geohash", geohash).endObject(); XContentBuilder json = jsonBuilder().startObject().field("lat", lat).field("lon", lon).field("geohash", geohash).endObject();
XContentParser parser = createParser(json); try (XContentParser parser = createParser(json)) {
parser.nextToken(); parser.nextToken();
Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser)); Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser));
assertThat(e.getMessage(), containsString("field must be either lat/lon or geohash")); assertThat(e.getMessage(), containsString("field must be either lat/lon or geohash"));
}
} }
public void testParseGeoPointArrayTooManyValues() throws IOException { public void testParseGeoPointArrayTooManyValues() throws IOException {
@ -517,12 +531,13 @@ public class GeoUtilsTests extends ESTestCase {
double lon = 0.0; double lon = 0.0;
double elev = 0.0; double elev = 0.0;
XContentBuilder json = jsonBuilder().startObject().startArray("foo").value(lon).value(lat).value(elev).endArray().endObject(); XContentBuilder json = jsonBuilder().startObject().startArray("foo").value(lon).value(lat).value(elev).endArray().endObject();
XContentParser parser = createParser(json); try (XContentParser parser = createParser(json)) {
while (parser.currentToken() != Token.START_ARRAY) { while (parser.currentToken() != Token.START_ARRAY) {
parser.nextToken(); parser.nextToken();
}
Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser));
assertThat(e.getMessage(), is("Exception parsing coordinates: found Z value [0.0] but [ignore_z_value] parameter is [false]"));
} }
Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser));
assertThat(e.getMessage(), is("Exception parsing coordinates: found Z value [0.0] but [ignore_z_value] parameter is [false]"));
} }
public void testParseGeoPointArray3D() throws IOException { public void testParseGeoPointArray3D() throws IOException {
@ -530,35 +545,38 @@ public class GeoUtilsTests extends ESTestCase {
double lon = -180.0; double lon = -180.0;
double elev = 0.0; double elev = 0.0;
XContentBuilder json = jsonBuilder().startObject().startArray("foo").value(lon).value(lat).value(elev).endArray().endObject(); XContentBuilder json = jsonBuilder().startObject().startArray("foo").value(lon).value(lat).value(elev).endArray().endObject();
XContentParser parser = createParser(json); try (XContentParser parser = createParser(json)) {
while (parser.currentToken() != Token.START_ARRAY) { while (parser.currentToken() != Token.START_ARRAY) {
parser.nextToken(); parser.nextToken();
}
GeoPoint point = GeoUtils.parseGeoPoint(parser, new GeoPoint(), true);
assertThat(point.lat(), equalTo(lat));
assertThat(point.lon(), equalTo(lon));
} }
GeoPoint point = GeoUtils.parseGeoPoint(parser, new GeoPoint(), true);
assertThat(point.lat(), equalTo(lat));
assertThat(point.lon(), equalTo(lon));
} }
public void testParseGeoPointArrayWrongType() throws IOException { public void testParseGeoPointArrayWrongType() throws IOException {
double lat = 0.0; double lat = 0.0;
boolean lon = false; boolean lon = false;
XContentBuilder json = jsonBuilder().startObject().startArray("foo").value(lon).value(lat).endArray().endObject(); XContentBuilder json = jsonBuilder().startObject().startArray("foo").value(lon).value(lat).endArray().endObject();
XContentParser parser = createParser(json); try (XContentParser parser = createParser(json)) {
while (parser.currentToken() != Token.START_ARRAY) { while (parser.currentToken() != Token.START_ARRAY) {
parser.nextToken(); parser.nextToken();
}
Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser));
assertThat(e.getMessage(), is("numeric value expected"));
} }
Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser));
assertThat(e.getMessage(), is("numeric value expected"));
} }
public void testParseGeoPointInvalidType() throws IOException { public void testParseGeoPointInvalidType() throws IOException {
XContentBuilder json = jsonBuilder().startObject().field("foo", 5).endObject(); XContentBuilder json = jsonBuilder().startObject().field("foo", 5).endObject();
XContentParser parser = createParser(json); try (XContentParser parser = createParser(json)) {
while (parser.currentToken() != Token.VALUE_NUMBER) { while (parser.currentToken() != Token.VALUE_NUMBER) {
parser.nextToken(); parser.nextToken();
}
Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser));
assertThat(e.getMessage(), is("geo_point expected"));
} }
Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser));
assertThat(e.getMessage(), is("geo_point expected"));
} }
public void testPrefixTreeCellSizes() { public void testPrefixTreeCellSizes() {
@ -619,9 +637,10 @@ public class GeoUtilsTests extends ESTestCase {
} }
private GeoPoint parseGeohash(String geohash, GeoUtils.EffectivePoint effectivePoint) throws IOException { private GeoPoint parseGeohash(String geohash, GeoUtils.EffectivePoint effectivePoint) throws IOException {
XContentParser parser = createParser(jsonBuilder().startObject().field("geohash", geohash).endObject()); try (XContentParser parser = createParser(jsonBuilder().startObject().field("geohash", geohash).endObject())) {
parser.nextToken(); parser.nextToken();
return GeoUtils.parseGeoPoint(parser, new GeoPoint(), randomBoolean(), effectivePoint); return GeoUtils.parseGeoPoint(parser, new GeoPoint(), randomBoolean(), effectivePoint);
}
} }
private static void assertNormalizedPoint(GeoPoint input, GeoPoint expected) { private static void assertNormalizedPoint(GeoPoint input, GeoPoint expected) {

View File

@ -57,15 +57,16 @@ public class IngestMetadataTests extends ESTestCase {
ingestMetadata.toXContent(builder, ToXContent.EMPTY_PARAMS); ingestMetadata.toXContent(builder, ToXContent.EMPTY_PARAMS);
builder.endObject(); builder.endObject();
XContentBuilder shuffled = shuffleXContent(builder); XContentBuilder shuffled = shuffleXContent(builder);
final XContentParser parser = createParser(shuffled); try (XContentParser parser = createParser(shuffled)) {
MetaData.Custom custom = IngestMetadata.fromXContent(parser); MetaData.Custom custom = IngestMetadata.fromXContent(parser);
assertTrue(custom instanceof IngestMetadata); assertTrue(custom instanceof IngestMetadata);
IngestMetadata m = (IngestMetadata) custom; IngestMetadata m = (IngestMetadata) custom;
assertEquals(2, m.getPipelines().size()); assertEquals(2, m.getPipelines().size());
assertEquals("1", m.getPipelines().get("1").getId()); assertEquals("1", m.getPipelines().get("1").getId());
assertEquals("2", m.getPipelines().get("2").getId()); assertEquals("2", m.getPipelines().get("2").getId());
assertEquals(pipeline.getConfigAsMap(), m.getPipelines().get("1").getConfigAsMap()); assertEquals(pipeline.getConfigAsMap(), m.getPipelines().get("1").getConfigAsMap());
assertEquals(pipeline2.getConfigAsMap(), m.getPipelines().get("2").getConfigAsMap()); assertEquals(pipeline2.getConfigAsMap(), m.getPipelines().get("2").getConfigAsMap());
}
} }
public void testDiff() throws Exception { public void testDiff() throws Exception {

View File

@ -174,8 +174,10 @@ public class PersistentTasksCustomMetaDataTests extends AbstractDiffableSerializ
XContentType xContentType = randomFrom(XContentType.values()); XContentType xContentType = randomFrom(XContentType.values());
BytesReference shuffled = toShuffledXContent(testInstance, xContentType, params, false); BytesReference shuffled = toShuffledXContent(testInstance, xContentType, params, false);
XContentParser parser = createParser(XContentFactory.xContent(xContentType), shuffled); PersistentTasksCustomMetaData newInstance;
PersistentTasksCustomMetaData newInstance = doParseInstance(parser); try (XContentParser parser = createParser(XContentFactory.xContent(xContentType), shuffled)) {
newInstance = doParseInstance(parser);
}
assertNotSame(newInstance, testInstance); assertNotSame(newInstance, testInstance);
assertEquals(testInstance.tasks().size(), newInstance.tasks().size()); assertEquals(testInstance.tasks().size(), newInstance.tasks().size());

View File

@ -62,11 +62,12 @@ public class RepositoryDataTests extends ESTestCase {
RepositoryData repositoryData = generateRandomRepoData(); RepositoryData repositoryData = generateRandomRepoData();
XContentBuilder builder = JsonXContent.contentBuilder(); XContentBuilder builder = JsonXContent.contentBuilder();
repositoryData.snapshotsToXContent(builder, ToXContent.EMPTY_PARAMS); repositoryData.snapshotsToXContent(builder, ToXContent.EMPTY_PARAMS);
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder))) {
long gen = (long) randomIntBetween(0, 500); long gen = (long) randomIntBetween(0, 500);
RepositoryData fromXContent = RepositoryData.snapshotsFromXContent(parser, gen); RepositoryData fromXContent = RepositoryData.snapshotsFromXContent(parser, gen);
assertEquals(repositoryData, fromXContent); assertEquals(repositoryData, fromXContent);
assertEquals(gen, fromXContent.getGenId()); assertEquals(gen, fromXContent.getGenId());
}
} }
public void testAddSnapshots() { public void testAddSnapshots() {
@ -166,7 +167,10 @@ public class RepositoryDataTests extends ESTestCase {
XContentBuilder builder = XContentBuilder.builder(xContent); XContentBuilder builder = XContentBuilder.builder(xContent);
repositoryData.snapshotsToXContent(builder, ToXContent.EMPTY_PARAMS); repositoryData.snapshotsToXContent(builder, ToXContent.EMPTY_PARAMS);
RepositoryData parsedRepositoryData = RepositoryData.snapshotsFromXContent(createParser(builder), repositoryData.getGenId()); RepositoryData parsedRepositoryData;
try (XContentParser xParser = createParser(builder)) {
parsedRepositoryData = RepositoryData.snapshotsFromXContent(xParser, repositoryData.getGenId());
}
assertEquals(repositoryData, parsedRepositoryData); assertEquals(repositoryData, parsedRepositoryData);
Map<String, SnapshotId> snapshotIds = new HashMap<>(); Map<String, SnapshotId> snapshotIds = new HashMap<>();
@ -195,10 +199,12 @@ public class RepositoryDataTests extends ESTestCase {
final XContentBuilder corruptedBuilder = XContentBuilder.builder(xContent); final XContentBuilder corruptedBuilder = XContentBuilder.builder(xContent);
corruptedRepositoryData.snapshotsToXContent(corruptedBuilder, ToXContent.EMPTY_PARAMS); corruptedRepositoryData.snapshotsToXContent(corruptedBuilder, ToXContent.EMPTY_PARAMS);
ElasticsearchParseException e = expectThrows(ElasticsearchParseException.class, () -> try (XContentParser xParser = createParser(corruptedBuilder)) {
RepositoryData.snapshotsFromXContent(createParser(corruptedBuilder), corruptedRepositoryData.getGenId())); ElasticsearchParseException e = expectThrows(ElasticsearchParseException.class, () ->
assertThat(e.getMessage(), equalTo("Detected a corrupted repository, index " + corruptedIndexId + " references an unknown " + RepositoryData.snapshotsFromXContent(xParser, corruptedRepositoryData.getGenId()));
"snapshot uuid [_does_not_exist]")); assertThat(e.getMessage(), equalTo("Detected a corrupted repository, index " + corruptedIndexId + " references an unknown " +
"snapshot uuid [_does_not_exist]"));
}
} }
public void testIndexThatReferenceANullSnapshot() throws IOException { public void testIndexThatReferenceANullSnapshot() throws IOException {
@ -230,9 +236,12 @@ public class RepositoryDataTests extends ESTestCase {
} }
builder.endObject(); builder.endObject();
ElasticsearchParseException e = expectThrows(ElasticsearchParseException.class, () -> try (XContentParser xParser = createParser(builder)) {
RepositoryData.snapshotsFromXContent(createParser(builder), randomNonNegativeLong())); ElasticsearchParseException e = expectThrows(ElasticsearchParseException.class, () ->
assertThat(e.getMessage(), equalTo("Detected a corrupted repository, index [docs/_id] references an unknown snapshot uuid [null]")); RepositoryData.snapshotsFromXContent(xParser, randomNonNegativeLong()));
assertThat(e.getMessage(), equalTo("Detected a corrupted repository, " +
"index [docs/_id] references an unknown snapshot uuid [null]"));
}
} }
public static RepositoryData generateRandomRepoData() { public static RepositoryData generateRandomRepoData() {

View File

@ -37,28 +37,29 @@ import static org.mockito.Mockito.mock;
public class RestAnalyzeActionTests extends ESTestCase { public class RestAnalyzeActionTests extends ESTestCase {
public void testParseXContentForAnalyzeRequest() throws Exception { public void testParseXContentForAnalyzeRequest() throws Exception {
XContentParser content = createParser(XContentFactory.jsonBuilder() try (XContentParser content = createParser(XContentFactory.jsonBuilder()
.startObject() .startObject()
.field("text", "THIS IS A TEST") .field("text", "THIS IS A TEST")
.field("tokenizer", "keyword") .field("tokenizer", "keyword")
.array("filter", "lowercase") .array("filter", "lowercase")
.endObject()); .endObject())) {
AnalyzeRequest analyzeRequest = new AnalyzeRequest("for test"); AnalyzeRequest analyzeRequest = new AnalyzeRequest("for test");
RestAnalyzeAction.buildFromContent(content, analyzeRequest); RestAnalyzeAction.buildFromContent(content, analyzeRequest);
assertThat(analyzeRequest.text().length, equalTo(1)); assertThat(analyzeRequest.text().length, equalTo(1));
assertThat(analyzeRequest.text(), equalTo(new String[]{"THIS IS A TEST"})); assertThat(analyzeRequest.text(), equalTo(new String[]{"THIS IS A TEST"}));
assertThat(analyzeRequest.tokenizer().name, equalTo("keyword")); assertThat(analyzeRequest.tokenizer().name, equalTo("keyword"));
assertThat(analyzeRequest.tokenFilters().size(), equalTo(1)); assertThat(analyzeRequest.tokenFilters().size(), equalTo(1));
for (AnalyzeRequest.NameOrDefinition filter : analyzeRequest.tokenFilters()) { for (AnalyzeRequest.NameOrDefinition filter : analyzeRequest.tokenFilters()) {
assertThat(filter.name, equalTo("lowercase")); assertThat(filter.name, equalTo("lowercase"));
}
} }
} }
public void testParseXContentForAnalyzeRequestWithCustomFilters() throws Exception { public void testParseXContentForAnalyzeRequestWithCustomFilters() throws Exception {
XContentParser content = createParser(XContentFactory.jsonBuilder() try (XContentParser content = createParser(XContentFactory.jsonBuilder()
.startObject() .startObject()
.field("text", "THIS IS A TEST") .field("text", "THIS IS A TEST")
.field("tokenizer", "keyword") .field("tokenizer", "keyword")
@ -76,21 +77,22 @@ public class RestAnalyzeActionTests extends ESTestCase {
.endObject() .endObject()
.endArray() .endArray()
.field("normalizer", "normalizer") .field("normalizer", "normalizer")
.endObject()); .endObject())) {
AnalyzeRequest analyzeRequest = new AnalyzeRequest("for test"); AnalyzeRequest analyzeRequest = new AnalyzeRequest("for test");
RestAnalyzeAction.buildFromContent(content, analyzeRequest); RestAnalyzeAction.buildFromContent(content, analyzeRequest);
assertThat(analyzeRequest.text().length, equalTo(1)); assertThat(analyzeRequest.text().length, equalTo(1));
assertThat(analyzeRequest.text(), equalTo(new String[]{"THIS IS A TEST"})); assertThat(analyzeRequest.text(), equalTo(new String[]{"THIS IS A TEST"}));
assertThat(analyzeRequest.tokenizer().name, equalTo("keyword")); assertThat(analyzeRequest.tokenizer().name, equalTo("keyword"));
assertThat(analyzeRequest.tokenFilters().size(), equalTo(2)); assertThat(analyzeRequest.tokenFilters().size(), equalTo(2));
assertThat(analyzeRequest.tokenFilters().get(0).name, equalTo("lowercase")); assertThat(analyzeRequest.tokenFilters().get(0).name, equalTo("lowercase"));
assertThat(analyzeRequest.tokenFilters().get(1).definition, notNullValue()); assertThat(analyzeRequest.tokenFilters().get(1).definition, notNullValue());
assertThat(analyzeRequest.charFilters().size(), equalTo(1)); assertThat(analyzeRequest.charFilters().size(), equalTo(1));
assertThat(analyzeRequest.charFilters().get(0).definition, notNullValue()); assertThat(analyzeRequest.charFilters().get(0).definition, notNullValue());
assertThat(analyzeRequest.normalizer(), equalTo("normalizer")); assertThat(analyzeRequest.normalizer(), equalTo("normalizer"));
}
} }
public void testParseXContentForAnalyzeRequestWithInvalidJsonThrowsException() throws Exception { public void testParseXContentForAnalyzeRequestWithInvalidJsonThrowsException() throws Exception {
@ -103,84 +105,83 @@ public class RestAnalyzeActionTests extends ESTestCase {
public void testParseXContentForAnalyzeRequestWithUnknownParamThrowsException() throws Exception { public void testParseXContentForAnalyzeRequestWithUnknownParamThrowsException() throws Exception {
AnalyzeRequest analyzeRequest = new AnalyzeRequest("for test"); AnalyzeRequest analyzeRequest = new AnalyzeRequest("for test");
XContentParser invalidContent = createParser(XContentFactory.jsonBuilder() try (XContentParser invalidContent = createParser(XContentFactory.jsonBuilder()
.startObject() .startObject()
.field("text", "THIS IS A TEST") .field("text", "THIS IS A TEST")
.field("unknown", "keyword") .field("unknown", "keyword")
.endObject()); .endObject())) {
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, IllegalArgumentException e = expectThrows(IllegalArgumentException.class,
() -> RestAnalyzeAction.buildFromContent(invalidContent, analyzeRequest)); () -> RestAnalyzeAction.buildFromContent(invalidContent, analyzeRequest));
assertThat(e.getMessage(), startsWith("Unknown parameter [unknown]")); assertThat(e.getMessage(), startsWith("Unknown parameter [unknown]"));
}
} }
public void testParseXContentForAnalyzeRequestWithInvalidStringExplainParamThrowsException() throws Exception { public void testParseXContentForAnalyzeRequestWithInvalidStringExplainParamThrowsException() throws Exception {
AnalyzeRequest analyzeRequest = new AnalyzeRequest("for test"); AnalyzeRequest analyzeRequest = new AnalyzeRequest("for test");
XContentParser invalidExplain = createParser(XContentFactory.jsonBuilder() try (XContentParser invalidExplain = createParser(XContentFactory.jsonBuilder()
.startObject() .startObject()
.field("explain", "fals") .field("explain", "fals")
.endObject()); .endObject())) {
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, IllegalArgumentException e = expectThrows(IllegalArgumentException.class,
() -> RestAnalyzeAction.buildFromContent(invalidExplain, analyzeRequest)); () -> RestAnalyzeAction.buildFromContent(invalidExplain, analyzeRequest));
assertThat(e.getMessage(), startsWith("explain must be either 'true' or 'false'")); assertThat(e.getMessage(), startsWith("explain must be either 'true' or 'false'"));
}
} }
public void testParseXContentForAnalyzeRequestWithInvalidNormalizerThrowsException() throws Exception { public void testParseXContentForAnalyzeRequestWithInvalidNormalizerThrowsException() throws Exception {
AnalyzeRequest analyzeRequest = new AnalyzeRequest("for test"); AnalyzeRequest analyzeRequest = new AnalyzeRequest("for test");
XContentParser invalidExplain = createParser(XContentFactory.jsonBuilder() try (XContentParser invalidExplain = createParser(XContentFactory.jsonBuilder()
.startObject() .startObject()
.field("normalizer", true) .field("normalizer", true)
.endObject()); .endObject())) {
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, IllegalArgumentException e = expectThrows(IllegalArgumentException.class,
() -> RestAnalyzeAction.buildFromContent(invalidExplain, analyzeRequest)); () -> RestAnalyzeAction.buildFromContent(invalidExplain, analyzeRequest));
assertThat(e.getMessage(), startsWith("normalizer should be normalizer's name")); assertThat(e.getMessage(), startsWith("normalizer should be normalizer's name"));
}
} }
public void testDeprecatedParamIn2xException() throws Exception { public void testDeprecatedParamIn2xException() throws Exception {
{ try (XContentParser parser = createParser(XContentFactory.jsonBuilder()
XContentParser parser = createParser(XContentFactory.jsonBuilder() .startObject()
.startObject() .field("text", "THIS IS A TEST")
.field("text", "THIS IS A TEST") .field("tokenizer", "keyword")
.field("tokenizer", "keyword") .array("filters", "lowercase")
.array("filters", "lowercase") .endObject())) {
.endObject());
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> RestAnalyzeAction.buildFromContent(parser, IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> RestAnalyzeAction.buildFromContent(parser,
new AnalyzeRequest("for test"))); new AnalyzeRequest("for test")));
assertThat(e.getMessage(), startsWith("Unknown parameter [filters]")); assertThat(e.getMessage(), startsWith("Unknown parameter [filters]"));
} }
{ try (XContentParser parser = createParser(XContentFactory.jsonBuilder()
XContentParser parser = createParser(XContentFactory.jsonBuilder() .startObject()
.startObject() .field("text", "THIS IS A TEST")
.field("text", "THIS IS A TEST") .field("tokenizer", "keyword")
.field("tokenizer", "keyword") .array("token_filters", "lowercase")
.array("token_filters", "lowercase") .endObject())) {
.endObject());
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> RestAnalyzeAction.buildFromContent(parser, IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> RestAnalyzeAction.buildFromContent(parser,
new AnalyzeRequest("for test"))); new AnalyzeRequest("for test")));
assertThat(e.getMessage(), startsWith("Unknown parameter [token_filters]")); assertThat(e.getMessage(), startsWith("Unknown parameter [token_filters]"));
} }
{ try (XContentParser parser = createParser(XContentFactory.jsonBuilder()
XContentParser parser = createParser(XContentFactory.jsonBuilder() .startObject()
.startObject() .field("text", "THIS IS A TEST")
.field("text", "THIS IS A TEST") .field("tokenizer", "keyword")
.field("tokenizer", "keyword") .array("char_filters", "lowercase")
.array("char_filters", "lowercase") .endObject())) {
.endObject());
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> RestAnalyzeAction.buildFromContent(parser, IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> RestAnalyzeAction.buildFromContent(parser,
new AnalyzeRequest("for test"))); new AnalyzeRequest("for test")));
assertThat(e.getMessage(), startsWith("Unknown parameter [char_filters]")); assertThat(e.getMessage(), startsWith("Unknown parameter [char_filters]"));
} }
{ try (XContentParser parser = createParser(XContentFactory.jsonBuilder()
XContentParser parser = createParser(XContentFactory.jsonBuilder() .startObject()
.startObject() .field("text", "THIS IS A TEST")
.field("text", "THIS IS A TEST") .field("tokenizer", "keyword")
.field("tokenizer", "keyword") .array("token_filter", "lowercase")
.array("token_filter", "lowercase") .endObject())) {
.endObject());
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> RestAnalyzeAction.buildFromContent(parser, IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> RestAnalyzeAction.buildFromContent(parser,
new AnalyzeRequest("for test"))); new AnalyzeRequest("for test")));
assertThat(e.getMessage(), startsWith("Unknown parameter [token_filter]")); assertThat(e.getMessage(), startsWith("Unknown parameter [token_filter]"));
} }
} }

View File

@ -89,9 +89,11 @@ public class ScriptTests extends ESTestCase {
Script expectedScript = createScript(); Script expectedScript = createScript();
try (XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values()))) { try (XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values()))) {
expectedScript.toXContent(builder, ToXContent.EMPTY_PARAMS); expectedScript.toXContent(builder, ToXContent.EMPTY_PARAMS);
Settings settings = Settings.fromXContent(createParser(builder)); try (XContentParser xParser = createParser(builder)) {
Script actualScript = Script.parse(settings); Settings settings = Settings.fromXContent(xParser);
assertThat(actualScript, equalTo(expectedScript)); Script actualScript = Script.parse(settings);
assertThat(actualScript, equalTo(expectedScript));
}
} }
} }
} }

View File

@ -58,10 +58,11 @@ public class NestedIdentityTests extends ESTestCase {
builder.prettyPrint(); builder.prettyPrint();
} }
builder = nestedIdentity.innerToXContent(builder, ToXContent.EMPTY_PARAMS); builder = nestedIdentity.innerToXContent(builder, ToXContent.EMPTY_PARAMS);
XContentParser parser = createParser(builder); try (XContentParser parser = createParser(builder)) {
NestedIdentity parsedNestedIdentity = NestedIdentity.fromXContent(parser); NestedIdentity parsedNestedIdentity = NestedIdentity.fromXContent(parser);
assertEquals(nestedIdentity, parsedNestedIdentity); assertEquals(nestedIdentity, parsedNestedIdentity);
assertNull(parser.nextToken()); assertNull(parser.nextToken());
}
} }
public void testToXContent() throws IOException { public void testToXContent() throws IOException {

View File

@ -56,13 +56,14 @@ public class AggregationCollectorTests extends ESSingleNodeTestCase {
} }
private boolean needsScores(IndexService index, String agg) throws IOException { private boolean needsScores(IndexService index, String agg) throws IOException {
XContentParser aggParser = createParser(JsonXContent.jsonXContent, agg); try (XContentParser aggParser = createParser(JsonXContent.jsonXContent, agg)) {
aggParser.nextToken(); aggParser.nextToken();
SearchContext context = createSearchContext(index); SearchContext context = createSearchContext(index);
final AggregatorFactories factories = AggregatorFactories.parseAggregators(aggParser).build(context, null); final AggregatorFactories factories = AggregatorFactories.parseAggregators(aggParser).build(context, null);
final Aggregator[] aggregators = factories.createTopLevelAggregators(); final Aggregator[] aggregators = factories.createTopLevelAggregators();
assertEquals(1, aggregators.length); assertEquals(1, aggregators.length);
return aggregators[0].needsScores(); return aggregators[0].needsScores();
}
} }
} }

View File

@ -106,13 +106,14 @@ public abstract class BasePipelineAggregationTestCase<AF extends AbstractPipelin
} }
factoriesBuilder.toXContent(builder, ToXContent.EMPTY_PARAMS); factoriesBuilder.toXContent(builder, ToXContent.EMPTY_PARAMS);
XContentBuilder shuffled = shuffleXContent(builder); XContentBuilder shuffled = shuffleXContent(builder);
XContentParser parser = createParser(shuffled); try (XContentParser parser = createParser(shuffled)) {
String contentString = factoriesBuilder.toString(); String contentString = factoriesBuilder.toString();
logger.info("Content string: {}", contentString); logger.info("Content string: {}", contentString);
PipelineAggregationBuilder newAgg = parse(parser); PipelineAggregationBuilder newAgg = parse(parser);
assertNotSame(newAgg, testAgg); assertNotSame(newAgg, testAgg);
assertEquals(testAgg, newAgg); assertEquals(testAgg, newAgg);
assertEquals(testAgg.hashCode(), newAgg.hashCode()); assertEquals(testAgg.hashCode(), newAgg.hashCode());
}
} }
protected PipelineAggregationBuilder parse(XContentParser parser) throws IOException { protected PipelineAggregationBuilder parse(XContentParser parser) throws IOException {

View File

@ -94,34 +94,37 @@ public class FiltersTests extends BaseAggregationTestCase<FiltersAggregationBuil
builder.startObject(); builder.startObject();
builder.startArray("filters").endArray(); builder.startArray("filters").endArray();
builder.endObject(); builder.endObject();
XContentParser parser = createParser(shuffleXContent(builder)); try (XContentParser parser = createParser(shuffleXContent(builder))) {
parser.nextToken(); parser.nextToken();
FiltersAggregationBuilder filters = FiltersAggregationBuilder.parse("agg_name", parser); FiltersAggregationBuilder filters = FiltersAggregationBuilder.parse("agg_name", parser);
// The other bucket is disabled by default // The other bucket is disabled by default
assertFalse(filters.otherBucket()); assertFalse(filters.otherBucket());
builder = XContentFactory.contentBuilder(randomFrom(XContentType.values())); builder = XContentFactory.contentBuilder(randomFrom(XContentType.values()));
builder.startObject(); builder.startObject();
builder.startArray("filters").endArray(); builder.startArray("filters").endArray();
builder.field("other_bucket_key", "some_key"); builder.field("other_bucket_key", "some_key");
builder.endObject(); builder.endObject();
parser = createParser(shuffleXContent(builder)); }
parser.nextToken(); try (XContentParser parser = createParser(shuffleXContent(builder))) {
filters = FiltersAggregationBuilder.parse("agg_name", parser); parser.nextToken();
// but setting a key enables it automatically FiltersAggregationBuilder filters = FiltersAggregationBuilder.parse("agg_name", parser);
assertTrue(filters.otherBucket()); // but setting a key enables it automatically
assertTrue(filters.otherBucket());
builder = XContentFactory.contentBuilder(randomFrom(XContentType.values())); builder = XContentFactory.contentBuilder(randomFrom(XContentType.values()));
builder.startObject(); builder.startObject();
builder.startArray("filters").endArray(); builder.startArray("filters").endArray();
builder.field("other_bucket", false); builder.field("other_bucket", false);
builder.field("other_bucket_key", "some_key"); builder.field("other_bucket_key", "some_key");
builder.endObject(); builder.endObject();
parser = createParser(shuffleXContent(builder)); }
parser.nextToken(); try (XContentParser parser = createParser(shuffleXContent(builder))) {
filters = FiltersAggregationBuilder.parse("agg_name", parser); parser.nextToken();
// unless the other bucket is explicitly disabled FiltersAggregationBuilder filters = FiltersAggregationBuilder.parse("agg_name", parser);
assertFalse(filters.otherBucket()); // unless the other bucket is explicitly disabled
assertFalse(filters.otherBucket());
}
} }
public void testRewrite() throws IOException { public void testRewrite() throws IOException {

View File

@ -264,9 +264,8 @@ public class SignificanceHeuristicTests extends ESTestCase {
protected void checkParseException(ParseFieldRegistry<SignificanceHeuristicParser> significanceHeuristicParserRegistry, protected void checkParseException(ParseFieldRegistry<SignificanceHeuristicParser> significanceHeuristicParserRegistry,
String faultyHeuristicDefinition, String expectedError) throws IOException { String faultyHeuristicDefinition, String expectedError) throws IOException {
try { try (XContentParser stParser = createParser(JsonXContent.jsonXContent,
XContentParser stParser = createParser(JsonXContent.jsonXContent, "{\"field\":\"text\", " + faultyHeuristicDefinition + ",\"min_doc_count\":200}")) {
"{\"field\":\"text\", " + faultyHeuristicDefinition + ",\"min_doc_count\":200}");
stParser.nextToken(); stParser.nextToken();
SignificantTermsAggregationBuilder.getParser(significanceHeuristicParserRegistry).parse("testagg", stParser); SignificantTermsAggregationBuilder.getParser(significanceHeuristicParserRegistry).parse("testagg", stParser);
fail(); fail();
@ -301,9 +300,10 @@ public class SignificanceHeuristicTests extends ESTestCase {
protected SignificanceHeuristic parseFromString(ParseFieldRegistry<SignificanceHeuristicParser> significanceHeuristicParserRegistry, protected SignificanceHeuristic parseFromString(ParseFieldRegistry<SignificanceHeuristicParser> significanceHeuristicParserRegistry,
String heuristicString) throws IOException { String heuristicString) throws IOException {
XContentParser stParser = createParser(JsonXContent.jsonXContent, try (XContentParser stParser = createParser(JsonXContent.jsonXContent,
"{\"field\":\"text\", " + heuristicString + ", \"min_doc_count\":200}"); "{\"field\":\"text\", " + heuristicString + ", \"min_doc_count\":200}")) {
return parseSignificanceHeuristic(significanceHeuristicParserRegistry, stParser); return parseSignificanceHeuristic(significanceHeuristicParserRegistry, stParser);
}
} }
void testBackgroundAssertions(SignificanceHeuristic heuristicIsSuperset, SignificanceHeuristic heuristicNotSuperset) { void testBackgroundAssertions(SignificanceHeuristic heuristicIsSuperset, SignificanceHeuristic heuristicNotSuperset) {

View File

@ -214,21 +214,22 @@ public class IncludeExcludeTests extends ESTestCase {
incExc.toXContent(builder, ToXContent.EMPTY_PARAMS); incExc.toXContent(builder, ToXContent.EMPTY_PARAMS);
builder.endObject(); builder.endObject();
XContentParser parser = createParser(builder); try (XContentParser parser = createParser(builder)) {
XContentParser.Token token = parser.nextToken(); XContentParser.Token token = parser.nextToken();
assertEquals(token, XContentParser.Token.START_OBJECT); assertEquals(token, XContentParser.Token.START_OBJECT);
token = parser.nextToken(); token = parser.nextToken();
assertEquals(token, XContentParser.Token.FIELD_NAME); assertEquals(token, XContentParser.Token.FIELD_NAME);
assertEquals(field.getPreferredName(), parser.currentName()); assertEquals(field.getPreferredName(), parser.currentName());
token = parser.nextToken(); token = parser.nextToken();
if (field.getPreferredName().equalsIgnoreCase("include")) { if (field.getPreferredName().equalsIgnoreCase("include")) {
return IncludeExclude.parseInclude(parser); return IncludeExclude.parseInclude(parser);
} else if (field.getPreferredName().equalsIgnoreCase("exclude")) { } else if (field.getPreferredName().equalsIgnoreCase("exclude")) {
return IncludeExclude.parseExclude(parser); return IncludeExclude.parseExclude(parser);
} else { } else {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Unexpected field name serialized in test: " + field.getPreferredName()); "Unexpected field name serialized in test: " + field.getPreferredName());
}
} }
} }
@ -260,28 +261,29 @@ public class IncludeExcludeTests extends ESTestCase {
incExc.toXContent(builder, ToXContent.EMPTY_PARAMS); incExc.toXContent(builder, ToXContent.EMPTY_PARAMS);
builder.endObject(); builder.endObject();
XContentParser parser = createParser(builder); try (XContentParser parser = createParser(builder)) {
XContentParser.Token token = parser.nextToken(); XContentParser.Token token = parser.nextToken();
assertEquals(token, XContentParser.Token.START_OBJECT); assertEquals(token, XContentParser.Token.START_OBJECT);
IncludeExclude inc = null; IncludeExclude inc = null;
IncludeExclude exc = null; IncludeExclude exc = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
assertEquals(XContentParser.Token.FIELD_NAME, token); assertEquals(XContentParser.Token.FIELD_NAME, token);
if (IncludeExclude.INCLUDE_FIELD.match(parser.currentName(), parser.getDeprecationHandler())) { if (IncludeExclude.INCLUDE_FIELD.match(parser.currentName(), parser.getDeprecationHandler())) {
token = parser.nextToken(); token = parser.nextToken();
inc = IncludeExclude.parseInclude(parser); inc = IncludeExclude.parseInclude(parser);
} else if (IncludeExclude.EXCLUDE_FIELD.match(parser.currentName(), parser.getDeprecationHandler())) { } else if (IncludeExclude.EXCLUDE_FIELD.match(parser.currentName(), parser.getDeprecationHandler())) {
token = parser.nextToken(); token = parser.nextToken();
exc = IncludeExclude.parseExclude(parser); exc = IncludeExclude.parseExclude(parser);
} else { } else {
throw new IllegalArgumentException("Unexpected field name serialized in test: " + parser.currentName()); throw new IllegalArgumentException("Unexpected field name serialized in test: " + parser.currentName());
}
} }
assertNotNull(inc);
assertNotNull(exc);
// Include and Exclude clauses are parsed independently and then merged
return IncludeExclude.merge(inc, exc);
} }
assertNotNull(inc);
assertNotNull(exc);
// Include and Exclude clauses are parsed independently and then merged
return IncludeExclude.merge(inc, exc);
} }
} }

View File

@ -64,7 +64,9 @@ public class SearchSourceBuilderTests extends AbstractSearchTestCase {
builder.prettyPrint(); builder.prettyPrint();
} }
testSearchSourceBuilder.toXContent(builder, ToXContent.EMPTY_PARAMS); testSearchSourceBuilder.toXContent(builder, ToXContent.EMPTY_PARAMS);
assertParseSearchSource(testSearchSourceBuilder, createParser(builder)); try (XContentParser xParser = createParser(builder)) {
assertParseSearchSource(testSearchSourceBuilder, xParser);
}
} }
public void testFromXContentInvalid() throws IOException { public void testFromXContentInvalid() throws IOException {

View File

@ -139,17 +139,18 @@ public class HighlightBuilderTests extends ESTestCase {
shuffled = shuffleXContent(builder, "fields"); shuffled = shuffleXContent(builder, "fields");
} }
XContentParser parser = createParser(shuffled); try (XContentParser parser = createParser(shuffled)) {
parser.nextToken(); parser.nextToken();
HighlightBuilder secondHighlightBuilder; HighlightBuilder secondHighlightBuilder;
try { try {
secondHighlightBuilder = HighlightBuilder.fromXContent(parser); secondHighlightBuilder = HighlightBuilder.fromXContent(parser);
} catch (RuntimeException e) { } catch (RuntimeException e) {
throw new RuntimeException("Error parsing " + highlightBuilder, e); throw new RuntimeException("Error parsing " + highlightBuilder, e);
}
assertNotSame(highlightBuilder, secondHighlightBuilder);
assertEquals(highlightBuilder, secondHighlightBuilder);
assertEquals(highlightBuilder.hashCode(), secondHighlightBuilder.hashCode());
} }
assertNotSame(highlightBuilder, secondHighlightBuilder);
assertEquals(highlightBuilder, secondHighlightBuilder);
assertEquals(highlightBuilder.hashCode(), secondHighlightBuilder.hashCode());
} }
} }
@ -179,8 +180,9 @@ public class HighlightBuilderTests extends ESTestCase {
} }
private <T extends Throwable> T expectParseThrows(Class<T> exceptionClass, String highlightElement) throws IOException { private <T extends Throwable> T expectParseThrows(Class<T> exceptionClass, String highlightElement) throws IOException {
XContentParser parser = createParser(JsonXContent.jsonXContent, highlightElement); try (XContentParser parser = createParser(JsonXContent.jsonXContent, highlightElement)) {
return expectThrows(exceptionClass, () -> HighlightBuilder.fromXContent(parser)); return expectThrows(exceptionClass, () -> HighlightBuilder.fromXContent(parser));
}
} }
/** /**
@ -389,30 +391,32 @@ public class HighlightBuilderTests extends ESTestCase {
String highlightElement = "{\n" + String highlightElement = "{\n" +
" \"tags_schema\" : \"styled\"\n" + " \"tags_schema\" : \"styled\"\n" +
"}\n"; "}\n";
XContentParser parser = createParser(JsonXContent.jsonXContent, highlightElement); try (XContentParser parser = createParser(JsonXContent.jsonXContent, highlightElement)) {
HighlightBuilder highlightBuilder = HighlightBuilder.fromXContent(parser); HighlightBuilder highlightBuilder = HighlightBuilder.fromXContent(parser);
assertArrayEquals("setting tags_schema 'styled' should alter pre_tags", HighlightBuilder.DEFAULT_STYLED_PRE_TAG, assertArrayEquals("setting tags_schema 'styled' should alter pre_tags", HighlightBuilder.DEFAULT_STYLED_PRE_TAG,
highlightBuilder.preTags()); highlightBuilder.preTags());
assertArrayEquals("setting tags_schema 'styled' should alter post_tags", HighlightBuilder.DEFAULT_STYLED_POST_TAGS, assertArrayEquals("setting tags_schema 'styled' should alter post_tags", HighlightBuilder.DEFAULT_STYLED_POST_TAGS,
highlightBuilder.postTags()); highlightBuilder.postTags());
highlightElement = "{\n" + highlightElement = "{\n" +
" \"tags_schema\" : \"default\"\n" + " \"tags_schema\" : \"default\"\n" +
"}\n"; "}\n";
parser = createParser(JsonXContent.jsonXContent, highlightElement); }
try (XContentParser parser = createParser(JsonXContent.jsonXContent, highlightElement)) {
highlightBuilder = HighlightBuilder.fromXContent(parser); HighlightBuilder highlightBuilder = HighlightBuilder.fromXContent(parser);
assertArrayEquals("setting tags_schema 'default' should alter pre_tags", HighlightBuilder.DEFAULT_PRE_TAGS, assertArrayEquals("setting tags_schema 'default' should alter pre_tags", HighlightBuilder.DEFAULT_PRE_TAGS,
highlightBuilder.preTags()); highlightBuilder.preTags());
assertArrayEquals("setting tags_schema 'default' should alter post_tags", HighlightBuilder.DEFAULT_POST_TAGS, assertArrayEquals("setting tags_schema 'default' should alter post_tags", HighlightBuilder.DEFAULT_POST_TAGS,
highlightBuilder.postTags()); highlightBuilder.postTags());
XContentParseException e = expectParseThrows(XContentParseException.class, "{\n" + XContentParseException e = expectParseThrows(XContentParseException.class, "{\n" +
" \"tags_schema\" : \"somthing_else\"\n" + " \"tags_schema\" : \"somthing_else\"\n" +
"}\n"); "}\n");
assertThat(e.getMessage(), containsString("[highlight] failed to parse field [tags_schema]")); assertThat(e.getMessage(), containsString("[highlight] failed to parse field [tags_schema]"));
assertEquals("Unknown tag schema [somthing_else]", e.getCause().getMessage()); assertEquals("Unknown tag schema [somthing_else]", e.getCause().getMessage());
}
} }
/** /**
@ -420,22 +424,22 @@ public class HighlightBuilderTests extends ESTestCase {
*/ */
public void testParsingEmptyStructure() throws IOException { public void testParsingEmptyStructure() throws IOException {
String highlightElement = "{ }"; String highlightElement = "{ }";
XContentParser parser = createParser(JsonXContent.jsonXContent, highlightElement); try (XContentParser parser = createParser(JsonXContent.jsonXContent, highlightElement)) {
HighlightBuilder highlightBuilder = HighlightBuilder.fromXContent(parser);
HighlightBuilder highlightBuilder = HighlightBuilder.fromXContent(parser); assertEquals("expected plain HighlightBuilder", new HighlightBuilder(), highlightBuilder);
assertEquals("expected plain HighlightBuilder", new HighlightBuilder(), highlightBuilder); }
highlightElement = "{ \"fields\" : { } }"; highlightElement = "{ \"fields\" : { } }";
parser = createParser(JsonXContent.jsonXContent, highlightElement); try (XContentParser parser = createParser(JsonXContent.jsonXContent, highlightElement)) {
HighlightBuilder highlightBuilder = HighlightBuilder.fromXContent(parser);
highlightBuilder = HighlightBuilder.fromXContent(parser); assertEquals("defining no field should return plain HighlightBuilder", new HighlightBuilder(), highlightBuilder);
assertEquals("defining no field should return plain HighlightBuilder", new HighlightBuilder(), highlightBuilder); }
highlightElement = "{ \"fields\" : { \"foo\" : { } } }"; highlightElement = "{ \"fields\" : { \"foo\" : { } } }";
parser = createParser(JsonXContent.jsonXContent, highlightElement); try (XContentParser parser = createParser(JsonXContent.jsonXContent, highlightElement)) {
HighlightBuilder highlightBuilder = HighlightBuilder.fromXContent(parser);
highlightBuilder = HighlightBuilder.fromXContent(parser); assertEquals("expected HighlightBuilder with field", new HighlightBuilder().field(new Field("foo")), highlightBuilder);
assertEquals("expected HighlightBuilder with field", new HighlightBuilder().field(new Field("foo")), highlightBuilder); }
} }
public void testPreTagsWithoutPostTags() throws IOException { public void testPreTagsWithoutPostTags() throws IOException {

View File

@ -62,16 +62,17 @@ public class HighlightFieldTests extends ESTestCase {
builder.startObject(); // we need to wrap xContent output in proper object to create a parser for it builder.startObject(); // we need to wrap xContent output in proper object to create a parser for it
builder = highlightField.toXContent(builder, ToXContent.EMPTY_PARAMS); builder = highlightField.toXContent(builder, ToXContent.EMPTY_PARAMS);
builder.endObject(); builder.endObject();
XContentParser parser = createParser(builder); try (XContentParser parser = createParser(builder)) {
parser.nextToken(); // skip to the opening object token, fromXContent advances from here and starts with the field name parser.nextToken(); // skip to the opening object token, fromXContent advances from here and starts with the field name
parser.nextToken(); parser.nextToken();
HighlightField parsedField = HighlightField.fromXContent(parser); HighlightField parsedField = HighlightField.fromXContent(parser);
assertEquals(highlightField, parsedField); assertEquals(highlightField, parsedField);
if (highlightField.fragments() != null) { if (highlightField.fragments() != null) {
assertEquals(XContentParser.Token.END_ARRAY, parser.currentToken()); assertEquals(XContentParser.Token.END_ARRAY, parser.currentToken());
}
assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
assertNull(parser.nextToken());
} }
assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
assertNull(parser.nextToken());
} }
public void testToXContent() throws IOException { public void testToXContent() throws IOException {

View File

@ -121,12 +121,13 @@ public class QueryRescorerBuilderTests extends ESTestCase {
XContentBuilder shuffled = shuffleXContent(builder); XContentBuilder shuffled = shuffleXContent(builder);
XContentParser parser = createParser(shuffled); try (XContentParser parser = createParser(shuffled)) {
parser.nextToken(); parser.nextToken();
RescorerBuilder<?> secondRescoreBuilder = RescorerBuilder.parseFromXContent(parser); RescorerBuilder<?> secondRescoreBuilder = RescorerBuilder.parseFromXContent(parser);
assertNotSame(rescoreBuilder, secondRescoreBuilder); assertNotSame(rescoreBuilder, secondRescoreBuilder);
assertEquals(rescoreBuilder, secondRescoreBuilder); assertEquals(rescoreBuilder, secondRescoreBuilder);
assertEquals(rescoreBuilder.hashCode(), secondRescoreBuilder.hashCode()); assertEquals(rescoreBuilder.hashCode(), secondRescoreBuilder.hashCode());
}
} }
} }
@ -214,67 +215,61 @@ public class QueryRescorerBuilderTests extends ESTestCase {
public void testUnknownFieldsExpection() throws IOException { public void testUnknownFieldsExpection() throws IOException {
String rescoreElement = "{\n" + String rescoreElement = "{\n" +
" \"window_size\" : 20,\n" + " \"window_size\" : 20,\n" +
" \"bad_rescorer_name\" : { }\n" + " \"bad_rescorer_name\" : { }\n" +
"}\n"; "}\n";
{ try (XContentParser parser = createParser(rescoreElement)) {
XContentParser parser = createParser(rescoreElement);
Exception e = expectThrows(NamedObjectNotFoundException.class, () -> RescorerBuilder.parseFromXContent(parser)); Exception e = expectThrows(NamedObjectNotFoundException.class, () -> RescorerBuilder.parseFromXContent(parser));
assertEquals("[3:27] unable to parse RescorerBuilder with name [bad_rescorer_name]: parser not found", e.getMessage()); assertEquals("[3:27] unable to parse RescorerBuilder with name [bad_rescorer_name]: parser not found", e.getMessage());
} }
rescoreElement = "{\n" + rescoreElement = "{\n" +
" \"bad_fieldName\" : 20\n" + " \"bad_fieldName\" : 20\n" +
"}\n"; "}\n";
{ try (XContentParser parser = createParser(rescoreElement)) {
XContentParser parser = createParser(rescoreElement);
Exception e = expectThrows(ParsingException.class, () -> RescorerBuilder.parseFromXContent(parser)); Exception e = expectThrows(ParsingException.class, () -> RescorerBuilder.parseFromXContent(parser));
assertEquals("rescore doesn't support [bad_fieldName]", e.getMessage()); assertEquals("rescore doesn't support [bad_fieldName]", e.getMessage());
} }
rescoreElement = "{\n" + rescoreElement = "{\n" +
" \"window_size\" : 20,\n" + " \"window_size\" : 20,\n" +
" \"query\" : [ ]\n" + " \"query\" : [ ]\n" +
"}\n"; "}\n";
{ try (XContentParser parser = createParser(rescoreElement)) {
XContentParser parser = createParser(rescoreElement);
Exception e = expectThrows(ParsingException.class, () -> RescorerBuilder.parseFromXContent(parser)); Exception e = expectThrows(ParsingException.class, () -> RescorerBuilder.parseFromXContent(parser));
assertEquals("unexpected token [START_ARRAY] after [query]", e.getMessage()); assertEquals("unexpected token [START_ARRAY] after [query]", e.getMessage());
} }
rescoreElement = "{ }"; rescoreElement = "{ }";
{ try (XContentParser parser = createParser(rescoreElement)) {
XContentParser parser = createParser(rescoreElement);
Exception e = expectThrows(ParsingException.class, () -> RescorerBuilder.parseFromXContent(parser)); Exception e = expectThrows(ParsingException.class, () -> RescorerBuilder.parseFromXContent(parser));
assertEquals("missing rescore type", e.getMessage()); assertEquals("missing rescore type", e.getMessage());
} }
rescoreElement = "{\n" + rescoreElement = "{\n" +
" \"window_size\" : 20,\n" + " \"window_size\" : 20,\n" +
" \"query\" : { \"bad_fieldname\" : 1.0 } \n" + " \"query\" : { \"bad_fieldname\" : 1.0 } \n" +
"}\n"; "}\n";
{ try (XContentParser parser = createParser(rescoreElement)) {
XContentParser parser = createParser(rescoreElement);
XContentParseException e = expectThrows(XContentParseException.class, () -> RescorerBuilder.parseFromXContent(parser)); XContentParseException e = expectThrows(XContentParseException.class, () -> RescorerBuilder.parseFromXContent(parser));
assertEquals("[3:17] [query] unknown field [bad_fieldname], parser not found", e.getMessage()); assertEquals("[3:17] [query] unknown field [bad_fieldname], parser not found", e.getMessage());
} }
rescoreElement = "{\n" + rescoreElement = "{\n" +
" \"window_size\" : 20,\n" + " \"window_size\" : 20,\n" +
" \"query\" : { \"rescore_query\" : { \"unknown_queryname\" : { } } } \n" + " \"query\" : { \"rescore_query\" : { \"unknown_queryname\" : { } } } \n" +
"}\n"; "}\n";
{ try (XContentParser parser = createParser(rescoreElement)) {
XContentParser parser = createParser(rescoreElement);
Exception e = expectThrows(XContentParseException.class, () -> RescorerBuilder.parseFromXContent(parser)); Exception e = expectThrows(XContentParseException.class, () -> RescorerBuilder.parseFromXContent(parser));
assertThat(e.getMessage(), containsString("[query] failed to parse field [rescore_query]")); assertThat(e.getMessage(), containsString("[query] failed to parse field [rescore_query]"));
} }
rescoreElement = "{\n" + rescoreElement = "{\n" +
" \"window_size\" : 20,\n" + " \"window_size\" : 20,\n" +
" \"query\" : { \"rescore_query\" : { \"match_all\" : { } } } \n" " \"query\" : { \"rescore_query\" : { \"match_all\" : { } } } \n"
+ "}\n"; + "}\n";
XContentParser parser = createParser(rescoreElement); try (XContentParser parser = createParser(rescoreElement)) {
RescorerBuilder.parseFromXContent(parser); RescorerBuilder.parseFromXContent(parser);
}
} }
/** /**

View File

@ -136,11 +136,12 @@ public class SearchAfterBuilderTests extends ESTestCase {
} }
jsonBuilder.endArray(); jsonBuilder.endArray();
jsonBuilder.endObject(); jsonBuilder.endObject();
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(jsonBuilder)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(jsonBuilder))) {
parser.nextToken(); parser.nextToken();
parser.nextToken(); parser.nextToken();
parser.nextToken(); parser.nextToken();
return SearchAfterBuilder.fromXContent(parser); return SearchAfterBuilder.fromXContent(parser);
}
} }
private static SearchAfterBuilder serializedCopy(SearchAfterBuilder original) throws IOException { private static SearchAfterBuilder serializedCopy(SearchAfterBuilder original) throws IOException {
@ -174,14 +175,15 @@ public class SearchAfterBuilderTests extends ESTestCase {
builder.startObject(); builder.startObject();
searchAfterBuilder.innerToXContent(builder); searchAfterBuilder.innerToXContent(builder);
builder.endObject(); builder.endObject();
XContentParser parser = createParser(shuffleXContent(builder)); try (XContentParser parser = createParser(shuffleXContent(builder))) {
parser.nextToken(); parser.nextToken();
parser.nextToken(); parser.nextToken();
parser.nextToken(); parser.nextToken();
SearchAfterBuilder secondSearchAfterBuilder = SearchAfterBuilder.fromXContent(parser); SearchAfterBuilder secondSearchAfterBuilder = SearchAfterBuilder.fromXContent(parser);
assertNotSame(searchAfterBuilder, secondSearchAfterBuilder); assertNotSame(searchAfterBuilder, secondSearchAfterBuilder);
assertEquals(searchAfterBuilder, secondSearchAfterBuilder); assertEquals(searchAfterBuilder, secondSearchAfterBuilder);
assertEquals(searchAfterBuilder.hashCode(), secondSearchAfterBuilder.hashCode()); assertEquals(searchAfterBuilder.hashCode(), secondSearchAfterBuilder.hashCode());
}
} }
} }

View File

@ -306,11 +306,12 @@ public class SliceBuilderTests extends ESTestCase {
builder.startObject(); builder.startObject();
sliceBuilder.innerToXContent(builder); sliceBuilder.innerToXContent(builder);
builder.endObject(); builder.endObject();
XContentParser parser = createParser(shuffleXContent(builder)); try (XContentParser parser = createParser(shuffleXContent(builder))) {
SliceBuilder secondSliceBuilder = SliceBuilder.fromXContent(parser); SliceBuilder secondSliceBuilder = SliceBuilder.fromXContent(parser);
assertNotSame(sliceBuilder, secondSliceBuilder); assertNotSame(sliceBuilder, secondSliceBuilder);
assertEquals(sliceBuilder, secondSliceBuilder); assertEquals(sliceBuilder, secondSliceBuilder);
assertEquals(sliceBuilder.hashCode(), secondSliceBuilder.hashCode()); assertEquals(sliceBuilder.hashCode(), secondSliceBuilder.hashCode());
}
} }
public void testInvalidArguments() throws Exception { public void testInvalidArguments() throws Exception {

View File

@ -121,21 +121,22 @@ public abstract class AbstractSortTestCase<T extends SortBuilder<T>> extends EST
} }
testItem.toXContent(builder, ToXContent.EMPTY_PARAMS); testItem.toXContent(builder, ToXContent.EMPTY_PARAMS);
XContentBuilder shuffled = shuffleXContent(builder); XContentBuilder shuffled = shuffleXContent(builder);
XContentParser itemParser = createParser(shuffled); try (XContentParser itemParser = createParser(shuffled)) {
itemParser.nextToken(); itemParser.nextToken();
/* /*
* filter out name of sort, or field name to sort on for element fieldSort * filter out name of sort, or field name to sort on for element fieldSort
*/ */
itemParser.nextToken(); itemParser.nextToken();
String elementName = itemParser.currentName(); String elementName = itemParser.currentName();
itemParser.nextToken(); itemParser.nextToken();
T parsedItem = fromXContent(itemParser, elementName); T parsedItem = fromXContent(itemParser, elementName);
assertNotSame(testItem, parsedItem); assertNotSame(testItem, parsedItem);
assertEquals(testItem, parsedItem); assertEquals(testItem, parsedItem);
assertEquals(testItem.hashCode(), parsedItem.hashCode()); assertEquals(testItem.hashCode(), parsedItem.hashCode());
assertWarnings(testItem); assertWarnings(testItem);
}
} }
} }

View File

@ -304,14 +304,15 @@ public class FieldSortBuilderTests extends AbstractSortTestCase<FieldSortBuilder
public void testUnknownOptionFails() throws IOException { public void testUnknownOptionFails() throws IOException {
String json = "{ \"post_date\" : {\"reverse\" : true} },\n"; String json = "{ \"post_date\" : {\"reverse\" : true} },\n";
XContentParser parser = createParser(JsonXContent.jsonXContent, json); try (XContentParser parser = createParser(JsonXContent.jsonXContent, json)) {
// need to skip until parser is located on second START_OBJECT // need to skip until parser is located on second START_OBJECT
parser.nextToken(); parser.nextToken();
parser.nextToken(); parser.nextToken();
parser.nextToken(); parser.nextToken();
XContentParseException e = expectThrows(XContentParseException.class, () -> FieldSortBuilder.fromXContent(parser, "")); XContentParseException e = expectThrows(XContentParseException.class, () -> FieldSortBuilder.fromXContent(parser, ""));
assertEquals("[1:18] [field_sort] unknown field [reverse], parser not found", e.getMessage()); assertEquals("[1:18] [field_sort] unknown field [reverse], parser not found", e.getMessage());
}
} }
@Override @Override

View File

@ -232,12 +232,13 @@ public class GeoDistanceSortBuilderTests extends AbstractSortTestCase<GeoDistanc
" \"distance_type\" : \"arc\",\n" + " \"distance_type\" : \"arc\",\n" +
" \"mode\" : \"SUM\"\n" + " \"mode\" : \"SUM\"\n" +
"}"; "}";
XContentParser itemParser = createParser(JsonXContent.jsonXContent, json); try (XContentParser itemParser = createParser(JsonXContent.jsonXContent, json)) {
itemParser.nextToken(); itemParser.nextToken();
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, IllegalArgumentException e = expectThrows(IllegalArgumentException.class,
() -> GeoDistanceSortBuilder.fromXContent(itemParser, "")); () -> GeoDistanceSortBuilder.fromXContent(itemParser, ""));
assertEquals("sort_mode [sum] isn't supported for sorting by geo distance", e.getMessage()); assertEquals("sort_mode [sum] isn't supported for sorting by geo distance", e.getMessage());
}
} }
public void testGeoDistanceSortCanBeParsedFromGeoHash() throws IOException { public void testGeoDistanceSortCanBeParsedFromGeoHash() throws IOException {
@ -258,16 +259,17 @@ public class GeoDistanceSortBuilderTests extends AbstractSortTestCase<GeoDistanc
" },\n" + " },\n" +
" \"validation_method\" : \"STRICT\"\n" + " \"validation_method\" : \"STRICT\"\n" +
" }"; " }";
XContentParser itemParser = createParser(JsonXContent.jsonXContent, json); try (XContentParser itemParser = createParser(JsonXContent.jsonXContent, json)) {
itemParser.nextToken(); itemParser.nextToken();
GeoDistanceSortBuilder result = GeoDistanceSortBuilder.fromXContent(itemParser, json); GeoDistanceSortBuilder result = GeoDistanceSortBuilder.fromXContent(itemParser, json);
assertEquals("[-19.700583312660456, -2.8225036337971687, " assertEquals("[-19.700583312660456, -2.8225036337971687, "
+ "31.537466906011105, -74.63590376079082, " + "31.537466906011105, -74.63590376079082, "
+ "43.71844606474042, -5.548660643398762, " + "43.71844606474042, -5.548660643398762, "
+ "-37.20467280596495, 38.71751043945551, " + "-37.20467280596495, 38.71751043945551, "
+ "-69.44606635719538, 84.25200328230858, " + "-69.44606635719538, 84.25200328230858, "
+ "-39.03717711567879, 44.74099852144718]", Arrays.toString(result.points())); + "-39.03717711567879, 44.74099852144718]", Arrays.toString(result.points()));
}
} }
public void testGeoDistanceSortParserManyPointsNoException() throws Exception { public void testGeoDistanceSortParserManyPointsNoException() throws Exception {
@ -380,9 +382,10 @@ public class GeoDistanceSortBuilderTests extends AbstractSortTestCase<GeoDistanc
} }
private GeoDistanceSortBuilder parse(XContentBuilder sortBuilder) throws Exception { private GeoDistanceSortBuilder parse(XContentBuilder sortBuilder) throws Exception {
XContentParser parser = createParser(sortBuilder); try (XContentParser parser = createParser(sortBuilder)) {
parser.nextToken(); parser.nextToken();
return GeoDistanceSortBuilder.fromXContent(parser, null); return GeoDistanceSortBuilder.fromXContent(parser, null);
}
} }
@Override @Override

View File

@ -73,12 +73,13 @@ public class NestedSortBuilderTests extends ESTestCase {
XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values())); XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values()));
testItem.toXContent(builder, ToXContent.EMPTY_PARAMS); testItem.toXContent(builder, ToXContent.EMPTY_PARAMS);
XContentBuilder shuffled = shuffleXContent(builder); XContentBuilder shuffled = shuffleXContent(builder);
XContentParser parser = createParser(shuffled); try (XContentParser parser = createParser(shuffled)) {
parser.nextToken(); parser.nextToken();
NestedSortBuilder parsedItem = NestedSortBuilder.fromXContent(parser); NestedSortBuilder parsedItem = NestedSortBuilder.fromXContent(parser);
assertNotSame(testItem, parsedItem); assertNotSame(testItem, parsedItem);
assertEquals(testItem, parsedItem); assertEquals(testItem, parsedItem);
assertEquals(testItem.hashCode(), parsedItem.hashCode()); assertEquals(testItem.hashCode(), parsedItem.hashCode());
}
} }
} }

View File

@ -177,20 +177,21 @@ public class ScriptSortBuilderTests extends AbstractSortTestCase<ScriptSortBuild
"\"mode\" : \"max\",\n" + "\"mode\" : \"max\",\n" +
"\"order\" : \"asc\"\n" + "\"order\" : \"asc\"\n" +
"} }\n"; "} }\n";
XContentParser parser = createParser(JsonXContent.jsonXContent, scriptSort); try (XContentParser parser = createParser(JsonXContent.jsonXContent, scriptSort)) {
parser.nextToken(); parser.nextToken();
parser.nextToken(); parser.nextToken();
parser.nextToken(); parser.nextToken();
ScriptSortBuilder builder = ScriptSortBuilder.fromXContent(parser, null); ScriptSortBuilder builder = ScriptSortBuilder.fromXContent(parser, null);
assertEquals("doc['field_name'].value * factor", builder.script().getIdOrCode()); assertEquals("doc['field_name'].value * factor", builder.script().getIdOrCode());
assertEquals(Script.DEFAULT_SCRIPT_LANG, builder.script().getLang()); assertEquals(Script.DEFAULT_SCRIPT_LANG, builder.script().getLang());
assertEquals(1.1, builder.script().getParams().get("factor")); assertEquals(1.1, builder.script().getParams().get("factor"));
assertEquals(ScriptType.INLINE, builder.script().getType()); assertEquals(ScriptType.INLINE, builder.script().getType());
assertEquals(ScriptSortType.NUMBER, builder.type()); assertEquals(ScriptSortType.NUMBER, builder.type());
assertEquals(SortOrder.ASC, builder.order()); assertEquals(SortOrder.ASC, builder.order());
assertEquals(SortMode.MAX, builder.sortMode()); assertEquals(SortMode.MAX, builder.sortMode());
assertNull(builder.getNestedSort()); assertNull(builder.getNestedSort());
}
} }
public void testParseJson_simple() throws IOException { public void testParseJson_simple() throws IOException {
@ -201,54 +202,58 @@ public class ScriptSortBuilderTests extends AbstractSortTestCase<ScriptSortBuild
"\"mode\" : \"max\",\n" + "\"mode\" : \"max\",\n" +
"\"order\" : \"asc\"\n" + "\"order\" : \"asc\"\n" +
"} }\n"; "} }\n";
XContentParser parser = createParser(JsonXContent.jsonXContent, scriptSort); try (XContentParser parser = createParser(JsonXContent.jsonXContent, scriptSort)) {
parser.nextToken(); parser.nextToken();
parser.nextToken(); parser.nextToken();
parser.nextToken(); parser.nextToken();
ScriptSortBuilder builder = ScriptSortBuilder.fromXContent(parser, null); ScriptSortBuilder builder = ScriptSortBuilder.fromXContent(parser, null);
assertEquals("doc['field_name'].value", builder.script().getIdOrCode()); assertEquals("doc['field_name'].value", builder.script().getIdOrCode());
assertEquals(Script.DEFAULT_SCRIPT_LANG, builder.script().getLang()); assertEquals(Script.DEFAULT_SCRIPT_LANG, builder.script().getLang());
assertEquals(builder.script().getParams(), Collections.emptyMap()); assertEquals(builder.script().getParams(), Collections.emptyMap());
assertEquals(ScriptType.INLINE, builder.script().getType()); assertEquals(ScriptType.INLINE, builder.script().getType());
assertEquals(ScriptSortType.NUMBER, builder.type()); assertEquals(ScriptSortType.NUMBER, builder.type());
assertEquals(SortOrder.ASC, builder.order()); assertEquals(SortOrder.ASC, builder.order());
assertEquals(SortMode.MAX, builder.sortMode()); assertEquals(SortMode.MAX, builder.sortMode());
assertNull(builder.getNestedSort()); assertNull(builder.getNestedSort());
}
} }
public void testParseBadFieldNameExceptions() throws IOException { public void testParseBadFieldNameExceptions() throws IOException {
String scriptSort = "{\"_script\" : {" + "\"bad_field\" : \"number\"" + "} }"; String scriptSort = "{\"_script\" : {" + "\"bad_field\" : \"number\"" + "} }";
XContentParser parser = createParser(JsonXContent.jsonXContent, scriptSort); try (XContentParser parser = createParser(JsonXContent.jsonXContent, scriptSort)) {
parser.nextToken(); parser.nextToken();
parser.nextToken(); parser.nextToken();
parser.nextToken(); parser.nextToken();
XContentParseException e = expectThrows(XContentParseException.class, () -> ScriptSortBuilder.fromXContent(parser, null)); XContentParseException e = expectThrows(XContentParseException.class, () -> ScriptSortBuilder.fromXContent(parser, null));
assertEquals("[1:15] [_script] unknown field [bad_field], parser not found", e.getMessage()); assertEquals("[1:15] [_script] unknown field [bad_field], parser not found", e.getMessage());
}
} }
public void testParseBadFieldNameExceptionsOnStartObject() throws IOException { public void testParseBadFieldNameExceptionsOnStartObject() throws IOException {
String scriptSort = "{\"_script\" : {" + "\"bad_field\" : { \"order\" : \"asc\" } } }"; String scriptSort = "{\"_script\" : {" + "\"bad_field\" : { \"order\" : \"asc\" } } }";
XContentParser parser = createParser(JsonXContent.jsonXContent, scriptSort); try (XContentParser parser = createParser(JsonXContent.jsonXContent, scriptSort)) {
parser.nextToken(); parser.nextToken();
parser.nextToken(); parser.nextToken();
parser.nextToken(); parser.nextToken();
XContentParseException e = expectThrows(XContentParseException.class, () -> ScriptSortBuilder.fromXContent(parser, null)); XContentParseException e = expectThrows(XContentParseException.class, () -> ScriptSortBuilder.fromXContent(parser, null));
assertEquals("[1:15] [_script] unknown field [bad_field], parser not found", e.getMessage()); assertEquals("[1:15] [_script] unknown field [bad_field], parser not found", e.getMessage());
}
} }
public void testParseUnexpectedToken() throws IOException { public void testParseUnexpectedToken() throws IOException {
String scriptSort = "{\"_script\" : {" + "\"script\" : [ \"order\" : \"asc\" ] } }"; String scriptSort = "{\"_script\" : {" + "\"script\" : [ \"order\" : \"asc\" ] } }";
XContentParser parser = createParser(JsonXContent.jsonXContent, scriptSort); try (XContentParser parser = createParser(JsonXContent.jsonXContent, scriptSort)) {
parser.nextToken(); parser.nextToken();
parser.nextToken(); parser.nextToken();
parser.nextToken(); parser.nextToken();
Exception e = expectThrows(XContentParseException.class, () -> ScriptSortBuilder.fromXContent(parser, null)); Exception e = expectThrows(XContentParseException.class, () -> ScriptSortBuilder.fromXContent(parser, null));
assertThat(e.getMessage(), containsString("[_script] script doesn't support values of type: START_ARRAY")); assertThat(e.getMessage(), containsString("[_script] script doesn't support values of type: START_ARRAY"));
}
} }
/** /**

View File

@ -252,12 +252,13 @@ public class SortBuilderTests extends ESTestCase {
} }
private List<SortBuilder<?>> parseSort(String jsonString) throws IOException { private List<SortBuilder<?>> parseSort(String jsonString) throws IOException {
XContentParser itemParser = createParser(JsonXContent.jsonXContent, jsonString); try (XContentParser itemParser = createParser(JsonXContent.jsonXContent, jsonString)) {
assertEquals(XContentParser.Token.START_OBJECT, itemParser.nextToken()); assertEquals(XContentParser.Token.START_OBJECT, itemParser.nextToken());
assertEquals(XContentParser.Token.FIELD_NAME, itemParser.nextToken()); assertEquals(XContentParser.Token.FIELD_NAME, itemParser.nextToken());
assertEquals("sort", itemParser.currentName()); assertEquals("sort", itemParser.currentName());
itemParser.nextToken(); itemParser.nextToken();
return SortBuilder.fromXContent(itemParser); return SortBuilder.fromXContent(itemParser);
}
} }
} }

View File

@ -140,14 +140,15 @@ public abstract class AbstractSuggestionBuilderTestCase<SB extends SuggestionBui
xContentBuilder.endObject(); xContentBuilder.endObject();
XContentBuilder shuffled = shuffleXContent(xContentBuilder, shuffleProtectedFields()); XContentBuilder shuffled = shuffleXContent(xContentBuilder, shuffleProtectedFields());
XContentParser parser = createParser(shuffled); try (XContentParser parser = createParser(shuffled)) {
// we need to skip the start object and the name, those will be parsed by outer SuggestBuilder // we need to skip the start object and the name, those will be parsed by outer SuggestBuilder
parser.nextToken(); parser.nextToken();
SuggestionBuilder<?> secondSuggestionBuilder = SuggestionBuilder.fromXContent(parser); SuggestionBuilder<?> secondSuggestionBuilder = SuggestionBuilder.fromXContent(parser);
assertNotSame(suggestionBuilder, secondSuggestionBuilder); assertNotSame(suggestionBuilder, secondSuggestionBuilder);
assertEquals(suggestionBuilder, secondSuggestionBuilder); assertEquals(suggestionBuilder, secondSuggestionBuilder);
assertEquals(suggestionBuilder.hashCode(), secondSuggestionBuilder.hashCode()); assertEquals(suggestionBuilder.hashCode(), secondSuggestionBuilder.hashCode());
}
} }
} }

View File

@ -74,11 +74,12 @@ public class SuggestBuilderTests extends ESTestCase {
xContentBuilder.prettyPrint(); xContentBuilder.prettyPrint();
} }
suggestBuilder.toXContent(xContentBuilder, ToXContent.EMPTY_PARAMS); suggestBuilder.toXContent(xContentBuilder, ToXContent.EMPTY_PARAMS);
XContentParser parser = createParser(xContentBuilder); try (XContentParser parser = createParser(xContentBuilder)) {
SuggestBuilder secondSuggestBuilder = SuggestBuilder.fromXContent(parser); SuggestBuilder secondSuggestBuilder = SuggestBuilder.fromXContent(parser);
assertNotSame(suggestBuilder, secondSuggestBuilder); assertNotSame(suggestBuilder, secondSuggestBuilder);
assertEquals(suggestBuilder, secondSuggestBuilder); assertEquals(suggestBuilder, secondSuggestBuilder);
assertEquals(suggestBuilder.hashCode(), secondSuggestBuilder.hashCode()); assertEquals(suggestBuilder.hashCode(), secondSuggestBuilder.hashCode());
}
} }
} }

View File

@ -368,44 +368,48 @@ public class CategoryContextMappingTests extends ESSingleNodeTestCase {
public void testQueryContextParsingBasic() throws Exception { public void testQueryContextParsingBasic() throws Exception {
XContentBuilder builder = jsonBuilder().value("context1"); XContentBuilder builder = jsonBuilder().value("context1");
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder))) {
CategoryContextMapping mapping = ContextBuilder.category("cat").build(); CategoryContextMapping mapping = ContextBuilder.category("cat").build();
List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser); List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser);
assertThat(internalQueryContexts.size(), equalTo(1)); assertThat(internalQueryContexts.size(), equalTo(1));
assertThat(internalQueryContexts.get(0).context, equalTo("context1")); assertThat(internalQueryContexts.get(0).context, equalTo("context1"));
assertThat(internalQueryContexts.get(0).boost, equalTo(1)); assertThat(internalQueryContexts.get(0).boost, equalTo(1));
assertThat(internalQueryContexts.get(0).isPrefix, equalTo(false)); assertThat(internalQueryContexts.get(0).isPrefix, equalTo(false));
}
} }
public void testBooleanQueryContextParsingBasic() throws Exception { public void testBooleanQueryContextParsingBasic() throws Exception {
XContentBuilder builder = jsonBuilder().value(true); XContentBuilder builder = jsonBuilder().value(true);
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder))) {
CategoryContextMapping mapping = ContextBuilder.category("cat").build(); CategoryContextMapping mapping = ContextBuilder.category("cat").build();
List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser); List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser);
assertThat(internalQueryContexts.size(), equalTo(1)); assertThat(internalQueryContexts.size(), equalTo(1));
assertThat(internalQueryContexts.get(0).context, equalTo("true")); assertThat(internalQueryContexts.get(0).context, equalTo("true"));
assertThat(internalQueryContexts.get(0).boost, equalTo(1)); assertThat(internalQueryContexts.get(0).boost, equalTo(1));
assertThat(internalQueryContexts.get(0).isPrefix, equalTo(false)); assertThat(internalQueryContexts.get(0).isPrefix, equalTo(false));
}
} }
public void testNumberQueryContextParsingBasic() throws Exception { public void testNumberQueryContextParsingBasic() throws Exception {
XContentBuilder builder = jsonBuilder().value(10); XContentBuilder builder = jsonBuilder().value(10);
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder))) {
CategoryContextMapping mapping = ContextBuilder.category("cat").build(); CategoryContextMapping mapping = ContextBuilder.category("cat").build();
List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser); List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser);
assertThat(internalQueryContexts.size(), equalTo(1)); assertThat(internalQueryContexts.size(), equalTo(1));
assertThat(internalQueryContexts.get(0).context, equalTo("10")); assertThat(internalQueryContexts.get(0).context, equalTo("10"));
assertThat(internalQueryContexts.get(0).boost, equalTo(1)); assertThat(internalQueryContexts.get(0).boost, equalTo(1));
assertThat(internalQueryContexts.get(0).isPrefix, equalTo(false)); assertThat(internalQueryContexts.get(0).isPrefix, equalTo(false));
}
} }
public void testNULLQueryContextParsingBasic() throws Exception { public void testNULLQueryContextParsingBasic() throws Exception {
XContentBuilder builder = jsonBuilder().nullValue(); XContentBuilder builder = jsonBuilder().nullValue();
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder))) {
CategoryContextMapping mapping = ContextBuilder.category("cat").build(); CategoryContextMapping mapping = ContextBuilder.category("cat").build();
XContentParseException e = expectThrows(XContentParseException.class, () -> mapping.parseQueryContext(parser)); XContentParseException e = expectThrows(XContentParseException.class, () -> mapping.parseQueryContext(parser));
assertThat(ExceptionsHelper.detailedMessage(e), containsString("category context must be an object, string, number or boolean")); assertThat(ExceptionsHelper.detailedMessage(e), containsString("category context must be an object, string, number or boolean"));
}
} }
public void testQueryContextParsingArray() throws Exception { public void testQueryContextParsingArray() throws Exception {
@ -413,16 +417,17 @@ public class CategoryContextMappingTests extends ESSingleNodeTestCase {
.value("context1") .value("context1")
.value("context2") .value("context2")
.endArray(); .endArray();
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder))) {
CategoryContextMapping mapping = ContextBuilder.category("cat").build(); CategoryContextMapping mapping = ContextBuilder.category("cat").build();
List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser); List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser);
assertThat(internalQueryContexts.size(), equalTo(2)); assertThat(internalQueryContexts.size(), equalTo(2));
assertThat(internalQueryContexts.get(0).context, equalTo("context1")); assertThat(internalQueryContexts.get(0).context, equalTo("context1"));
assertThat(internalQueryContexts.get(0).boost, equalTo(1)); assertThat(internalQueryContexts.get(0).boost, equalTo(1));
assertThat(internalQueryContexts.get(0).isPrefix, equalTo(false)); assertThat(internalQueryContexts.get(0).isPrefix, equalTo(false));
assertThat(internalQueryContexts.get(1).context, equalTo("context2")); assertThat(internalQueryContexts.get(1).context, equalTo("context2"));
assertThat(internalQueryContexts.get(1).boost, equalTo(1)); assertThat(internalQueryContexts.get(1).boost, equalTo(1));
assertThat(internalQueryContexts.get(1).isPrefix, equalTo(false)); assertThat(internalQueryContexts.get(1).isPrefix, equalTo(false));
}
} }
public void testQueryContextParsingMixedTypeValuesArray() throws Exception { public void testQueryContextParsingMixedTypeValuesArray() throws Exception {
@ -432,22 +437,23 @@ public class CategoryContextMappingTests extends ESSingleNodeTestCase {
.value(true) .value(true)
.value(10) .value(10)
.endArray(); .endArray();
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder))) {
CategoryContextMapping mapping = ContextBuilder.category("cat").build(); CategoryContextMapping mapping = ContextBuilder.category("cat").build();
List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser); List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser);
assertThat(internalQueryContexts.size(), equalTo(4)); assertThat(internalQueryContexts.size(), equalTo(4));
assertThat(internalQueryContexts.get(0).context, equalTo("context1")); assertThat(internalQueryContexts.get(0).context, equalTo("context1"));
assertThat(internalQueryContexts.get(0).boost, equalTo(1)); assertThat(internalQueryContexts.get(0).boost, equalTo(1));
assertThat(internalQueryContexts.get(0).isPrefix, equalTo(false)); assertThat(internalQueryContexts.get(0).isPrefix, equalTo(false));
assertThat(internalQueryContexts.get(1).context, equalTo("context2")); assertThat(internalQueryContexts.get(1).context, equalTo("context2"));
assertThat(internalQueryContexts.get(1).boost, equalTo(1)); assertThat(internalQueryContexts.get(1).boost, equalTo(1));
assertThat(internalQueryContexts.get(1).isPrefix, equalTo(false)); assertThat(internalQueryContexts.get(1).isPrefix, equalTo(false));
assertThat(internalQueryContexts.get(2).context, equalTo("true")); assertThat(internalQueryContexts.get(2).context, equalTo("true"));
assertThat(internalQueryContexts.get(2).boost, equalTo(1)); assertThat(internalQueryContexts.get(2).boost, equalTo(1));
assertThat(internalQueryContexts.get(2).isPrefix, equalTo(false)); assertThat(internalQueryContexts.get(2).isPrefix, equalTo(false));
assertThat(internalQueryContexts.get(3).context, equalTo("10")); assertThat(internalQueryContexts.get(3).context, equalTo("10"));
assertThat(internalQueryContexts.get(3).boost, equalTo(1)); assertThat(internalQueryContexts.get(3).boost, equalTo(1));
assertThat(internalQueryContexts.get(3).isPrefix, equalTo(false)); assertThat(internalQueryContexts.get(3).isPrefix, equalTo(false));
}
} }
public void testQueryContextParsingMixedTypeValuesArrayHavingNULL() throws Exception { public void testQueryContextParsingMixedTypeValuesArrayHavingNULL() throws Exception {
@ -458,11 +464,12 @@ public class CategoryContextMappingTests extends ESSingleNodeTestCase {
.value(10) .value(10)
.nullValue() .nullValue()
.endArray(); .endArray();
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder))) {
CategoryContextMapping mapping = ContextBuilder.category("cat").build(); CategoryContextMapping mapping = ContextBuilder.category("cat").build();
XContentParseException e = expectThrows(XContentParseException.class, () -> mapping.parseQueryContext(parser)); XContentParseException e = expectThrows(XContentParseException.class, () -> mapping.parseQueryContext(parser));
assertThat(ExceptionsHelper.detailedMessage(e), containsString("category context must be an object, string, number or boolean")); assertThat(ExceptionsHelper.detailedMessage(e), containsString("category context must be an object, string, number or boolean"));
}
} }
public void testQueryContextParsingObject() throws Exception { public void testQueryContextParsingObject() throws Exception {
@ -471,13 +478,14 @@ public class CategoryContextMappingTests extends ESSingleNodeTestCase {
.field("boost", 10) .field("boost", 10)
.field("prefix", true) .field("prefix", true)
.endObject(); .endObject();
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder))) {
CategoryContextMapping mapping = ContextBuilder.category("cat").build(); CategoryContextMapping mapping = ContextBuilder.category("cat").build();
List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser); List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser);
assertThat(internalQueryContexts.size(), equalTo(1)); assertThat(internalQueryContexts.size(), equalTo(1));
assertThat(internalQueryContexts.get(0).context, equalTo("context1")); assertThat(internalQueryContexts.get(0).context, equalTo("context1"));
assertThat(internalQueryContexts.get(0).boost, equalTo(10)); assertThat(internalQueryContexts.get(0).boost, equalTo(10));
assertThat(internalQueryContexts.get(0).isPrefix, equalTo(true)); assertThat(internalQueryContexts.get(0).isPrefix, equalTo(true));
}
} }
public void testQueryContextParsingObjectHavingBoolean() throws Exception { public void testQueryContextParsingObjectHavingBoolean() throws Exception {
@ -486,13 +494,14 @@ public class CategoryContextMappingTests extends ESSingleNodeTestCase {
.field("boost", 10) .field("boost", 10)
.field("prefix", true) .field("prefix", true)
.endObject(); .endObject();
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder))) {
CategoryContextMapping mapping = ContextBuilder.category("cat").build(); CategoryContextMapping mapping = ContextBuilder.category("cat").build();
List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser); List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser);
assertThat(internalQueryContexts.size(), equalTo(1)); assertThat(internalQueryContexts.size(), equalTo(1));
assertThat(internalQueryContexts.get(0).context, equalTo("false")); assertThat(internalQueryContexts.get(0).context, equalTo("false"));
assertThat(internalQueryContexts.get(0).boost, equalTo(10)); assertThat(internalQueryContexts.get(0).boost, equalTo(10));
assertThat(internalQueryContexts.get(0).isPrefix, equalTo(true)); assertThat(internalQueryContexts.get(0).isPrefix, equalTo(true));
}
} }
public void testQueryContextParsingObjectHavingNumber() throws Exception { public void testQueryContextParsingObjectHavingNumber() throws Exception {
@ -501,13 +510,14 @@ public class CategoryContextMappingTests extends ESSingleNodeTestCase {
.field("boost", 10) .field("boost", 10)
.field("prefix", true) .field("prefix", true)
.endObject(); .endObject();
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder))) {
CategoryContextMapping mapping = ContextBuilder.category("cat").build(); CategoryContextMapping mapping = ContextBuilder.category("cat").build();
List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser); List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser);
assertThat(internalQueryContexts.size(), equalTo(1)); assertThat(internalQueryContexts.size(), equalTo(1));
assertThat(internalQueryContexts.get(0).context, equalTo("333")); assertThat(internalQueryContexts.get(0).context, equalTo("333"));
assertThat(internalQueryContexts.get(0).boost, equalTo(10)); assertThat(internalQueryContexts.get(0).boost, equalTo(10));
assertThat(internalQueryContexts.get(0).isPrefix, equalTo(true)); assertThat(internalQueryContexts.get(0).isPrefix, equalTo(true));
}
} }
public void testQueryContextParsingObjectHavingNULL() throws Exception { public void testQueryContextParsingObjectHavingNULL() throws Exception {
@ -516,11 +526,12 @@ public class CategoryContextMappingTests extends ESSingleNodeTestCase {
.field("boost", 10) .field("boost", 10)
.field("prefix", true) .field("prefix", true)
.endObject(); .endObject();
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder))) {
CategoryContextMapping mapping = ContextBuilder.category("cat").build(); CategoryContextMapping mapping = ContextBuilder.category("cat").build();
Exception e = expectThrows(XContentParseException.class, () -> mapping.parseQueryContext(parser)); Exception e = expectThrows(XContentParseException.class, () -> mapping.parseQueryContext(parser));
assertThat(e.getMessage(), containsString("category context must be a string, number or boolean")); assertThat(e.getMessage(), containsString("category context must be a string, number or boolean"));
}
} }
public void testQueryContextParsingObjectArray() throws Exception { public void testQueryContextParsingObjectArray() throws Exception {
@ -536,16 +547,17 @@ public class CategoryContextMappingTests extends ESSingleNodeTestCase {
.field("prefix", false) .field("prefix", false)
.endObject() .endObject()
.endArray(); .endArray();
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder))) {
CategoryContextMapping mapping = ContextBuilder.category("cat").build(); CategoryContextMapping mapping = ContextBuilder.category("cat").build();
List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser); List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser);
assertThat(internalQueryContexts.size(), equalTo(2)); assertThat(internalQueryContexts.size(), equalTo(2));
assertThat(internalQueryContexts.get(0).context, equalTo("context1")); assertThat(internalQueryContexts.get(0).context, equalTo("context1"));
assertThat(internalQueryContexts.get(0).boost, equalTo(2)); assertThat(internalQueryContexts.get(0).boost, equalTo(2));
assertThat(internalQueryContexts.get(0).isPrefix, equalTo(true)); assertThat(internalQueryContexts.get(0).isPrefix, equalTo(true));
assertThat(internalQueryContexts.get(1).context, equalTo("context2")); assertThat(internalQueryContexts.get(1).context, equalTo("context2"));
assertThat(internalQueryContexts.get(1).boost, equalTo(3)); assertThat(internalQueryContexts.get(1).boost, equalTo(3));
assertThat(internalQueryContexts.get(1).isPrefix, equalTo(false)); assertThat(internalQueryContexts.get(1).isPrefix, equalTo(false));
}
} }
public void testQueryContextParsingMixedTypeObjectArray() throws Exception { public void testQueryContextParsingMixedTypeObjectArray() throws Exception {
@ -571,22 +583,23 @@ public class CategoryContextMappingTests extends ESSingleNodeTestCase {
.field("prefix", false) .field("prefix", false)
.endObject() .endObject()
.endArray(); .endArray();
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder))) {
CategoryContextMapping mapping = ContextBuilder.category("cat").build(); CategoryContextMapping mapping = ContextBuilder.category("cat").build();
List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser); List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser);
assertThat(internalQueryContexts.size(), equalTo(4)); assertThat(internalQueryContexts.size(), equalTo(4));
assertThat(internalQueryContexts.get(0).context, equalTo("context1")); assertThat(internalQueryContexts.get(0).context, equalTo("context1"));
assertThat(internalQueryContexts.get(0).boost, equalTo(2)); assertThat(internalQueryContexts.get(0).boost, equalTo(2));
assertThat(internalQueryContexts.get(0).isPrefix, equalTo(true)); assertThat(internalQueryContexts.get(0).isPrefix, equalTo(true));
assertThat(internalQueryContexts.get(1).context, equalTo("context2")); assertThat(internalQueryContexts.get(1).context, equalTo("context2"));
assertThat(internalQueryContexts.get(1).boost, equalTo(3)); assertThat(internalQueryContexts.get(1).boost, equalTo(3));
assertThat(internalQueryContexts.get(1).isPrefix, equalTo(false)); assertThat(internalQueryContexts.get(1).isPrefix, equalTo(false));
assertThat(internalQueryContexts.get(2).context, equalTo("true")); assertThat(internalQueryContexts.get(2).context, equalTo("true"));
assertThat(internalQueryContexts.get(2).boost, equalTo(3)); assertThat(internalQueryContexts.get(2).boost, equalTo(3));
assertThat(internalQueryContexts.get(2).isPrefix, equalTo(false)); assertThat(internalQueryContexts.get(2).isPrefix, equalTo(false));
assertThat(internalQueryContexts.get(3).context, equalTo("333")); assertThat(internalQueryContexts.get(3).context, equalTo("333"));
assertThat(internalQueryContexts.get(3).boost, equalTo(3)); assertThat(internalQueryContexts.get(3).boost, equalTo(3));
assertThat(internalQueryContexts.get(3).isPrefix, equalTo(false)); assertThat(internalQueryContexts.get(3).isPrefix, equalTo(false));
}
} }
public void testQueryContextParsingMixedTypeObjectArrayHavingNULL() throws Exception { public void testQueryContextParsingMixedTypeObjectArrayHavingNULL() throws Exception {
@ -617,11 +630,12 @@ public class CategoryContextMappingTests extends ESSingleNodeTestCase {
.field("prefix", false) .field("prefix", false)
.endObject() .endObject()
.endArray(); .endArray();
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder))) {
CategoryContextMapping mapping = ContextBuilder.category("cat").build(); CategoryContextMapping mapping = ContextBuilder.category("cat").build();
XContentParseException e = expectThrows(XContentParseException.class, () -> mapping.parseQueryContext(parser)); XContentParseException e = expectThrows(XContentParseException.class, () -> mapping.parseQueryContext(parser));
assertThat(ExceptionsHelper.detailedMessage(e), containsString("category context must be a string, number or boolean")); assertThat(ExceptionsHelper.detailedMessage(e), containsString("category context must be a string, number or boolean"));
}
} }
@ -640,22 +654,23 @@ public class CategoryContextMappingTests extends ESSingleNodeTestCase {
.field("prefix", true) .field("prefix", true)
.endObject() .endObject()
.endArray(); .endArray();
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder))) {
CategoryContextMapping mapping = ContextBuilder.category("cat").build(); CategoryContextMapping mapping = ContextBuilder.category("cat").build();
List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser); List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser);
assertThat(internalQueryContexts.size(), equalTo(4)); assertThat(internalQueryContexts.size(), equalTo(4));
assertThat(internalQueryContexts.get(0).context, equalTo("context1")); assertThat(internalQueryContexts.get(0).context, equalTo("context1"));
assertThat(internalQueryContexts.get(0).boost, equalTo(2)); assertThat(internalQueryContexts.get(0).boost, equalTo(2));
assertThat(internalQueryContexts.get(0).isPrefix, equalTo(true)); assertThat(internalQueryContexts.get(0).isPrefix, equalTo(true));
assertThat(internalQueryContexts.get(1).context, equalTo("context2")); assertThat(internalQueryContexts.get(1).context, equalTo("context2"));
assertThat(internalQueryContexts.get(1).boost, equalTo(1)); assertThat(internalQueryContexts.get(1).boost, equalTo(1));
assertThat(internalQueryContexts.get(1).isPrefix, equalTo(false)); assertThat(internalQueryContexts.get(1).isPrefix, equalTo(false));
assertThat(internalQueryContexts.get(2).context, equalTo("false")); assertThat(internalQueryContexts.get(2).context, equalTo("false"));
assertThat(internalQueryContexts.get(2).boost, equalTo(1)); assertThat(internalQueryContexts.get(2).boost, equalTo(1));
assertThat(internalQueryContexts.get(2).isPrefix, equalTo(false)); assertThat(internalQueryContexts.get(2).isPrefix, equalTo(false));
assertThat(internalQueryContexts.get(3).context, equalTo("333")); assertThat(internalQueryContexts.get(3).context, equalTo("333"));
assertThat(internalQueryContexts.get(3).boost, equalTo(2)); assertThat(internalQueryContexts.get(3).boost, equalTo(2));
assertThat(internalQueryContexts.get(3).isPrefix, equalTo(true)); assertThat(internalQueryContexts.get(3).isPrefix, equalTo(true));
}
} }
public void testQueryContextParsingMixedHavingNULL() throws Exception { public void testQueryContextParsingMixedHavingNULL() throws Exception {
@ -674,11 +689,12 @@ public class CategoryContextMappingTests extends ESSingleNodeTestCase {
.endObject() .endObject()
.nullValue() .nullValue()
.endArray(); .endArray();
XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder))) {
CategoryContextMapping mapping = ContextBuilder.category("cat").build(); CategoryContextMapping mapping = ContextBuilder.category("cat").build();
XContentParseException e = expectThrows(XContentParseException.class, () -> mapping.parseQueryContext(parser)); XContentParseException e = expectThrows(XContentParseException.class, () -> mapping.parseQueryContext(parser));
assertThat(ExceptionsHelper.detailedMessage(e), containsString("category context must be an object, string, number or boolean")); assertThat(ExceptionsHelper.detailedMessage(e), containsString("category context must be an object, string, number or boolean"));
}
} }
public void testUnknownQueryContextParsing() throws Exception { public void testUnknownQueryContextParsing() throws Exception {

View File

@ -124,12 +124,13 @@ public class DirectCandidateGeneratorTests extends ESTestCase {
builder.prettyPrint(); builder.prettyPrint();
} }
generator.toXContent(builder, ToXContent.EMPTY_PARAMS); generator.toXContent(builder, ToXContent.EMPTY_PARAMS);
XContentParser parser = createParser(shuffleXContent(builder)); try (XContentParser parser = createParser(shuffleXContent(builder))) {
parser.nextToken(); parser.nextToken();
DirectCandidateGeneratorBuilder secondGenerator = DirectCandidateGeneratorBuilder.PARSER.apply(parser, null); DirectCandidateGeneratorBuilder secondGenerator = DirectCandidateGeneratorBuilder.PARSER.apply(parser, null);
assertNotSame(generator, secondGenerator); assertNotSame(generator, secondGenerator);
assertEquals(generator, secondGenerator); assertEquals(generator, secondGenerator);
assertEquals(generator.hashCode(), secondGenerator.hashCode()); assertEquals(generator.hashCode(), secondGenerator.hashCode());
}
} }
} }
@ -187,9 +188,10 @@ public class DirectCandidateGeneratorTests extends ESTestCase {
private void assertIllegalXContent(String directGenerator, Class<? extends Exception> exceptionClass, String exceptionMsg) private void assertIllegalXContent(String directGenerator, Class<? extends Exception> exceptionClass, String exceptionMsg)
throws IOException { throws IOException {
XContentParser parser = createParser(JsonXContent.jsonXContent, directGenerator); try (XContentParser parser = createParser(JsonXContent.jsonXContent, directGenerator)) {
Exception e = expectThrows(exceptionClass, () -> DirectCandidateGeneratorBuilder.PARSER.apply(parser, null)); Exception e = expectThrows(exceptionClass, () -> DirectCandidateGeneratorBuilder.PARSER.apply(parser, null));
assertThat(e.getMessage(), containsString(exceptionMsg)); assertThat(e.getMessage(), containsString(exceptionMsg));
}
} }
/** /**

View File

@ -95,12 +95,13 @@ public abstract class SmoothingModelTestCase extends ESTestCase {
contentBuilder.startObject(); contentBuilder.startObject();
testModel.innerToXContent(contentBuilder, ToXContent.EMPTY_PARAMS); testModel.innerToXContent(contentBuilder, ToXContent.EMPTY_PARAMS);
contentBuilder.endObject(); contentBuilder.endObject();
XContentParser parser = createParser(shuffleXContent(contentBuilder)); try (XContentParser parser = createParser(shuffleXContent(contentBuilder))) {
parser.nextToken(); // go to start token, real parsing would do that in the outer element parser parser.nextToken(); // go to start token, real parsing would do that in the outer element parser
SmoothingModel parsedModel = fromXContent(parser); SmoothingModel parsedModel = fromXContent(parser);
assertNotSame(testModel, parsedModel); assertNotSame(testModel, parsedModel);
assertEquals(testModel, parsedModel); assertEquals(testModel, parsedModel);
assertEquals(testModel.hashCode(), parsedModel.hashCode()); assertEquals(testModel.hashCode(), parsedModel.hashCode());
}
} }
/** /**