Search in sources :

Example 1 with ResponseListener

use of org.elasticsearch.client.ResponseListener in project elasticsearch by elastic.

the class WaitForRefreshAndCloseTests method start.

private ActionFuture<String> start(String method, String path, HttpEntity body) {
    PlainActionFuture<String> future = new PlainActionFuture<>();
    Map<String, String> params = new HashMap<>();
    params.put("refresh", "wait_for");
    params.put("error_trace", "");
    client().performRequestAsync(method, docPath() + path, params, body, new ResponseListener() {

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

        @Override
        public void onFailure(Exception exception) {
            future.onFailure(exception);
        }
    });
    return future;
}
Also used : Response(org.elasticsearch.client.Response) PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture) HashMap(java.util.HashMap) ResponseListener(org.elasticsearch.client.ResponseListener) IOException(java.io.IOException) ResponseException(org.elasticsearch.client.ResponseException) IOException(java.io.IOException)

Example 2 with ResponseListener

use of org.elasticsearch.client.ResponseListener in project elasticsearch by elastic.

the class RemoteScrollableHitSource method execute.

private <T> void execute(String method, String uri, Map<String, String> params, HttpEntity entity, BiFunction<XContentParser, XContentType, T> parser, Consumer<? super T> listener) {
    // Preserve the thread context so headers survive after the call
    java.util.function.Supplier<ThreadContext.StoredContext> contextSupplier = threadPool.getThreadContext().newRestorableContext(true);
    class RetryHelper extends AbstractRunnable {

        private final Iterator<TimeValue> retries = backoffPolicy.iterator();

        @Override
        protected void doRun() throws Exception {
            client.performRequestAsync(method, uri, params, entity, new ResponseListener() {

                @Override
                public void onSuccess(org.elasticsearch.client.Response response) {
                    // Restore the thread context to get the precious headers
                    try (ThreadContext.StoredContext ctx = contextSupplier.get()) {
                        // eliminates compiler warning
                        assert ctx != null;
                        T parsedResponse;
                        try {
                            HttpEntity responseEntity = response.getEntity();
                            InputStream content = responseEntity.getContent();
                            XContentType xContentType = null;
                            if (responseEntity.getContentType() != null) {
                                final String mimeType = ContentType.parse(responseEntity.getContentType().getValue()).getMimeType();
                                xContentType = XContentType.fromMediaType(mimeType);
                            }
                            if (xContentType == null) {
                                try {
                                    throw new ElasticsearchException("Response didn't include Content-Type: " + bodyMessage(response.getEntity()));
                                } catch (IOException e) {
                                    ElasticsearchException ee = new ElasticsearchException("Error extracting body from response");
                                    ee.addSuppressed(e);
                                    throw ee;
                                }
                            }
                            // EMPTY is safe here because we don't call namedObject
                            try (XContentParser xContentParser = xContentType.xContent().createParser(NamedXContentRegistry.EMPTY, content)) {
                                parsedResponse = parser.apply(xContentParser, xContentType);
                            } catch (ParsingException e) {
                                /* Because we're streaming the response we can't get a copy of it here. The best we can do is hint that it
                                 * is totally wrong and we're probably not talking to Elasticsearch. */
                                throw new ElasticsearchException("Error parsing the response, remote is likely not an Elasticsearch instance", e);
                            }
                        } catch (IOException e) {
                            throw new ElasticsearchException("Error deserializing response, remote is likely not an Elasticsearch instance", e);
                        }
                        listener.accept(parsedResponse);
                    }
                }

                @Override
                public void onFailure(Exception e) {
                    try (ThreadContext.StoredContext ctx = contextSupplier.get()) {
                        // eliminates compiler warning
                        assert ctx != null;
                        if (e instanceof ResponseException) {
                            ResponseException re = (ResponseException) e;
                            if (RestStatus.TOO_MANY_REQUESTS.getStatus() == re.getResponse().getStatusLine().getStatusCode()) {
                                if (retries.hasNext()) {
                                    TimeValue delay = retries.next();
                                    logger.trace((Supplier<?>) () -> new ParameterizedMessage("retrying rejected search after [{}]", delay), e);
                                    countSearchRetry.run();
                                    threadPool.schedule(delay, ThreadPool.Names.SAME, RetryHelper.this);
                                    return;
                                }
                            }
                            e = wrapExceptionToPreserveStatus(re.getResponse().getStatusLine().getStatusCode(), re.getResponse().getEntity(), re);
                        } else if (e instanceof ContentTooLongException) {
                            e = new IllegalArgumentException("Remote responded with a chunk that was too large. Use a smaller batch size.", e);
                        }
                        fail.accept(e);
                    }
                }
            });
        }

        @Override
        public void onFailure(Exception t) {
            fail.accept(t);
        }
    }
    new RetryHelper().run();
}
Also used : AbstractRunnable(org.elasticsearch.common.util.concurrent.AbstractRunnable) HttpEntity(org.apache.http.HttpEntity) ResponseException(org.elasticsearch.client.ResponseException) ElasticsearchException(org.elasticsearch.ElasticsearchException) XContentType(org.elasticsearch.common.xcontent.XContentType) ParsingException(org.elasticsearch.common.ParsingException) Iterator(java.util.Iterator) Supplier(org.apache.logging.log4j.util.Supplier) TimeValue(org.elasticsearch.common.unit.TimeValue) InputStream(java.io.InputStream) ContentTooLongException(org.apache.http.ContentTooLongException) ResponseListener(org.elasticsearch.client.ResponseListener) IOException(java.io.IOException) ElasticsearchException(org.elasticsearch.ElasticsearchException) ResponseException(org.elasticsearch.client.ResponseException) ContentTooLongException(org.apache.http.ContentTooLongException) ParsingException(org.elasticsearch.common.ParsingException) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException) IOException(java.io.IOException) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Aggregations

IOException (java.io.IOException)2 ResponseException (org.elasticsearch.client.ResponseException)2 ResponseListener (org.elasticsearch.client.ResponseListener)2 InputStream (java.io.InputStream)1 HashMap (java.util.HashMap)1 Iterator (java.util.Iterator)1 ContentTooLongException (org.apache.http.ContentTooLongException)1 HttpEntity (org.apache.http.HttpEntity)1 ParameterizedMessage (org.apache.logging.log4j.message.ParameterizedMessage)1 Supplier (org.apache.logging.log4j.util.Supplier)1 ElasticsearchException (org.elasticsearch.ElasticsearchException)1 ElasticsearchStatusException (org.elasticsearch.ElasticsearchStatusException)1 PlainActionFuture (org.elasticsearch.action.support.PlainActionFuture)1 Response (org.elasticsearch.client.Response)1 ParsingException (org.elasticsearch.common.ParsingException)1 TimeValue (org.elasticsearch.common.unit.TimeValue)1 AbstractRunnable (org.elasticsearch.common.util.concurrent.AbstractRunnable)1 XContentParser (org.elasticsearch.common.xcontent.XContentParser)1 XContentType (org.elasticsearch.common.xcontent.XContentType)1