Search in sources :

Example 81 with Response

use of org.opensearch.client.Response in project OpenSearch by opensearch-project.

the class SearchDocumentationIT method registerQueryScript.

protected void registerQueryScript(RestClient restClient) throws IOException {
    // tag::register-script
    Request scriptRequest = new Request("POST", "_scripts/title_search");
    scriptRequest.setJsonEntity("{" + "  \"script\": {" + "    \"lang\": \"mustache\"," + "    \"source\": {" + "      \"query\": { \"match\" : { \"{{field}}\" : \"{{value}}\" } }," + "      \"size\" : \"{{size}}\"" + "    }" + "  }" + "}");
    Response scriptResponse = restClient.performRequest(scriptRequest);
    // end::register-script
    assertEquals(RestStatus.OK.getStatus(), scriptResponse.getStatusLine().getStatusCode());
}
Also used : IndexResponse(org.opensearch.action.index.IndexResponse) RankEvalResponse(org.opensearch.index.rankeval.RankEvalResponse) MultiSearchResponse(org.opensearch.action.search.MultiSearchResponse) FieldCapabilitiesResponse(org.opensearch.action.fieldcaps.FieldCapabilitiesResponse) SearchTemplateResponse(org.opensearch.script.mustache.SearchTemplateResponse) MultiSearchTemplateResponse(org.opensearch.script.mustache.MultiSearchTemplateResponse) CountResponse(org.opensearch.client.core.CountResponse) Response(org.opensearch.client.Response) ClearScrollResponse(org.opensearch.action.search.ClearScrollResponse) SearchResponse(org.opensearch.action.search.SearchResponse) ExplainResponse(org.opensearch.action.explain.ExplainResponse) CreateIndexResponse(org.opensearch.client.indices.CreateIndexResponse) BulkResponse(org.opensearch.action.bulk.BulkResponse) WriteRequest(org.opensearch.action.support.WriteRequest) RatedRequest(org.opensearch.index.rankeval.RatedRequest) FieldCapabilitiesRequest(org.opensearch.action.fieldcaps.FieldCapabilitiesRequest) CreateIndexRequest(org.opensearch.client.indices.CreateIndexRequest) MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest) SearchScrollRequest(org.opensearch.action.search.SearchScrollRequest) ExplainRequest(org.opensearch.action.explain.ExplainRequest) SearchRequest(org.opensearch.action.search.SearchRequest) BulkRequest(org.opensearch.action.bulk.BulkRequest) Request(org.opensearch.client.Request) CountRequest(org.opensearch.client.core.CountRequest) SearchTemplateRequest(org.opensearch.script.mustache.SearchTemplateRequest) RankEvalRequest(org.opensearch.index.rankeval.RankEvalRequest) MultiSearchTemplateRequest(org.opensearch.script.mustache.MultiSearchTemplateRequest) ClearScrollRequest(org.opensearch.action.search.ClearScrollRequest) IndexRequest(org.opensearch.action.index.IndexRequest)

Example 82 with Response

use of org.opensearch.client.Response in project OpenSearch by opensearch-project.

the class CreatedLocationHeaderIT method locationTestCase.

private void locationTestCase(String method, String url) throws IOException {
    final Request request = new Request(method, url);
    request.setJsonEntity("{\"test\": \"test\"}");
    locationTestCase(client().performRequest(request));
    // we have to delete the index otherwise the second indexing request will route to the single shard and not produce a 201
    final Response response = client().performRequest(new Request("DELETE", "test"));
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    final Request withRouting = new Request(method, url);
    withRouting.addParameter("routing", "cat");
    withRouting.setJsonEntity("{\"test\": \"test\"}");
    locationTestCase(client().performRequest(withRouting));
}
Also used : Response(org.opensearch.client.Response) Request(org.opensearch.client.Request)

Example 83 with Response

use of org.opensearch.client.Response in project OpenSearch by opensearch-project.

the class WaitForRefreshAndCloseIT method start.

private ActionFuture<String> start(Request request) {
    PlainActionFuture<String> future = new PlainActionFuture<>();
    request.addParameter("refresh", "wait_for");
    request.addParameter("error_trace", "");
    client().performRequestAsync(request, new ResponseListener() {

        @Override
        public void onSuccess(Response response) {
            try {
                future.onResponse(EntityUtils.toString(response.getEntity()));
            } catch (IOException e) {
                future.onFailure(e);
            }
        }

        @Override
        public void onFailure(Exception exception) {
            future.onFailure(exception);
        }
    });
    return future;
}
Also used : Response(org.opensearch.client.Response) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) Matchers.containsString(org.hamcrest.Matchers.containsString) ResponseListener(org.opensearch.client.ResponseListener) IOException(java.io.IOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ResponseException(org.opensearch.client.ResponseException)

Example 84 with Response

use of org.opensearch.client.Response in project opensearch-java by opensearch-project.

the class OpenSearchRestHighLevelClientTestCase method wipeAllOSIndices.

@SuppressWarnings("unchecked")
@After
protected void wipeAllOSIndices() throws IOException {
    Response response = adminClient().performRequest(new Request("GET", "/_cat/indices?format=json&expand_wildcards=all"));
    XContentType xContentType = XContentType.fromMediaTypeOrFormat(response.getEntity().getContentType().getValue());
    XContentParser parser = xContentType.xContent().createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, response.getEntity().getContent());
    try {
        XContentParser.Token token = parser.nextToken();
        List<Map<String, Object>> parserList;
        if (token == XContentParser.Token.START_ARRAY) {
            parserList = parser.listOrderedMap().stream().map(obj -> (Map<String, Object>) obj).collect(Collectors.toList());
        } else {
            parserList = Collections.singletonList(parser.mapOrdered());
        }
        for (Map<String, Object> index : parserList) {
            String indexName = (String) index.get("index");
            if (indexName != null && !".opendistro_security".equals(indexName)) {
                adminClient().performRequest(new Request("DELETE", "/" + indexName));
            }
        }
    } finally {
        parser.close();
    }
}
Also used : Response(org.opensearch.client.Response) XContentType(org.opensearch.common.xcontent.XContentType) Request(org.opensearch.client.Request) Map(java.util.Map) XContentParser(org.opensearch.common.xcontent.XContentParser) After(org.junit.After)

Example 85 with Response

use of org.opensearch.client.Response in project OpenSearch by opensearch-project.

the class RestClientDocumentation method usage.

// end::rest-client-options-singleton
@SuppressWarnings("unused")
public void usage() throws IOException, InterruptedException {
    // tag::rest-client-init
    RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200, "http"), new HttpHost("localhost", 9201, "http")).build();
    // end::rest-client-init
    // tag::rest-client-close
    restClient.close();
    // end::rest-client-close
    {
        // tag::rest-client-init-default-headers
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
        Header[] defaultHeaders = new Header[] { new BasicHeader("header", "value") };
        // <1>
        builder.setDefaultHeaders(defaultHeaders);
    // end::rest-client-init-default-headers
    }
    {
        // tag::rest-client-init-node-selector
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
        // <1>
        builder.setNodeSelector(NodeSelector.SKIP_DEDICATED_MASTERS);
    // end::rest-client-init-node-selector
    }
    {
        // tag::rest-client-init-allocation-aware-selector
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
        builder.setNodeSelector(new // <1>
        NodeSelector() {

            @Override
            public void select(Iterable<Node> nodes) {
                /*
                     * Prefer any node that belongs to rack_one. If none is around
                     * we will go to another rack till it's time to try and revive
                     * some of the nodes that belong to rack_one.
                     */
                boolean foundOne = false;
                for (Node node : nodes) {
                    String rackId = node.getAttributes().get("rack_id").get(0);
                    if ("rack_one".equals(rackId)) {
                        foundOne = true;
                        break;
                    }
                }
                if (foundOne) {
                    Iterator<Node> nodesIt = nodes.iterator();
                    while (nodesIt.hasNext()) {
                        Node node = nodesIt.next();
                        String rackId = node.getAttributes().get("rack_id").get(0);
                        if ("rack_one".equals(rackId) == false) {
                            nodesIt.remove();
                        }
                    }
                }
            }
        });
    // end::rest-client-init-allocation-aware-selector
    }
    {
        // tag::rest-client-init-failure-listener
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
        builder.setFailureListener(new RestClient.FailureListener() {

            @Override
            public void onFailure(Node node) {
            // <1>
            }
        });
    // end::rest-client-init-failure-listener
    }
    {
        // tag::rest-client-init-request-config-callback
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
        builder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {

            @Override
            public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
                // <1>
                return requestConfigBuilder.setSocketTimeout(10000);
            }
        });
    // end::rest-client-init-request-config-callback
    }
    {
        // tag::rest-client-init-client-config-callback
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
        builder.setHttpClientConfigCallback(new HttpClientConfigCallback() {

            @Override
            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                return httpClientBuilder.setProxy(// <1>
                new HttpHost("proxy", 9000, "http"));
            }
        });
    // end::rest-client-init-client-config-callback
    }
    {
        // tag::rest-client-sync
        Request request = new Request(// <1>
        "GET", // <2>
        "/");
        Response response = restClient.performRequest(request);
    // end::rest-client-sync
    }
    {
        // tag::rest-client-async
        Request request = new Request(// <1>
        "GET", // <2>
        "/");
        Cancellable cancellable = restClient.performRequestAsync(request, new ResponseListener() {

            @Override
            public void onSuccess(Response response) {
            // <3>
            }

            @Override
            public void onFailure(Exception exception) {
            // <4>
            }
        });
    // end::rest-client-async
    }
    {
        Request request = new Request("GET", "/");
        // tag::rest-client-parameters
        request.addParameter("pretty", "true");
        // end::rest-client-parameters
        // tag::rest-client-body
        request.setEntity(new NStringEntity("{\"json\":\"text\"}", ContentType.APPLICATION_JSON));
        // end::rest-client-body
        // tag::rest-client-body-shorter
        request.setJsonEntity("{\"json\":\"text\"}");
        // end::rest-client-body-shorter
        // tag::rest-client-options-set-singleton
        request.setOptions(COMMON_OPTIONS);
        // end::rest-client-options-set-singleton
        {
            // tag::rest-client-options-customize-header
            RequestOptions.Builder options = COMMON_OPTIONS.toBuilder();
            options.addHeader("cats", "knock things off of other things");
            request.setOptions(options);
        // end::rest-client-options-customize-header
        }
    }
    {
        HttpEntity[] documents = new HttpEntity[10];
        // tag::rest-client-async-example
        final CountDownLatch latch = new CountDownLatch(documents.length);
        for (int i = 0; i < documents.length; i++) {
            Request request = new Request("PUT", "/posts/doc/" + i);
            // let's assume that the documents are stored in an HttpEntity array
            request.setEntity(documents[i]);
            restClient.performRequestAsync(request, new ResponseListener() {

                @Override
                public void onSuccess(Response response) {
                    // <1>
                    latch.countDown();
                }

                @Override
                public void onFailure(Exception exception) {
                    // <2>
                    latch.countDown();
                }
            });
        }
        latch.await();
    // end::rest-client-async-example
    }
    {
        // tag::rest-client-async-cancel
        Request request = new Request("GET", "/posts/_search");
        Cancellable cancellable = restClient.performRequestAsync(request, new ResponseListener() {

            @Override
            public void onSuccess(Response response) {
            // <1>
            }

            @Override
            public void onFailure(Exception exception) {
            // <2>
            }
        });
        cancellable.cancel();
    // end::rest-client-async-cancel
    }
    {
        // tag::rest-client-response2
        Response response = restClient.performRequest(new Request("GET", "/"));
        // <1>
        RequestLine requestLine = response.getRequestLine();
        // <2>
        HttpHost host = response.getHost();
        // <3>
        int statusCode = response.getStatusLine().getStatusCode();
        // <4>
        Header[] headers = response.getHeaders();
        // <5>
        String responseBody = EntityUtils.toString(response.getEntity());
    // end::rest-client-response2
    }
}
Also used : RequestOptions(org.opensearch.client.RequestOptions) Cancellable(org.opensearch.client.Cancellable) Node(org.opensearch.client.Node) RestClientBuilder(org.opensearch.client.RestClientBuilder) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) HttpAsyncClientBuilder(org.apache.http.impl.nio.client.HttpAsyncClientBuilder) RestClientBuilder(org.opensearch.client.RestClientBuilder) NStringEntity(org.apache.http.nio.entity.NStringEntity) HttpHost(org.apache.http.HttpHost) RequestConfig(org.apache.http.client.config.RequestConfig) RestClient(org.opensearch.client.RestClient) Request(org.opensearch.client.Request) ResponseListener(org.opensearch.client.ResponseListener) CountDownLatch(java.util.concurrent.CountDownLatch) IOException(java.io.IOException) HttpAsyncClientBuilder(org.apache.http.impl.nio.client.HttpAsyncClientBuilder) Response(org.opensearch.client.Response) RequestLine(org.apache.http.RequestLine) HttpClientConfigCallback(org.opensearch.client.RestClientBuilder.HttpClientConfigCallback) NodeSelector(org.opensearch.client.NodeSelector) BasicHeader(org.apache.http.message.BasicHeader)

Aggregations

Response (org.opensearch.client.Response)134 Request (org.opensearch.client.Request)113 ResponseException (org.opensearch.client.ResponseException)24 Map (java.util.Map)23 Matchers.containsString (org.hamcrest.Matchers.containsString)20 ArrayList (java.util.ArrayList)17 PutRepositoryRequest (org.opensearch.action.admin.cluster.repositories.put.PutRepositoryRequest)16 RestClient (org.opensearch.client.RestClient)15 HashMap (java.util.HashMap)14 RequestOptions (org.opensearch.client.RequestOptions)12 ObjectPath (org.opensearch.test.rest.yaml.ObjectPath)12 IndexRequest (org.opensearch.action.index.IndexRequest)11 IOException (java.io.IOException)10 List (java.util.List)10 CountDownLatch (java.util.concurrent.CountDownLatch)8 Version (org.opensearch.Version)8 WriteRequest (org.opensearch.action.support.WriteRequest)8 ListTasksResponse (org.opensearch.action.admin.cluster.node.tasks.list.ListTasksResponse)7 IndexResponse (org.opensearch.action.index.IndexResponse)7 CreateIndexRequest (org.opensearch.client.indices.CreateIndexRequest)7