Example usage for org.apache.http.concurrent FutureCallback FutureCallback

List of usage examples for org.apache.http.concurrent FutureCallback FutureCallback

Introduction

In this page you can find the example usage for org.apache.http.concurrent FutureCallback FutureCallback.

Prototype

FutureCallback

Source Link

Usage

From source file:org.jaqpot.core.service.client.jpdi.JPDIClientImpl.java

@Override
public Future<Dataset> predict(Dataset inputDataset, Model model, MetaInfo datasetMeta, String taskId) {

    CompletableFuture<Dataset> futureDataset = new CompletableFuture<>();

    Dataset dataset = DatasetFactory.copy(inputDataset);
    Dataset tempWithDependentFeatures = DatasetFactory.copy(dataset,
            new HashSet<>(model.getDependentFeatures()));

    dataset.getDataEntry().parallelStream().forEach(dataEntry -> {
        dataEntry.getValues().keySet().retainAll(model.getIndependentFeatures());
    });//from ww w.  j  av  a 2  s.  co  m
    PredictionRequest predictionRequest = new PredictionRequest();
    predictionRequest.setDataset(dataset);
    predictionRequest.setRawModel(model.getActualModel());
    predictionRequest.setAdditionalInfo(model.getAdditionalInfo());

    final HttpPost request = new HttpPost(model.getAlgorithm().getPredictionService());
    request.addHeader("Accept", "application/json");
    request.addHeader("Content-Type", "application/json");

    PipedOutputStream out = new PipedOutputStream();
    PipedInputStream in;
    try {
        in = new PipedInputStream(out);
    } catch (IOException ex) {
        futureDataset.completeExceptionally(ex);
        return futureDataset;
    }
    request.setEntity(new InputStreamEntity(in, ContentType.APPLICATION_JSON));

    Future futureResponse = client.execute(request, new FutureCallback<HttpResponse>() {

        @Override
        public void completed(final HttpResponse response) {
            futureMap.remove(taskId);
            int status = response.getStatusLine().getStatusCode();
            try {
                InputStream responseStream = response.getEntity().getContent();

                switch (status) {
                case 200:
                case 201:
                    try {
                        PredictionResponse predictionResponse = serializer.parse(responseStream,
                                PredictionResponse.class);

                        List<LinkedHashMap<String, Object>> predictions = predictionResponse.getPredictions();
                        if (dataset.getDataEntry().isEmpty()) {
                            DatasetFactory.addEmptyRows(dataset, predictions.size());
                        }
                        List<Feature> features = featureHandler
                                .findBySource("algorithm/" + model.getAlgorithm().getId());
                        IntStream.range(0, dataset.getDataEntry().size())
                                // .parallel()
                                .forEach(i -> {
                                    Map<String, Object> row = predictions.get(i);
                                    DataEntry dataEntry = dataset.getDataEntry().get(i);
                                    if (model.getAlgorithm().getOntologicalClasses().contains("ot:Scaling")
                                            || model.getAlgorithm().getOntologicalClasses()
                                                    .contains("ot:Transformation")) {
                                        dataEntry.getValues().clear();
                                        dataset.getFeatures().clear();
                                    }
                                    row.entrySet().stream().forEach(entry -> {
                                        //                                                    Feature feature = featureHandler.findByTitleAndSource(entry.getKey(), "algorithm/" + model.getAlgorithm().getId());
                                        Feature feature = features.stream()
                                                .filter(f -> f.getMeta().getTitles().contains(entry.getKey()))
                                                .findFirst().orElse(null);
                                        if (feature == null) {
                                            return;
                                        }
                                        dataEntry.getValues().put(baseURI + "feature/" + feature.getId(),
                                                entry.getValue());
                                        FeatureInfo featInfo = new FeatureInfo(
                                                baseURI + "feature/" + feature.getId(),
                                                feature.getMeta().getTitles().stream().findFirst().get());
                                        featInfo.setCategory(Dataset.DescriptorCategory.PREDICTED);
                                        dataset.getFeatures().add(featInfo);
                                    });
                                });
                        dataset.setId(randomStringGenerator.nextString(20));
                        dataset.setTotalRows(dataset.getDataEntry().size());
                        dataset.setMeta(datasetMeta);
                        futureDataset.complete(DatasetFactory.mergeColumns(dataset, tempWithDependentFeatures));
                    } catch (Exception ex) {
                        futureDataset.completeExceptionally(ex);
                    }
                    break;
                case 400:
                    String message = new BufferedReader(new InputStreamReader(responseStream)).lines()
                            .collect(Collectors.joining("\n"));
                    futureDataset.completeExceptionally(new BadRequestException(message));
                    break;
                case 404:
                    message = new BufferedReader(new InputStreamReader(responseStream)).lines()
                            .collect(Collectors.joining("\n"));
                    futureDataset.completeExceptionally(new NotFoundException(message));
                    break;
                case 500:
                    message = new BufferedReader(new InputStreamReader(responseStream)).lines()
                            .collect(Collectors.joining("\n"));
                    futureDataset.completeExceptionally(new InternalServerErrorException(message));
                    break;
                default:
                    message = new BufferedReader(new InputStreamReader(responseStream)).lines()
                            .collect(Collectors.joining("\n"));
                    futureDataset.completeExceptionally(new InternalServerErrorException(message));
                }
            } catch (IOException | UnsupportedOperationException ex) {
                futureDataset.completeExceptionally(ex);
            }
        }

        @Override
        public void failed(final Exception ex) {
            futureMap.remove(taskId);
            futureDataset.completeExceptionally(new InternalServerErrorException(ex));
        }

        @Override
        public void cancelled() {
            futureMap.remove(taskId);
            futureDataset.cancel(true);
        }
    });
    serializer.write(predictionRequest, out);
    try {
        out.close();
    } catch (IOException ex) {
        futureDataset.completeExceptionally(ex);
    }
    futureMap.put(taskId, futureResponse);
    return futureDataset;
}

From source file:com.vmware.loginsightapi.LogInsightClient.java

/**
 * Ingest messages to loginsight/*w w w .  j  a  v a2 s.  co m*/
 * 
 * @param messages
 *            IngestionRequest object with list of messages
 * @return IngestionResponse CompletableFuture object
 * @see IngestionRequest
 * @see IngestionResponse
 */
public CompletableFuture<IngestionResponse> ingest(IngestionRequest messages) {
    HttpPost httpPost = null;
    CompletableFuture<IngestionResponse> completableFuture = new CompletableFuture<IngestionResponse>();
    try {
        httpPost = getIngestionHttpRequest(messages);
        logger.info("Sending : " + messages.toJson());
        asyncHttpClient.execute(httpPost, new FutureCallback<HttpResponse>() {

            @Override
            public void completed(HttpResponse httpResponse) {

                try {
                    String responseString = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8");
                    logger.warn("Response: " + responseString);
                    completableFuture.complete(IngestionResponse.fromJsonString(responseString));

                } catch (IOException e) {
                    e.printStackTrace();
                    completableFuture.completeExceptionally(
                            new LogInsightApiException("Unable to process the query response", e));
                }
            }

            @Override
            public void failed(Exception ex) {
                completableFuture.completeExceptionally(new LogInsightApiException("Ingestion failed", ex));
            }

            @Override
            public void cancelled() {
                completableFuture.completeExceptionally(new LogInsightApiException("Ingestion cancelled"));
            }

        });
    } catch (Exception e) {
        completableFuture.completeExceptionally(new LogInsightApiException("Ingestion failed", e));
    }
    return completableFuture;
}

From source file:com.github.avarabyeu.restendpoint.http.HttpClientRestEndpoint.java

/**
 * Executes {@link org.apache.http.client.methods.HttpUriRequest}
 *
 * @param rq       - Request//from w  w  w  .  ja  va 2 s  . c  om
 * @param callback - Callback to be applied on response
 * @param <RS>     type of response
 * @return - Serialized Response Body
 * @throws RestEndpointIOException IO exception
 */
private <RS> Will<Response<RS>> executeInternal(final HttpUriRequest rq, final HttpEntityCallback<RS> callback)
        throws RestEndpointIOException {

    final SettableFuture<Response<RS>> future = SettableFuture.create();
    httpClient.execute(rq, new FutureCallback<org.apache.http.HttpResponse>() {

        @Override
        public void completed(final org.apache.http.HttpResponse response) {
            try {
                if (errorHandler.hasError(response)) {
                    errorHandler.handle(rq, response);
                }

                HttpEntity entity = response.getEntity();
                Header[] allHeaders = response.getAllHeaders();
                ImmutableMultimap.Builder<String, String> headersBuilder = ImmutableMultimap.builder();
                for (Header header : allHeaders) {
                    for (HeaderElement element : header.getElements()) {
                        headersBuilder.put(header.getName(),
                                null == element.getValue() ? "" : element.getValue());
                    }
                }

                Response<RS> rs = new Response<RS>(rq.getURI().toASCIIString(),
                        response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(),
                        headersBuilder.build(), callback.callback(entity));

                future.set(rs);
            } catch (SerializerException e) {
                future.setException(e);
            } catch (IOException e) {
                future.setException(new RestEndpointIOException("Unable to execute request", e));
            } catch (Exception e) {
                future.setException(e);
            }

        }

        @Override
        public void failed(final Exception ex) {
            future.setException(new RestEndpointIOException("Unable to execute request", ex));
        }

        @Override
        public void cancelled() {
            final TimeoutException timeoutException = new TimeoutException();
            future.setException(timeoutException);
        }

    });
    return Wills.forListenableFuture(future);

}

From source file:org.elasticsearch.client.RestClient.java

private void performRequestAsync(final long startTime, final HostTuple<Iterator<HttpHost>> hostTuple,
        final HttpRequestBase request, final Set<Integer> ignoreErrorCodes,
        final HttpAsyncResponseConsumerFactory httpAsyncResponseConsumerFactory,
        final FailureTrackingResponseListener listener) {
    final HttpHost host = hostTuple.hosts.next();
    //we stream the request body if the entity allows for it
    final HttpAsyncRequestProducer requestProducer = HttpAsyncMethods.create(host, request);
    final HttpAsyncResponseConsumer<HttpResponse> asyncResponseConsumer = httpAsyncResponseConsumerFactory
            .createHttpAsyncResponseConsumer();
    final HttpClientContext context = HttpClientContext.create();
    context.setAuthCache(hostTuple.authCache);
    client.execute(requestProducer, asyncResponseConsumer, context, new FutureCallback<HttpResponse>() {
        @Override/*from w ww .ja  v a 2 s.c o m*/
        public void completed(HttpResponse httpResponse) {
            try {
                RequestLogger.logResponse(logger, request, host, httpResponse);
                int statusCode = httpResponse.getStatusLine().getStatusCode();
                Response response = new Response(request.getRequestLine(), host, httpResponse);
                if (isSuccessfulResponse(statusCode)
                        || ignoreErrorCodes.contains(response.getStatusLine().getStatusCode())) {
                    onResponse(host);
                    listener.onSuccess(response);
                } else {
                    ResponseException responseException = new ResponseException(response);
                    if (isRetryStatus(statusCode)) {
                        //mark host dead and retry against next one
                        onFailure(host);
                        retryIfPossible(responseException);
                    } else {
                        //mark host alive and don't retry, as the error should be a request problem
                        onResponse(host);
                        listener.onDefinitiveFailure(responseException);
                    }
                }
            } catch (Exception e) {
                listener.onDefinitiveFailure(e);
            }
        }

        @Override
        public void failed(Exception failure) {
            try {
                RequestLogger.logFailedRequest(logger, request, host, failure);
                onFailure(host);
                retryIfPossible(failure);
            } catch (Exception e) {
                listener.onDefinitiveFailure(e);
            }
        }

        private void retryIfPossible(Exception exception) {
            if (hostTuple.hosts.hasNext()) {
                //in case we are retrying, check whether maxRetryTimeout has been reached
                long timeElapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
                long timeout = maxRetryTimeoutMillis - timeElapsedMillis;
                if (timeout <= 0) {
                    IOException retryTimeoutException = new IOException(
                            "request retries exceeded max retry timeout [" + maxRetryTimeoutMillis + "]");
                    listener.onDefinitiveFailure(retryTimeoutException);
                } else {
                    listener.trackFailure(exception);
                    request.reset();
                    performRequestAsync(startTime, hostTuple, request, ignoreErrorCodes,
                            httpAsyncResponseConsumerFactory, listener);
                }
            } else {
                listener.onDefinitiveFailure(exception);
            }
        }

        @Override
        public void cancelled() {
            listener.onDefinitiveFailure(new ExecutionException("request was cancelled", null));
        }
    });
}

From source file:org.apache.camel.component.olingo2.api.Olingo2AppIntegrationTest.java

private static void generateSampleData(String serviceUrl) throws IOException {
    final HttpPost httpUriRequest = new HttpPost(serviceUrl.substring(0, serviceUrl.lastIndexOf('/')) + INDEX);
    httpUriRequest.setEntity(new ByteArrayEntity(GEN_SAMPLE_DATA.getBytes()));
    ((Olingo2AppImpl) olingoApp).execute(httpUriRequest, ContentType.APPLICATION_FORM_URLENCODED,
            new FutureCallback<HttpResponse>() {
                @Override/*w ww .  ja va  2  s .  c o  m*/
                public void completed(HttpResponse result) {
                    try {
                        AbstractFutureCallback.checkStatus(result);
                        LOG.info("Sample data generated  {}", result.getStatusLine());
                    } catch (ODataApplicationException e) {
                        LOG.error("Sample data generation error: " + e.getMessage(), e);
                    }
                }

                @Override
                public void failed(Exception ex) {
                    LOG.error("Error generating sample data " + ex.getMessage(), ex);
                }

                @Override
                public void cancelled() {
                    LOG.error("Sample data generation canceled!");
                }
            });
}

From source file:org.apache.http.impl.client.cache.AsynchronousAsyncValidationRequest.java

@Override
public void run() {
    try {/*from  w w  w .j  a v a  2  s  . co m*/
        final FutureCallback<HttpResponse> callback = new FutureCallback<HttpResponse>() {

            @Override
            public void cancelled() {
            }

            @Override
            public void completed(final HttpResponse httpResponse) {
            }

            @Override
            public void failed(final Exception e) {
                log.debug("Asynchronous revalidation failed", e);
            }
        };
        final BasicFuture<HttpResponse> future = new BasicFuture<HttpResponse>(callback);
        this.cachingAsyncClient.revalidateCacheEntry(future, this.target, this.request, this.clientContext,
                this.cacheEntry);
        future.get();
    } catch (final ProtocolException pe) {
        this.log.error("ProtocolException thrown during asynchronous revalidation", pe);
    } catch (final ExecutionException e) {
        this.log.error("Exception thrown during asynchronous revalidation", e.getCause());
    } catch (final InterruptedException e) {
        Thread.currentThread().interrupt();
    } finally {
        this.parent.markComplete(this.identifier);
    }
}

From source file:org.apache.http.impl.nio.client.AbstractClientExchangeHandler.java

final void requestConnection() {
    final HttpRoute route = this.routeRef.get();
    if (this.log.isDebugEnabled()) {
        this.log.debug("[exchange: " + this.id + "] Request connection for " + route);
    }/*from   w  ww.  j  a v  a2 s .c  o m*/

    discardConnection();

    this.validDurationRef.set(null);
    this.routeTrackerRef.set(null);
    this.routeEstablished.set(false);

    final Object userToken = this.localContext.getUserToken();
    final RequestConfig config = this.localContext.getRequestConfig();
    this.connmgr.requestConnection(route, userToken, config.getConnectTimeout(),
            config.getConnectionRequestTimeout(), TimeUnit.MILLISECONDS,
            new FutureCallback<NHttpClientConnection>() {

                @Override
                public void completed(final NHttpClientConnection managedConn) {
                    connectionAllocated(managedConn);
                }

                @Override
                public void failed(final Exception ex) {
                    connectionRequestFailed(ex);
                }

                @Override
                public void cancelled() {
                    connectionRequestCancelled();
                }

            });
}

From source file:org.rapidoid.http.HttpClient.java

private <T> FutureCallback<HttpResponse> callback(final Callback<byte[]> callback,
        final Callback<byte[]> promise, final boolean fullResponse) {

    return new FutureCallback<HttpResponse>() {

        @Override//from ww  w .  ja  v  a  2  s  .c  o  m
        public void completed(HttpResponse response) {
            int statusCode = response.getStatusLine().getStatusCode();

            if (!fullResponse && statusCode != 200) {
                Callbacks.error(callback, new HttpException(statusCode));
                Callbacks.error(promise, new HttpException(statusCode));
                return;
            }

            byte[] bytes;

            if (response.getEntity() != null) {
                try {
                    if (fullResponse) {
                        bytes = responseToString(response).getBytes();
                    } else {
                        InputStream resp = response.getEntity().getContent();
                        bytes = IOUtils.toByteArray(resp);
                    }

                } catch (Exception e) {
                    Callbacks.error(callback, e);
                    Callbacks.error(promise, e);
                    return;
                }
            } else {
                bytes = new byte[0];
            }

            Callbacks.success(callback, bytes);
            Callbacks.success(promise, bytes);
        }

        @Override
        public void failed(Exception e) {
            Callbacks.error(callback, e);
            Callbacks.error(promise, e);
        }

        @Override
        public void cancelled() {
            Callbacks.error(callback, new CancellationException());
            Callbacks.error(promise, new CancellationException());
        }
    };
}

From source file:org.wso2.carbon.device.mgt.iot.firealarm.api.FireAlarmControllerService.java

private String sendCommandViaHTTP(final String deviceIp, int deviceServerPort, String callUrlPattern,
        boolean fireAndForgot) throws DeviceManagementException {

    if (deviceServerPort == 0) {
        deviceServerPort = 80;/*www .java2  s.com*/
    }

    String responseMsg = "";
    String urlString = URL_PREFIX + deviceIp + ":" + deviceServerPort + callUrlPattern;

    if (log.isDebugEnabled()) {
        log.debug(urlString);
    }

    if (!fireAndForgot) {
        HttpURLConnection httpConnection = getHttpConnection(urlString);

        try {
            httpConnection.setRequestMethod(HttpMethod.GET);
        } catch (ProtocolException e) {
            String errorMsg = "Protocol specific error occurred when trying to set method to GET" + " for:"
                    + urlString;
            log.error(errorMsg);
            throw new DeviceManagementException(errorMsg, e);
        }

        responseMsg = readResponseFromGetRequest(httpConnection);

    } else {
        CloseableHttpAsyncClient httpclient = null;
        try {

            httpclient = HttpAsyncClients.createDefault();
            httpclient.start();
            HttpGet request = new HttpGet(urlString);
            final CountDownLatch latch = new CountDownLatch(1);
            Future<HttpResponse> future = httpclient.execute(request, new FutureCallback<HttpResponse>() {
                @Override
                public void completed(HttpResponse httpResponse) {
                    latch.countDown();
                }

                @Override
                public void failed(Exception e) {
                    latch.countDown();
                }

                @Override
                public void cancelled() {
                    latch.countDown();
                }
            });

            latch.await();

        } catch (InterruptedException e) {
            if (log.isDebugEnabled()) {
                log.debug("Sync Interrupted");
            }
        } finally {
            try {
                if (httpclient != null) {
                    httpclient.close();

                }
            } catch (IOException e) {
                if (log.isDebugEnabled()) {
                    log.debug("Failed on close");
                }
            }
        }

    }

    return responseMsg;
}