Java Code Examples for org.elasticsearch.common.xcontent.ToXContent

The following examples show how to use org.elasticsearch.common.xcontent.ToXContent. These examples are extracted from open source projects. 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
protected static JsonObject readResponse(ToXContent toXContent) {
    try {
        final XContentBuilder builder = XContentFactory.jsonBuilder();
        if (toXContent.isFragment()) {
            builder.startObject();
            toXContent.toXContent(builder, SearchResponse.EMPTY_PARAMS);
            builder.endObject();
        } else {
            toXContent.toXContent(builder, SearchResponse.EMPTY_PARAMS);
        }

        return new JsonObject(builder.string());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 2
Source Project: Siamese   Source File: ESConnector.java    License: GNU General Public License v3.0 6 votes vote down vote up
public long getIndicesStats(String indexName) {
        IndicesStatsResponse indicesStatsResponse = client.admin().indices().prepareStats(indexName)
                .all()
                .execute().actionGet();

        XContentBuilder builder = null;
        try {
            builder = XContentFactory.jsonBuilder();
            builder.startObject();
            indicesStatsResponse.toXContent(builder, ToXContent.EMPTY_PARAMS);
            builder.endObject();
            String jsonResponse = builder.prettyPrint().string();

            JsonParser jsonParser = new JsonParser(); // from import com.google.gson.JsonParser;
            Long docCount = jsonParser.parse(jsonResponse)
                    .getAsJsonObject().get("_all")
                    .getAsJsonObject().get("primaries")
                    .getAsJsonObject().get("docs")
                    .getAsJsonObject().get("count").getAsLong();
//            System.out.println(docCount);
            return docCount;
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
    }
 
Example 3
Source Project: Elasticsearch   Source File: UserProperty.java    License: Apache License 2.0 6 votes vote down vote up
public static void toXContent(UserProperty userProperty, XContentBuilder builder, ToXContent.Params params) throws IOException {
    builder.startObject(userProperty.usernameWithTenant, XContentBuilder.FieldCaseConversion.NONE);
    builder.field("password", userProperty.password);
    {
        builder.startObject("db_privileges");
        for (String dbName : userProperty.dbPrivileges.keySet()) {
            builder.array(dbName, userProperty.dbPrivileges.get(dbName).toArray());
        }
        builder.endObject();

        builder.startObject("table_privileges");
        for (String tableName : userProperty.tablePrivileges.keySet()) {
            builder.array(tableName, userProperty.tablePrivileges.get(tableName).toArray());
        }
        builder.endObject();
    }
    builder.array("ip_whitelist", userProperty.ipWhiteList.toArray());
    builder.array("hostname_whitelist", userProperty.hostnameWhiteList.toArray());
    builder.array("hostip_whitelist", userProperty.hostIpWhiteList.toArray());
    builder.endObject();
}
 
Example 4
Source Project: ElasticUtils   Source File: BaseElasticSearchMapping.java    License: MIT License 6 votes vote down vote up
public XContentBuilder internalGetMapping() throws IOException {

        // Configure the RootObjectMapper:
        RootObjectMapper.Builder rootObjectMapperBuilder = getRootObjectBuilder();

        // Populate the Settings:
        Settings.Builder settingsBuilder = getSettingsBuilder();

        // Build the Mapping:
        Mapping mapping = new Mapping(
                version,
                rootObjectMapperBuilder.build(new Mapper.BuilderContext(settingsBuilder.build(), new ContentPath())),
                getMetaDataFieldMappers(),
                getSourceTransforms(),
                getMetaData());

        // Turn it into JsonXContent:
        return mapping.toXContent(JsonXContent.contentBuilder().startObject(), ToXContent.EMPTY_PARAMS);
    }
 
Example 5
Source Project: Elasticsearch   Source File: IndexWarmersMetaData.java    License: Apache License 2.0 6 votes vote down vote up
public static void toXContent(Entry entry, XContentBuilder builder, ToXContent.Params params) throws IOException {
    boolean binary = params.paramAsBoolean("binary", false);
    builder.startObject(entry.name(), XContentBuilder.FieldCaseConversion.NONE);
    builder.field("types", entry.types());
    if (entry.requestCache() != null) {
        builder.field("requestCache", entry.requestCache());
    }
    builder.field("source");
    if (binary) {
        builder.value(entry.source());
    } else {
        Map<String, Object> mapping;
        try (XContentParser parser = XContentFactory.xContent(entry.source()).createParser(entry.source())) {
            mapping = parser.mapOrdered();
        }
        builder.map(mapping);
    }
    builder.endObject();
}
 
Example 6
Source Project: fess   Source File: SystemMonitorTarget.java    License: Apache License 2.0 6 votes vote down vote up
private void appendElasticsearchStats(final StringBuilder buf) {
    String stats = null;
    try {
        final FessEsClient esClient = ComponentUtil.getFessEsClient();
        final NodesStatsResponse response = esClient.admin().cluster().prepareNodesStats().all().execute().actionGet(10000L);
        final XContentBuilder builder = XContentFactory.jsonBuilder();
        builder.startObject();
        response.toXContent(builder, ToXContent.EMPTY_PARAMS);
        builder.endObject();
        builder.flush();
        try (OutputStream out = builder.getOutputStream()) {
            stats = ((ByteArrayOutputStream) out).toString(Constants.UTF_8);
        }
    } catch (final Exception e) {
        logger.debug("Failed to access Elasticsearch stats.", e);
    }
    buf.append("\"elasticsearch\":").append(stats).append(',');
}
 
Example 7
Source Project: Elasticsearch   Source File: SearchStats.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {
    builder.startObject(Fields.SEARCH);
    builder.field(Fields.OPEN_CONTEXTS, openContexts);
    totalStats.toXContent(builder, params);
    if (groupStats != null && !groupStats.isEmpty()) {
        builder.startObject(Fields.GROUPS);
        for (Map.Entry<String, Stats> entry : groupStats.entrySet()) {
            builder.startObject(entry.getKey(), XContentBuilder.FieldCaseConversion.NONE);
            entry.getValue().toXContent(builder, params);
            builder.endObject();
        }
        builder.endObject();
    }
    builder.endObject();
    return builder;
}
 
Example 8
Source Project: elasticsearch-carrot2   Source File: SampleIndexTestCase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Roundtrip to/from JSON.
 */
protected static void checkJsonSerialization(ClusteringActionResponse result) throws IOException {
   XContentBuilder builder = XContentFactory.jsonBuilder().prettyPrint();
   builder.startObject();
   result.toXContent(builder, ToXContent.EMPTY_PARAMS);
   builder.endObject();
   String json = Strings.toString(builder);

   try (XContentParser parser = JsonXContent.jsonXContent.createParser(NamedXContentRegistry.EMPTY,
       DeprecationHandler.THROW_UNSUPPORTED_OPERATION, json)) {
      Map<String, Object> mapAndClose = parser.map();
      Assertions.assertThat(mapAndClose)
          .as("json-result")
          .containsKey(Fields.CLUSTERS);
   }
}
 
Example 9
Source Project: crate   Source File: AliasMetaData.java    License: Apache License 2.0 6 votes vote down vote up
public static void toXContent(AliasMetaData aliasMetaData, XContentBuilder builder, ToXContent.Params params) throws IOException {
    builder.startObject(aliasMetaData.alias());

    boolean binary = params.paramAsBoolean("binary", false);

    if (aliasMetaData.filter() != null) {
        if (binary) {
            builder.field("filter", aliasMetaData.filter.compressed());
        } else {
            builder.field("filter", XContentHelper.convertToMap(new BytesArray(aliasMetaData.filter().uncompressed()), true).v2());
        }
    }
    if (aliasMetaData.indexRouting() != null) {
        builder.field("index_routing", aliasMetaData.indexRouting());
    }
    if (aliasMetaData.searchRouting() != null) {
        builder.field("search_routing", aliasMetaData.searchRouting());
    }

    if (aliasMetaData.writeIndex() != null) {
        builder.field("is_write_index", aliasMetaData.writeIndex());
    }

    builder.endObject();
}
 
Example 10
Source Project: ElasticUtils   Source File: BaseElasticSearchMapping.java    License: MIT License 6 votes vote down vote up
public XContentBuilder internalGetMapping() throws IOException {

        // Configure the RootObjectMapper:
        RootObjectMapper.Builder rootObjectMapperBuilder = getRootObjectBuilder();

        // Populate the Settings:
        Settings.Builder settingsBuilder = getSettingsBuilder();

        //new Mapping(arg0, arg1, arg2, arg3)getSourceTransforms(),
        // Build the Mapping:
        Mapping mapping = new Mapping(
                version,
                rootObjectMapperBuilder.build(new Mapper.BuilderContext(settingsBuilder.build(), new ContentPath(1))),
                getMetaDataFieldMappers(),
                getMeta());

        // Turn it into JsonXContent:
        return mapping.toXContent(XContentFactory.jsonBuilder().startObject(), new ToXContent.MapParams(emptyMap())).endObject();
    }
 
Example 11
Source Project: crate   Source File: CompressedXContent.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create a {@link CompressedXContent} out of a {@link ToXContent} instance.
 */
public CompressedXContent(ToXContent xcontent, XContentType type, ToXContent.Params params) throws IOException {
    BytesStreamOutput bStream = new BytesStreamOutput();
    OutputStream compressedStream = CompressorFactory.COMPRESSOR.streamOutput(bStream);
    CRC32 crc32 = new CRC32();
    try (OutputStream checkedStream = new CheckedOutputStream(compressedStream, crc32)) {
        try (XContentBuilder builder = XContentFactory.contentBuilder(type, checkedStream)) {
            builder.startObject();
            xcontent.toXContent(builder, params);
            builder.endObject();
        }
    }
    this.bytes = BytesReference.toBytes(bStream.bytes());
    this.crc32 = (int) crc32.getValue();
    assertConsistent();
}
 
Example 12
Source Project: ElasticUtils   Source File: BaseElasticSearchMapping.java    License: MIT License 6 votes vote down vote up
public XContentBuilder internalGetMapping() throws IOException {

        // Configure the RootObjectMapper:
        RootObjectMapper.Builder rootObjectMapperBuilder = getRootObjectBuilder();

        // Populate the Settings:
        Settings.Builder settingsBuilder = getSettingsBuilder();

        //new Mapping(arg0, arg1, arg2, arg3)getSourceTransforms(),
        // Build the Mapping:
        Mapping mapping = new Mapping(
                version,
                rootObjectMapperBuilder.build(new Mapper.BuilderContext(settingsBuilder.build(), new ContentPath(1))),
                getMetaDataFieldMappers(),
                getMeta());

        // Turn it into JsonXContent:
        return mapping.toXContent(XContentFactory.jsonBuilder().startObject(), new ToXContent.MapParams(emptyMap())).endObject();
    }
 
Example 13
private void writeAliases(List<AliasMetadata> aliases, XContentBuilder builder, ToXContent.Params params) throws IOException {
    builder.startObject(Fields.ALIASES);
    if (aliases != null) {
        for (AliasMetadata alias : aliases) {
            AliasMetadata.Builder.toXContent(alias, builder, params);
        }
    }
    builder.endObject();
}
 
Example 14
public static Map<String, Object> convertJsonToxToStructuredMap(ToXContent jsonContent) {
    Map<String, Object> map = null;
    try {
        final BytesReference bytes = XContentHelper.toXContent(jsonContent, XContentType.JSON, false);
        map = XContentHelper.convertToMap(bytes, false, XContentType.JSON).v2();
    } catch (IOException e1) {
        throw ExceptionsHelper.convertToElastic(e1);
    }

    return map;
}
 
Example 15
public static JsonNode convertJsonToJackson(ToXContent jsonContent, boolean omitDefaults) {
    try {
        Map<String, String> pm = new HashMap<>(1);
        pm.put("omit_defaults", String.valueOf(omitDefaults));
        ToXContent.MapParams params = new ToXContent.MapParams(pm);

        final BytesReference bytes = XContentHelper.toXContent(jsonContent, XContentType.JSON, params, false);
        return DefaultObjectMapper.readTree(bytes.utf8ToString());
    } catch (IOException e1) {
        throw ExceptionsHelper.convertToElastic(e1);
    }

}
 
Example 16
Source Project: crate   Source File: CoordinationMetaDataTests.java    License: Apache License 2.0 5 votes vote down vote up
public void testXContent() throws IOException {
    CoordinationMetaData originalMeta = new CoordinationMetaData(randomNonNegativeLong(), randomVotingConfig(), randomVotingConfig(),
            randomVotingTombstones());

    final XContentBuilder builder = JsonXContent.contentBuilder();
    builder.startObject();
    originalMeta.toXContent(builder, ToXContent.EMPTY_PARAMS);
    builder.endObject();

    try (XContentParser parser = createParser(JsonXContent.JSON_XCONTENT, BytesReference.bytes(builder))) {
        final CoordinationMetaData fromXContentMeta = CoordinationMetaData.fromXContent(parser);
        assertThat(originalMeta, equalTo(fromXContentMeta));
    }
}
 
Example 17
Source Project: Elasticsearch   Source File: RestoreSnapshotResponse.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {
    if (restoreInfo != null) {
        builder.field(Fields.SNAPSHOT);
        restoreInfo.toXContent(builder, params);
    } else {
        builder.field(Fields.ACCEPTED, true);
    }
    return builder;
}
 
Example 18
Source Project: elasticshell   Source File: StatsRequestBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected XContentBuilder toXContent(IndicesStatsRequest request, IndicesStatsResponse response, XContentBuilder builder) throws IOException {
    builder.startObject();
    builder.field(Fields.OK, true);
    buildBroadcastShardsHeader(builder, response);
    response.toXContent(builder, ToXContent.EMPTY_PARAMS);
    builder.endObject();
    return builder;
}
 
Example 19
Source Project: anomaly-detection   Source File: ADStatsResponse.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    XContentBuilder xContentBuilder = builder.startObject();
    for (Map.Entry<String, Object> clusterStat : clusterStats.entrySet()) {
        builder.field(clusterStat.getKey(), clusterStat.getValue());
    }
    adStatsNodesResponse.toXContent(xContentBuilder, ToXContent.EMPTY_PARAMS);
    return xContentBuilder.endObject();
}
 
Example 20
Source Project: elasticshell   Source File: StatusRequestBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected XContentBuilder toXContent(IndicesStatusRequest request, IndicesStatusResponse response, XContentBuilder builder) throws IOException {
    builder.startObject();
    builder.field(Fields.OK, true);
    buildBroadcastShardsHeader(builder, response);
    response.toXContent(builder, ToXContent.EMPTY_PARAMS);
    builder.endObject();
    return builder;
}
 
Example 21
Source Project: anomaly-detection   Source File: AnomalyDetectorJobTests.java    License: Apache License 2.0 5 votes vote down vote up
public void testParseAnomalyDetectorJob() throws IOException {
    AnomalyDetectorJob anomalyDetectorJob = TestHelpers.randomAnomalyDetectorJob();
    String anomalyDetectorJobString = TestHelpers
        .xContentBuilderToString(anomalyDetectorJob.toXContent(TestHelpers.builder(), ToXContent.EMPTY_PARAMS));
    anomalyDetectorJobString = anomalyDetectorJobString
        .replaceFirst("\\{", String.format(Locale.ROOT, "{\"%s\":\"%s\",", randomAlphaOfLength(5), randomAlphaOfLength(5)));

    AnomalyDetectorJob parsedAnomalyDetectorJob = AnomalyDetectorJob.parse(TestHelpers.parser(anomalyDetectorJobString));
    assertEquals("Parsing anomaly detect result doesn't work", anomalyDetectorJob, parsedAnomalyDetectorJob);
}
 
Example 22
Source Project: anomaly-detection   Source File: FeatureTests.java    License: Apache License 2.0 5 votes vote down vote up
public void testParseFeature() throws IOException {
    Feature feature = TestHelpers.randomFeature();
    String featureString = TestHelpers.xContentBuilderToString(feature.toXContent(TestHelpers.builder(), ToXContent.EMPTY_PARAMS));
    featureString = featureString
        .replaceFirst("\\{", String.format(Locale.ROOT, "{\"%s\":\"%s\",", randomAlphaOfLength(5), randomAlphaOfLength(5)));
    Feature parsedFeature = Feature.parse(TestHelpers.parser(featureString));
    assertEquals("Parsing feature doesn't work", feature, parsedFeature);
}
 
Example 23
Source Project: anomaly-detection   Source File: AnomalyDetectorTests.java    License: Apache License 2.0 5 votes vote down vote up
public void testParseAnomalyDetector() throws IOException {
    AnomalyDetector detector = TestHelpers.randomAnomalyDetector(TestHelpers.randomUiMetadata(), Instant.now());
    String detectorString = TestHelpers.xContentBuilderToString(detector.toXContent(TestHelpers.builder(), ToXContent.EMPTY_PARAMS));
    detectorString = detectorString
        .replaceFirst("\\{", String.format(Locale.ROOT, "{\"%s\":\"%s\",", randomAlphaOfLength(5), randomAlphaOfLength(5)));
    AnomalyDetector parsedDetector = AnomalyDetector.parse(TestHelpers.parser(detectorString));
    assertEquals("Parsing anomaly detector doesn't work", detector, parsedDetector);
}
 
Example 24
Source Project: elasticsearch-sql   Source File: Paramer.java    License: Apache License 2.0 5 votes vote down vote up
public static ToXContent fullParamer(QueryStringQueryBuilder query, Paramer paramer) {
    if (paramer.analysis != null) {
        query.analyzer(paramer.analysis);
    }

    if (paramer.boost != null) {
        query.boost(paramer.boost);
    }

    if (paramer.slop != null) {
        query.phraseSlop(paramer.slop);
    }

    if (paramer.defaultField != null) {
        query.defaultField(paramer.defaultField);
    }

    if (paramer.tieBreaker != null) {
        query.tieBreaker(paramer.tieBreaker);
    }

    if (paramer.operator != null) {
        query.defaultOperator(paramer.operator);
    }

    if (paramer.type != null) {
        query.type(MultiMatchQueryBuilder.Type.parse(paramer.type.toLowerCase(Locale.ROOT), LoggingDeprecationHandler.INSTANCE));
    }

    if (paramer.minimumShouldMatch != null) {
        query.minimumShouldMatch(paramer.minimumShouldMatch);
    }

    query.fields(paramer.fieldsBoosts);

    return query;
}
 
Example 25
@Override
public void doXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {
  builder.startObject(FieldDataTermsQueryParser.NAME);
    builder.startObject(name);
      builder.field("value", value);
      builder.field("_cache_key", cacheKey);
    builder.endObject();
  builder.endObject();
}
 
Example 26
Source Project: elasticsearch-rest-command   Source File: Search.java    License: The Unlicense 5 votes vote down vote up
static void dumpSearchScript(SearchRequestBuilder search, ESLogger logger) {

		try {
			XContentBuilder builder = XContentFactory
					.contentBuilder(XContentType.JSON);
			search.internalBuilder().toXContent(builder,
					ToXContent.EMPTY_PARAMS);
			logger.info(builder.bytes().toUtf8());

		} catch (IOException e) {
			logger.info(e.getMessage());
		}

	}
 
Example 27
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 28
Source Project: crate   Source File: GetSnapshotsResponse.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {
    builder.startObject();
    builder.startArray("snapshots");
    for (SnapshotInfo snapshotInfo : snapshots) {
        snapshotInfo.toXContent(builder, params);
    }
    builder.endArray();
    builder.endObject();
    return builder;
}
 
Example 29
Source Project: anomaly-detection   Source File: RCFResultTests.java    License: 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 30
Source Project: anomaly-detection   Source File: DeleteTests.java    License: Apache License 2.0 5 votes vote down vote up
public <R extends ToXContent> void testJsonRequestTemplate(R request, Supplier<String> requestSupplier) throws IOException,
    JsonPathNotFoundException {
    XContentBuilder builder = jsonBuilder();
    request.toXContent(builder, ToXContent.EMPTY_PARAMS);

    String json = Strings.toString(builder);
    assertEquals(JsonDeserializer.getTextValue(json, CommonMessageAttributes.ID_JSON_KEY), requestSupplier.get());
}