org.elasticsearch.common.xcontent.ToXContent Java Examples

The following examples show how to use org.elasticsearch.common.xcontent.ToXContent. 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: BaseElasticSearchMapping.java    From ElasticUtils with 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 #2
Source File: CompressedXContent.java    From crate with 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 #3
Source File: UserProperty.java    From Elasticsearch with 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 File: BaseElasticSearchMapping.java    From ElasticUtils with 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 File: IndexWarmersMetaData.java    From Elasticsearch with 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 File: AliasMetaData.java    From crate with 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 #7
Source File: BaseElasticSearchMapping.java    From ElasticUtils with 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 #8
Source File: ElasticSearchServiceMapper.java    From vertx-elasticsearch-service with Apache License 2.0 6 votes vote down vote up
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 #9
Source File: ESConnector.java    From Siamese with 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 #10
Source File: SystemMonitorTarget.java    From fess with 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 #11
Source File: SearchStats.java    From Elasticsearch with 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 #12
Source File: SampleIndexTestCase.java    From elasticsearch-carrot2 with 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 #13
Source File: CompressedXContent.java    From Elasticsearch with Apache License 2.0 5 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.defaultCompressor().streamOutput(bStream);
    CRC32 crc32 = new CRC32();
    OutputStream checkedStream = new CheckedOutputStream(compressedStream, crc32);
    try (XContentBuilder builder = XContentFactory.contentBuilder(type, checkedStream)) {
        builder.startObject();
        xcontent.toXContent(builder, params);
        builder.endObject();
    }
    this.bytes = bStream.bytes().toBytes();
    this.crc32 = (int) crc32.getValue();
    assertConsistent();
}
 
Example #14
Source File: Paramer.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
public static ToXContent fullParamer(SpanNearQueryBuilder query, Paramer paramer) {
    if (paramer.boost != null) {
        query.boost(paramer.boost);
    }

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

    return query;
}
 
Example #15
Source File: StoredFeatureParserTests.java    From elasticsearch-learning-to-rank with Apache License 2.0 5 votes vote down vote up
public void testToXContent() throws IOException {
    String featureString = generateTestFeature();
    StoredFeature feature = parse(featureString);
    XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
    featureString = Strings.toString(feature.toXContent(builder, ToXContent.EMPTY_PARAMS));
    StoredFeature featureReparsed = parse(featureString);
    assertTestFeature(featureReparsed);
}
 
Example #16
Source File: SnapshotsInProgress.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {
    builder.startArray(Fields.SNAPSHOTS);
    for (Entry entry : entries) {
        toXContent(entry, builder, params);
    }
    builder.endArray();
    return builder;
}
 
Example #17
Source File: RestoreInProgress.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {
    builder.startArray("snapshots");
    for (Entry entry : entries) {
        toXContent(entry, builder, params);
    }
    builder.endArray();
    return builder;
}
 
Example #18
Source File: RestoreInProgress.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Serializes single restore operation
 *
 * @param entry   restore operation metadata
 * @param builder XContent builder
 * @param params  serialization parameters
 */
public void toXContent(Entry entry, XContentBuilder builder, ToXContent.Params params) throws IOException {
    builder.startObject();
    builder.field("snapshot", entry.snapshotId().getSnapshot());
    builder.field("repository", entry.snapshotId().getRepository());
    builder.field("state", entry.state());
    builder.startArray("indices");
    {
        for (String index : entry.indices()) {
            builder.value(index);
        }
    }
    builder.endArray();
    builder.startArray("shards");
    {
        for (Map.Entry<ShardId, ShardRestoreStatus> shardEntry : entry.shards.entrySet()) {
            ShardId shardId = shardEntry.getKey();
            ShardRestoreStatus status = shardEntry.getValue();
            builder.startObject();
            {
                builder.field("index", shardId.getIndex());
                builder.field("shard", shardId.getId());
                builder.field("state", status.state());
            }
            builder.endObject();
        }
    }

    builder.endArray();
    builder.endObject();
}
 
Example #19
Source File: ThreadPoolStats.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {
    builder.startObject(Fields.THREAD_POOL);
    for (Stats stat : stats) {
        stat.toXContent(builder, params);
    }
    builder.endObject();
    return builder;
}
 
Example #20
Source File: FulltextAnalyzerResolver.java    From crate with Apache License 2.0 5 votes vote down vote up
public static BytesReference encodeSettings(Settings settings) {
    try {
        XContentBuilder builder = XContentFactory.jsonBuilder();
        builder.startObject();
        settings.toXContent(builder, new ToXContent.MapParams(Collections.emptyMap()));
        builder.endObject();
        return BytesReference.bytes(builder);
    } catch (IOException e) {
        // this is a memory stream so no real I/O happens and a IOException can't really happen at runtime
        throw new RuntimeException(e);
    }
}
 
Example #21
Source File: MetaStateService.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a StateFormat that can read and write {@link IndexMetaData}
 */
static MetaDataStateFormat<IndexMetaData> indexStateFormat(XContentType format, final ToXContent.Params formatParams) {
    return new MetaDataStateFormat<IndexMetaData>(format, INDEX_STATE_FILE_PREFIX) {

        @Override
        public void toXContent(XContentBuilder builder, IndexMetaData state) throws IOException {
            IndexMetaData.Builder.toXContent(state, builder, formatParams);            }

        @Override
        public IndexMetaData fromXContent(XContentParser parser) throws IOException {
            return IndexMetaData.Builder.fromXContent(parser);
        }
    };
}
 
Example #22
Source File: RestGetIndicesAliasesAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
    final String[] aliases = Strings.splitStringByCommaToArray(request.param("name"));

    ClusterStateRequest clusterStateRequest = Requests.clusterStateRequest()
            .routingTable(false)
            .nodes(false)
            .indices(indices);
    clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local()));

    client.admin().cluster().state(clusterStateRequest, new RestBuilderListener<ClusterStateResponse>(channel) {
        @Override
        public RestResponse buildResponse(ClusterStateResponse response, XContentBuilder builder) throws Exception {
            MetaData metaData = response.getState().metaData();
            builder.startObject();

            final boolean isAllAliasesRequested = isAllOrWildcard(aliases);
            for (IndexMetaData indexMetaData : metaData) {
                builder.startObject(indexMetaData.getIndex(), XContentBuilder.FieldCaseConversion.NONE);
                builder.startObject("aliases");

                for (ObjectCursor<AliasMetaData> cursor : indexMetaData.getAliases().values()) {
                    if (isAllAliasesRequested || Regex.simpleMatch(aliases, cursor.value.alias())) {
                        AliasMetaData.Builder.toXContent(cursor.value, builder, ToXContent.EMPTY_PARAMS);
                    }
                }

                builder.endObject();
                builder.endObject();
            }

            builder.endObject();
            return new BytesRestResponse(OK, builder);
        }
    });
}
 
Example #23
Source File: AbstractAllocateAllocationCommand.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {
    builder.startObject();
    builder.field(INDEX_FIELD, index());
    builder.field(SHARD_FIELD, shardId());
    builder.field(NODE_FIELD, node());
    extraXContent(builder);
    return builder.endObject();
}
 
Example #24
Source File: BytesRestResponse.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private static XContentBuilder convert(RestChannel channel, RestStatus status, Throwable t) throws IOException {
    XContentBuilder builder = channel.newErrorBuilder().startObject();
    if (t == null) {
        builder.field("error", "unknown");
    } else if (channel.detailedErrorsEnabled()) {
        final ToXContent.Params params;
        if (channel.request().paramAsBoolean("error_trace", !ElasticsearchException.REST_EXCEPTION_SKIP_STACK_TRACE_DEFAULT)) {
            params =  new ToXContent.DelegatingMapParams(Collections.singletonMap(ElasticsearchException.REST_EXCEPTION_SKIP_STACK_TRACE, "false"), channel.request());
        } else {
            if (status.getStatus() < 500) {
                SUPPRESSED_ERROR_LOGGER.debug("{} Params: {}", t, channel.request().path(), channel.request().params());
            } else {
                SUPPRESSED_ERROR_LOGGER.warn("{} Params: {}", t, channel.request().path(), channel.request().params());
            }
            params = channel.request();
        }
        builder.field("error");
        builder.startObject();
        final ElasticsearchException[] rootCauses = ElasticsearchException.guessRootCauses(t);
        builder.field("root_cause");
        builder.startArray();
        for (ElasticsearchException rootCause : rootCauses){
            builder.startObject();
            rootCause.toXContent(builder, new ToXContent.DelegatingMapParams(Collections.singletonMap(ElasticsearchException.REST_EXCEPTION_SKIP_CAUSE, "true"), params));
            builder.endObject();
        }
        builder.endArray();

        ElasticsearchException.toXContent(builder, params, t);
        builder.endObject();
    } else {
        builder.field("error", simpleMessage(t));
    }
    builder.field("status", status.getStatus());
    builder.endObject();
    return builder;
}
 
Example #25
Source File: SearchUtilsTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private void assertSearchBuilder(SortBuilder sortBuilder, String field, String order) throws Exception {
  //see https://github.com/elastic/elasticsearch/issues/20853 as to why i can't do something simple like
  //assertThat(sortBuilders.get(0).toString(), is("somejson"));
  XContentBuilder xContentBuilder = mock(XContentBuilder.class);
  sortBuilder.toXContent(xContentBuilder, ToXContent.EMPTY_PARAMS);
  verify(xContentBuilder).startObject(field);
  verify(xContentBuilder).field("order", order);
  verify(xContentBuilder).endObject();
  verifyNoMoreInteractions(xContentBuilder);
}
 
Example #26
Source File: SearchShardsRequestBuilder.java    From elasticshell with Apache License 2.0 5 votes vote down vote up
@Override
protected XContentBuilder toXContent(ClusterSearchShardsRequest request, ClusterSearchShardsResponse response, XContentBuilder builder) throws IOException {
    builder.startObject();
    builder.field(Fields.OK, true);
    response.toXContent(builder, ToXContent.EMPTY_PARAMS);
    builder.endObject();
    return builder;
}
 
Example #27
Source File: IndexId.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {
    builder.startObject();
    builder.field(NAME, name);
    builder.field(ID, id);
    builder.endObject();
    return builder;
}
 
Example #28
Source File: ContextMapping.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    try {
        return toXContent(JsonXContent.contentBuilder(), ToXContent.EMPTY_PARAMS).string();
    } catch (IOException e) {
        return super.toString();
    }
}
 
Example #29
Source File: SuggestRequestBuilder.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
protected SuggestRequest beforeExecute(SuggestRequest request) {
    try {
        XContentBuilder builder = XContentFactory.contentBuilder(Requests.CONTENT_TYPE);
        suggest.toXContent(builder, ToXContent.EMPTY_PARAMS);
        request.suggest(builder.bytes());
    } catch (IOException e) {
        throw new ElasticsearchException("Unable to build suggestion request", e);
    }
    return request;
}
 
Example #30
Source File: GetIndexRequestRestListener.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
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();
}