Search in sources :

Example 1 with RestStatus

use of org.opensearch.rest.RestStatus in project OpenSearch by opensearch-project.

the class RestHighLevelClient method parseResponseException.

/**
 * Converts a {@link ResponseException} obtained from the low level REST client into an {@link OpenSearchException}.
 * If a response body was returned, tries to parse it as an error returned from OpenSearch.
 * If no response body was returned or anything goes wrong while parsing the error, returns a new {@link OpenSearchStatusException}
 * that wraps the original {@link ResponseException}. The potential exception obtained while parsing is added to the returned
 * exception as a suppressed exception. This method is guaranteed to not throw any exception eventually thrown while parsing.
 */
protected final OpenSearchStatusException parseResponseException(ResponseException responseException) {
    Response response = responseException.getResponse();
    HttpEntity entity = response.getEntity();
    OpenSearchStatusException opensearchException;
    RestStatus restStatus = RestStatus.fromCode(response.getStatusLine().getStatusCode());
    if (entity == null) {
        opensearchException = new OpenSearchStatusException(responseException.getMessage(), restStatus, responseException);
    } else {
        try {
            opensearchException = parseEntity(entity, BytesRestResponse::errorFromXContent);
            opensearchException.addSuppressed(responseException);
        } catch (Exception e) {
            opensearchException = new OpenSearchStatusException("Unable to parse response body", restStatus, responseException);
            opensearchException.addSuppressed(e);
        }
    }
    return opensearchException;
}
Also used : MainResponse(org.opensearch.client.core.MainResponse) IndexResponse(org.opensearch.action.index.IndexResponse) MultiTermVectorsResponse(org.opensearch.client.core.MultiTermVectorsResponse) RankEvalResponse(org.opensearch.index.rankeval.RankEvalResponse) BytesRestResponse(org.opensearch.rest.BytesRestResponse) MultiSearchResponse(org.opensearch.action.search.MultiSearchResponse) UpdateResponse(org.opensearch.action.update.UpdateResponse) FieldCapabilitiesResponse(org.opensearch.action.fieldcaps.FieldCapabilitiesResponse) TermVectorsResponse(org.opensearch.client.core.TermVectorsResponse) DeleteResponse(org.opensearch.action.delete.DeleteResponse) SearchTemplateResponse(org.opensearch.script.mustache.SearchTemplateResponse) MultiSearchTemplateResponse(org.opensearch.script.mustache.MultiSearchTemplateResponse) MultiGetResponse(org.opensearch.action.get.MultiGetResponse) TaskSubmissionResponse(org.opensearch.client.tasks.TaskSubmissionResponse) GetResponse(org.opensearch.action.get.GetResponse) CountResponse(org.opensearch.client.core.CountResponse) GetStoredScriptResponse(org.opensearch.action.admin.cluster.storedscripts.GetStoredScriptResponse) GetSourceResponse(org.opensearch.client.core.GetSourceResponse) ListTasksResponse(org.opensearch.action.admin.cluster.node.tasks.list.ListTasksResponse) ClearScrollResponse(org.opensearch.action.search.ClearScrollResponse) SearchResponse(org.opensearch.action.search.SearchResponse) ExplainResponse(org.opensearch.action.explain.ExplainResponse) AcknowledgedResponse(org.opensearch.action.support.master.AcknowledgedResponse) BulkByScrollResponse(org.opensearch.index.reindex.BulkByScrollResponse) BulkResponse(org.opensearch.action.bulk.BulkResponse) HttpEntity(org.apache.http.HttpEntity) RestStatus(org.opensearch.rest.RestStatus) IOException(java.io.IOException) OpenSearchStatusException(org.opensearch.OpenSearchStatusException) OpenSearchException(org.opensearch.OpenSearchException) ActionRequestValidationException(org.opensearch.action.ActionRequestValidationException) OpenSearchStatusException(org.opensearch.OpenSearchStatusException)

Example 2 with RestStatus

use of org.opensearch.rest.RestStatus in project OpenSearch by opensearch-project.

the class RestHighLevelClientTests method testPerformRequestOnResponseExceptionWithEntity.

public void testPerformRequestOnResponseExceptionWithEntity() throws IOException {
    MainRequest mainRequest = new MainRequest();
    CheckedFunction<MainRequest, Request, IOException> requestConverter = request -> new Request(HttpGet.METHOD_NAME, "/");
    RestStatus restStatus = randomFrom(RestStatus.values());
    HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus));
    httpResponse.setEntity(new NStringEntity("{\"error\":\"test error message\",\"status\":" + restStatus.getStatus() + "}", ContentType.APPLICATION_JSON));
    Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
    ResponseException responseException = new ResponseException(mockResponse);
    when(restClient.performRequest(any(Request.class))).thenThrow(responseException);
    OpenSearchException openSearchException = expectThrows(OpenSearchException.class, () -> restHighLevelClient.performRequest(mainRequest, requestConverter, RequestOptions.DEFAULT, response -> response.getStatusLine().getStatusCode(), Collections.emptySet()));
    assertEquals("OpenSearch exception [type=exception, reason=test error message]", openSearchException.getMessage());
    assertEquals(restStatus, openSearchException.status());
    assertSame(responseException, openSearchException.getSuppressed()[0]);
}
Also used : InternalAggregationTestCase(org.opensearch.test.InternalAggregationTestCase) Arrays(java.util.Arrays) Aggregation(org.opensearch.search.aggregations.Aggregation) MainResponse(org.opensearch.client.core.MainResponse) ToXContentFragment(org.opensearch.common.xcontent.ToXContentFragment) CheckedFunction(org.opensearch.common.CheckedFunction) ToXContent(org.opensearch.common.xcontent.ToXContent) CoreMatchers.endsWith(org.hamcrest.CoreMatchers.endsWith) ChildrenAggregationBuilder(org.opensearch.join.aggregations.ChildrenAggregationBuilder) ActionRequest(org.opensearch.action.ActionRequest) OpenSearchException(org.opensearch.OpenSearchException) StatusLine(org.apache.http.StatusLine) NByteArrayEntity(org.apache.http.nio.entity.NByteArrayEntity) XContentParser(org.opensearch.common.xcontent.XContentParser) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) EvaluationMetric(org.opensearch.index.rankeval.EvaluationMetric) RequestLine(org.apache.http.RequestLine) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) InternalAggregations(org.opensearch.search.aggregations.InternalAggregations) Map(java.util.Map) NStringEntity(org.apache.http.nio.entity.NStringEntity) ActionListener(org.opensearch.action.ActionListener) JsonParseException(com.fasterxml.jackson.core.JsonParseException) Method(java.lang.reflect.Method) PrecisionAtK(org.opensearch.index.rankeval.PrecisionAtK) ClientYamlSuiteRestSpec(org.opensearch.test.rest.yaml.restspec.ClientYamlSuiteRestSpec) MetricDetail(org.opensearch.index.rankeval.MetricDetail) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) HttpEntity(org.apache.http.HttpEntity) ContentType(org.apache.http.entity.ContentType) Set(java.util.Set) RestStatus(org.opensearch.rest.RestStatus) Collectors(java.util.stream.Collectors) Tuple(org.opensearch.common.collect.Tuple) RecallAtK(org.opensearch.index.rankeval.RecallAtK) List(java.util.List) Stream(java.util.stream.Stream) HttpGet(org.apache.http.client.methods.HttpGet) Modifier(java.lang.reflect.Modifier) Optional(java.util.Optional) MeanReciprocalRank(org.opensearch.index.rankeval.MeanReciprocalRank) Mockito.any(org.mockito.Mockito.any) SmileXContent(org.opensearch.common.xcontent.smile.SmileXContent) Mockito.mock(org.mockito.Mockito.mock) BytesReference(org.opensearch.common.bytes.BytesReference) BasicStatusLine(org.apache.http.message.BasicStatusLine) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) CborXContent(org.opensearch.common.xcontent.cbor.CborXContent) ExpectedReciprocalRank(org.opensearch.index.rankeval.ExpectedReciprocalRank) HashMap(java.util.HashMap) SearchHits(org.opensearch.search.SearchHits) AtomicReference(java.util.concurrent.atomic.AtomicReference) ActionRequestValidationException(org.opensearch.action.ActionRequestValidationException) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) XContentHelper.toXContent(org.opensearch.common.xcontent.XContentHelper.toXContent) SearchScrollRequest(org.opensearch.action.search.SearchScrollRequest) SocketTimeoutException(java.net.SocketTimeoutException) ClearScrollResponse(org.opensearch.action.search.ClearScrollResponse) SearchResponse(org.opensearch.action.search.SearchResponse) ClientYamlSuiteRestApi(org.opensearch.test.rest.yaml.restspec.ClientYamlSuiteRestApi) MainRequest(org.opensearch.client.core.MainRequest) Before(org.junit.Before) MatrixStatsAggregationBuilder(org.opensearch.search.aggregations.matrix.stats.MatrixStatsAggregationBuilder) BasicRequestLine(org.apache.http.message.BasicRequestLine) Matchers(org.hamcrest.Matchers) IOException(java.io.IOException) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) DiscountedCumulativeGain(org.opensearch.index.rankeval.DiscountedCumulativeGain) ProtocolVersion(org.apache.http.ProtocolVersion) Sets(org.opensearch.common.util.set.Sets) SearchResponseSections(org.opensearch.action.search.SearchResponseSections) Suggest(org.opensearch.search.suggest.Suggest) ClearScrollRequest(org.opensearch.action.search.ClearScrollRequest) ShardSearchFailure(org.opensearch.action.search.ShardSearchFailure) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) HttpResponse(org.apache.http.HttpResponse) HttpHost(org.apache.http.HttpHost) Collections(java.util.Collections) MainRequest(org.opensearch.client.core.MainRequest) ActionRequest(org.opensearch.action.ActionRequest) SearchScrollRequest(org.opensearch.action.search.SearchScrollRequest) MainRequest(org.opensearch.client.core.MainRequest) ClearScrollRequest(org.opensearch.action.search.ClearScrollRequest) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) MainResponse(org.opensearch.client.core.MainResponse) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) ClearScrollResponse(org.opensearch.action.search.ClearScrollResponse) SearchResponse(org.opensearch.action.search.SearchResponse) HttpResponse(org.apache.http.HttpResponse) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) NStringEntity(org.apache.http.nio.entity.NStringEntity) RestStatus(org.opensearch.rest.RestStatus) HttpHost(org.apache.http.HttpHost) OpenSearchException(org.opensearch.OpenSearchException)

Example 3 with RestStatus

use of org.opensearch.rest.RestStatus in project OpenSearch by opensearch-project.

the class RestHighLevelClientTests method testPerformRequestOnResponseExceptionWithBrokenEntity.

public void testPerformRequestOnResponseExceptionWithBrokenEntity() throws IOException {
    MainRequest mainRequest = new MainRequest();
    CheckedFunction<MainRequest, Request, IOException> requestConverter = request -> new Request(HttpGet.METHOD_NAME, "/");
    RestStatus restStatus = randomFrom(RestStatus.values());
    HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus));
    httpResponse.setEntity(new NStringEntity("{\"error\":", ContentType.APPLICATION_JSON));
    Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
    ResponseException responseException = new ResponseException(mockResponse);
    when(restClient.performRequest(any(Request.class))).thenThrow(responseException);
    OpenSearchException openSearchException = expectThrows(OpenSearchException.class, () -> restHighLevelClient.performRequest(mainRequest, requestConverter, RequestOptions.DEFAULT, response -> response.getStatusLine().getStatusCode(), Collections.emptySet()));
    assertEquals("Unable to parse response body", openSearchException.getMessage());
    assertEquals(restStatus, openSearchException.status());
    assertSame(responseException, openSearchException.getCause());
    assertThat(openSearchException.getSuppressed()[0], instanceOf(JsonParseException.class));
}
Also used : InternalAggregationTestCase(org.opensearch.test.InternalAggregationTestCase) Arrays(java.util.Arrays) Aggregation(org.opensearch.search.aggregations.Aggregation) MainResponse(org.opensearch.client.core.MainResponse) ToXContentFragment(org.opensearch.common.xcontent.ToXContentFragment) CheckedFunction(org.opensearch.common.CheckedFunction) ToXContent(org.opensearch.common.xcontent.ToXContent) CoreMatchers.endsWith(org.hamcrest.CoreMatchers.endsWith) ChildrenAggregationBuilder(org.opensearch.join.aggregations.ChildrenAggregationBuilder) ActionRequest(org.opensearch.action.ActionRequest) OpenSearchException(org.opensearch.OpenSearchException) StatusLine(org.apache.http.StatusLine) NByteArrayEntity(org.apache.http.nio.entity.NByteArrayEntity) XContentParser(org.opensearch.common.xcontent.XContentParser) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) EvaluationMetric(org.opensearch.index.rankeval.EvaluationMetric) RequestLine(org.apache.http.RequestLine) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) InternalAggregations(org.opensearch.search.aggregations.InternalAggregations) Map(java.util.Map) NStringEntity(org.apache.http.nio.entity.NStringEntity) ActionListener(org.opensearch.action.ActionListener) JsonParseException(com.fasterxml.jackson.core.JsonParseException) Method(java.lang.reflect.Method) PrecisionAtK(org.opensearch.index.rankeval.PrecisionAtK) ClientYamlSuiteRestSpec(org.opensearch.test.rest.yaml.restspec.ClientYamlSuiteRestSpec) MetricDetail(org.opensearch.index.rankeval.MetricDetail) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) HttpEntity(org.apache.http.HttpEntity) ContentType(org.apache.http.entity.ContentType) Set(java.util.Set) RestStatus(org.opensearch.rest.RestStatus) Collectors(java.util.stream.Collectors) Tuple(org.opensearch.common.collect.Tuple) RecallAtK(org.opensearch.index.rankeval.RecallAtK) List(java.util.List) Stream(java.util.stream.Stream) HttpGet(org.apache.http.client.methods.HttpGet) Modifier(java.lang.reflect.Modifier) Optional(java.util.Optional) MeanReciprocalRank(org.opensearch.index.rankeval.MeanReciprocalRank) Mockito.any(org.mockito.Mockito.any) SmileXContent(org.opensearch.common.xcontent.smile.SmileXContent) Mockito.mock(org.mockito.Mockito.mock) BytesReference(org.opensearch.common.bytes.BytesReference) BasicStatusLine(org.apache.http.message.BasicStatusLine) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) CborXContent(org.opensearch.common.xcontent.cbor.CborXContent) ExpectedReciprocalRank(org.opensearch.index.rankeval.ExpectedReciprocalRank) HashMap(java.util.HashMap) SearchHits(org.opensearch.search.SearchHits) AtomicReference(java.util.concurrent.atomic.AtomicReference) ActionRequestValidationException(org.opensearch.action.ActionRequestValidationException) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) XContentHelper.toXContent(org.opensearch.common.xcontent.XContentHelper.toXContent) SearchScrollRequest(org.opensearch.action.search.SearchScrollRequest) SocketTimeoutException(java.net.SocketTimeoutException) ClearScrollResponse(org.opensearch.action.search.ClearScrollResponse) SearchResponse(org.opensearch.action.search.SearchResponse) ClientYamlSuiteRestApi(org.opensearch.test.rest.yaml.restspec.ClientYamlSuiteRestApi) MainRequest(org.opensearch.client.core.MainRequest) Before(org.junit.Before) MatrixStatsAggregationBuilder(org.opensearch.search.aggregations.matrix.stats.MatrixStatsAggregationBuilder) BasicRequestLine(org.apache.http.message.BasicRequestLine) Matchers(org.hamcrest.Matchers) IOException(java.io.IOException) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) DiscountedCumulativeGain(org.opensearch.index.rankeval.DiscountedCumulativeGain) ProtocolVersion(org.apache.http.ProtocolVersion) Sets(org.opensearch.common.util.set.Sets) SearchResponseSections(org.opensearch.action.search.SearchResponseSections) Suggest(org.opensearch.search.suggest.Suggest) ClearScrollRequest(org.opensearch.action.search.ClearScrollRequest) ShardSearchFailure(org.opensearch.action.search.ShardSearchFailure) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) HttpResponse(org.apache.http.HttpResponse) HttpHost(org.apache.http.HttpHost) Collections(java.util.Collections) MainRequest(org.opensearch.client.core.MainRequest) ActionRequest(org.opensearch.action.ActionRequest) SearchScrollRequest(org.opensearch.action.search.SearchScrollRequest) MainRequest(org.opensearch.client.core.MainRequest) ClearScrollRequest(org.opensearch.action.search.ClearScrollRequest) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) MainResponse(org.opensearch.client.core.MainResponse) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) ClearScrollResponse(org.opensearch.action.search.ClearScrollResponse) SearchResponse(org.opensearch.action.search.SearchResponse) HttpResponse(org.apache.http.HttpResponse) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) NStringEntity(org.apache.http.nio.entity.NStringEntity) RestStatus(org.opensearch.rest.RestStatus) HttpHost(org.apache.http.HttpHost) OpenSearchException(org.opensearch.OpenSearchException)

Example 4 with RestStatus

use of org.opensearch.rest.RestStatus in project OpenSearch by opensearch-project.

the class RestHighLevelClientTests method testPerformRequestOnSuccess.

public void testPerformRequestOnSuccess() throws IOException {
    MainRequest mainRequest = new MainRequest();
    CheckedFunction<MainRequest, Request, IOException> requestConverter = request -> new Request(HttpGet.METHOD_NAME, "/");
    RestStatus restStatus = randomFrom(RestStatus.values());
    HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus));
    Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
    when(restClient.performRequest(any(Request.class))).thenReturn(mockResponse);
    {
        Integer result = restHighLevelClient.performRequest(mainRequest, requestConverter, RequestOptions.DEFAULT, response -> response.getStatusLine().getStatusCode(), Collections.emptySet());
        assertEquals(restStatus.getStatus(), result.intValue());
    }
    {
        IOException ioe = expectThrows(IOException.class, () -> restHighLevelClient.performRequest(mainRequest, requestConverter, RequestOptions.DEFAULT, response -> {
            throw new IllegalStateException();
        }, Collections.emptySet()));
        assertEquals("Unable to parse response body for Response{requestLine=GET / http/1.1, host=http://localhost:9200, " + "response=http/1.1 " + restStatus.getStatus() + " " + restStatus.name() + "}", ioe.getMessage());
    }
}
Also used : InternalAggregationTestCase(org.opensearch.test.InternalAggregationTestCase) Arrays(java.util.Arrays) Aggregation(org.opensearch.search.aggregations.Aggregation) MainResponse(org.opensearch.client.core.MainResponse) ToXContentFragment(org.opensearch.common.xcontent.ToXContentFragment) CheckedFunction(org.opensearch.common.CheckedFunction) ToXContent(org.opensearch.common.xcontent.ToXContent) CoreMatchers.endsWith(org.hamcrest.CoreMatchers.endsWith) ChildrenAggregationBuilder(org.opensearch.join.aggregations.ChildrenAggregationBuilder) ActionRequest(org.opensearch.action.ActionRequest) OpenSearchException(org.opensearch.OpenSearchException) StatusLine(org.apache.http.StatusLine) NByteArrayEntity(org.apache.http.nio.entity.NByteArrayEntity) XContentParser(org.opensearch.common.xcontent.XContentParser) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) EvaluationMetric(org.opensearch.index.rankeval.EvaluationMetric) RequestLine(org.apache.http.RequestLine) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) InternalAggregations(org.opensearch.search.aggregations.InternalAggregations) Map(java.util.Map) NStringEntity(org.apache.http.nio.entity.NStringEntity) ActionListener(org.opensearch.action.ActionListener) JsonParseException(com.fasterxml.jackson.core.JsonParseException) Method(java.lang.reflect.Method) PrecisionAtK(org.opensearch.index.rankeval.PrecisionAtK) ClientYamlSuiteRestSpec(org.opensearch.test.rest.yaml.restspec.ClientYamlSuiteRestSpec) MetricDetail(org.opensearch.index.rankeval.MetricDetail) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) HttpEntity(org.apache.http.HttpEntity) ContentType(org.apache.http.entity.ContentType) Set(java.util.Set) RestStatus(org.opensearch.rest.RestStatus) Collectors(java.util.stream.Collectors) Tuple(org.opensearch.common.collect.Tuple) RecallAtK(org.opensearch.index.rankeval.RecallAtK) List(java.util.List) Stream(java.util.stream.Stream) HttpGet(org.apache.http.client.methods.HttpGet) Modifier(java.lang.reflect.Modifier) Optional(java.util.Optional) MeanReciprocalRank(org.opensearch.index.rankeval.MeanReciprocalRank) Mockito.any(org.mockito.Mockito.any) SmileXContent(org.opensearch.common.xcontent.smile.SmileXContent) Mockito.mock(org.mockito.Mockito.mock) BytesReference(org.opensearch.common.bytes.BytesReference) BasicStatusLine(org.apache.http.message.BasicStatusLine) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) CborXContent(org.opensearch.common.xcontent.cbor.CborXContent) ExpectedReciprocalRank(org.opensearch.index.rankeval.ExpectedReciprocalRank) HashMap(java.util.HashMap) SearchHits(org.opensearch.search.SearchHits) AtomicReference(java.util.concurrent.atomic.AtomicReference) ActionRequestValidationException(org.opensearch.action.ActionRequestValidationException) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) XContentHelper.toXContent(org.opensearch.common.xcontent.XContentHelper.toXContent) SearchScrollRequest(org.opensearch.action.search.SearchScrollRequest) SocketTimeoutException(java.net.SocketTimeoutException) ClearScrollResponse(org.opensearch.action.search.ClearScrollResponse) SearchResponse(org.opensearch.action.search.SearchResponse) ClientYamlSuiteRestApi(org.opensearch.test.rest.yaml.restspec.ClientYamlSuiteRestApi) MainRequest(org.opensearch.client.core.MainRequest) Before(org.junit.Before) MatrixStatsAggregationBuilder(org.opensearch.search.aggregations.matrix.stats.MatrixStatsAggregationBuilder) BasicRequestLine(org.apache.http.message.BasicRequestLine) Matchers(org.hamcrest.Matchers) IOException(java.io.IOException) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) DiscountedCumulativeGain(org.opensearch.index.rankeval.DiscountedCumulativeGain) ProtocolVersion(org.apache.http.ProtocolVersion) Sets(org.opensearch.common.util.set.Sets) SearchResponseSections(org.opensearch.action.search.SearchResponseSections) Suggest(org.opensearch.search.suggest.Suggest) ClearScrollRequest(org.opensearch.action.search.ClearScrollRequest) ShardSearchFailure(org.opensearch.action.search.ShardSearchFailure) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) HttpResponse(org.apache.http.HttpResponse) HttpHost(org.apache.http.HttpHost) Collections(java.util.Collections) MainResponse(org.opensearch.client.core.MainResponse) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) ClearScrollResponse(org.opensearch.action.search.ClearScrollResponse) SearchResponse(org.opensearch.action.search.SearchResponse) HttpResponse(org.apache.http.HttpResponse) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MainRequest(org.opensearch.client.core.MainRequest) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) RestStatus(org.opensearch.rest.RestStatus) HttpHost(org.apache.http.HttpHost) ActionRequest(org.opensearch.action.ActionRequest) SearchScrollRequest(org.opensearch.action.search.SearchScrollRequest) MainRequest(org.opensearch.client.core.MainRequest) ClearScrollRequest(org.opensearch.action.search.ClearScrollRequest) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException)

Example 5 with RestStatus

use of org.opensearch.rest.RestStatus in project OpenSearch by opensearch-project.

the class ClusterClientDocumentationIT method testClusterHealth.

@SuppressWarnings("unused")
public void testClusterHealth() throws IOException {
    RestHighLevelClient client = highLevelClient();
    client.indices().create(new CreateIndexRequest("index"), RequestOptions.DEFAULT);
    {
        // tag::health-request
        ClusterHealthRequest request = new ClusterHealthRequest();
    // end::health-request
    }
    {
        // tag::health-request-indices-ctr
        ClusterHealthRequest request = new ClusterHealthRequest("index1", "index2");
    // end::health-request-indices-ctr
    }
    {
        // tag::health-request-indices-setter
        ClusterHealthRequest request = new ClusterHealthRequest();
        request.indices("index1", "index2");
    // end::health-request-indices-setter
    }
    ClusterHealthRequest request = new ClusterHealthRequest();
    // tag::health-request-timeout
    // <1>
    request.timeout(TimeValue.timeValueSeconds(50));
    // <2>
    request.timeout("50s");
    // end::health-request-timeout
    // tag::health-request-master-timeout
    // <1>
    request.masterNodeTimeout(TimeValue.timeValueSeconds(20));
    // <2>
    request.masterNodeTimeout("20s");
    // end::health-request-master-timeout
    // tag::health-request-wait-status
    // <1>
    request.waitForStatus(ClusterHealthStatus.YELLOW);
    // <2>
    request.waitForYellowStatus();
    // end::health-request-wait-status
    // tag::health-request-wait-events
    // <1>
    request.waitForEvents(Priority.NORMAL);
    // end::health-request-wait-events
    // tag::health-request-level
    // <1>
    request.level(ClusterHealthRequest.Level.SHARDS);
    // end::health-request-level
    // tag::health-request-wait-relocation
    // <1>
    request.waitForNoRelocatingShards(true);
    // end::health-request-wait-relocation
    // tag::health-request-wait-initializing
    // <1>
    request.waitForNoInitializingShards(true);
    // end::health-request-wait-initializing
    // tag::health-request-wait-nodes
    // <1>
    request.waitForNodes("2");
    // <2>
    request.waitForNodes(">=2");
    // <3>
    request.waitForNodes("le(2)");
    // end::health-request-wait-nodes
    // tag::health-request-wait-active
    // <1>
    request.waitForActiveShards(ActiveShardCount.ALL);
    // <2>
    request.waitForActiveShards(1);
    // end::health-request-wait-active
    // tag::health-request-local
    // <1>
    request.local(true);
    // end::health-request-local
    // tag::health-execute
    ClusterHealthResponse response = client.cluster().health(request, RequestOptions.DEFAULT);
    // end::health-execute
    assertThat(response.isTimedOut(), equalTo(false));
    assertThat(response.status(), equalTo(RestStatus.OK));
    assertThat(response.getStatus(), equalTo(ClusterHealthStatus.YELLOW));
    assertThat(response, notNullValue());
    // tag::health-response-general
    // <1>
    String clusterName = response.getClusterName();
    // <2>
    ClusterHealthStatus status = response.getStatus();
    // end::health-response-general
    // tag::health-response-request-status
    // <1>
    boolean timedOut = response.isTimedOut();
    // <2>
    RestStatus restStatus = response.status();
    // end::health-response-request-status
    // tag::health-response-nodes
    // <1>
    int numberOfNodes = response.getNumberOfNodes();
    // <2>
    int numberOfDataNodes = response.getNumberOfDataNodes();
    // end::health-response-nodes
    {
        // tag::health-response-shards
        // <1>
        int activeShards = response.getActiveShards();
        // <2>
        int activePrimaryShards = response.getActivePrimaryShards();
        // <3>
        int relocatingShards = response.getRelocatingShards();
        // <4>
        int initializingShards = response.getInitializingShards();
        // <5>
        int unassignedShards = response.getUnassignedShards();
        // <6>
        int delayedUnassignedShards = response.getDelayedUnassignedShards();
        // <7>
        double activeShardsPercent = response.getActiveShardsPercent();
    // end::health-response-shards
    }
    // tag::health-response-task
    // <1>
    TimeValue taskMaxWaitingTime = response.getTaskMaxWaitingTime();
    // <2>
    int numberOfPendingTasks = response.getNumberOfPendingTasks();
    // <3>
    int numberOfInFlightFetch = response.getNumberOfInFlightFetch();
    // end::health-response-task
    // tag::health-response-indices
    // <1>
    Map<String, ClusterIndexHealth> indices = response.getIndices();
    // end::health-response-indices
    {
        // tag::health-response-index
        // <1>
        ClusterIndexHealth index = indices.get("index");
        ClusterHealthStatus indexStatus = index.getStatus();
        int numberOfShards = index.getNumberOfShards();
        int numberOfReplicas = index.getNumberOfReplicas();
        int activeShards = index.getActiveShards();
        int activePrimaryShards = index.getActivePrimaryShards();
        int initializingShards = index.getInitializingShards();
        int relocatingShards = index.getRelocatingShards();
        int unassignedShards = index.getUnassignedShards();
        // end::health-response-index
        // tag::health-response-shard-details
        // <1>
        Map<Integer, ClusterShardHealth> shards = index.getShards();
        ClusterShardHealth shardHealth = shards.get(0);
        int shardId = shardHealth.getShardId();
        ClusterHealthStatus shardStatus = shardHealth.getStatus();
        int active = shardHealth.getActiveShards();
        int initializing = shardHealth.getInitializingShards();
        int unassigned = shardHealth.getUnassignedShards();
        int relocating = shardHealth.getRelocatingShards();
        boolean primaryActive = shardHealth.isPrimaryActive();
    // end::health-response-shard-details
    }
}
Also used : ClusterHealthResponse(org.opensearch.action.admin.cluster.health.ClusterHealthResponse) ClusterHealthRequest(org.opensearch.action.admin.cluster.health.ClusterHealthRequest) ClusterIndexHealth(org.opensearch.cluster.health.ClusterIndexHealth) RestHighLevelClient(org.opensearch.client.RestHighLevelClient) ClusterHealthStatus(org.opensearch.cluster.health.ClusterHealthStatus) RestStatus(org.opensearch.rest.RestStatus) ClusterShardHealth(org.opensearch.cluster.health.ClusterShardHealth) CreateIndexRequest(org.opensearch.client.indices.CreateIndexRequest) HashMap(java.util.HashMap) Map(java.util.Map) TimeValue(org.opensearch.common.unit.TimeValue)

Aggregations

RestStatus (org.opensearch.rest.RestStatus)35 IOException (java.io.IOException)21 List (java.util.List)15 OpenSearchException (org.opensearch.OpenSearchException)13 SearchResponse (org.opensearch.action.search.SearchResponse)10 ClearScrollResponse (org.opensearch.action.search.ClearScrollResponse)9 MainResponse (org.opensearch.client.core.MainResponse)9 ArrayList (java.util.ArrayList)8 HashMap (java.util.HashMap)8 HashSet (java.util.HashSet)8 Map (java.util.Map)8 Set (java.util.Set)8 HttpHost (org.apache.http.HttpHost)8 HttpResponse (org.apache.http.HttpResponse)8 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)8 HttpEntity (org.apache.http.HttpEntity)7 XContentBuilder (org.opensearch.common.xcontent.XContentBuilder)7 RestRequest (org.opensearch.rest.RestRequest)7 Collections (java.util.Collections)6 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6