Search in sources :

Example 1 with XContentParser

use of org.opensearch.common.xcontent.XContentParser in project OpenSearch by opensearch-project.

the class RequestConverters method bulk.

static Request bulk(BulkRequest bulkRequest) throws IOException {
    Request request = new Request(HttpPost.METHOD_NAME, "/_bulk");
    Params parameters = new Params();
    parameters.withTimeout(bulkRequest.timeout());
    parameters.withRefreshPolicy(bulkRequest.getRefreshPolicy());
    parameters.withPipeline(bulkRequest.pipeline());
    parameters.withRouting(bulkRequest.routing());
    // Bulk API only supports newline delimited JSON or Smile. Before executing
    // the bulk, we need to check that all requests have the same content-type
    // and this content-type is supported by the Bulk API.
    XContentType bulkContentType = null;
    for (int i = 0; i < bulkRequest.numberOfActions(); i++) {
        DocWriteRequest<?> action = bulkRequest.requests().get(i);
        DocWriteRequest.OpType opType = action.opType();
        if (opType == DocWriteRequest.OpType.INDEX || opType == DocWriteRequest.OpType.CREATE) {
            bulkContentType = enforceSameContentType((IndexRequest) action, bulkContentType);
        } else if (opType == DocWriteRequest.OpType.UPDATE) {
            UpdateRequest updateRequest = (UpdateRequest) action;
            if (updateRequest.doc() != null) {
                bulkContentType = enforceSameContentType(updateRequest.doc(), bulkContentType);
            }
            if (updateRequest.upsertRequest() != null) {
                bulkContentType = enforceSameContentType(updateRequest.upsertRequest(), bulkContentType);
            }
        }
    }
    if (bulkContentType == null) {
        bulkContentType = XContentType.JSON;
    }
    final byte separator = bulkContentType.xContent().streamSeparator();
    final ContentType requestContentType = createContentType(bulkContentType);
    ByteArrayOutputStream content = new ByteArrayOutputStream();
    for (DocWriteRequest<?> action : bulkRequest.requests()) {
        DocWriteRequest.OpType opType = action.opType();
        try (XContentBuilder metadata = XContentBuilder.builder(bulkContentType.xContent())) {
            metadata.startObject();
            {
                metadata.startObject(opType.getLowercase());
                if (Strings.hasLength(action.index())) {
                    metadata.field("_index", action.index());
                }
                if (Strings.hasLength(action.id())) {
                    metadata.field("_id", action.id());
                }
                if (Strings.hasLength(action.routing())) {
                    metadata.field("routing", action.routing());
                }
                if (action.version() != Versions.MATCH_ANY) {
                    metadata.field("version", action.version());
                }
                VersionType versionType = action.versionType();
                if (versionType != VersionType.INTERNAL) {
                    if (versionType == VersionType.EXTERNAL) {
                        metadata.field("version_type", "external");
                    } else if (versionType == VersionType.EXTERNAL_GTE) {
                        metadata.field("version_type", "external_gte");
                    }
                }
                if (action.ifSeqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO) {
                    metadata.field("if_seq_no", action.ifSeqNo());
                    metadata.field("if_primary_term", action.ifPrimaryTerm());
                }
                if (opType == DocWriteRequest.OpType.INDEX || opType == DocWriteRequest.OpType.CREATE) {
                    IndexRequest indexRequest = (IndexRequest) action;
                    if (Strings.hasLength(indexRequest.getPipeline())) {
                        metadata.field("pipeline", indexRequest.getPipeline());
                    }
                } else if (opType == DocWriteRequest.OpType.UPDATE) {
                    UpdateRequest updateRequest = (UpdateRequest) action;
                    if (updateRequest.retryOnConflict() > 0) {
                        metadata.field("retry_on_conflict", updateRequest.retryOnConflict());
                    }
                    if (updateRequest.fetchSource() != null) {
                        metadata.field("_source", updateRequest.fetchSource());
                    }
                }
                metadata.endObject();
            }
            metadata.endObject();
            BytesRef metadataSource = BytesReference.bytes(metadata).toBytesRef();
            content.write(metadataSource.bytes, metadataSource.offset, metadataSource.length);
            content.write(separator);
        }
        BytesRef source = null;
        if (opType == DocWriteRequest.OpType.INDEX || opType == DocWriteRequest.OpType.CREATE) {
            IndexRequest indexRequest = (IndexRequest) action;
            BytesReference indexSource = indexRequest.source();
            XContentType indexXContentType = indexRequest.getContentType();
            try (XContentParser parser = XContentHelper.createParser(/*
                         * EMPTY and THROW are fine here because we just call
                         * copyCurrentStructure which doesn't touch the
                         * registry or deprecation.
                         */
            NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, indexSource, indexXContentType)) {
                try (XContentBuilder builder = XContentBuilder.builder(bulkContentType.xContent())) {
                    builder.copyCurrentStructure(parser);
                    source = BytesReference.bytes(builder).toBytesRef();
                }
            }
        } else if (opType == DocWriteRequest.OpType.UPDATE) {
            source = XContentHelper.toXContent((UpdateRequest) action, bulkContentType, false).toBytesRef();
        }
        if (source != null) {
            content.write(source.bytes, source.offset, source.length);
            content.write(separator);
        }
    }
    request.addParameters(parameters.asMap());
    request.setEntity(new NByteArrayEntity(content.toByteArray(), 0, content.size(), requestContentType));
    return request;
}
Also used : BytesReference(org.opensearch.common.bytes.BytesReference) ContentType(org.apache.http.entity.ContentType) XContentType(org.opensearch.common.xcontent.XContentType) UpdateRequest(org.opensearch.action.update.UpdateRequest) BulkRequest(org.opensearch.action.bulk.BulkRequest) WriteRequest(org.opensearch.action.support.WriteRequest) AbstractBulkByScrollRequest(org.opensearch.index.reindex.AbstractBulkByScrollRequest) GetStoredScriptRequest(org.opensearch.action.admin.cluster.storedscripts.GetStoredScriptRequest) AnalyzeRequest(org.opensearch.client.indices.AnalyzeRequest) DeleteRequest(org.opensearch.action.delete.DeleteRequest) CountRequest(org.opensearch.client.core.CountRequest) TermVectorsRequest(org.opensearch.client.core.TermVectorsRequest) FieldCapabilitiesRequest(org.opensearch.action.fieldcaps.FieldCapabilitiesRequest) UpdateRequest(org.opensearch.action.update.UpdateRequest) SearchTemplateRequest(org.opensearch.script.mustache.SearchTemplateRequest) RankEvalRequest(org.opensearch.index.rankeval.RankEvalRequest) GetSourceRequest(org.opensearch.client.core.GetSourceRequest) MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest) DocWriteRequest(org.opensearch.action.DocWriteRequest) SearchScrollRequest(org.opensearch.action.search.SearchScrollRequest) ExplainRequest(org.opensearch.action.explain.ExplainRequest) SearchRequest(org.opensearch.action.search.SearchRequest) DeleteStoredScriptRequest(org.opensearch.action.admin.cluster.storedscripts.DeleteStoredScriptRequest) GetRequest(org.opensearch.action.get.GetRequest) MultiSearchTemplateRequest(org.opensearch.script.mustache.MultiSearchTemplateRequest) PutStoredScriptRequest(org.opensearch.action.admin.cluster.storedscripts.PutStoredScriptRequest) UpdateByQueryRequest(org.opensearch.index.reindex.UpdateByQueryRequest) MultiTermVectorsRequest(org.opensearch.client.core.MultiTermVectorsRequest) ClearScrollRequest(org.opensearch.action.search.ClearScrollRequest) DeleteByQueryRequest(org.opensearch.index.reindex.DeleteByQueryRequest) IndexRequest(org.opensearch.action.index.IndexRequest) ClusterHealthRequest(org.opensearch.action.admin.cluster.health.ClusterHealthRequest) ReindexRequest(org.opensearch.index.reindex.ReindexRequest) MultiGetRequest(org.opensearch.action.get.MultiGetRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IndexRequest(org.opensearch.action.index.IndexRequest) VersionType(org.opensearch.index.VersionType) XContentType(org.opensearch.common.xcontent.XContentType) NByteArrayEntity(org.apache.http.nio.entity.NByteArrayEntity) DocWriteRequest(org.opensearch.action.DocWriteRequest) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) BytesRef(org.apache.lucene.util.BytesRef) XContentParser(org.opensearch.common.xcontent.XContentParser)

Example 2 with XContentParser

use of org.opensearch.common.xcontent.XContentParser in project OpenSearch by opensearch-project.

the class RequestConvertersTests method testUpdate.

public void testUpdate() throws IOException {
    XContentType xContentType = randomFrom(XContentType.values());
    Map<String, String> expectedParams = new HashMap<>();
    String index = randomAlphaOfLengthBetween(3, 10);
    String id = randomAlphaOfLengthBetween(3, 10);
    UpdateRequest updateRequest = new UpdateRequest(index, id);
    updateRequest.detectNoop(randomBoolean());
    if (randomBoolean()) {
        BytesReference source = RandomObjects.randomSource(random(), xContentType);
        updateRequest.doc(new IndexRequest().source(source, xContentType));
        boolean docAsUpsert = randomBoolean();
        updateRequest.docAsUpsert(docAsUpsert);
        if (docAsUpsert) {
            expectedParams.put("doc_as_upsert", "true");
        }
    } else {
        updateRequest.script(mockScript("_value + 1"));
        updateRequest.scriptedUpsert(randomBoolean());
    }
    if (randomBoolean()) {
        BytesReference source = RandomObjects.randomSource(random(), xContentType);
        updateRequest.upsert(new IndexRequest().source(source, xContentType));
    }
    if (randomBoolean()) {
        String routing = randomAlphaOfLengthBetween(3, 10);
        updateRequest.routing(routing);
        expectedParams.put("routing", routing);
    }
    if (randomBoolean()) {
        String timeout = randomTimeValue();
        updateRequest.timeout(timeout);
        expectedParams.put("timeout", timeout);
    } else {
        expectedParams.put("timeout", ReplicationRequest.DEFAULT_TIMEOUT.getStringRep());
    }
    if (randomBoolean()) {
        WriteRequest.RefreshPolicy refreshPolicy = randomFrom(WriteRequest.RefreshPolicy.values());
        updateRequest.setRefreshPolicy(refreshPolicy);
        if (refreshPolicy != WriteRequest.RefreshPolicy.NONE) {
            expectedParams.put("refresh", refreshPolicy.getValue());
        }
    }
    setRandomWaitForActiveShards(updateRequest::waitForActiveShards, expectedParams);
    // if* params are passed in the body
    setRandomIfSeqNoAndTerm(updateRequest, new HashMap<>());
    if (randomBoolean()) {
        int retryOnConflict = randomIntBetween(0, 5);
        updateRequest.retryOnConflict(retryOnConflict);
        if (retryOnConflict > 0) {
            expectedParams.put("retry_on_conflict", String.valueOf(retryOnConflict));
        }
    }
    if (randomBoolean()) {
        randomizeFetchSourceContextParams(updateRequest::fetchSource, expectedParams);
    }
    Request request = RequestConverters.update(updateRequest);
    assertEquals("/" + index + "/_update/" + id, request.getEndpoint());
    assertEquals(expectedParams, request.getParameters());
    assertEquals(HttpPost.METHOD_NAME, request.getMethod());
    HttpEntity entity = request.getEntity();
    assertTrue(entity instanceof NByteArrayEntity);
    UpdateRequest parsedUpdateRequest = new UpdateRequest();
    XContentType entityContentType = XContentType.fromMediaTypeOrFormat(entity.getContentType().getValue());
    try (XContentParser parser = createParser(entityContentType.xContent(), entity.getContent())) {
        parsedUpdateRequest.fromXContent(parser);
    }
    assertEquals(updateRequest.scriptedUpsert(), parsedUpdateRequest.scriptedUpsert());
    assertEquals(updateRequest.docAsUpsert(), parsedUpdateRequest.docAsUpsert());
    assertEquals(updateRequest.detectNoop(), parsedUpdateRequest.detectNoop());
    assertEquals(updateRequest.fetchSource(), parsedUpdateRequest.fetchSource());
    assertIfSeqNoAndTerm(updateRequest, parsedUpdateRequest);
    assertEquals(updateRequest.script(), parsedUpdateRequest.script());
    if (updateRequest.doc() != null) {
        assertToXContentEquivalent(updateRequest.doc().source(), parsedUpdateRequest.doc().source(), xContentType);
    } else {
        assertNull(parsedUpdateRequest.doc());
    }
    if (updateRequest.upsertRequest() != null) {
        assertToXContentEquivalent(updateRequest.upsertRequest().source(), parsedUpdateRequest.upsertRequest().source(), xContentType);
    } else {
        assertNull(parsedUpdateRequest.upsertRequest());
    }
}
Also used : BytesReference(org.opensearch.common.bytes.BytesReference) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) UpdateRequest(org.opensearch.action.update.UpdateRequest) WriteRequest(org.opensearch.action.support.WriteRequest) DocWriteRequest(org.opensearch.action.DocWriteRequest) RandomSearchRequestGenerator.randomSearchRequest(org.opensearch.search.RandomSearchRequestGenerator.randomSearchRequest) MasterNodeRequest(org.opensearch.action.support.master.MasterNodeRequest) WriteRequest(org.opensearch.action.support.WriteRequest) AbstractBulkByScrollRequest(org.opensearch.index.reindex.AbstractBulkByScrollRequest) RatedRequest(org.opensearch.index.rankeval.RatedRequest) DeleteRequest(org.opensearch.action.delete.DeleteRequest) TermVectorsRequest(org.opensearch.client.core.TermVectorsRequest) AcknowledgedRequest(org.opensearch.action.support.master.AcknowledgedRequest) FieldCapabilitiesRequest(org.opensearch.action.fieldcaps.FieldCapabilitiesRequest) UpdateRequest(org.opensearch.action.update.UpdateRequest) GetSourceRequest(org.opensearch.client.core.GetSourceRequest) MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest) DocWriteRequest(org.opensearch.action.DocWriteRequest) SearchScrollRequest(org.opensearch.action.search.SearchScrollRequest) ExplainRequest(org.opensearch.action.explain.ExplainRequest) SearchRequest(org.opensearch.action.search.SearchRequest) PutStoredScriptRequest(org.opensearch.action.admin.cluster.storedscripts.PutStoredScriptRequest) DeleteByQueryRequest(org.opensearch.index.reindex.DeleteByQueryRequest) MultiGetRequest(org.opensearch.action.get.MultiGetRequest) BulkRequest(org.opensearch.action.bulk.BulkRequest) GetStoredScriptRequest(org.opensearch.action.admin.cluster.storedscripts.GetStoredScriptRequest) ReplicationRequest(org.opensearch.action.support.replication.ReplicationRequest) AnalyzeRequest(org.opensearch.client.indices.AnalyzeRequest) CountRequest(org.opensearch.client.core.CountRequest) BulkShardRequest(org.opensearch.action.bulk.BulkShardRequest) SearchTemplateRequest(org.opensearch.script.mustache.SearchTemplateRequest) RankEvalRequest(org.opensearch.index.rankeval.RankEvalRequest) DeleteStoredScriptRequest(org.opensearch.action.admin.cluster.storedscripts.DeleteStoredScriptRequest) GetRequest(org.opensearch.action.get.GetRequest) MultiSearchTemplateRequest(org.opensearch.script.mustache.MultiSearchTemplateRequest) UpdateByQueryRequest(org.opensearch.index.reindex.UpdateByQueryRequest) MultiTermVectorsRequest(org.opensearch.client.core.MultiTermVectorsRequest) ClearScrollRequest(org.opensearch.action.search.ClearScrollRequest) IndexRequest(org.opensearch.action.index.IndexRequest) ReindexRequest(org.opensearch.index.reindex.ReindexRequest) IndexRequest(org.opensearch.action.index.IndexRequest) XContentType(org.opensearch.common.xcontent.XContentType) NByteArrayEntity(org.apache.http.nio.entity.NByteArrayEntity) XContentParser(org.opensearch.common.xcontent.XContentParser)

Example 3 with XContentParser

use of org.opensearch.common.xcontent.XContentParser in project OpenSearch by opensearch-project.

the class RequestConvertersTests method testMultiSearch.

public void testMultiSearch() throws IOException {
    int numberOfSearchRequests = randomIntBetween(0, 32);
    MultiSearchRequest multiSearchRequest = new MultiSearchRequest();
    for (int i = 0; i < numberOfSearchRequests; i++) {
        SearchRequest searchRequest = randomSearchRequest(() -> {
            // No need to return a very complex SearchSourceBuilder here, that is tested
            // elsewhere
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.from(randomInt(10));
            searchSourceBuilder.size(randomIntBetween(20, 100));
            return searchSourceBuilder;
        });
        // scroll is not supported in the current msearch api, so unset it:
        searchRequest.scroll((Scroll) null);
        // only expand_wildcards, ignore_unavailable and allow_no_indices can be
        // specified from msearch api, so unset other options:
        IndicesOptions randomlyGenerated = searchRequest.indicesOptions();
        IndicesOptions msearchDefault = new MultiSearchRequest().indicesOptions();
        searchRequest.indicesOptions(IndicesOptions.fromOptions(randomlyGenerated.ignoreUnavailable(), randomlyGenerated.allowNoIndices(), randomlyGenerated.expandWildcardsOpen(), randomlyGenerated.expandWildcardsClosed(), msearchDefault.expandWildcardsHidden(), msearchDefault.allowAliasesToMultipleIndices(), msearchDefault.forbidClosedIndices(), msearchDefault.ignoreAliases(), msearchDefault.ignoreThrottled()));
        multiSearchRequest.add(searchRequest);
    }
    Map<String, String> expectedParams = new HashMap<>();
    expectedParams.put(RestSearchAction.TYPED_KEYS_PARAM, "true");
    if (randomBoolean()) {
        multiSearchRequest.maxConcurrentSearchRequests(randomIntBetween(1, 8));
        expectedParams.put("max_concurrent_searches", Integer.toString(multiSearchRequest.maxConcurrentSearchRequests()));
    }
    Request request = RequestConverters.multiSearch(multiSearchRequest);
    assertEquals("/_msearch", request.getEndpoint());
    assertEquals(HttpPost.METHOD_NAME, request.getMethod());
    assertEquals(expectedParams, request.getParameters());
    List<SearchRequest> requests = new ArrayList<>();
    CheckedBiConsumer<SearchRequest, XContentParser, IOException> consumer = (searchRequest, p) -> {
        SearchSourceBuilder searchSourceBuilder = SearchSourceBuilder.fromXContent(p, false);
        if (searchSourceBuilder.equals(new SearchSourceBuilder()) == false) {
            searchRequest.source(searchSourceBuilder);
        }
        requests.add(searchRequest);
    };
    MultiSearchRequest.readMultiLineFormat(new BytesArray(EntityUtils.toByteArray(request.getEntity())), REQUEST_BODY_CONTENT_TYPE.xContent(), consumer, null, multiSearchRequest.indicesOptions(), null, null, null, xContentRegistry(), true, deprecationLogger);
    assertEquals(requests, multiSearchRequest.requests());
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) Arrays(java.util.Arrays) NByteArrayEntity(org.apache.http.nio.entity.NByteArrayEntity) Strings(org.opensearch.common.Strings) ScriptType(org.opensearch.script.ScriptType) RandomSearchRequestGenerator.randomSearchRequest(org.opensearch.search.RandomSearchRequestGenerator.randomSearchRequest) MasterNodeRequest(org.opensearch.action.support.master.MasterNodeRequest) WriteRequest(org.opensearch.action.support.WriteRequest) AbstractBulkByScrollRequest(org.opensearch.index.reindex.AbstractBulkByScrollRequest) RatedRequest(org.opensearch.index.rankeval.RatedRequest) Map(java.util.Map) Matchers.nullValue(org.hamcrest.Matchers.nullValue) DeleteRequest(org.opensearch.action.delete.DeleteRequest) ValueType(org.opensearch.search.aggregations.support.ValueType) TermVectorsRequest(org.opensearch.client.core.TermVectorsRequest) TimeValue(org.opensearch.common.unit.TimeValue) PrecisionAtK(org.opensearch.index.rankeval.PrecisionAtK) AcknowledgedRequest(org.opensearch.action.support.master.AcknowledgedRequest) FieldCapabilitiesRequest(org.opensearch.action.fieldcaps.FieldCapabilitiesRequest) VersionType(org.opensearch.index.VersionType) SuggestBuilder(org.opensearch.search.suggest.SuggestBuilder) BytesArray(org.opensearch.common.bytes.BytesArray) CollapseBuilder(org.opensearch.search.collapse.CollapseBuilder) UpdateRequest(org.opensearch.action.update.UpdateRequest) XContentType(org.opensearch.common.xcontent.XContentType) OpenSearchAssertions.assertToXContentEquivalent(org.opensearch.test.hamcrest.OpenSearchAssertions.assertToXContentEquivalent) GetSourceRequest(org.opensearch.client.core.GetSourceRequest) HttpHead(org.apache.http.client.methods.HttpHead) MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) DocWriteRequest(org.opensearch.action.DocWriteRequest) RemoteInfo(org.opensearch.index.reindex.RemoteInfo) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) RestSearchAction(org.opensearch.rest.action.search.RestSearchAction) SearchScrollRequest(org.opensearch.action.search.SearchScrollRequest) Streams(org.opensearch.common.io.Streams) ExplainRequest(org.opensearch.action.explain.ExplainRequest) SearchRequest(org.opensearch.action.search.SearchRequest) QueryBuilders(org.opensearch.index.query.QueryBuilders) Versions(org.opensearch.common.lucene.uid.Versions) QueryRescorerBuilder(org.opensearch.search.rescore.QueryRescorerBuilder) SearchType(org.opensearch.action.search.SearchType) TaskId(org.opensearch.tasks.TaskId) IOException(java.io.IOException) PutStoredScriptRequest(org.opensearch.action.admin.cluster.storedscripts.PutStoredScriptRequest) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) XContentHelper(org.opensearch.common.xcontent.XContentHelper) RankEvalSpec(org.opensearch.index.rankeval.RankEvalSpec) EndpointBuilder(org.opensearch.client.RequestConverters.EndpointBuilder) RestRankEvalAction(org.opensearch.index.rankeval.RestRankEvalAction) DeleteByQueryRequest(org.opensearch.index.reindex.DeleteByQueryRequest) RequestConverters.enforceSameContentType(org.opensearch.client.RequestConverters.enforceSameContentType) CompletionSuggestionBuilder(org.opensearch.search.suggest.completion.CompletionSuggestionBuilder) MultiGetRequest(org.opensearch.action.get.MultiGetRequest) ToXContent(org.opensearch.common.xcontent.ToXContent) BiFunction(java.util.function.BiFunction) BulkRequest(org.opensearch.action.bulk.BulkRequest) Matchers.hasKey(org.hamcrest.Matchers.hasKey) EntityUtils(org.apache.http.util.EntityUtils) XContentParser(org.opensearch.common.xcontent.XContentParser) MapperService(org.opensearch.index.mapper.MapperService) QueryBuilders.matchAllQuery(org.opensearch.index.query.QueryBuilders.matchAllQuery) Locale(java.util.Locale) GetStoredScriptRequest(org.opensearch.action.admin.cluster.storedscripts.GetStoredScriptRequest) ReplicationRequest(org.opensearch.action.support.replication.ReplicationRequest) AnalyzeRequest(org.opensearch.client.indices.AnalyzeRequest) Scroll(org.opensearch.search.Scroll) RandomObjects(org.opensearch.test.RandomObjects) CountRequest(org.opensearch.client.core.CountRequest) BulkShardRequest(org.opensearch.action.bulk.BulkShardRequest) Script(org.opensearch.script.Script) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) HttpEntity(org.apache.http.HttpEntity) Tuple(org.opensearch.common.collect.Tuple) List(java.util.List) HttpGet(org.apache.http.client.methods.HttpGet) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) SearchTemplateRequest(org.opensearch.script.mustache.SearchTemplateRequest) RankEvalRequest(org.opensearch.index.rankeval.RankEvalRequest) BytesReference(org.opensearch.common.bytes.BytesReference) CheckedBiConsumer(org.opensearch.common.CheckedBiConsumer) HighlightBuilder(org.opensearch.search.fetch.subphase.highlight.HighlightBuilder) HashMap(java.util.HashMap) IndicesOptions(org.opensearch.action.support.IndicesOptions) Function(java.util.function.Function) REQUEST_BODY_CONTENT_TYPE(org.opensearch.client.RequestConverters.REQUEST_BODY_CONTENT_TYPE) DeprecationLogger(org.opensearch.common.logging.DeprecationLogger) HashSet(java.util.HashSet) HttpDelete(org.apache.http.client.methods.HttpDelete) Collections.singletonMap(java.util.Collections.singletonMap) Matchers.hasEntry(org.hamcrest.Matchers.hasEntry) DeleteStoredScriptRequest(org.opensearch.action.admin.cluster.storedscripts.DeleteStoredScriptRequest) Collections.emptyMap(java.util.Collections.emptyMap) GetRequest(org.opensearch.action.get.GetRequest) MultiSearchTemplateRequest(org.opensearch.script.mustache.MultiSearchTemplateRequest) TermQueryBuilder(org.opensearch.index.query.TermQueryBuilder) Matchers(org.hamcrest.Matchers) ActiveShardCount(org.opensearch.action.support.ActiveShardCount) Consumer(java.util.function.Consumer) UpdateByQueryRequest(org.opensearch.index.reindex.UpdateByQueryRequest) HttpPut(org.apache.http.client.methods.HttpPut) MultiTermVectorsRequest(org.opensearch.client.core.MultiTermVectorsRequest) TermsAggregationBuilder(org.opensearch.search.aggregations.bucket.terms.TermsAggregationBuilder) ClearScrollRequest(org.opensearch.action.search.ClearScrollRequest) StringJoiner(java.util.StringJoiner) JsonXContent(org.opensearch.common.xcontent.json.JsonXContent) IndexRequest(org.opensearch.action.index.IndexRequest) MatchAllQueryBuilder(org.opensearch.index.query.MatchAllQueryBuilder) ReindexRequest(org.opensearch.index.reindex.ReindexRequest) Collections(java.util.Collections) FetchSourceContext(org.opensearch.search.fetch.subphase.FetchSourceContext) InputStream(java.io.InputStream) RandomSearchRequestGenerator.randomSearchRequest(org.opensearch.search.RandomSearchRequestGenerator.randomSearchRequest) MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest) SearchRequest(org.opensearch.action.search.SearchRequest) BytesArray(org.opensearch.common.bytes.BytesArray) HashMap(java.util.HashMap) RandomSearchRequestGenerator.randomSearchRequest(org.opensearch.search.RandomSearchRequestGenerator.randomSearchRequest) MasterNodeRequest(org.opensearch.action.support.master.MasterNodeRequest) WriteRequest(org.opensearch.action.support.WriteRequest) AbstractBulkByScrollRequest(org.opensearch.index.reindex.AbstractBulkByScrollRequest) RatedRequest(org.opensearch.index.rankeval.RatedRequest) DeleteRequest(org.opensearch.action.delete.DeleteRequest) TermVectorsRequest(org.opensearch.client.core.TermVectorsRequest) AcknowledgedRequest(org.opensearch.action.support.master.AcknowledgedRequest) FieldCapabilitiesRequest(org.opensearch.action.fieldcaps.FieldCapabilitiesRequest) UpdateRequest(org.opensearch.action.update.UpdateRequest) GetSourceRequest(org.opensearch.client.core.GetSourceRequest) MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest) DocWriteRequest(org.opensearch.action.DocWriteRequest) SearchScrollRequest(org.opensearch.action.search.SearchScrollRequest) ExplainRequest(org.opensearch.action.explain.ExplainRequest) SearchRequest(org.opensearch.action.search.SearchRequest) PutStoredScriptRequest(org.opensearch.action.admin.cluster.storedscripts.PutStoredScriptRequest) DeleteByQueryRequest(org.opensearch.index.reindex.DeleteByQueryRequest) MultiGetRequest(org.opensearch.action.get.MultiGetRequest) BulkRequest(org.opensearch.action.bulk.BulkRequest) GetStoredScriptRequest(org.opensearch.action.admin.cluster.storedscripts.GetStoredScriptRequest) ReplicationRequest(org.opensearch.action.support.replication.ReplicationRequest) AnalyzeRequest(org.opensearch.client.indices.AnalyzeRequest) CountRequest(org.opensearch.client.core.CountRequest) BulkShardRequest(org.opensearch.action.bulk.BulkShardRequest) SearchTemplateRequest(org.opensearch.script.mustache.SearchTemplateRequest) RankEvalRequest(org.opensearch.index.rankeval.RankEvalRequest) DeleteStoredScriptRequest(org.opensearch.action.admin.cluster.storedscripts.DeleteStoredScriptRequest) GetRequest(org.opensearch.action.get.GetRequest) MultiSearchTemplateRequest(org.opensearch.script.mustache.MultiSearchTemplateRequest) UpdateByQueryRequest(org.opensearch.index.reindex.UpdateByQueryRequest) MultiTermVectorsRequest(org.opensearch.client.core.MultiTermVectorsRequest) ClearScrollRequest(org.opensearch.action.search.ClearScrollRequest) IndexRequest(org.opensearch.action.index.IndexRequest) ReindexRequest(org.opensearch.index.reindex.ReindexRequest) ArrayList(java.util.ArrayList) IOException(java.io.IOException) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest) IndicesOptions(org.opensearch.action.support.IndicesOptions) XContentParser(org.opensearch.common.xcontent.XContentParser)

Example 4 with XContentParser

use of org.opensearch.common.xcontent.XContentParser in project OpenSearch by opensearch-project.

the class GetAliasesResponseTests method testFromXContentWithOpenSearchException.

public void testFromXContentWithOpenSearchException() throws IOException {
    String xContent = "{" + "  \"error\": {" + "    \"root_cause\": [" + "      {" + "        \"type\": \"index_not_found_exception\"," + "        \"reason\": \"no such index [index]\"," + "        \"resource.type\": \"index_or_alias\"," + "        \"resource.id\": \"index\"," + "        \"index_uuid\": \"_na_\"," + "        \"index\": \"index\"" + "      }" + "    ]," + "    \"type\": \"index_not_found_exception\"," + "    \"reason\": \"no such index [index]\"," + "    \"resource.type\": \"index_or_alias\"," + "    \"resource.id\": \"index\"," + "    \"index_uuid\": \"_na_\"," + "    \"index\": \"index\"" + "  }," + "  \"status\": 404" + "}";
    try (XContentParser parser = createParser(JsonXContent.jsonXContent, xContent)) {
        GetAliasesResponse getAliasesResponse = GetAliasesResponse.fromXContent(parser);
        assertThat(getAliasesResponse.getError(), nullValue());
        assertThat(getAliasesResponse.status(), equalTo(RestStatus.NOT_FOUND));
        assertThat(getAliasesResponse.getException().getMessage(), equalTo("OpenSearch exception [type=index_not_found_exception, reason=no such index [index]]"));
    }
}
Also used : XContentParser(org.opensearch.common.xcontent.XContentParser)

Example 5 with XContentParser

use of org.opensearch.common.xcontent.XContentParser in project OpenSearch by opensearch-project.

the class GetAliasesResponseTests method testFromXContentWithMissingAndFoundAlias.

public void testFromXContentWithMissingAndFoundAlias() throws IOException {
    String xContent = "{" + "  \"error\": \"alias [something] missing\"," + "  \"status\": 404," + "  \"index\": {" + "    \"aliases\": {" + "      \"alias\": {}" + "    }" + "  }" + "}";
    final String index = "index";
    try (XContentParser parser = createParser(JsonXContent.jsonXContent, xContent)) {
        GetAliasesResponse response = GetAliasesResponse.fromXContent(parser);
        assertThat(response.status(), equalTo(RestStatus.NOT_FOUND));
        assertThat(response.getError(), equalTo("alias [something] missing"));
        assertThat(response.getAliases().size(), equalTo(1));
        assertThat(response.getAliases().get(index).size(), equalTo(1));
        AliasMetadata aliasMetadata = response.getAliases().get(index).iterator().next();
        assertThat(aliasMetadata.alias(), equalTo("alias"));
        assertThat(response.getException(), nullValue());
    }
}
Also used : AliasMetadata(org.opensearch.cluster.metadata.AliasMetadata) XContentParser(org.opensearch.common.xcontent.XContentParser)

Aggregations

XContentParser (org.opensearch.common.xcontent.XContentParser)602 XContentBuilder (org.opensearch.common.xcontent.XContentBuilder)222 ParsingException (org.opensearch.common.ParsingException)105 BytesReference (org.opensearch.common.bytes.BytesReference)104 IOException (java.io.IOException)97 XContentType (org.opensearch.common.xcontent.XContentType)88 ArrayList (java.util.ArrayList)73 OpenSearchParseException (org.opensearch.OpenSearchParseException)55 Matchers.containsString (org.hamcrest.Matchers.containsString)51 List (java.util.List)43 XContentParseException (org.opensearch.common.xcontent.XContentParseException)40 HashMap (java.util.HashMap)38 ToXContent (org.opensearch.common.xcontent.ToXContent)38 Map (java.util.Map)32 BytesArray (org.opensearch.common.bytes.BytesArray)26 ShardId (org.opensearch.index.shard.ShardId)25 XContent (org.opensearch.common.xcontent.XContent)19 NamedXContentRegistry (org.opensearch.common.xcontent.NamedXContentRegistry)16 CategoryContextMapping (org.opensearch.search.suggest.completion.context.CategoryContextMapping)16 Collections (java.util.Collections)15