Java 类org.elasticsearch.common.xcontent.XContent 实例源码

项目:elasticsearch_my    文件:ElasticsearchExceptionTests.java   
public void testFromXContent() throws IOException {
    final XContent xContent = randomFrom(XContentType.values()).xContent();
    XContentBuilder builder = XContentBuilder.builder(xContent)
                                                .startObject()
                                                    .field("type", "foo")
                                                    .field("reason", "something went wrong")
                                                    .field("stack_trace", "...")
                                                .endObject();

    ElasticsearchException parsed;
    try (XContentParser parser = createParser(xContent, builder.bytes())) {
        assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
        parsed = ElasticsearchException.fromXContent(parser);
        assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken());
        assertNull(parser.nextToken());
    }

    assertNotNull(parsed);
    assertEquals(parsed.getMessage(), "Elasticsearch exception [type=foo, reason=something went wrong, stack_trace=...]");
}
项目:elasticsearch_my    文件:ElasticsearchExceptionTests.java   
public void testThrowableToAndFromXContent() throws IOException {
    final XContent xContent = randomFrom(XContentType.values()).xContent();

    final Tuple<Throwable, ElasticsearchException> exceptions = randomExceptions();
    final Throwable throwable = exceptions.v1();

    BytesReference throwableBytes = XContentHelper.toXContent((builder, params) -> {
        ElasticsearchException.generateThrowableXContent(builder, params, throwable);
        return builder;
    }, xContent.type(), randomBoolean());

    ElasticsearchException parsedException;
    try (XContentParser parser = createParser(xContent, throwableBytes)) {
        assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
        parsedException = ElasticsearchException.fromXContent(parser);
        assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken());
        assertNull(parser.nextToken());
    }
    assertDeepEquals(exceptions.v2(), parsedException);
}
项目:elasticsearch_my    文件:ElasticsearchExceptionTests.java   
public void testUnknownFailureToAndFromXContent() throws IOException {
    final XContent xContent = randomFrom(XContentType.values()).xContent();

    BytesReference failureBytes = XContentHelper.toXContent((builder, params) -> {
        // Prints a null failure using generateFailureXContent()
        ElasticsearchException.generateFailureXContent(builder, params, null, randomBoolean());
        return builder;
    }, xContent.type(), randomBoolean());

    ElasticsearchException parsedFailure;
    try (XContentParser parser = createParser(xContent, failureBytes)) {
        assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
        assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
        parsedFailure = ElasticsearchException.failureFromXContent(parser);
        assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
        assertNull(parser.nextToken());
    }

    // Failure was null, expecting a "unknown" reason
    assertEquals("Elasticsearch exception [type=exception, reason=unknown]", parsedFailure.getMessage());
    assertEquals(0, parsedFailure.getHeaders().size());
    assertEquals(0, parsedFailure.getMetadata().size());
}
项目:elasticsearch_my    文件:AggregatorFactoriesTests.java   
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]"));
}
项目:elasticsearch_my    文件:AggregatorFactoriesTests.java   
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 + "]"));
}
项目:elasticsearch_my    文件:SuggestionTests.java   
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());
    }
}
项目:elasticsearch_my    文件:FunctionScoreQueryBuilderTests.java   
public void testMalformedQueryMultipleQueryElements() throws IOException {
    assumeFalse("Test only makes sense if XContent parser doesn't have strict duplicate checks enabled",
        XContent.isStrictDuplicateDetectionEnabled());
    String json = "{\n" +
            "    \"function_score\":{\n" +
            "        \"query\":{\n" +
            "            \"bool\":{\n" +
            "                \"must\":{\"match\":{\"field\":\"value\"}}" +
            "             }\n" +
            "            },\n" +
            "        \"query\":{\n" +
            "            \"bool\":{\n" +
            "                \"must\":{\"match\":{\"field\":\"value\"}}" +
            "             }\n" +
            "            }\n" +
            "        }\n" +
            "    }\n" +
            "}";
    expectParsingException(json, "[query] is already defined.");
}
项目:elasticsearch_my    文件:BoolQueryBuilderTests.java   
/**
 * test that two queries in object throws error
 */
public void testTooManyQueriesInObject() throws IOException {
    assumeFalse("Test only makes sense if XContent parser doesn't have strict duplicate checks enabled",
        XContent.isStrictDuplicateDetectionEnabled());
    String clauseType = randomFrom("must", "should", "must_not", "filter");
    // should also throw error if invalid query is preceded by a valid one
    String query = "{\n" +
            "  \"bool\": {\n" +
            "    \"" + clauseType + "\": {\n" +
            "      \"match\": {\n" +
            "        \"foo\": \"bar\"\n" +
            "      },\n" +
            "      \"match\": {\n" +
            "        \"baz\": \"buzz\"\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
            "}";
    ParsingException ex = expectThrows(ParsingException.class, () -> parseQuery(query));
    assertEquals("[match] malformed query, expected [END_OBJECT] but found [FIELD_NAME]", ex.getMessage());
}
项目:elasticsearch_my    文件:PercolateQueryBuilder.java   
private static PercolateQuery.QueryStore createStore(PercolatorFieldMapper.FieldType fieldType,
                                                     QueryShardContext context,
                                                     boolean mapUnmappedFieldsAsString) {
    return ctx -> {
        LeafReader leafReader = ctx.reader();
        BinaryDocValues binaryDocValues = leafReader.getBinaryDocValues(fieldType.queryBuilderField.name());
        if (binaryDocValues == null) {
            return docId -> null;
        }

        Bits bits = leafReader.getDocsWithField(fieldType.queryBuilderField.name());
        return docId -> {
            if (bits.get(docId)) {
                BytesRef qbSource = binaryDocValues.get(docId);
                if (qbSource.length > 0) {
                    XContent xContent = PercolatorFieldMapper.QUERY_BUILDER_CONTENT_TYPE.xContent();
                    try (XContentParser sourceParser = xContent.createParser(context.getXContentRegistry(), qbSource.bytes,
                            qbSource.offset, qbSource.length)) {
                        return parseQuery(context, mapUnmappedFieldsAsString, sourceParser);
                    }
                } else {
                    return null;
                }
            } else {
                return null;
            }
        };
    };
}
项目:elasticsearch_my    文件:ObjectPath.java   
public static ObjectPath createFromXContent(XContent xContent, BytesReference input) throws IOException {
    try (XContentParser parser = xContent.createParser(NamedXContentRegistry.EMPTY, input)) {
        if (parser.nextToken() == XContentParser.Token.START_ARRAY) {
            return new ObjectPath(parser.listOrderedMap());
        }
        return new ObjectPath(parser.mapOrdered());
    }
}
项目:elasticsearch_my    文件:ClientYamlSuiteRestApiParserFailingTests.java   
public void testDuplicateParts() throws Exception {
    assumeFalse("Test only makes sense if XContent parser doesn't have strict duplicate checks enabled",
        XContent.isStrictDuplicateDetectionEnabled());
    parseAndExpectFailure("{\n" +
            "  \"ping\": {" +
            "    \"documentation\": \"http://www.elasticsearch.org/guide/\"," +
            "    \"methods\": [\"PUT\"]," +
            "    \"url\": {" +
            "      \"path\": \"/\"," +
            "      \"paths\": [\"/\"]," +
            "      \"parts\": {" +
            "        \"index\": {" +
            "          \"type\" : \"string\",\n" +
            "          \"description\" : \"index part\"\n" +
            "        }," +
            "        \"type\": {" +
            "          \"type\" : \"string\",\n" +
            "          \"description\" : \"type part\"\n" +
            "        }," +
            "        \"index\": {" +
            "          \"type\" : \"string\",\n" +
            "          \"description\" : \"index parameter part\"\n" +
            "        }" +
            "      }," +
            "      \"params\": {" +
            "        \"type\" : \"boolean\",\n" +
            "        \"description\" : \"Whether specified concrete indices should be ignored when unavailable (missing or closed)\"" +
            "      }" +
            "    }," +
            "    \"body\": null" +
            "  }" +
            "}", "Found duplicate part [index]");
}
项目:elasticsearch_my    文件:ClientYamlSuiteRestApiParserFailingTests.java   
public void testDuplicateParams() throws Exception {
    assumeFalse("Test only makes sense if XContent parser doesn't have strict duplicate checks enabled",
        XContent.isStrictDuplicateDetectionEnabled());
    parseAndExpectFailure("{\n" +
            "  \"ping\": {" +
            "    \"documentation\": \"http://www.elasticsearch.org/guide/\"," +
            "    \"methods\": [\"PUT\"]," +
            "    \"url\": {" +
            "      \"path\": \"/\"," +
            "      \"paths\": [\"/\"]," +
            "      \"parts\": {" +
            "      }," +
            "      \"params\": {" +
            "        \"timeout\": {" +
            "          \"type\" : \"string\",\n" +
            "          \"description\" : \"timeout parameter\"\n" +
            "        }," +
            "        \"refresh\": {" +
            "          \"type\" : \"string\",\n" +
            "          \"description\" : \"refresh parameter\"\n" +
            "        }," +
            "        \"timeout\": {" +
            "          \"type\" : \"string\",\n" +
            "          \"description\" : \"timeout parameter again\"\n" +
            "        }" +
            "      }" +
            "    }," +
            "    \"body\": null" +
            "  }" +
            "}", "Found duplicate param [timeout]");
}
项目:elasticsearch_my    文件:DoSectionTests.java   
public void testParseDoSectionWithJsonMultipleBodiesRepeatedProperty() throws Exception {
    assumeFalse("Test only makes sense if XContent parser doesn't have strict duplicate checks enabled",
        XContent.isStrictDuplicateDetectionEnabled());

    String[] bodies = new String[] {
            "{ \"index\": { \"_index\":\"test_index\", \"_type\":\"test_type\", \"_id\":\"test_id\" } }",
            "{ \"f1\":\"v1\", \"f2\":42 }",
    };
    parser = createParser(YamlXContent.yamlXContent,
            "bulk:\n" +
            "    refresh: true\n" +
            "    body: \n" +
            "        " + bodies[0] + "\n" +
            "    body: \n" +
            "        " + bodies[1]
    );

    DoSection doSection = DoSection.parse(parser);
    ApiCallSection apiCallSection = doSection.getApiCallSection();

    assertThat(apiCallSection, notNullValue());
    assertThat(apiCallSection.getApi(), equalTo("bulk"));
    assertThat(apiCallSection.getParams().size(), equalTo(1));
    assertThat(apiCallSection.getParams().get("refresh"), equalTo("true"));
    assertThat(apiCallSection.hasBody(), equalTo(true));
    assertThat(apiCallSection.getBodies().size(), equalTo(bodies.length));
    for (int i = 0; i < bodies.length; i++) {
        assertJsonEquals(apiCallSection.getBodies().get(i), bodies[i]);
    }
}
项目:elasticsearch_my    文件:DoSectionTests.java   
public void testParseDoSectionWithYamlMultipleBodiesRepeatedProperty() throws Exception {
    assumeFalse("Test only makes sense if XContent parser doesn't have strict duplicate checks enabled",
        XContent.isStrictDuplicateDetectionEnabled());

    parser = createParser(YamlXContent.yamlXContent,
            "bulk:\n" +
            "    refresh: true\n" +
            "    body:\n" +
            "        index:\n" +
            "            _index: test_index\n" +
            "            _type:  test_type\n" +
            "            _id:    test_id\n" +
            "    body:\n" +
            "        f1: v1\n" +
            "        f2: 42\n"
    );
    String[] bodies = new String[2];
    bodies[0] = "{\"index\": {\"_index\": \"test_index\", \"_type\":  \"test_type\", \"_id\": \"test_id\"}}";
    bodies[1] = "{ \"f1\":\"v1\", \"f2\": 42 }";

    DoSection doSection = DoSection.parse(parser);
    ApiCallSection apiCallSection = doSection.getApiCallSection();

    assertThat(apiCallSection, notNullValue());
    assertThat(apiCallSection.getApi(), equalTo("bulk"));
    assertThat(apiCallSection.getParams().size(), equalTo(1));
    assertThat(apiCallSection.getParams().get("refresh"), equalTo("true"));
    assertThat(apiCallSection.hasBody(), equalTo(true));
    assertThat(apiCallSection.getBodies().size(), equalTo(bodies.length));

    for (int i = 0; i < bodies.length; i++) {
        assertJsonEquals(apiCallSection.getBodies().get(i), bodies[i]);
    }
}
项目:elasticsearch_my    文件:JsonXContentGenerator.java   
protected void copyRawValue(BytesReference content, XContent xContent) throws IOException {
    // EMPTY is safe here because we never call namedObject
    try (StreamInput input = content.streamInput();
         XContentParser parser = xContent.createParser(NamedXContentRegistry.EMPTY, input)) {
        copyCurrentStructure(parser);
    }
}
项目:elasticsearch_my    文件:ElasticsearchExceptionTests.java   
public void testFromXContentWithCause() throws IOException {
    ElasticsearchException e = new ElasticsearchException("foo",
            new ElasticsearchException("bar",
                    new ElasticsearchException("baz",
                            new RoutingMissingException("_test", "_type", "_id"))));

    final XContent xContent = randomFrom(XContentType.values()).xContent();
    XContentBuilder builder = XContentBuilder.builder(xContent).startObject().value(e).endObject();

    ElasticsearchException parsed;
    try (XContentParser parser = createParser(builder)) {
        assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
        parsed = ElasticsearchException.fromXContent(parser);
        assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken());
        assertNull(parser.nextToken());
    }

    assertNotNull(parsed);
    assertEquals(parsed.getMessage(), "Elasticsearch exception [type=exception, reason=foo]");

    ElasticsearchException cause = (ElasticsearchException) parsed.getCause();
    assertEquals(cause.getMessage(), "Elasticsearch exception [type=exception, reason=bar]");

    cause = (ElasticsearchException) cause.getCause();
    assertEquals(cause.getMessage(), "Elasticsearch exception [type=exception, reason=baz]");

    cause = (ElasticsearchException) cause.getCause();
    assertEquals(cause.getMessage(),
            "Elasticsearch exception [type=routing_missing_exception, reason=routing is required for [_test]/[_type]/[_id]]");
    assertThat(cause.getHeaderKeys(), hasSize(0));
    assertThat(cause.getMetadataKeys(), hasSize(2));
    assertThat(cause.getMetadata("es.index"), hasItem("_test"));
    assertThat(cause.getMetadata("es.index_uuid"), hasItem("_na_"));
}
项目:elasticsearch_my    文件:ElasticsearchExceptionTests.java   
public void testFailureToAndFromXContentWithNoDetails() throws IOException {
    final XContent xContent = randomFrom(XContentType.values()).xContent();

    final Exception failure = (Exception) randomExceptions().v1();
    BytesReference failureBytes = XContentHelper.toXContent((builder, params) -> {
        ElasticsearchException.generateFailureXContent(builder, params, failure, false);
        return builder;
    }, xContent.type(), randomBoolean());

    try (XContentParser parser = createParser(xContent, failureBytes)) {
        failureBytes = shuffleXContent(parser, randomBoolean()).bytes();
    }

    ElasticsearchException parsedFailure;
    try (XContentParser parser = createParser(xContent, failureBytes)) {
        assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
        assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
        parsedFailure = ElasticsearchException.failureFromXContent(parser);
        assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
        assertNull(parser.nextToken());
    }
    assertNotNull(parsedFailure);

    String reason;
    if (failure instanceof ElasticsearchException) {
        reason = failure.getClass().getSimpleName() + "[" + failure.getMessage() + "]";
    } else {
        reason = "No ElasticsearchException found";
    }
    assertEquals(ElasticsearchException.buildMessage("exception", reason, null), parsedFailure.getMessage());
    assertEquals(0, parsedFailure.getHeaders().size());
    assertEquals(0, parsedFailure.getMetadata().size());
    assertNull(parsedFailure.getCause());
}
项目:elasticsearch_my    文件:DirectCandidateGeneratorTests.java   
/**
 * test that bad xContent throws exception
 */
public void testIllegalXContent() throws IOException {
    // test missing fieldname
    String directGenerator = "{ }";
    assertIllegalXContent(directGenerator, IllegalArgumentException.class,
            "Required [field]");

    // test two fieldnames
    if (XContent.isStrictDuplicateDetectionEnabled()) {
        logger.info("Skipping test as it uses a custom duplicate check that is obsolete when strict duplicate checks are enabled.");
    } else {
        directGenerator = "{ \"field\" : \"f1\", \"field\" : \"f2\" }";
        assertIllegalXContent(directGenerator, ParsingException.class,
            "[direct_generator] failed to parse field [field]");
    }

    // test unknown field
    directGenerator = "{ \"unknown_param\" : \"f1\" }";
    assertIllegalXContent(directGenerator, IllegalArgumentException.class,
            "[direct_generator] unknown field [unknown_param], parser not found");

    // test bad value for field (e.g. size expects an int)
    directGenerator = "{ \"size\" : \"xxl\" }";
    assertIllegalXContent(directGenerator, ParsingException.class,
            "[direct_generator] failed to parse field [size]");

    // test unexpected token
    directGenerator = "{ \"size\" : [ \"xxl\" ] }";
    assertIllegalXContent(directGenerator, IllegalArgumentException.class,
            "[direct_generator] size doesn't support values of type: START_ARRAY");
}
项目:elasticsearch_my    文件:ConstantScoreQueryBuilderTests.java   
/**
 * test that multiple "filter" elements causes {@link ParsingException}
 */
public void testMultipleFilterElements() throws IOException {
    assumeFalse("Test only makes sense if XContent parser doesn't have strict duplicate checks enabled",
        XContent.isStrictDuplicateDetectionEnabled());
    String queryString = "{ \"" + ConstantScoreQueryBuilder.NAME + "\" : {\n" +
                                "\"filter\" : { \"term\": { \"foo\": \"a\" } },\n" +
                                "\"filter\" : { \"term\": { \"foo\": \"x\" } },\n" +
                        "} }";
    ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(queryString));
    assertThat(e.getMessage(), containsString("accepts only one 'filter' element"));
}
项目:elasticsearch_my    文件:JsonSettingsLoaderTests.java   
public void testDuplicateKeysThrowsException() {
    assumeFalse("Test only makes sense if XContent parser doesn't have strict duplicate checks enabled",
        XContent.isStrictDuplicateDetectionEnabled());
    final String json = "{\"foo\":\"bar\",\"foo\":\"baz\"}";
    final SettingsException e = expectThrows(SettingsException.class,
        () -> Settings.builder().loadFromSource(json, XContentType.JSON).build());
    assertEquals(e.getCause().getClass(), ElasticsearchParseException.class);
    assertThat(
            e.toString(),
            containsString("duplicate settings key [foo] " +
                    "found at line number [1], " +
                    "column number [20], " +
                    "previous value [bar], " +
                    "current value [baz]"));
}
项目:elasticsearch_my    文件:YamlSettingsLoaderTests.java   
public void testDuplicateKeysThrowsException() {
    assumeFalse("Test only makes sense if XContent parser doesn't have strict duplicate checks enabled",
        XContent.isStrictDuplicateDetectionEnabled());

    String yaml = "foo: bar\nfoo: baz";
    SettingsException e = expectThrows(SettingsException.class, () -> {
        Settings.builder().loadFromSource(yaml, XContentType.YAML);
    });
    assertEquals(e.getCause().getClass(), ElasticsearchParseException.class);
    String msg = e.getCause().getMessage();
    assertTrue(
        msg,
        msg.contains("duplicate settings key [foo] found at line number [2], column number [6], " +
            "previous value [bar], current value [baz]"));
}
项目:elasticsearch_my    文件:AbstractFilteringJsonGeneratorTestCase.java   
protected void assertBinary(XContentBuilder expected, XContentBuilder builder) {
    assertNotNull(builder);
    assertNotNull(expected);

    try {
        XContent xContent = XContentFactory.xContent(builder.contentType());
        XContentParser jsonParser = createParser(xContent, expected.bytes());
        XContentParser testParser = createParser(xContent, builder.bytes());

        while (true) {
            XContentParser.Token token1 = jsonParser.nextToken();
            XContentParser.Token token2 = testParser.nextToken();
            if (token1 == null) {
                assertThat(token2, nullValue());
                return;
            }
            assertThat(token1, equalTo(token2));
            switch (token1) {
                case FIELD_NAME:
                    assertThat(jsonParser.currentName(), equalTo(testParser.currentName()));
                    break;
                case VALUE_STRING:
                    assertThat(jsonParser.text(), equalTo(testParser.text()));
                    break;
                case VALUE_NUMBER:
                    assertThat(jsonParser.numberType(), equalTo(testParser.numberType()));
                    assertThat(jsonParser.numberValue(), equalTo(testParser.numberValue()));
                    break;
            }
        }
    } catch (Exception e) {
        fail("Fail to verify the result of the XContentBuilder: " + e.getMessage());
    }
}
项目:elasticsearch_my    文件:SearchPhaseExecutionExceptionTests.java   
public void testToAndFromXContent() throws IOException {
    final XContent xContent = randomFrom(XContentType.values()).xContent();

    ShardSearchFailure[] shardSearchFailures = new ShardSearchFailure[randomIntBetween(1, 5)];
    for (int i = 0; i < shardSearchFailures.length; i++) {
        Exception cause = randomFrom(
                new ParsingException(1, 2, "foobar", null),
                new InvalidIndexTemplateException("foo", "bar"),
                new TimestampParsingException("foo", null),
                new NullPointerException()
        );
        shardSearchFailures[i] = new  ShardSearchFailure(cause, new SearchShardTarget("node_" + i, new Index("test", "_na_"), i));
    }

    final String phase = randomFrom("query", "search", "other");
    SearchPhaseExecutionException actual = new SearchPhaseExecutionException(phase, "unexpected failures", shardSearchFailures);

    BytesReference exceptionBytes = XContentHelper.toXContent(actual, xContent.type(), randomBoolean());

    ElasticsearchException parsedException;
    try (XContentParser parser = createParser(xContent, exceptionBytes)) {
        assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
        parsedException = ElasticsearchException.fromXContent(parser);
        assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken());
        assertNull(parser.nextToken());
    }

    assertNotNull(parsedException);
    assertThat(parsedException.getHeaderKeys(), hasSize(0));
    assertThat(parsedException.getMetadataKeys(), hasSize(1));
    assertThat(parsedException.getMetadata("es.phase"), hasItem(phase));
    // SearchPhaseExecutionException has no cause field
    assertNull(parsedException.getCause());
}
项目:siren-join    文件:BaseTransportCoordinateSearchAction.java   
protected XContentBuilder buildSource(XContent content, Map<String, Object> map) {
  try {
    // Enforce the content type to be CBOR as it is more efficient for large byte arrays
    return XContentBuilder.builder(XContentType.CBOR.xContent()).map(map);
  }
  catch (IOException e) {
    logger.error("failed to build source", e);
    throw new IllegalStateException("Failed to build source", e);
  }
}
项目:elasticsearch-xml    文件:XmlXContentFactory.java   
/**
 * Guesses the content (type) based on the provided char sequence.
 */
public static XContent xContent(CharSequence content) {
    XmlXContentType type = xContentType(content);
    if (type == null) {
        throw new ElasticsearchParseException("Failed to derive xcontent from " + content);
    }
    return xContent(type);
}
项目:elasticsearch-xml    文件:XmlXContentFactory.java   
/**
 * Guesses the content type based on the provided bytes.
 */
public static XContent xContent(byte[] data, int offset, int length) {
    XmlXContentType type = xContentType(data, offset, length);
    if (type == null) {
        throw new ElasticsearchParseException("Failed to derive xcontent from (offset=" + offset + ", length=" + length + "): " + Arrays.toString(data));
    }
    return xContent(type);
}
项目:elasticsearch-xml    文件:XmlXContentFactory.java   
public static XContent xContent(BytesReference bytes) {
    XmlXContentType type = xContentType(bytes);
    if (type == null) {
        throw new ElasticsearchParseException("Failed to derive xcontent from " + bytes);
    }
    return xContent(type);
}
项目:calcite    文件:Elasticsearch5Table.java   
@Override protected Enumerable<Object> find(String index, List<String> ops,
    List<Map.Entry<String, Class>> fields) {
  final String dbName = index;

  final SearchSourceBuilder searchSourceBuilder;
  if (ops.isEmpty()) {
    searchSourceBuilder = new SearchSourceBuilder();
  } else {
    String queryString = "{" + Util.toString(ops, "", ", ", "") + "}";
    NamedXContentRegistry xContentRegistry = NamedXContentRegistry.EMPTY;
    XContent xContent = JsonXContent.jsonXContent;
    try (XContentParser parser = xContent.createParser(xContentRegistry, queryString)) {
      final QueryParseContext queryParseContext = new QueryParseContext(parser);
      searchSourceBuilder = SearchSourceBuilder.fromXContent(queryParseContext);
    } catch (IOException ex) {
      throw new RuntimeException(ex);
    }
  }
  final Function1<SearchHit, Object> getter = Elasticsearch5Enumerator.getter(fields);

  return new AbstractEnumerable<Object>() {
    public Enumerator<Object> enumerator() {
      final Iterator<SearchHit> cursor = client.prepareSearch(dbName).setTypes(typeName)
          .setSource(searchSourceBuilder)
          .execute().actionGet().getHits().iterator();
      return new Elasticsearch5Enumerator(cursor, getter);
    }
  };
}
项目:elasticsearch_my    文件:ESTestCase.java   
/**
 * Create a new {@link XContentParser}.
 */
protected final XContentParser createParser(XContent xContent, String data) throws IOException {
    return xContent.createParser(xContentRegistry(), data);
}
项目:elasticsearch_my    文件:ESTestCase.java   
/**
 * Create a new {@link XContentParser}.
 */
protected final XContentParser createParser(XContent xContent, InputStream data) throws IOException {
    return xContent.createParser(xContentRegistry(), data);
}
项目:elasticsearch_my    文件:ESTestCase.java   
/**
 * Create a new {@link XContentParser}.
 */
protected final XContentParser createParser(XContent xContent, byte[] data) throws IOException {
    return xContent.createParser(xContentRegistry(), data);
}
项目:elasticsearch_my    文件:ESTestCase.java   
/**
 * Create a new {@link XContentParser}.
 */
protected final XContentParser createParser(XContent xContent, BytesReference data) throws IOException {
    return xContent.createParser(xContentRegistry(), data);
}
项目:elasticsearch_my    文件:ElasticsearchExceptionTests.java   
public void testFromXContentWithHeadersAndMetadata() throws IOException {
    RoutingMissingException routing = new RoutingMissingException("_test", "_type", "_id");
    ElasticsearchException baz = new ElasticsearchException("baz", routing);
    baz.addHeader("baz_0", "baz0");
    baz.addMetadata("es.baz_1", "baz1");
    baz.addHeader("baz_2", "baz2");
    baz.addMetadata("es.baz_3", "baz3");
    ElasticsearchException bar = new ElasticsearchException("bar", baz);
    bar.addMetadata("es.bar_0", "bar0");
    bar.addHeader("bar_1", "bar1");
    bar.addMetadata("es.bar_2", "bar2");
    ElasticsearchException foo = new ElasticsearchException("foo", bar);
    foo.addMetadata("es.foo_0", "foo0");
    foo.addHeader("foo_1", "foo1");

    final XContent xContent = randomFrom(XContentType.values()).xContent();
    XContentBuilder builder = XContentBuilder.builder(xContent).startObject().value(foo).endObject();

    ElasticsearchException parsed;
    try (XContentParser parser = createParser(builder)) {
        assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
        parsed = ElasticsearchException.fromXContent(parser);
        assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken());
        assertNull(parser.nextToken());
    }

    assertNotNull(parsed);
    assertEquals(parsed.getMessage(), "Elasticsearch exception [type=exception, reason=foo]");
    assertThat(parsed.getHeaderKeys(), hasSize(1));
    assertThat(parsed.getHeader("foo_1"), hasItem("foo1"));
    assertThat(parsed.getMetadataKeys(), hasSize(1));
    assertThat(parsed.getMetadata("es.foo_0"), hasItem("foo0"));

    ElasticsearchException cause = (ElasticsearchException) parsed.getCause();
    assertEquals(cause.getMessage(), "Elasticsearch exception [type=exception, reason=bar]");
    assertThat(cause.getHeaderKeys(), hasSize(1));
    assertThat(cause.getHeader("bar_1"), hasItem("bar1"));
    assertThat(cause.getMetadataKeys(), hasSize(2));
    assertThat(cause.getMetadata("es.bar_0"), hasItem("bar0"));
    assertThat(cause.getMetadata("es.bar_2"), hasItem("bar2"));

    cause = (ElasticsearchException) cause.getCause();
    assertEquals(cause.getMessage(), "Elasticsearch exception [type=exception, reason=baz]");
    assertThat(cause.getHeaderKeys(), hasSize(2));
    assertThat(cause.getHeader("baz_0"), hasItem("baz0"));
    assertThat(cause.getHeader("baz_2"), hasItem("baz2"));
    assertThat(cause.getMetadataKeys(), hasSize(2));
    assertThat(cause.getMetadata("es.baz_1"), hasItem("baz1"));
    assertThat(cause.getMetadata("es.baz_3"), hasItem("baz3"));

    cause = (ElasticsearchException) cause.getCause();
    assertEquals(cause.getMessage(),
            "Elasticsearch exception [type=routing_missing_exception, reason=routing is required for [_test]/[_type]/[_id]]");
    assertThat(cause.getHeaderKeys(), hasSize(0));
    assertThat(cause.getMetadataKeys(), hasSize(2));
    assertThat(cause.getMetadata("es.index"), hasItem("_test"));
    assertThat(cause.getMetadata("es.index_uuid"), hasItem("_na_"));
}
项目:elasticsearch_my    文件:ElasticsearchExceptionTests.java   
/**
 * Test that some values like arrays of numbers are ignored when parsing back
 * an exception.
 */
public void testFromXContentWithIgnoredMetadataAndHeaders() throws IOException {
    final XContent xContent = randomFrom(XContentType.values()).xContent();

    // The exception content to parse is built using a XContentBuilder
    // because the current Java API does not allow to add metadata/headers
    // of other types than list of strings.
    BytesReference originalBytes;
    try (XContentBuilder builder = XContentBuilder.builder(xContent)) {
        builder.startObject()
                .field("metadata_int", 1)
                .array("metadata_array_of_ints", new int[]{8, 13, 21})
                .field("reason", "Custom reason")
                .array("metadata_array_of_boolean", new boolean[]{false, false})
                .startArray("metadata_array_of_objects")
                    .startObject()
                        .field("object_array_one", "value_one")
                    .endObject()
                    .startObject()
                        .field("object_array_two", "value_two")
                    .endObject()
                .endArray()
                .field("type", "custom_exception")
                .field("metadata_long", 1L)
                .array("metadata_array_of_longs", new long[]{2L, 3L, 5L})
                .field("metadata_other", "some metadata")
                .startObject("header")
                    .field("header_string", "some header")
                    .array("header_array_of_strings", new String[]{"foo", "bar", "baz"})
                .endObject()
                .startObject("metadata_object")
                    .field("object_field", "value")
                .endObject()
        .endObject();

        originalBytes = builder.bytes();
    }

    ElasticsearchException parsedException;
    try (XContentParser parser = createParser(xContent, originalBytes)) {
        assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
        parsedException = ElasticsearchException.fromXContent(parser);
        assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken());
        assertNull(parser.nextToken());
    }

    assertNotNull(parsedException);
    assertEquals("Elasticsearch exception [type=custom_exception, reason=Custom reason]", parsedException.getMessage());
    assertEquals(2, parsedException.getHeaderKeys().size());
    assertThat(parsedException.getHeader("header_string"), hasItem("some header"));
    assertThat(parsedException.getHeader("header_array_of_strings"), hasItems("foo", "bar", "baz"));
    assertEquals(1, parsedException.getMetadataKeys().size());
    assertThat(parsedException.getMetadata("es.metadata_other"), hasItem("some metadata"));
}
项目:elasticsearch-queryexpansion-plugin    文件:AbstractITCase.java   
/**
 * Create a new {@link XContentParser}.
 */
protected static XContentParser createParser(XContent xContent, String data) throws IOException {
    return xContent.createParser(xContentRegistry(), data);
}
项目:elasticsearch-queryexpansion-plugin    文件:AbstractITCase.java   
/**
 * Create a new {@link XContentParser}.
 */
protected static XContentParser createParser(XContent xContent, InputStream data) throws IOException {
    return xContent.createParser(xContentRegistry(), data);
}
项目:elasticsearch-queryexpansion-plugin    文件:AbstractITCase.java   
/**
 * Create a new {@link XContentParser}.
 */
protected static XContentParser createParser(XContent xContent, byte[] data) throws IOException {
    return xContent.createParser(xContentRegistry(), data);
}
项目:elasticsearch-queryexpansion-plugin    文件:AbstractITCase.java   
/**
 * Create a new {@link XContentParser}.
 */
protected static XContentParser createParser(XContent xContent, BytesReference data) throws IOException {
    return xContent.createParser(xContentRegistry(), data);
}
项目:elasticsearch-xml    文件:XmlXContentFactory.java   
/**
 * Returns the {@link org.elasticsearch.common.xcontent.XContent} for the provided content type.
 */
public static XContent xContent(XmlXContentType type) {
    return type.xContent();
}
项目:elasticsearch-xml    文件:XmlXContentFactory.java   
/**
 * Guesses the content type based on the provided bytes.
 */
public static XContent xContent(byte[] data) {
    return xContent(data, 0, data.length);
}