@Override public void execute(IngestDocument document) throws Exception { String stringValue = document.getFieldValue(field, String.class); try { Map<String, Object> mapValue = XContentHelper.convertToMap(JsonXContent.jsonXContent, stringValue, false); if (addToRoot) { for (Map.Entry<String, Object> entry : mapValue.entrySet()) { document.setFieldValue(entry.getKey(), entry.getValue()); } } else { document.setFieldValue(targetField, mapValue); } } catch (ElasticsearchParseException e) { throw new IllegalArgumentException(e); } }
/** * Test that template can contain conditional clause. In this case it is at * the beginning of the string. */ public void testTemplateQueryAsEscapedStringStartingWithConditionalClause() throws Exception { SearchRequest searchRequest = new SearchRequest(); searchRequest.indices("_all"); String templateString = "{" + " \"inline\" : \"{ {{#use_size}} \\\"size\\\": \\\"{{size}}\\\", {{/use_size}} \\\"query\\\":{\\\"match_all\\\":{}}}\"," + " \"params\":{" + " \"size\": 1," + " \"use_size\": true" + " }" + "}"; SearchTemplateRequest request = RestSearchTemplateAction.parse(createParser(JsonXContent.jsonXContent, templateString)); request.setRequest(searchRequest); SearchTemplateResponse searchResponse = client().execute(SearchTemplateAction.INSTANCE, request).get(); assertThat(searchResponse.getResponse().getHits().getHits().length, equalTo(1)); }
public void testPipelineQueryParameterIsError() throws IOException { RestReindexAction action = new RestReindexAction(Settings.EMPTY, mock(RestController.class)); FakeRestRequest.Builder request = new FakeRestRequest.Builder(xContentRegistry()); try (XContentBuilder body = JsonXContent.contentBuilder().prettyPrint()) { body.startObject(); { body.startObject("source"); { body.field("index", "source"); } body.endObject(); body.startObject("dest"); { body.field("index", "dest"); } body.endObject(); } body.endObject(); request.withContent(body.bytes(), body.contentType()); } request.withParams(singletonMap("pipeline", "doesn't matter")); Exception e = expectThrows(IllegalArgumentException.class, () -> action.buildRequest(request.build())); assertEquals("_reindex doesn't support [pipeline] as a query parmaeter. Specify it in the [dest] object instead.", e.getMessage()); }
/** * Return a {@link String} that is the json representation of the provided {@link ToXContent}. * Wraps the output into an anonymous object. */ public static String toString(ToXContent toXContent) { try { XContentBuilder builder = JsonXContent.contentBuilder(); if (toXContent.isFragment()) { builder.startObject(); } toXContent.toXContent(builder, ToXContent.EMPTY_PARAMS); if (toXContent.isFragment()) { builder.endObject(); } return builder.string(); } catch (IOException e) { return "Error building toString out of XContent: " + ExceptionsHelper.stackTrace(e); } }
public void testXContent() throws IOException { IndexId indexId = new IndexId(randomAsciiOfLength(8), UUIDs.randomBase64UUID()); XContentBuilder builder = JsonXContent.contentBuilder(); indexId.toXContent(builder, ToXContent.EMPTY_PARAMS); XContentParser parser = createParser(JsonXContent.jsonXContent, builder.bytes()); assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); String name = null; String id = null; while (parser.nextToken() != XContentParser.Token.END_OBJECT) { final String currentFieldName = parser.currentName(); parser.nextToken(); if (currentFieldName.equals(IndexId.NAME)) { name = parser.text(); } else if (currentFieldName.equals(IndexId.ID)) { id = parser.text(); } } assertNotNull(name); assertNotNull(id); assertEquals(indexId, new IndexId(name, id)); }
public void testFailWithSubAgg() throws Exception { String source = "{\n" + " \"top-tags\": {\n" + " \"terms\": {\n" + " \"field\": \"tags\"\n" + " },\n" + " \"aggs\": {\n" + " \"top_tags_hits\": {\n" + " \"top_hits\": {},\n" + " \"aggs\": {\n" + " \"max\": {\n" + " \"max\": {\n" + " \"field\": \"age\"\n" + " }\n" + " }\n" + " }\n" + " }\n" + " }\n" + " }\n" + "}"; XContentParser parser = createParser(JsonXContent.jsonXContent, source); QueryParseContext parseContext = new QueryParseContext(parser); assertSame(XContentParser.Token.START_OBJECT, parser.nextToken()); Exception e = expectThrows(AggregationInitializationException.class, () -> AggregatorFactories.parseAggregators(parseContext)); assertThat(e.toString(), containsString("Aggregator [top_tags_hits] of type [top_hits] cannot accept sub-aggregations")); }
public void testSettingsFiltering() throws IOException { AzureRepositoryPlugin p = new AzureRepositoryPlugin(); SettingsModule module = new SettingsModule(Settings.EMPTY, p.getSettings(), p.getSettingsFilter()); SettingsFilter settingsFilter = ModuleTestCase.bindAndGetInstance(module, SettingsFilter.class); // Test using direct filtering Settings filteredSettings = settingsFilter.filter(settings); assertThat(filteredSettings.getAsMap().keySet(), contains("cloud.azure.storage.azure1.default")); // Test using toXContent filtering RestRequest request = new FakeRestRequest(); settingsFilter.addFilterSettingParams(request); XContentBuilder xContentBuilder = XContentBuilder.builder(JsonXContent.jsonXContent); xContentBuilder.startObject(); settings.toXContent(xContentBuilder, request); xContentBuilder.endObject(); String filteredSettingsString = xContentBuilder.string(); filteredSettings = Settings.builder().loadFromSource(filteredSettingsString, xContentBuilder.contentType()).build(); assertThat(filteredSettings.getAsMap().keySet(), contains("cloud.azure.storage.azure1.default")); }
public void testXContentRoundTrip() throws Exception { ExtendedBounds orig = randomExtendedBounds(); try (XContentBuilder out = JsonXContent.contentBuilder()) { out.startObject(); orig.toXContent(out, ToXContent.EMPTY_PARAMS); out.endObject(); try (XContentParser in = createParser(JsonXContent.jsonXContent, out.bytes())) { XContentParser.Token token = in.currentToken(); assertNull(token); token = in.nextToken(); assertThat(token, equalTo(XContentParser.Token.START_OBJECT)); token = in.nextToken(); assertThat(token, equalTo(XContentParser.Token.FIELD_NAME)); assertThat(in.currentName(), equalTo(ExtendedBounds.EXTENDED_BOUNDS_FIELD.getPreferredName())); ExtendedBounds read = ExtendedBounds.PARSER.apply(in, null); assertEquals(orig, read); } catch (Exception e) { throw new Exception("Error parsing [" + out.bytes().utf8ToString() + "]", e); } } }
public void testTwoTypes() throws Exception { XContentBuilder source = JsonXContent.contentBuilder() .startObject() .startObject("in_stock") .startObject("filter") .startObject("range") .startObject("stock") .field("gt", 0) .endObject() .endObject() .endObject() .startObject("terms") .field("field", "stock") .endObject() .endObject() .endObject(); XContentParser parser = createParser(source); QueryParseContext parseContext = new QueryParseContext(parser); assertSame(XContentParser.Token.START_OBJECT, parser.nextToken()); Exception e = expectThrows(ParsingException.class, () -> AggregatorFactories.parseAggregators(parseContext)); assertThat(e.toString(), containsString("Found two aggregation type definitions in [in_stock]: [filter] and [terms]")); }
public void testTwoAggs() throws Exception { assumeFalse("Test only makes sense if XContent parser doesn't have strict duplicate checks enabled", XContent.isStrictDuplicateDetectionEnabled()); XContentBuilder source = JsonXContent.contentBuilder() .startObject() .startObject("by_date") .startObject("date_histogram") .field("field", "timestamp") .field("interval", "month") .endObject() .startObject("aggs") .startObject("tag_count") .startObject("cardinality") .field("field", "tag") .endObject() .endObject() .endObject() .startObject("aggs") // 2nd "aggs": illegal .startObject("tag_count2") .startObject("cardinality") .field("field", "tag") .endObject() .endObject() .endObject() .endObject() .endObject(); XContentParser parser = createParser(source); QueryParseContext parseContext = new QueryParseContext(parser); assertSame(XContentParser.Token.START_OBJECT, parser.nextToken()); Exception e = expectThrows(ParsingException.class, () -> AggregatorFactories.parseAggregators(parseContext)); assertThat(e.toString(), containsString("Found two sub aggregation definitions under [by_date]")); }
public void testSameAggregationName() throws Exception { assumeFalse("Test only makes sense if XContent parser doesn't have strict duplicate checks enabled", XContent.isStrictDuplicateDetectionEnabled()); final String name = randomAsciiOfLengthBetween(1, 10); XContentBuilder source = JsonXContent.contentBuilder() .startObject() .startObject(name) .startObject("terms") .field("field", "a") .endObject() .endObject() .startObject(name) .startObject("terms") .field("field", "b") .endObject() .endObject() .endObject(); XContentParser parser = createParser(source); QueryParseContext parseContext = new QueryParseContext(parser); assertSame(XContentParser.Token.START_OBJECT, parser.nextToken()); Exception e = expectThrows(ParsingException.class, () -> AggregatorFactories.parseAggregators(parseContext)); assertThat(e.toString(), containsString("Two sibling aggregations cannot have the same name: [" + name + "]")); }
public void testMissingName() throws Exception { XContentBuilder source = JsonXContent.contentBuilder() .startObject() .startObject("by_date") .startObject("date_histogram") .field("field", "timestamp") .field("interval", "month") .endObject() .startObject("aggs") // the aggregation name is missing //.startObject("tag_count") .startObject("cardinality") .field("field", "tag") .endObject() //.endObject() .endObject() .endObject() .endObject(); XContentParser parser = createParser(source); QueryParseContext parseContext = new QueryParseContext(parser); assertSame(XContentParser.Token.START_OBJECT, parser.nextToken()); Exception e = expectThrows(ParsingException.class, () -> AggregatorFactories.parseAggregators(parseContext)); assertThat(e.toString(), containsString("Expected [START_OBJECT] under [field], but got a [VALUE_STRING] in [cardinality]")); }
public void testMissingType() throws Exception { XContentBuilder source = JsonXContent.contentBuilder() .startObject() .startObject("by_date") .startObject("date_histogram") .field("field", "timestamp") .field("interval", "month") .endObject() .startObject("aggs") .startObject("tag_count") // the aggregation type is missing //.startObject("cardinality") .field("field", "tag") //.endObject() .endObject() .endObject() .endObject() .endObject(); XContentParser parser = createParser(source); QueryParseContext parseContext = new QueryParseContext(parser); assertSame(XContentParser.Token.START_OBJECT, parser.nextToken()); Exception e = expectThrows(ParsingException.class, () -> AggregatorFactories.parseAggregators(parseContext)); assertThat(e.toString(), containsString("Expected [START_OBJECT] under [field], but got a [VALUE_STRING] in [tag_count]")); }
public void testQueryContextParsingArray() throws Exception { XContentBuilder builder = jsonBuilder().startArray() .value("context1") .value("context2") .endArray(); XContentParser parser = createParser(JsonXContent.jsonXContent, builder.bytes()); CategoryContextMapping mapping = ContextBuilder.category("cat").build(); List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(createParseContext(parser)); assertThat(internalQueryContexts.size(), equalTo(2)); assertThat(internalQueryContexts.get(0).context, equalTo("context1")); assertThat(internalQueryContexts.get(0).boost, equalTo(1)); assertThat(internalQueryContexts.get(0).isPrefix, equalTo(false)); assertThat(internalQueryContexts.get(1).context, equalTo("context2")); assertThat(internalQueryContexts.get(1).boost, equalTo(1)); assertThat(internalQueryContexts.get(1).isPrefix, equalTo(false)); }
public void testFailOnValueType() throws IOException { XContentParser parser = createParser(JsonXContent.jsonXContent, "{\"numeric_value\" : false}"); class TestStruct { public String test; } ObjectParser<TestStruct, Void> objectParser = new ObjectParser<>("foo"); TestStruct s = new TestStruct(); objectParser.declareField((i, c, x) -> c.test = i.text(), new ParseField("numeric_value"), ObjectParser.ValueType.FLOAT); try { objectParser.parse(parser, s, null); fail("wrong type - must be number"); } catch (IllegalArgumentException ex) { assertEquals(ex.getMessage(), "[foo] numeric_value doesn't support values of type: VALUE_BOOLEAN"); } }
@Test public void testSeqSpanQueryBuilder() throws IOException { String json = "{\n" + " \"seq_span\": {\n" + " \"field\": \"content\",\n" + " \"start_term\": \"a\",\n" + " \"end_term\": \"g\",\n" + " \"seq_term\": \"b c d e f\",\n" + " \"max_span\": 8\n" + " }\n" + "}"; XContentParser parser = JsonXContent.jsonXContent.createParser(null, json); QueryParseContext queryParseContext = new QueryParseContext(parser); SeqSpanQueryBuilder seqSpanQueryBuilder = new SeqSpanQueryParser().fromXContent(queryParseContext).orElse(null); System.out.println(seqSpanQueryBuilder); }
public void testParsingQueryContextGeoPoint() throws Exception { XContentBuilder builder = jsonBuilder().startObject() .field("lat", 23.654242) .field("lon", 90.047153) .endObject(); XContentParser parser = createParser(JsonXContent.jsonXContent, builder.bytes()); GeoContextMapping mapping = ContextBuilder.geo("geo").build(); List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(createParseContext(parser)); assertThat(internalQueryContexts.size(), equalTo(1 + 8)); Collection<String> locations = new ArrayList<>(); locations.add("wh0n94"); addNeighbors("wh0n94", GeoContextMapping.DEFAULT_PRECISION, locations); for (ContextMapping.InternalQueryContext internalQueryContext : internalQueryContexts) { assertThat(internalQueryContext.context, isIn(locations)); assertThat(internalQueryContext.boost, equalTo(1)); assertThat(internalQueryContext.isPrefix, equalTo(false)); } }
public void testObjectOrDefault() throws IOException { XContentParser parser = createParser(JsonXContent.jsonXContent, "{\"object\" : { \"test\": 2}}"); ObjectParser<StaticTestStruct, Void> objectParser = new ObjectParser<>("foo", StaticTestStruct::new); objectParser.declareInt(StaticTestStruct::setTest, new ParseField("test")); objectParser.declareObjectOrDefault(StaticTestStruct::setObject, objectParser, StaticTestStruct::new, new ParseField("object")); StaticTestStruct s = objectParser.parse(parser, null); assertEquals(s.object.test, 2); parser = createParser(JsonXContent.jsonXContent, "{\"object\" : false }"); s = objectParser.parse(parser, null); assertNull(s.object); parser = createParser(JsonXContent.jsonXContent, "{\"object\" : true }"); s = objectParser.parse(parser, null); assertNotNull(s.object); assertEquals(s.object.test, 0); }
public void testExcludes() throws Exception { String mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("_source").array("excludes", new String[]{"path1*"}).endObject() .endObject().endObject().string(); DocumentMapper documentMapper = createIndex("test").mapperService().documentMapperParser().parse("type", new CompressedXContent(mapping)); ParsedDocument doc = documentMapper.parse("test", "type", "1", XContentFactory.jsonBuilder().startObject() .startObject("path1").field("field1", "value1").endObject() .startObject("path2").field("field2", "value2").endObject() .endObject().bytes()); IndexableField sourceField = doc.rootDoc().getField("_source"); Map<String, Object> sourceAsMap; try (XContentParser parser = createParser(JsonXContent.jsonXContent, new BytesArray(sourceField.binaryValue()))) { sourceAsMap = parser.map(); } assertThat(sourceAsMap.containsKey("path1"), equalTo(false)); assertThat(sourceAsMap.containsKey("path2"), equalTo(true)); }
public void testUnknownSuggestionTypeThrows() throws IOException { XContent xContent = JsonXContent.jsonXContent; String suggestionString = "{\"unknownType#suggestionName\":" + "[{\"text\":\"entryText\"," + "\"offset\":42," + "\"length\":313," + "\"options\":[{\"text\":\"someText\"," + "\"highlighted\":\"somethingHighlighted\"," + "\"score\":1.3," + "\"collate_match\":true}]" + "}]" + "}"; try (XContentParser parser = xContent.createParser(xContentRegistry(), suggestionString)) { ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser::getTokenLocation); ensureExpectedToken(XContentParser.Token.FIELD_NAME, parser.nextToken(), parser::getTokenLocation); ParsingException e = expectThrows(ParsingException.class, () -> Suggestion.fromXContent(parser)); assertEquals("Unknown Suggestion [unknownType]", e.getMessage()); } }
public void testToXContent() throws IOException { HighlightField field = new HighlightField("foo", new Text[] { new Text("bar"), new Text("baz") }); XContentBuilder builder = JsonXContent.contentBuilder(); builder.prettyPrint(); builder.startObject(); field.toXContent(builder, ToXContent.EMPTY_PARAMS); builder.endObject(); assertEquals( "{\n" + " \"foo\" : [\n" + " \"bar\",\n" + " \"baz\"\n" + " ]\n" + "}", builder.string()); field = new HighlightField("foo", null); builder = JsonXContent.contentBuilder(); builder.prettyPrint(); builder.startObject(); field.toXContent(builder, ToXContent.EMPTY_PARAMS); builder.endObject(); assertEquals( "{\n" + " \"foo\" : null\n" + "}", builder.string()); }
public void testParseJson_simple() throws IOException { String scriptSort = "{\n" + "\"_script\" : {\n" + "\"type\" : \"number\",\n" + "\"script\" : \"doc['field_name'].value\",\n" + "\"mode\" : \"max\",\n" + "\"order\" : \"asc\"\n" + "} }\n"; XContentParser parser = createParser(JsonXContent.jsonXContent, scriptSort); parser.nextToken(); parser.nextToken(); parser.nextToken(); QueryParseContext context = new QueryParseContext(parser); ScriptSortBuilder builder = ScriptSortBuilder.fromXContent(context, null); assertEquals("doc['field_name'].value", builder.script().getIdOrCode()); assertEquals(Script.DEFAULT_SCRIPT_LANG, builder.script().getLang()); assertEquals(builder.script().getParams(), Collections.emptyMap()); assertEquals(ScriptType.INLINE, builder.script().getType()); assertEquals(ScriptSortType.NUMBER, builder.type()); assertEquals(SortOrder.ASC, builder.order()); assertEquals(SortMode.MAX, builder.sortMode()); assertNull(builder.getNestedFilter()); assertNull(builder.getNestedPath()); }
public void testEmptyList() throws IOException { XContentBuilder builder = XContentFactory.jsonBuilder().startObject() .startArray("some_array") .endArray().endObject(); try (XContentParser parser = createParser(JsonXContent.jsonXContent, builder.string())) { assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); assertEquals("some_array", parser.currentName()); if (random().nextBoolean()) { // sometimes read the start array token, sometimes not assertEquals(XContentParser.Token.START_ARRAY, parser.nextToken()); } assertEquals(Collections.emptyList(), parser.list()); } }
public void testSortModeSumIsRejectedInJSON() throws IOException { String json = "{\n" + " \"testname\" : [ {\n" + " \"lat\" : -6.046997540714173,\n" + " \"lon\" : -51.94128329747579\n" + " } ],\n" + " \"unit\" : \"m\",\n" + " \"distance_type\" : \"arc\",\n" + " \"mode\" : \"SUM\"\n" + "}"; XContentParser itemParser = createParser(JsonXContent.jsonXContent, json); itemParser.nextToken(); QueryParseContext context = new QueryParseContext(itemParser); IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> GeoDistanceSortBuilder.fromXContent(context, "")); assertEquals("sort_mode [sum] isn't supported for sorting by geo distance", e.getMessage()); }
public void testReadBooleans() throws IOException { String falsy = randomFrom("\"false\"", "false"); String truthy = randomFrom("\"true\"", "true"); try (XContentParser parser = createParser(JsonXContent.jsonXContent, "{\"foo\": " + falsy + ", \"bar\": " + truthy + "}")) { XContentParser.Token token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.START_OBJECT)); token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.currentName(), equalTo("foo")); token = parser.nextToken(); assertThat(token, isIn(Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_BOOLEAN))); assertTrue(parser.isBooleanValue()); assertFalse(parser.booleanValue()); token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.currentName(), equalTo("bar")); token = parser.nextToken(); assertThat(token, isIn(Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_BOOLEAN))); assertTrue(parser.isBooleanValue()); assertTrue(parser.booleanValue()); } }
public void testReverseOptionFails() throws IOException { String json = "{ \"post_date\" : {\"reverse\" : true} },\n"; XContentParser parser = createParser(JsonXContent.jsonXContent, json); // need to skip until parser is located on second START_OBJECT parser.nextToken(); parser.nextToken(); parser.nextToken(); QueryParseContext context = new QueryParseContext(parser); try { FieldSortBuilder.fromXContent(context, ""); fail("adding reverse sorting option should fail with an exception"); } catch (IllegalArgumentException e) { // all good } }
public void testNestedMapInList() throws IOException { XContentBuilder builder = XContentFactory.jsonBuilder().startObject() .startArray("some_array") .startObject().field("foo", "bar").endObject() .startObject().endObject() .endArray().endObject(); try (XContentParser parser = createParser(JsonXContent.jsonXContent, builder.string())) { assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); assertEquals("some_array", parser.currentName()); if (random().nextBoolean()) { // sometimes read the start array token, sometimes not assertEquals(XContentParser.Token.START_ARRAY, parser.nextToken()); } assertEquals( Arrays.asList(singletonMap("foo", "bar"), emptyMap()), parser.list()); } }
public void testReverseOptionFails() throws IOException { String json = "{ \"_score\": { \"reverse\": true }}"; XContentParser parser = createParser(JsonXContent.jsonXContent, json); // need to skip until parser is located on second START_OBJECT parser.nextToken(); parser.nextToken(); parser.nextToken(); QueryParseContext context = new QueryParseContext(parser); try { ScoreSortBuilder.fromXContent(context, "_score"); fail("adding reverse sorting option should fail with an exception"); } catch (IllegalArgumentException e) { // all good } }
private ClusterAllocationExplanation runExplain(boolean primary, String nodeId, boolean includeYesDecisions, boolean includeDiskInfo) throws Exception { ClusterAllocationExplanation explanation = client().admin().cluster().prepareAllocationExplain() .setIndex("idx").setShard(0).setPrimary(primary) .setIncludeYesDecisions(includeYesDecisions) .setIncludeDiskInfo(includeDiskInfo) .setCurrentNode(nodeId) .get().getExplanation(); if (logger.isDebugEnabled()) { XContentBuilder builder = JsonXContent.contentBuilder(); builder.prettyPrint(); builder.humanReadable(true); logger.debug("--> explain json output: \n{}", explanation.toXContent(builder, ToXContent.EMPTY_PARAMS).string()); } return explanation; }
public void testMultipleQueryObjectsAreRejected() throws Exception { String restContent = " { \"query\": {\n" + " \"multi_match\": {\n" + " \"query\": \"workd\",\n" + " \"fields\": [\"title^5\", \"plain_body\"]\n" + " },\n" + " \"filters\": {\n" + " \"terms\": {\n" + " \"status\": [ 3 ]\n" + " }\n" + " }\n" + " } }"; try (XContentParser parser = createParser(JsonXContent.jsonXContent, restContent)) { ParsingException e = expectThrows(ParsingException.class, () -> SearchSourceBuilder.fromXContent(createParseContext(parser))); assertEquals("[multi_match] malformed query, expected [END_OBJECT] but found [FIELD_NAME]", e.getMessage()); } }
/** * Validates that {@code max_determinized_states} can be parsed and lowers the allowed number of determinized states. */ public void testEnabledPositionIncrements() throws Exception { assumeTrue("test runs only when at least a type is registered", getCurrentTypes().length > 0); XContentBuilder builder = JsonXContent.contentBuilder(); builder.startObject(); { builder.startObject("query_string"); { builder.field("query", "text"); builder.field("default_field", STRING_FIELD_NAME); builder.field("enable_position_increments", false); } builder.endObject(); } builder.endObject(); QueryStringQueryBuilder queryBuilder = (QueryStringQueryBuilder) new QueryParseContext(createParser(builder)) .parseInnerQueryBuilder(); assertFalse(queryBuilder.enablePositionIncrements()); }
public void testParseNested() throws IOException { XContentParser parser = createParser(JsonXContent.jsonXContent, "{ \"test\" : 1, \"object\" : { \"test\": 2}}"); class TestStruct { public int test; TestStruct object; } ObjectParser<TestStruct, Void> objectParser = new ObjectParser<>("foo"); TestStruct s = new TestStruct(); s.object = new TestStruct(); objectParser.declareField((i, c, x) -> c.test = i.intValue(), new ParseField("test"), ValueType.INT); objectParser.declareField((i, c, x) -> objectParser.parse(parser, c.object, null), new ParseField("object"), ValueType.OBJECT); objectParser.parse(parser, s, null); assertEquals(s.test, 1); assertEquals(s.object.test, 2); }
public void testParseNamedObjectInOrderNotSupported() throws IOException { XContentParser parser = createParser(JsonXContent.jsonXContent, "{\"named\": [\n" + " {\"a\": {}}" + "]}"); // Create our own parser for this test so we can disable support for the "ordered" mode specified by the array above ObjectParser<NamedObjectHolder, Void> objectParser = new ObjectParser<>("named_object_holder", NamedObjectHolder::new); objectParser.declareNamedObjects(NamedObjectHolder::setNamed, NamedObject.PARSER, new ParseField("named")); // Now firing the xml through it fails ParsingException e = expectThrows(ParsingException.class, () -> objectParser.apply(parser, null)); assertEquals("[named_object_holder] failed to parse field [named]", e.getMessage()); assertEquals("[named] doesn't support arrays. Use a single object with multiple fields.", e.getCause().getMessage()); }
protected void sendResponse(final RestChannel channel, final Map<String, Object> params, final boolean pretty) { try { final XContentBuilder builder = JsonXContent.contentBuilder(); if (pretty) { builder.prettyPrint(); } builder.startObject(); builder.field("acknowledged", true); if (params != null) { for (final Map.Entry<String, Object> entry : params.entrySet()) { builder.field(entry.getKey(), entry.getValue()); } } builder.endObject(); channel.sendResponse(new BytesRestResponse(OK, builder)); } catch (final IOException e) { throw new ElasticsearchException("Failed to create a resposne.", e); } }
public void testParseNamedObjectJunkInArray() throws IOException { XContentParser parser = createParser(JsonXContent.jsonXContent, "{\"named\": [\n" + " \"junk\"" + "]}"); ParsingException e = expectThrows(ParsingException.class, () -> NamedObjectHolder.PARSER.apply(parser, null)); assertEquals("[named_object_holder] failed to parse field [named]", e.getMessage()); assertEquals( "[named] can be a single object with any number of fields or an array where each entry is an object with a single field", e.getCause().getMessage()); }
public void testParseNamedObjectInOrder() throws IOException { XContentParser parser = createParser(JsonXContent.jsonXContent, "{\"named\": [\n" + " {\"a\": {}}" + "]}"); NamedObjectHolder h = NamedObjectHolder.PARSER.apply(parser, null); assertThat(h.named, hasSize(1)); assertEquals("a", h.named.get(0).name); assertTrue(h.namedSuppliedInOrder); }
public void testSimple() throws IOException { String templateString = "{" + "\"inline\":{\"match_{{template}}\": {}}," + "\"params\":{\"template\":\"all\"}" + "}"; XContentParser parser = createParser(JsonXContent.jsonXContent, templateString); Script script = Script.parse(parser); CompiledScript compiledScript = new CompiledScript(ScriptType.INLINE, null, "mustache", qe.compile(null, script.getIdOrCode(), Collections.emptyMap())); ExecutableScript executableScript = qe.executable(compiledScript, script.getParams()); assertThat(((BytesReference) executableScript.run()).utf8ToString(), equalTo("{\"match_all\":{}}")); }
public void testParseTemplateAsSingleStringWithConditionalClause() throws IOException { String templateString = "{" + " \"inline\" : \"{ \\\"match_{{#use_it}}{{template}}{{/use_it}}\\\":{} }\"," + " \"params\":{" + " \"template\":\"all\"," + " \"use_it\": true" + " }" + "}"; XContentParser parser = createParser(JsonXContent.jsonXContent, templateString); Script script = Script.parse(parser); CompiledScript compiledScript = new CompiledScript(ScriptType.INLINE, null, "mustache", qe.compile(null, script.getIdOrCode(), Collections.emptyMap())); ExecutableScript executableScript = qe.executable(compiledScript, script.getParams()); assertThat(((BytesReference) executableScript.run()).utf8ToString(), equalTo("{ \"match_all\":{} }")); }
/** * Test that template can be expressed as a single escaped string. */ public void testTemplateQueryAsEscapedString() throws Exception { SearchRequest searchRequest = new SearchRequest(); searchRequest.indices("_all"); String query = "{" + " \"inline\" : \"{ \\\"size\\\": \\\"{{size}}\\\", \\\"query\\\":{\\\"match_all\\\":{}}}\"," + " \"params\":{" + " \"size\": 1" + " }" + "}"; SearchTemplateRequest request = RestSearchTemplateAction.parse(createParser(JsonXContent.jsonXContent, query)); request.setRequest(searchRequest); SearchTemplateResponse searchResponse = client().execute(SearchTemplateAction.INSTANCE, request).get(); assertThat(searchResponse.getResponse().getHits().getHits().length, equalTo(1)); }
public void testMissingAllConstructorArgsButNotRequired() throws IOException { XContentParser parser = createParser(JsonXContent.jsonXContent, "{\n" + " \"mineral\": 1\n" + "}"); HasCtorArguments parsed = HasCtorArguments.PARSER_ALL_OPTIONAL.apply(parser, null); assertEquals(1, parsed.mineral); }