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 Colin Goodheart-Smithe
parent 0f956290ea
commit e6dc01d2b7
No known key found for this signature in database
GPG Key ID: F975E7BDD739B3C7
53 changed files with 1186 additions and 1025 deletions

View File

@ -558,10 +558,11 @@ 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();
builder.startObject("aliases"); builder.startObject("aliases");

View File

@ -58,7 +58,7 @@ 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());
@ -66,6 +66,7 @@ public class ClusterUpdateSettingsRequestTests extends ESTestCase {
assertThat(parsedRequest.persistentSettings(), equalTo(request.persistentSettings())); assertThat(parsedRequest.persistentSettings(), equalTo(request.persistentSettings()));
} }
} }
}
private static ClusterUpdateSettingsRequest createTestItem() { private static ClusterUpdateSettingsRequest createTestItem() {
ClusterUpdateSettingsRequest request = new ClusterUpdateSettingsRequest(); ClusterUpdateSettingsRequest request = new ClusterUpdateSettingsRequest();

View File

@ -134,13 +134,14 @@ 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());
} }
} }
}
public static void assertAliasesEqual(Set<Alias> expected, Set<Alias> actual) throws IOException { public static void assertAliasesEqual(Set<Alias> expected, Set<Alias> actual) throws IOException {
assertEquals(expected, actual); assertEquals(expected, actual);

View File

@ -147,10 +147,11 @@ 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());
} }
}
/** /**
* Returns a random {@link PutMappingRequest}. * Returns a random {@link PutMappingRequest}.

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,7 +54,7 @@ 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,
@ -68,6 +68,7 @@ public class MultiGetRequestTests extends ESTestCase {
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 {
final XContentBuilder builder = XContentFactory.jsonBuilder(); final XContentBuilder builder = XContentFactory.jsonBuilder();
@ -141,7 +142,7 @@ 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());
@ -154,6 +155,7 @@ public class MultiGetRequestTests extends ESTestCase {
} }
} }
} }
}
private MultiGetRequest createTestInstance() { private MultiGetRequest createTestInstance() {
int numItems = randomIntBetween(0, 128); int numItems = randomIntBetween(0, 128);

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)) {
actual = MultiSearchResponse.fromXContext(parser);
assertThat(parser.nextToken(), nullValue()); 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,10 +223,11 @@ 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 {
final IndexGraveyard graveyard = IndexGraveyardTests.createRandom(); final IndexGraveyard graveyard = IndexGraveyardTests.createRandom();

View File

@ -50,16 +50,18 @@ 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) {
return new ShapeCollection<>(Arrays.asList(shapes), SPATIAL_CONTEXT); return new ShapeCollection<>(Arrays.asList(shapes), SPATIAL_CONTEXT);

View File

@ -193,19 +193,21 @@ 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
public void testParsePolygon() throws IOException { public void testParsePolygon() throws IOException {
@ -266,10 +268,11 @@ 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 {
XContentBuilder polygonGeoJson = XContentFactory.jsonBuilder() XContentBuilder polygonGeoJson = XContentFactory.jsonBuilder()
@ -285,10 +288,11 @@ 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 {
// test case 1: create an invalid point object with multipoint data format // test case 1: create an invalid point object with multipoint data format
@ -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,10 +315,11 @@ 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 {
// test case 1: create an invalid multipoint object with single coordinate // test case 1: create an invalid multipoint object with single coordinate
@ -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,10 +353,11 @@ 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 {
// test invalid multipolygon (an "accidental" polygon with inner rings outside outer ring) // test invalid multipolygon (an "accidental" polygon with inner rings outside outer ring)
@ -380,10 +389,11 @@ 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 {
// test invalid multipolygon (an "accidental" polygon with inner rings outside outer ring) // test invalid multipolygon (an "accidental" polygon with inner rings outside outer ring)
@ -419,10 +429,11 @@ 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);
} }
}
public void testParseOGCPolygonWithoutHoles() throws IOException { public void testParseOGCPolygonWithoutHoles() throws IOException {
@ -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,12 +514,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.assertMultiPolygon(shape); ElasticsearchGeoAssertions.assertMultiPolygon(shape);
} }
}
public void testParseOGCPolygonWithHoles() throws IOException { public void testParseOGCPolygonWithHoles() throws IOException {
// test 1: ccw poly not crossing dateline // test 1: ccw poly not crossing dateline
@ -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,12 +625,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.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,10 +723,11 @@ 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 {
XContentBuilder polygonGeoJson = XContentFactory.jsonBuilder() XContentBuilder polygonGeoJson = XContentFactory.jsonBuilder()
@ -764,10 +791,11 @@ 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
public void testParseMultiPoint() throws IOException { public void testParseMultiPoint() throws IOException {
@ -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,7 +59,7 @@ 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
@ -69,3 +69,4 @@ public class GeoUtilTests extends ESTestCase {
return precision; return precision;
} }
} }
}

View File

@ -79,7 +79,7 @@ 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);
@ -87,6 +87,7 @@ public abstract class AbstractShapeBuilderTestCase<SB extends ShapeBuilder> exte
assertEquals(testShape.hashCode(), parsedShape.hashCode()); assertEquals(testShape.hashCode(), parsedShape.hashCode());
} }
} }
}
/** /**
* Test serialization and deserialization of the test shape. * Test serialization and deserialization of the test shape.

View File

@ -45,7 +45,7 @@ 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));
@ -53,6 +53,7 @@ public class FuzzinessTests extends ESTestCase {
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);
Float floatRep = randomFloat(); Float floatRep = randomFloat();
@ -63,7 +64,7 @@ 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)));
@ -88,6 +89,7 @@ public class FuzzinessTests extends ESTestCase {
} }
} }
} }
}
{ {
XContentBuilder json; XContentBuilder json;
boolean isDefaultAutoFuzzinessTested = randomBoolean(); boolean isDefaultAutoFuzzinessTested = randomBoolean();
@ -102,7 +104,7 @@ 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));
@ -113,6 +115,7 @@ public class FuzzinessTests extends ESTestCase {
assertThat(parser.nextToken(), equalTo(XContentParser.Token.END_OBJECT)); assertThat(parser.nextToken(), equalTo(XContentParser.Token.END_OBJECT));
} }
} }
}
} }
@ -152,7 +155,7 @@ 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));
@ -162,6 +165,7 @@ public class FuzzinessTests extends ESTestCase {
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 {
BytesStreamOutput output = new BytesStreamOutput(); BytesStreamOutput output = new BytesStreamOutput();

View File

@ -274,7 +274,7 @@ 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");
@ -283,6 +283,7 @@ public abstract class BaseXContentTestCase extends ESTestCase {
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 {
assertResult("{'binary':null}", () -> builder().startObject().field("binary").value((byte[]) null).endObject()); assertResult("{'binary':null}", () -> builder().startObject().field("binary").value((byte[]) null).endObject());
@ -290,7 +291,7 @@ 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");
@ -299,6 +300,7 @@ public abstract class BaseXContentTestCase extends ESTestCase {
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 {
assertResult("{'binary':null}", () -> builder().startObject().field("binary").value(null, 0, 0).endObject()); assertResult("{'binary':null}", () -> builder().startObject().field("binary").value(null, 0, 0).endObject());
@ -315,7 +317,7 @@ 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");
@ -324,6 +326,7 @@ public abstract class BaseXContentTestCase extends ESTestCase {
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 {
assertResult("{'utf8':null}", () -> builder().startObject().nullField("utf8").endObject()); assertResult("{'utf8':null}", () -> builder().startObject().nullField("utf8").endObject());
@ -333,7 +336,7 @@ 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");
@ -342,6 +345,7 @@ public abstract class BaseXContentTestCase extends ESTestCase {
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 {
assertResult("{'text':null}", () -> builder().startObject().field("text", (Text) null).endObject()); assertResult("{'text':null}", () -> builder().startObject().field("text", (Text) null).endObject());
@ -351,7 +355,7 @@ 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");
@ -360,6 +364,7 @@ public abstract class BaseXContentTestCase extends ESTestCase {
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 {
assertResult("{'instant':null}", () -> builder().startObject().timeField("instant", (ReadableInstant) null).endObject()); assertResult("{'instant':null}", () -> builder().startObject().timeField("instant", (ReadableInstant) null).endObject());
@ -741,8 +746,8 @@ 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());
@ -754,6 +759,7 @@ public abstract class BaseXContentTestCase extends ESTestCase {
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 {
for (XContentType xcontentType : XContentType.values()) { for (XContentType xcontentType : XContentType.values()) {
@ -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,8 +800,8 @@ 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());
@ -805,6 +812,7 @@ public abstract class BaseXContentTestCase extends ESTestCase {
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,12 +830,13 @@ 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() {
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> XContentBuilder.ensureNameNotNull(null)); IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> XContentBuilder.ensureNameNotNull(null));
@ -984,10 +993,11 @@ 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();
@ -998,15 +1008,15 @@ public abstract class BaseXContentTestCase extends ESTestCase {
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"));
@ -1015,13 +1025,14 @@ public abstract class BaseXContentTestCase extends ESTestCase {
Exception e = expectThrows(NamedObjectNotFoundException.class, () -> p.namedObject(String.class, "doesn't matter", null)); Exception e = expectThrows(NamedObjectNotFoundException.class, () -> p.namedObject(String.class, "doesn't matter", null));
assertEquals("unknown named object category [java.lang.String]", e.getMessage()); assertEquals("unknown named object category [java.lang.String]", e.getMessage());
} }
{ }
XContentParser emptyRegistryParser = xcontentType().xContent() try (XContentParser emptyRegistryParser = xcontentType().xContent()
.createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, new byte[] {}); .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,11 +216,11 @@ 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;
try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder))) {
String currentFieldName = null; String currentFieldName = null;
assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT)); assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT));
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
@ -237,9 +237,9 @@ public class XContentBuilderTests extends ESTestCase {
} }
} }
} }
}
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"));
@ -254,6 +254,7 @@ public class XContentBuilderTests extends ESTestCase {
assertThat(i, equalTo(terms.size())); assertThat(i, equalTo(terms.size()));
} }
}
public void testHandlingOfPath() throws IOException { public void testHandlingOfPath() throws IOException {
Path path = PathUtils.get("path"); Path path = PathUtils.get("path");

View File

@ -33,10 +33,11 @@ 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,10 +56,11 @@ 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() {
Index index1 = new Index("a", "a"); Index index1 = new Index("a", "a");

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,9 +170,11 @@ 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)) {
Query parsedQuery = parseQuery(xParser).toQuery(createShardContext());
assertThat(parsedQuery, Matchers.instanceOf(MatchAllDocsQuery.class)); assertThat(parsedQuery, Matchers.instanceOf(MatchAllDocsQuery.class));
} }
}
public void testDefaultMinShouldMatch() throws Exception { public void testDefaultMinShouldMatch() throws Exception {
// Queries have a minShouldMatch of 0 // Queries have a minShouldMatch of 0

View File

@ -124,13 +124,14 @@ 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()));
} }
} }
}
public void testEqualsAndHashcode() { public void testEqualsAndHashcode() {
for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) { for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) {

View File

@ -107,17 +107,18 @@ 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 {
XContentBuilder content = JsonXContent.contentBuilder(); XContentBuilder content = JsonXContent.contentBuilder();
@ -125,17 +126,18 @@ 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 {
XContentBuilder content = JsonXContent.contentBuilder(); XContentBuilder content = JsonXContent.contentBuilder();
@ -143,18 +145,19 @@ 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 {
XContentBuilder content = JsonXContent.contentBuilder(); XContentBuilder content = JsonXContent.contentBuilder();
@ -162,18 +165,19 @@ 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();
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 testInvalidGeoHash() throws IOException { public void testInvalidGeoHash() throws IOException {
XContentBuilder content = JsonXContent.contentBuilder(); XContentBuilder content = JsonXContent.contentBuilder();
@ -181,12 +185,13 @@ 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 {
XContentBuilder content = JsonXContent.contentBuilder(); XContentBuilder content = JsonXContent.contentBuilder();

View File

@ -384,44 +384,49 @@ 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();
} }
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("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();
} }
point = GeoUtils.parseGeoPoint(parser); GeoPoint point = GeoUtils.parseGeoPoint(parser);
assertThat(point, equalTo(new GeoPoint(lat, lon))); assertThat(point, equalTo(new GeoPoint(lat, lon)));
} }
} }
}
public void testParseGeoPointStringZValueError() throws IOException { public void testParseGeoPointStringZValueError() throws IOException {
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;
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)); Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser, new GeoPoint(), false));
assertThat(e.getMessage(), containsString("but [ignore_z_value] parameter is [false]")); assertThat(e.getMessage(), containsString("but [ignore_z_value] parameter is [false]"));
} }
}
public void testParseGeoPointGeohash() throws IOException { public void testParseGeoPointGeohash() throws IOException {
for (int i = 0; i < 100; i++) { for (int i = 0; i < 100; i++) {
@ -431,106 +436,116 @@ 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(); parser.nextToken();
GeoPoint point = GeoUtils.parseGeoPoint(parser); GeoPoint point = GeoUtils.parseGeoPoint(parser);
assertThat(point.lat(), allOf(lessThanOrEqualTo(90.0), greaterThanOrEqualTo(-90.0))); assertThat(point.lat(), allOf(lessThanOrEqualTo(90.0), greaterThanOrEqualTo(-90.0)));
assertThat(point.lon(), allOf(lessThanOrEqualTo(180.0), greaterThanOrEqualTo(-180.0))); assertThat(point.lon(), allOf(lessThanOrEqualTo(180.0), greaterThanOrEqualTo(-180.0)));
}
json = jsonBuilder().startObject().field("geohash", geohashBuilder.toString()).endObject(); json = jsonBuilder().startObject().field("geohash", geohashBuilder.toString()).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();
} }
point = GeoUtils.parseGeoPoint(parser); GeoPoint point = GeoUtils.parseGeoPoint(parser);
assertThat(point.lat(), allOf(lessThanOrEqualTo(90.0), greaterThanOrEqualTo(-90.0))); assertThat(point.lat(), allOf(lessThanOrEqualTo(90.0), greaterThanOrEqualTo(-90.0)));
assertThat(point.lon(), allOf(lessThanOrEqualTo(180.0), greaterThanOrEqualTo(-180.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 {
double lat = 0.0; double lat = 0.0;
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 {
double lat = 0.0; double lat = 0.0;
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)); 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]")); 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 {
double lat = 90.0; double lat = 90.0;
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();
} }
@ -538,28 +553,31 @@ public class GeoUtilsTests extends ESTestCase {
assertThat(point.lat(), equalTo(lat)); assertThat(point.lat(), equalTo(lat));
assertThat(point.lon(), equalTo(lon)); 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)); Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser));
assertThat(e.getMessage(), is("numeric value expected")); 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)); Exception e = expectThrows(ElasticsearchParseException.class, () -> GeoUtils.parseGeoPoint(parser));
assertThat(e.getMessage(), is("geo_point expected")); assertThat(e.getMessage(), is("geo_point expected"));
} }
}
public void testPrefixTreeCellSizes() { public void testPrefixTreeCellSizes() {
assertThat(GeoUtils.EARTH_SEMI_MAJOR_AXIS, equalTo(DistanceUtils.EARTH_EQUATORIAL_RADIUS_KM * 1000)); assertThat(GeoUtils.EARTH_SEMI_MAJOR_AXIS, equalTo(DistanceUtils.EARTH_EQUATORIAL_RADIUS_KM * 1000));
@ -619,10 +637,11 @@ 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) {
GeoUtils.normalizePoint(input); GeoUtils.normalizePoint(input);

View File

@ -57,7 +57,7 @@ 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;
@ -67,6 +67,7 @@ public class IngestMetadataTests extends ESTestCase {
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 {
BytesReference pipelineConfig = new BytesArray("{}"); BytesReference pipelineConfig = new BytesArray("{}");

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,12 +62,13 @@ 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() {
RepositoryData repositoryData = generateRandomRepoData(); RepositoryData repositoryData = generateRandomRepoData();
@ -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,11 +199,13 @@ 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);
try (XContentParser xParser = createParser(corruptedBuilder)) {
ElasticsearchParseException e = expectThrows(ElasticsearchParseException.class, () -> ElasticsearchParseException e = expectThrows(ElasticsearchParseException.class, () ->
RepositoryData.snapshotsFromXContent(createParser(corruptedBuilder), corruptedRepositoryData.getGenId())); RepositoryData.snapshotsFromXContent(xParser, corruptedRepositoryData.getGenId()));
assertThat(e.getMessage(), equalTo("Detected a corrupted repository, index " + corruptedIndexId + " references an unknown " + assertThat(e.getMessage(), equalTo("Detected a corrupted repository, index " + corruptedIndexId + " references an unknown " +
"snapshot uuid [_does_not_exist]")); "snapshot uuid [_does_not_exist]"));
} }
}
public void testIndexThatReferenceANullSnapshot() throws IOException { public void testIndexThatReferenceANullSnapshot() throws IOException {
final XContentBuilder builder = XContentBuilder.builder(randomFrom(XContentType.JSON).xContent()); final XContentBuilder builder = XContentBuilder.builder(randomFrom(XContentType.JSON).xContent());
@ -230,9 +236,12 @@ public class RepositoryDataTests extends ESTestCase {
} }
builder.endObject(); builder.endObject();
try (XContentParser xParser = createParser(builder)) {
ElasticsearchParseException e = expectThrows(ElasticsearchParseException.class, () -> ElasticsearchParseException e = expectThrows(ElasticsearchParseException.class, () ->
RepositoryData.snapshotsFromXContent(createParser(builder), randomNonNegativeLong())); RepositoryData.snapshotsFromXContent(xParser, randomNonNegativeLong()));
assertThat(e.getMessage(), equalTo("Detected a corrupted repository, index [docs/_id] references an unknown snapshot uuid [null]")); 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,12 +37,12 @@ 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");
@ -56,9 +56,10 @@ public class RestAnalyzeActionTests extends ESTestCase {
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,7 +77,7 @@ 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");
@ -92,6 +93,7 @@ public class RestAnalyzeActionTests extends ESTestCase {
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 {
RestAnalyzeAction action = new RestAnalyzeAction(Settings.EMPTY, mock(RestController.class)); RestAnalyzeAction action = new RestAnalyzeAction(Settings.EMPTY, mock(RestController.class));
@ -103,82 +105,81 @@ 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)) {
Settings settings = Settings.fromXContent(xParser);
Script actualScript = Script.parse(settings); Script actualScript = Script.parse(settings);
assertThat(actualScript, equalTo(expectedScript)); assertThat(actualScript, equalTo(expectedScript));
} }
} }
} }
}

View File

@ -58,11 +58,12 @@ 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 {
NestedIdentity nestedIdentity = new NestedIdentity("foo", 5, null); NestedIdentity nestedIdentity = new NestedIdentity("foo", 5, null);

View File

@ -56,7 +56,7 @@ 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);
@ -64,5 +64,6 @@ public class AggregationCollectorTests extends ESSingleNodeTestCase {
assertEquals(1, aggregators.length); assertEquals(1, aggregators.length);
return aggregators[0].needsScores(); return aggregators[0].needsScores();
} }
}
} }

View File

@ -106,7 +106,7 @@ 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);
@ -114,6 +114,7 @@ public abstract class BasePipelineAggregationTestCase<AF extends AbstractPipelin
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 {
assertSame(XContentParser.Token.START_OBJECT, parser.nextToken()); assertSame(XContentParser.Token.START_OBJECT, parser.nextToken());

View File

@ -94,7 +94,7 @@ 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
@ -105,9 +105,10 @@ public class FiltersTests extends BaseAggregationTestCase<FiltersAggregationBuil
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)); }
try (XContentParser parser = createParser(shuffleXContent(builder))) {
parser.nextToken(); parser.nextToken();
filters = FiltersAggregationBuilder.parse("agg_name", parser); FiltersAggregationBuilder filters = FiltersAggregationBuilder.parse("agg_name", parser);
// but setting a key enables it automatically // but setting a key enables it automatically
assertTrue(filters.otherBucket()); assertTrue(filters.otherBucket());
@ -117,12 +118,14 @@ public class FiltersTests extends BaseAggregationTestCase<FiltersAggregationBuil
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)); }
try (XContentParser parser = createParser(shuffleXContent(builder))) {
parser.nextToken(); parser.nextToken();
filters = FiltersAggregationBuilder.parse("agg_name", parser); FiltersAggregationBuilder filters = FiltersAggregationBuilder.parse("agg_name", parser);
// unless the other bucket is explicitly disabled // unless the other bucket is explicitly disabled
assertFalse(filters.otherBucket()); assertFalse(filters.otherBucket());
} }
}
public void testRewrite() throws IOException { public void testRewrite() throws IOException {
// test non-keyed filter that doesn't rewrite // test non-keyed filter that doesn't rewrite

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,10 +300,11 @@ 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) {
try { try {

View File

@ -214,7 +214,7 @@ 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();
@ -231,6 +231,7 @@ public class IncludeExcludeTests extends ESTestCase {
"Unexpected field name serialized in test: " + field.getPreferredName()); "Unexpected field name serialized in test: " + field.getPreferredName());
} }
} }
}
public void testRegexIncludeAndExclude() throws IOException { public void testRegexIncludeAndExclude() throws IOException {
String incRegex = "foo.*"; String incRegex = "foo.*";
@ -260,7 +261,7 @@ 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);
@ -283,5 +284,6 @@ public class IncludeExcludeTests extends ESTestCase {
// Include and Exclude clauses are parsed independently and then merged // Include and Exclude clauses are parsed independently and then merged
return IncludeExclude.merge(inc, exc); 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,7 +139,7 @@ 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 {
@ -152,6 +152,7 @@ public class HighlightBuilderTests extends ESTestCase {
assertEquals(highlightBuilder.hashCode(), secondHighlightBuilder.hashCode()); assertEquals(highlightBuilder.hashCode(), secondHighlightBuilder.hashCode());
} }
} }
}
/** /**
* test that unknown array fields cause exception * test that unknown array fields cause exception
@ -179,9 +180,10 @@ 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));
} }
}
/** /**
* test that unknown field name cause exception * test that unknown field name cause exception
@ -389,7 +391,7 @@ 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,
@ -400,9 +402,10 @@ public class HighlightBuilderTests extends ESTestCase {
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,
@ -414,29 +417,30 @@ public class HighlightBuilderTests extends ESTestCase {
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());
} }
}
/** /**
* test parsing empty highlight or empty fields blocks * test parsing empty highlight or empty fields blocks
*/ */
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 {
ParsingException err = expectParseThrows(ParsingException.class, "{\n" + ParsingException err = expectParseThrows(ParsingException.class, "{\n" +

View File

@ -62,7 +62,7 @@ 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);
@ -73,6 +73,7 @@ public class HighlightFieldTests extends ESTestCase {
assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken()); assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
assertNull(parser.nextToken()); assertNull(parser.nextToken());
} }
}
public void testToXContent() throws IOException { public void testToXContent() throws IOException {
HighlightField field = new HighlightField("foo", new Text[] { new Text("bar"), new Text("baz") }); HighlightField field = new HighlightField("foo", new Text[] { new Text("bar"), new Text("baz") });

View File

@ -121,7 +121,7 @@ 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);
@ -129,6 +129,7 @@ public class QueryRescorerBuilderTests extends ESTestCase {
assertEquals(rescoreBuilder.hashCode(), secondRescoreBuilder.hashCode()); assertEquals(rescoreBuilder.hashCode(), secondRescoreBuilder.hashCode());
} }
} }
}
/** /**
* test that build() outputs a {@link RescoreContext} that has the same properties * test that build() outputs a {@link RescoreContext} that has the same properties
@ -217,17 +218,14 @@ public class QueryRescorerBuilderTests extends ESTestCase {
" \"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());
} }
@ -236,15 +234,13 @@ public class QueryRescorerBuilderTests extends ESTestCase {
" \"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());
} }
@ -253,8 +249,7 @@ public class QueryRescorerBuilderTests extends ESTestCase {
" \"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());
} }
@ -263,8 +258,7 @@ public class QueryRescorerBuilderTests extends ESTestCase {
" \"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]"));
} }
@ -273,9 +267,10 @@ public class QueryRescorerBuilderTests extends ESTestCase {
" \"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);
} }
}
/** /**
* create a new parser from the rescorer string representation and reset context with it * create a new parser from the rescorer string representation and reset context with it

View File

@ -136,12 +136,13 @@ 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 {
return copyWriteable(original, new NamedWriteableRegistry(Collections.emptyList()), SearchAfterBuilder::new); return copyWriteable(original, new NamedWriteableRegistry(Collections.emptyList()), SearchAfterBuilder::new);
@ -174,7 +175,7 @@ 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();
@ -184,6 +185,7 @@ public class SearchAfterBuilderTests extends ESTestCase {
assertEquals(searchAfterBuilder.hashCode(), secondSearchAfterBuilder.hashCode()); assertEquals(searchAfterBuilder.hashCode(), secondSearchAfterBuilder.hashCode());
} }
} }
}
public void testWithNullArray() throws Exception { public void testWithNullArray() throws Exception {
SearchAfterBuilder builder = new SearchAfterBuilder(); SearchAfterBuilder builder = new SearchAfterBuilder();

View File

@ -306,12 +306,13 @@ 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 {
Exception e = expectThrows(IllegalArgumentException.class, () -> new SliceBuilder("field", -1, 10)); Exception e = expectThrows(IllegalArgumentException.class, () -> new SliceBuilder("field", -1, 10));

View File

@ -121,7 +121,7 @@ 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();
/* /*
@ -138,6 +138,7 @@ public abstract class AbstractSortTestCase<T extends SortBuilder<T>> extends EST
assertWarnings(testItem); assertWarnings(testItem);
} }
} }
}
protected void assertWarnings(T testItem) { protected void assertWarnings(T testItem) {
// assert potential warnings based on the test sort configuration. Do nothing by default, subtests can overwrite // assert potential warnings based on the test sort configuration. Do nothing by default, subtests can overwrite

View File

@ -304,7 +304,7 @@ 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();
@ -313,6 +313,7 @@ public class FieldSortBuilderTests extends AbstractSortTestCase<FieldSortBuilder
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
protected MappedFieldType provideMappedFieldType(String name) { protected MappedFieldType provideMappedFieldType(String name) {

View File

@ -232,13 +232,14 @@ 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 {
String json = "{\n" + String json = "{\n" +
@ -258,7 +259,7 @@ 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);
@ -269,6 +270,7 @@ public class GeoDistanceSortBuilderTests extends AbstractSortTestCase<GeoDistanc
+ "-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 {
XContentBuilder sortBuilder = jsonBuilder(); XContentBuilder sortBuilder = jsonBuilder();
@ -380,10 +382,11 @@ 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
protected void assertWarnings(GeoDistanceSortBuilder testItem) { protected void assertWarnings(GeoDistanceSortBuilder testItem) {

View File

@ -73,7 +73,7 @@ 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);
@ -81,6 +81,7 @@ public class NestedSortBuilderTests extends ESTestCase {
assertEquals(testItem.hashCode(), parsedItem.hashCode()); assertEquals(testItem.hashCode(), parsedItem.hashCode());
} }
} }
}
/** /**
* Create a {@link NestedSortBuilder} with random path and filter of the given depth. * Create a {@link NestedSortBuilder} with random path and filter of the given depth.

View File

@ -177,7 +177,7 @@ 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();
@ -192,6 +192,7 @@ public class ScriptSortBuilderTests extends AbstractSortTestCase<ScriptSortBuild
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 {
String scriptSort = "{\n" + String scriptSort = "{\n" +
@ -201,7 +202,7 @@ 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();
@ -216,10 +217,11 @@ public class ScriptSortBuilderTests extends AbstractSortTestCase<ScriptSortBuild
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();
@ -227,11 +229,12 @@ public class ScriptSortBuilderTests extends AbstractSortTestCase<ScriptSortBuild
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();
@ -239,10 +242,11 @@ public class ScriptSortBuilderTests extends AbstractSortTestCase<ScriptSortBuild
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();
@ -250,6 +254,7 @@ public class ScriptSortBuilderTests extends AbstractSortTestCase<ScriptSortBuild
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"));
} }
}
/** /**
* script sort of type {@link ScriptSortType} does not work with {@link SortMode#AVG}, {@link SortMode#MEDIAN} or {@link SortMode#SUM} * script sort of type {@link ScriptSortType} does not work with {@link SortMode#AVG}, {@link SortMode#MEDIAN} or {@link SortMode#SUM}

View File

@ -252,7 +252,7 @@ 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());
@ -261,3 +261,4 @@ public class SortBuilderTests extends ESTestCase {
return SortBuilder.fromXContent(itemParser); return SortBuilder.fromXContent(itemParser);
} }
} }
}

View File

@ -140,7 +140,7 @@ 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();
@ -150,6 +150,7 @@ public abstract class AbstractSuggestionBuilderTestCase<SB extends SuggestionBui
assertEquals(suggestionBuilder.hashCode(), secondSuggestionBuilder.hashCode()); assertEquals(suggestionBuilder.hashCode(), secondSuggestionBuilder.hashCode());
} }
} }
}
public void testBuild() throws IOException { public void testBuild() throws IOException {
for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) { for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) {

View File

@ -74,13 +74,14 @@ 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());
} }
} }
}
/** /**
* Test equality and hashCode properties * Test equality and hashCode properties

View File

@ -368,7 +368,7 @@ 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));
@ -376,10 +376,11 @@ public class CategoryContextMappingTests extends ESSingleNodeTestCase {
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));
@ -387,10 +388,11 @@ public class CategoryContextMappingTests extends ESSingleNodeTestCase {
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));
@ -398,22 +400,24 @@ public class CategoryContextMappingTests extends ESSingleNodeTestCase {
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 {
XContentBuilder builder = jsonBuilder().startArray() XContentBuilder builder = jsonBuilder().startArray()
.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));
@ -424,6 +428,7 @@ public class CategoryContextMappingTests extends ESSingleNodeTestCase {
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 {
XContentBuilder builder = jsonBuilder().startArray() XContentBuilder builder = jsonBuilder().startArray()
@ -432,7 +437,7 @@ 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));
@ -449,6 +454,7 @@ public class CategoryContextMappingTests extends ESSingleNodeTestCase {
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 {
XContentBuilder builder = jsonBuilder().startArray() XContentBuilder builder = jsonBuilder().startArray()
@ -458,12 +464,13 @@ 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 {
XContentBuilder builder = jsonBuilder().startObject() XContentBuilder builder = jsonBuilder().startObject()
@ -471,7 +478,7 @@ 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));
@ -479,6 +486,7 @@ public class CategoryContextMappingTests extends ESSingleNodeTestCase {
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 {
XContentBuilder builder = jsonBuilder().startObject() XContentBuilder builder = jsonBuilder().startObject()
@ -486,7 +494,7 @@ 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));
@ -494,6 +502,7 @@ public class CategoryContextMappingTests extends ESSingleNodeTestCase {
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 {
XContentBuilder builder = jsonBuilder().startObject() XContentBuilder builder = jsonBuilder().startObject()
@ -501,7 +510,7 @@ 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));
@ -509,6 +518,7 @@ public class CategoryContextMappingTests extends ESSingleNodeTestCase {
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 {
XContentBuilder builder = jsonBuilder().startObject() XContentBuilder builder = jsonBuilder().startObject()
@ -516,12 +526,13 @@ 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 {
XContentBuilder builder = jsonBuilder().startArray() XContentBuilder builder = jsonBuilder().startArray()
@ -536,7 +547,7 @@ 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));
@ -547,6 +558,7 @@ public class CategoryContextMappingTests extends ESSingleNodeTestCase {
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 {
XContentBuilder builder = jsonBuilder().startArray() XContentBuilder builder = jsonBuilder().startArray()
@ -571,7 +583,7 @@ 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));
@ -588,6 +600,7 @@ public class CategoryContextMappingTests extends ESSingleNodeTestCase {
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 {
XContentBuilder builder = jsonBuilder().startArray() XContentBuilder builder = jsonBuilder().startArray()
@ -617,12 +630,13 @@ 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"));
} }
}
public void testQueryContextParsingMixed() throws Exception { public void testQueryContextParsingMixed() throws Exception {
@ -640,7 +654,7 @@ 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));
@ -657,6 +671,7 @@ public class CategoryContextMappingTests extends ESSingleNodeTestCase {
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 {
XContentBuilder builder = jsonBuilder().startArray() XContentBuilder builder = jsonBuilder().startArray()
@ -674,12 +689,13 @@ 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 {
String mapping = Strings.toString(jsonBuilder().startObject().startObject("type1") String mapping = Strings.toString(jsonBuilder().startObject().startObject("type1")

View File

@ -124,7 +124,7 @@ 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);
@ -132,6 +132,7 @@ public class DirectCandidateGeneratorTests extends ESTestCase {
assertEquals(generator.hashCode(), secondGenerator.hashCode()); assertEquals(generator.hashCode(), secondGenerator.hashCode());
} }
} }
}
public static void assertEqualGenerators(DirectCandidateGenerator first, DirectCandidateGenerator second) { public static void assertEqualGenerators(DirectCandidateGenerator first, DirectCandidateGenerator second) {
assertEquals(first.field(), second.field()); assertEquals(first.field(), second.field());
@ -187,10 +188,11 @@ 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));
} }
}
/** /**
* create random {@link DirectCandidateGeneratorBuilder} * create random {@link DirectCandidateGeneratorBuilder}

View File

@ -95,13 +95,14 @@ 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());
} }
}
/** /**
* Test the WordScorer emitted by the smoothing model * Test the WordScorer emitted by the smoothing model