Java Code Examples for org.elasticsearch.common.Strings#toString()

The following examples show how to use org.elasticsearch.common.Strings#toString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ArrayMapperTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidArrayNonConvertableType() throws Exception {
    String mapping = Strings.toString(XContentFactory.jsonBuilder()
        .startObject().startObject(TYPE).startObject("properties")
        .startObject("array_field")
        .field("type", ArrayMapper.CONTENT_TYPE)
        .startObject(ArrayMapper.INNER_TYPE)
        .field("type", "double")
        .endObject()
        .endObject()
        .endObject().endObject().endObject());
    DocumentMapper mapper = mapper(INDEX, mapping);

    expectedException.expect(MapperParsingException.class);
    expectedException.expectMessage("failed to parse field [array_field] of type [double]");

    BytesReference bytesReference = BytesReference.bytes(XContentFactory.jsonBuilder()
        .startObject()
        .array("array_field", true, false, true)
        .endObject());
    SourceToParse sourceToParse = new SourceToParse(INDEX, "abc", bytesReference, XContentType.JSON);
    mapper.parse(sourceToParse);
}
 
Example 2
Source File: ADStatsTests.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
@Test
public void testADStatsNodeResponse() throws IOException, JsonPathNotFoundException {
    Map<String, Object> stats = new HashMap<String, Object>() {
        {
            put("testKey", "testValue");
        }
    };

    // Test serialization
    ADStatsNodeResponse adStatsNodeResponse = new ADStatsNodeResponse(discoveryNode1, stats);
    BytesStreamOutput output = new BytesStreamOutput();
    adStatsNodeResponse.writeTo(output);
    StreamInput streamInput = output.bytes().streamInput();
    ADStatsNodeResponse readResponse = ADStatsNodeResponse.readStats(streamInput);
    assertEquals("readStats failed", readResponse.getStatsMap(), adStatsNodeResponse.getStatsMap());

    // Test toXContent
    XContentBuilder builder = jsonBuilder();
    adStatsNodeResponse.toXContent(builder.startObject(), ToXContent.EMPTY_PARAMS).endObject();
    String json = Strings.toString(builder);

    for (Map.Entry<String, Object> stat : stats.entrySet()) {
        assertEquals("toXContent does not work", JsonDeserializer.getTextValue(json, stat.getKey()), stat.getValue());
    }
}
 
Example 3
Source File: KeywordFieldMapperTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void test_keyword_field_parser_on_mapping_with_length_limit() throws Exception {
    String expectedMapping = Strings.toString(
        XContentFactory.jsonBuilder()
            .startObject()
                .startObject(TYPE)
                    .startObject("properties")
                        .startObject("text_col")
                            .field("type", "keyword")
                            .field("index", false)
                            .field("length_limit", 1)
                        .endObject()
                    .endObject()
                .endObject()
            .endObject());

    var parser = parser(new KeywordFieldMapper.TypeParser());
    // string -> doXContentBody -> parse -> string
    var compressedXContent = new CompressedXContent(expectedMapping);
    var mapper = parser.parse(TYPE, compressedXContent);
    var actualMapping = mapper.mappingSource().toString();

    assertThat(expectedMapping, is(actualMapping));
    assertThat(actualMapping, is(
        "{\"default\":{\"properties\":" +
        "{\"text_col\":{\"type\":\"keyword\",\"index\":false,\"length_limit\":1}}}}"));
}
 
Example 4
Source File: StringType.java    From crate with Apache License 2.0 5 votes vote down vote up
@Nonnull
private String convert(@Nonnull Object value) throws IllegalArgumentException {
    if (value instanceof String) {
        return (String) value;
    } else if (value instanceof BytesRef) {
        return ((BytesRef) value).utf8ToString();
    } else if (value instanceof Boolean) {
        return (boolean) value ? T : F;
    } else if (value instanceof Map) {
        try {
            //noinspection unchecked
            return Strings.toString(XContentFactory.jsonBuilder().map((Map<String, ?>) value));
        } catch (IOException e) {
            throw new IllegalArgumentException("Cannot cast `" + value + "` to type TEXT", e);
        }
    } else if (value instanceof Collection) {
        throw new IllegalArgumentException(
            String.format(Locale.ENGLISH, "Cannot cast %s to type TEXT", value));
    } else if (value.getClass().isArray()) {
        throw new IllegalArgumentException(
            String.format(Locale.ENGLISH, "Cannot cast %s to type TEXT", Arrays.toString((Object[]) value)));
    } else if (value instanceof TimeValue) {
        return ((TimeValue) value).getStringRep();
    } else if (value instanceof Regproc) {
        return ((Regproc) value).name();
    } else {
        return value.toString();
    }
}
 
Example 5
Source File: Mapping.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    try {
        XContentBuilder builder = XContentFactory.jsonBuilder().startObject();
        toXContent(builder, new ToXContent.MapParams(emptyMap()));
        return Strings.toString(builder.endObject());
    } catch (IOException bogus) {
        throw new UncheckedIOException(bogus);
    }
}
 
Example 6
Source File: MetaData.java    From crate with Apache License 2.0 5 votes vote down vote up
public static String toXContent(MetaData metaData) throws IOException {
    XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
    builder.startObject();
    toXContent(metaData, builder, ToXContent.EMPTY_PARAMS);
    builder.endObject();
    return Strings.toString(builder);
}
 
Example 7
Source File: ProfileTests.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
@Test
public void testProfileNodeResponse() throws IOException, JsonPathNotFoundException {

    // Test serialization
    ProfileNodeResponse profileNodeResponse = new ProfileNodeResponse(discoveryNode1, modelSizeMap1, shingleSize);
    BytesStreamOutput output = new BytesStreamOutput();
    profileNodeResponse.writeTo(output);
    StreamInput streamInput = output.bytes().streamInput();
    ProfileNodeResponse readResponse = ProfileNodeResponse.readProfiles(streamInput);
    assertEquals("serialization has the wrong model size", readResponse.getModelSize(), profileNodeResponse.getModelSize());
    assertEquals("serialization has the wrong shingle size", readResponse.getShingleSize(), profileNodeResponse.getShingleSize());

    // Test toXContent
    XContentBuilder builder = jsonBuilder();
    profileNodeResponse.toXContent(builder.startObject(), ToXContent.EMPTY_PARAMS).endObject();
    String json = Strings.toString(builder);

    for (Map.Entry<String, Long> profile : modelSizeMap1.entrySet()) {
        assertEquals(
            "toXContent has the wrong model size",
            JsonDeserializer.getLongValue(json, ProfileNodeResponse.MODEL_SIZE_IN_BYTES, profile.getKey()),
            profile.getValue().longValue()
        );
    }

    assertEquals(
        "toXContent has the wrong shingle size",
        JsonDeserializer.getIntValue(json, ProfileNodeResponse.SHINGLE_SIZE),
        shingleSize
    );
}
 
Example 8
Source File: DocumentGroup.java    From elasticsearch-carrot2 with Apache License 2.0 5 votes vote down vote up
public String toString() {
    try {
        XContentBuilder builder = XContentFactory.jsonBuilder().prettyPrint();
        toXContent(builder, EMPTY_PARAMS);
        return Strings.toString(builder);
    } catch (IOException e) {
        return "{ \"error\" : \"" + e.getMessage() + "\"}";
    }
}
 
Example 9
Source File: RCFResultTests.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
public void testJsonRequest() throws IOException, JsonPathNotFoundException {
    RCFResultRequest request = new RCFResultRequest("123", "123-rcf-1", new double[] { 0 });
    XContentBuilder builder = jsonBuilder();
    request.toXContent(builder, ToXContent.EMPTY_PARAMS);

    String json = Strings.toString(builder);
    assertEquals(JsonDeserializer.getTextValue(json, CommonMessageAttributes.ID_JSON_KEY), request.getAdID());
    assertArrayEquals(
        JsonDeserializer.getDoubleArrayValue(json, CommonMessageAttributes.FEATURE_JSON_KEY),
        request.getFeatures(),
        0.001
    );
}
 
Example 10
Source File: RestActionReceiversTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void testRestBulkRowCountReceiver() throws Exception {
    RestBulkRowCountReceiver.Result[] results = new RestBulkRowCountReceiver.Result[] {
        new RestBulkRowCountReceiver.Result(null, 1),
        new RestBulkRowCountReceiver.Result(null, 2),
        new RestBulkRowCountReceiver.Result(null, 3)
    };
    ResultToXContentBuilder builder = ResultToXContentBuilder.builder(JsonXContent.contentBuilder())
        .bulkRows(results);
    String s = Strings.toString(builder.build());
    assertEquals(s, "{\"results\":[{\"rowcount\":1},{\"rowcount\":2},{\"rowcount\":3}]}");
}
 
Example 11
Source File: CronTransportActionTests.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
public void testNormal() throws IOException, JsonPathNotFoundException {
    CronRequest request = new CronRequest();

    CronNodeRequest nodeRequest = new CronNodeRequest();
    BytesStreamOutput nodeRequestOut = new BytesStreamOutput();
    nodeRequestOut.setVersion(Version.CURRENT);
    nodeRequest.writeTo(nodeRequestOut);
    StreamInput siNode = nodeRequestOut.bytes().streamInput();

    CronNodeRequest nodeResponseRead = new CronNodeRequest(siNode);

    CronNodeResponse nodeResponse1 = action.nodeOperation(nodeResponseRead);
    CronNodeResponse nodeResponse2 = action.nodeOperation(new CronNodeRequest());

    CronResponse response = action.newResponse(request, Arrays.asList(nodeResponse1, nodeResponse2), Collections.emptyList());

    assertEquals(2, response.getNodes().size());
    assertTrue(!response.hasFailures());

    XContentBuilder builder = XContentFactory.jsonBuilder();
    builder.startObject();
    response.toXContent(builder, ToXContent.EMPTY_PARAMS);
    builder.endObject();

    String json = Strings.toString(builder);
    Function<JsonElement, String> function = (s) -> {
        try {
            return JsonDeserializer.getTextValue(s, CronNodeResponse.NODE_ID);
        } catch (Exception e) {
            Assert.fail(e.getMessage());
        }
        return null;
    };
    assertArrayEquals(
        JsonDeserializer.getArrayValue(json, function, CronResponse.NODES_JSON_KEY),
        new String[] { localNodeID, localNodeID }
    );
}
 
Example 12
Source File: Setting.java    From crate with Apache License 2.0 5 votes vote down vote up
private static String arrayToParsableString(List<String> array) {
    try {
        XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent());
        builder.startArray();
        for (String element : array) {
            builder.value(element);
        }
        builder.endArray();
        return Strings.toString(builder);
    } catch (IOException ex) {
        throw new ElasticsearchException(ex);
    }
}
 
Example 13
Source File: Settings.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    try (XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent())) {
        builder.startObject();
        toXContent(builder, new MapParams(Collections.singletonMap("flat_settings", "true")));
        builder.endObject();
        return Strings.toString(builder);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 14
Source File: ShapeBuilder.java    From crate with Apache License 2.0 4 votes vote down vote up
@Override
public String toString() {
    return Strings.toString(this, true, true);
}
 
Example 15
Source File: ArrayMapperTest.java    From crate with Apache License 2.0 4 votes vote down vote up
@Test
public void testObjectArrayMapping() throws Exception {
    // @formatter: off
    String mapping = Strings.toString(XContentFactory.jsonBuilder()
        .startObject()
            .startObject(TYPE)
                .startObject("properties")
                    .startObject("array_field")
                        .field("type", ArrayMapper.CONTENT_TYPE)
                        .startObject(ArrayMapper.INNER_TYPE)
                            .field("type", "object")
                            .field("dynamic", true)
                            .startObject("properties")
                                .startObject("s")
                                    .field("type", "keyword")
                                .endObject()
                            .endObject()
                        .endObject()
                    .endObject()
                .endObject()
            .endObject()
        .endObject());
    DocumentMapper mapper = mapper(INDEX, mapping);
    // child object mapper
    assertThat(mapper.objectMappers().get("array_field"), is(instanceOf(ObjectArrayMapper.class)));
    BytesReference bytesReference = BytesReference.bytes(XContentFactory.jsonBuilder()
        .startObject()
        .startArray("array_field")
        .startObject()
        .field("s", "a")
        .endObject()
        .startObject()
        .field("s", "b")
        .endObject()
        .startObject()
        .field("s", "c")
        .endObject()
        .endArray()
        .endObject());
    SourceToParse sourceToParse = new SourceToParse(INDEX, "abc", bytesReference, XContentType.JSON);
    ParsedDocument doc = mapper.parse(sourceToParse);
    // @formatter: off
    assertThat(doc.dynamicMappingsUpdate(), nullValue());
    assertThat(doc.docs().size(), is(1));
    assertThat(
        uniqueValuesFromFields(doc.docs().get(0), "array_field.s"),
        containsInAnyOrder("a", "b", "c"));
    assertThat(mapper.mappers().getMapper("array_field.s"), instanceOf(KeywordFieldMapper.class));
    assertThat(
        mapper.mappingSource().string(),
        is("{\"default\":{" +
           "\"properties\":{" +
           "\"array_field\":{" +
           "\"type\":\"array\"," +
           "\"inner\":{" +
           "\"dynamic\":\"true\"," +
           "\"properties\":{" +
           "\"s\":{" +
           "\"type\":\"keyword\"" +
           "}" +
           "}" +
           "}" +
           "}" +
           "}}}"));
}
 
Example 16
Source File: ActionWriteResponse.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public String toString() {
    return Strings.toString(this);
}
 
Example 17
Source File: UpdateSettingsRequest.java    From crate with Apache License 2.0 4 votes vote down vote up
@Override
public String toString() {
    return "indices : " + Arrays.toString(indices) + "," + Strings.toString(this);
}
 
Example 18
Source File: StoredFeature.java    From elasticsearch-learning-to-rank with Apache License 2.0 4 votes vote down vote up
public StoredFeature(String name, List<String> params, String templateLanguage, XContentBuilder template) {
    this(name, params, templateLanguage, Strings.toString(Objects.requireNonNull(template)), false);
}
 
Example 19
Source File: RestoreSnapshotRequest.java    From crate with Apache License 2.0 4 votes vote down vote up
@Override
public String toString() {
    return Strings.toString(this);
}
 
Example 20
Source File: AliasMetaData.java    From crate with Apache License 2.0 4 votes vote down vote up
@Override
public String toString() {
    return Strings.toString(this, true, true);
}