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.wso2.devicemgt.raspberry.agent.SidhdhiQuery.java

/**
 * Make http call to specified endpoint with events
 * @param inEvents//www. jav a  2  s  .c  om
 * @param bulbEP
 * @param logText
 */
private void performHTTPCall(Event[] inEvents, String bulbEP, String logText) {
    if (inEvents != null && inEvents.length > 0) {
        EventPrinter.print(inEvents);
        String url = constants.prop.getProperty(bulbEP);

        CloseableHttpAsyncClient httpclient = null;

        httpclient = HttpAsyncClients.createDefault();
        httpclient.start();
        HttpGet request = new HttpGet(url);
        log.info("Bulb Status : " + logText);
        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();
            }
        });

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

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

@Override
public Future<Model> train(Dataset dataset, Algorithm algorithm, Map<String, Object> parameters,
        String predictionFeature, MetaInfo modelMeta, String taskId) {

    CompletableFuture<Model> futureModel = new CompletableFuture<>();

    TrainingRequest trainingRequest = new TrainingRequest();
    trainingRequest.setDataset(dataset);
    trainingRequest.setParameters(parameters);
    trainingRequest.setPredictionFeature(predictionFeature);
    //        String trainingRequestString = serializer.write(trainingRequest);

    final HttpPost request = new HttpPost(algorithm.getTrainingService());

    PipedOutputStream out = new PipedOutputStream();
    PipedInputStream in;/*from w  w w  . jav  a2  s . com*/
    try {
        in = new PipedInputStream(out);
    } catch (IOException ex) {
        futureModel.completeExceptionally(ex);
        return futureModel;
    }
    InputStreamEntity entity = new InputStreamEntity(in, ContentType.APPLICATION_JSON);
    entity.setChunked(true);

    request.setEntity(entity);
    request.addHeader("Accept", "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:
                    TrainingResponse trainingResponse = serializer.parse(responseStream,
                            TrainingResponse.class);
                    Model model = new Model();
                    model.setId(randomStringGenerator.nextString(20));
                    model.setActualModel(trainingResponse.getRawModel());
                    model.setPmmlModel(trainingResponse.getPmmlModel());
                    model.setAdditionalInfo(trainingResponse.getAdditionalInfo());
                    model.setAlgorithm(algorithm);
                    model.setParameters(parameters);
                    model.setDatasetUri(dataset != null ? dataset.getDatasetURI() : null);

                    //Check if independedFeatures of model exist in dataset
                    List<String> filteredIndependedFeatures = new ArrayList<String>();

                    if (dataset != null && dataset.getFeatures() != null
                            && trainingResponse.getIndependentFeatures() != null)
                        for (String feature : trainingResponse.getIndependentFeatures()) {
                            for (FeatureInfo featureInfo : dataset.getFeatures()) {
                                if (feature.equals(featureInfo.getURI()))
                                    filteredIndependedFeatures.add(feature);
                            }
                        }

                    model.setIndependentFeatures(filteredIndependedFeatures);
                    model.setDependentFeatures(Arrays.asList(predictionFeature));
                    model.setMeta(modelMeta);

                    List<String> predictedFeatures = new ArrayList<>();
                    for (String featureTitle : trainingResponse.getPredictedFeatures()) {
                        Feature predictionFeatureResource = featureHandler.findByTitleAndSource(featureTitle,
                                "algorithm/" + algorithm.getId());
                        if (predictionFeatureResource == null) {
                            // Create the prediction features (POST /feature)
                            String predFeatID = randomStringGenerator.nextString(12);
                            predictionFeatureResource = new Feature();
                            predictionFeatureResource.setId(predFeatID);
                            predictionFeatureResource.setPredictorFor(predictionFeature);
                            predictionFeatureResource.setMeta(MetaInfoBuilder.builder()
                                    .addSources(
                                            /*messageBody.get("base_uri") + */"algorithm/" + algorithm.getId())
                                    .addComments("Feature created to hold predictions by algorithm with ID "
                                            + algorithm.getId())
                                    .addTitles(featureTitle).addSeeAlso(predictionFeature)
                                    .addCreators(algorithm.getMeta().getCreators()).build());
                            /* Create feature */
                            featureHandler.create(predictionFeatureResource);
                        }
                        predictedFeatures.add(baseURI + "feature/" + predictionFeatureResource.getId());
                    }
                    model.setPredictedFeatures(predictedFeatures);
                    futureModel.complete(model);
                    break;
                case 400:
                    String message = new BufferedReader(new InputStreamReader(responseStream)).lines()
                            .collect(Collectors.joining("\n"));
                    futureModel.completeExceptionally(new BadRequestException(message));
                    break;
                case 500:
                    message = new BufferedReader(new InputStreamReader(responseStream)).lines()
                            .collect(Collectors.joining("\n"));
                    futureModel.completeExceptionally(new InternalServerErrorException(message));
                    break;
                default:
                    message = new BufferedReader(new InputStreamReader(responseStream)).lines()
                            .collect(Collectors.joining("\n"));
                    futureModel.completeExceptionally(new InternalServerErrorException(message));
                }
            } catch (IOException | UnsupportedOperationException ex) {
                futureModel.completeExceptionally(ex);
            }
        }

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

        @Override
        public void cancelled() {
            futureMap.remove(taskId);
            futureModel.cancel(true);
        }

    });

    serializer.write(trainingRequest, out);
    try {
        out.close();
    } catch (IOException ex) {
        futureModel.completeExceptionally(ex);
    }

    futureMap.put(taskId, futureResponse);
    return futureModel;
}

From source file:com.smartling.cms.gateway.client.CmsGatewayClient.java

public Future<ResponseStatus<Void>> send(FileUpload response) throws CmsGatewayClientException, IOException {
    failIfClosed();/*  w  w  w. j  a  v a2s.c  o  m*/

    String requestId = response.getRequest().getId();
    URI uploadUri = getUploadChannelUri(requestId);
    HttpPost post = new HttpPost(uploadUri);
    HttpEntity httpEntity = response.getHttpEntity();
    post.setEntity(httpEntity);
    final String maskedUri = uploadUri.toString().replaceFirst("key=.*?&", "key=XXXXXXX&");
    logger.trace(String.format("Post upload to URI %1$s, length %2$d,  with content type %3$s", maskedUri,
            httpEntity.getContentLength(), httpEntity.getContentType()));
    return new ResponseStatusFuture(uploadChannel.execute(post, new FutureCallback<HttpResponse>() {
        @Override
        public void completed(HttpResponse result) {
            logger.trace(String.format("Post upload for URI %1$s completed status line %2$s", maskedUri,
                    result.getStatusLine()));
        }

        @Override
        public void failed(Exception ex) {
            logger.error(String.format("Post upload failed for URI %1$s: ", maskedUri), ex);
        }

        @Override
        public void cancelled() {
            logger.error(String.format("Post upload cancelled for URI %1$s: ", maskedUri));
        }
    }));
}

From source file:rx.apache.http.ObservableHttp.java

/**
 * Execute request using {@link HttpAsyncRequestProducer} to define HTTP Method, URI and payload (if applicable).
 * <p>//from   w w  w.j  a va  2s.c  o  m
 * If the response is chunked (or flushed progressively such as with <i>text/event-stream</i> <a href="http://www.w3.org/TR/2009/WD-eventsource-20091029/">Server-Sent Events</a>) this will call
 * {@link Observer#onNext} multiple times.
 * <p>
 * Use {@code HttpAsyncMethods.create* } factory methods to create {@link HttpAsyncRequestProducer} instances.
 * <p>
 * A client can be retrieved like this:
 * <p>
 * <pre> {@code      CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault(); } </pre>
 * <p>
 * A client with custom configurations can be created like this:
 * </p>
 * <pre> {@code
 * final RequestConfig requestConfig = RequestConfig.custom()
 *     .setSocketTimeout(3000)
 *     .setConnectTimeout(3000).build();
 * final CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom()
 *     .setDefaultRequestConfig(requestConfig)
 *     .setMaxConnPerRoute(20)
 *     .setMaxConnTotal(50)
 *     .build();
 * httpclient.start();
 * }</pre>
 *
 *
 * @param requestProducer
 * @param client
 * @param context The HttpContext
 * @return the observable HTTP response stream
 */
public static ObservableHttp<ObservableHttpResponse> createRequest(
        final HttpAsyncRequestProducer requestProducer, final HttpAsyncClient client,
        final HttpContext context) {

    return ObservableHttp.create(new OnSubscribe<ObservableHttpResponse>() {

        @Override
        public void call(final Subscriber<? super ObservableHttpResponse> observer) {

            final CompositeSubscription parentSubscription = new CompositeSubscription();
            observer.add(parentSubscription);

            // return a Subscription that wraps the Future so it can be cancelled
            parentSubscription.add(Subscriptions.from(
                    client.execute(requestProducer, new ResponseConsumerDelegate(observer, parentSubscription),
                            context, new FutureCallback<HttpResponse>() {

                                @Override
                                public void completed(HttpResponse result) {
                                    observer.onCompleted();
                                }

                                @Override
                                public void failed(Exception ex) {
                                    observer.onError(ex);
                                }

                                @Override
                                public void cancelled() {
                                    observer.onCompleted();
                                }

                            })));
        }
    });
}

From source file:io.wcm.caravan.io.http.impl.ResilientHttpImpl.java

private Observable<Response> getHttpObservable(String serviceName, String urlPrefix, Request request) {
    return Observable.<Response>create(new Observable.OnSubscribe<Response>() {

        @Override/* ww  w  . j a va 2 s .  com*/
        public void call(final Subscriber<? super Response> subscriber) {
            HttpUriRequest httpRequest = RequestUtil.buildHttpRequest(urlPrefix, request);

            if (log.isDebugEnabled()) {
                log.debug("Execute: " + httpRequest.getURI() + "\n" + request.toString());
            }

            HttpAsyncClient httpClient = httpClientFactory.getAsync(httpRequest.getURI());
            httpClient.execute(httpRequest, new FutureCallback<HttpResponse>() {

                @Override
                public void completed(HttpResponse result) {
                    StatusLine status = result.getStatusLine();
                    HttpEntity entity = result.getEntity();
                    try {
                        if (status.getStatusCode() >= 500) {
                            subscriber.onError(new IllegalResponseRuntimeException(serviceName, request,
                                    httpRequest.getURI().toString(), status.getStatusCode(),
                                    EntityUtils.toString(entity), "Executing '" + httpRequest.getURI()
                                            + "' failed: " + result.getStatusLine()));
                            EntityUtils.consumeQuietly(entity);
                        } else {
                            Response response = Response.create(status.getStatusCode(),
                                    status.getReasonPhrase(), RequestUtil.toHeadersMap(result.getAllHeaders()),
                                    entity.getContent(),
                                    entity.getContentLength() > 0 ? (int) entity.getContentLength() : null);
                            subscriber.onNext(response);
                            subscriber.onCompleted();
                        }
                    } catch (Throwable ex) {
                        subscriber.onError(new IOException(
                                "Reading response of '" + httpRequest.getURI() + "' failed.", ex));
                        EntityUtils.consumeQuietly(entity);
                    }
                }

                @Override
                public void failed(Exception ex) {
                    if (ex instanceof SocketTimeoutException) {
                        subscriber.onError(new IOException(
                                "Socket timeout executing '" + httpRequest.getURI() + "'.", ex));
                    } else {
                        subscriber.onError(
                                new IOException("Executing '" + httpRequest.getURI() + "' failed.", ex));
                    }
                }

                @Override
                public void cancelled() {
                    subscriber.onError(new IOException("Getting " + httpRequest.getURI() + " was cancelled."));
                }

            });
        }

    });
}

From source file:org.opendaylight.fpc.notification.HTTPNotifier.java

@Override
public void run() {
    this.run = true;
    LOG.info("HTTPNotifier RUN started");
    try {//from   ww  w . jav  a  2s .com
        while (run) {
            SimpleEntry<Uri, Notification> obj = (AbstractMap.SimpleEntry<Uri, Notification>) blockingNotificationQueue
                    .take();
            String postBody = null;
            try {
                if (obj.getValue() instanceof ConfigResultNotification) {
                    postBody = fpcCodecUtils.notificationToJsonString(ConfigResultNotification.class,
                            (DataObject) obj.getValue(), true);
                } else if (obj.getValue() instanceof Notify) {
                    postBody = fpcCodecUtils.notificationToJsonString(Notify.class, (DataObject) obj.getValue(),
                            true);
                }
            } catch (Exception e) {
                ErrorLog.logError(e.getStackTrace());
            }
            if (obj.getKey() != null && postBody != null) {
                String url = obj.getKey().getValue();
                try {
                    client.start();
                    HttpRequest post = HttpAsyncMethods.createPost(url, postBody, ContentType.APPLICATION_JSON)
                            .generateRequest();
                    post.setHeader("User-Agent", "ODL Notification Agent");
                    post.setHeader("charset", "utf-8");
                    client.execute((HttpUriRequest) post, new FutureCallback<HttpResponse>() {
                        @Override
                        public void cancelled() {
                            LOG.error(post.getRequestLine() + "-> Cancelled");
                        }

                        @Override
                        public void completed(HttpResponse resp) {
                            try {
                                if (obj.getValue() instanceof Notify) {
                                    if (((Notify) obj.getValue())
                                            .getValue() instanceof DownlinkDataNotification) {
                                        String body = handler.handleResponse(resp);
                                        JSONObject json_body = new JSONObject(body);
                                        api.ddnAck(json_body);
                                        LOG.info("Response Body: " + body);
                                    }
                                }
                            } catch (IOException e) {
                                ErrorLog.logError(e.getStackTrace());
                            }
                        }

                        @Override
                        public void failed(Exception e) {
                            ErrorLog.logError(post.getRequestLine() + "->" + e.getMessage(), e.getStackTrace());
                        }
                    });
                } catch (UnsupportedEncodingException e) {
                    ErrorLog.logError(e.getStackTrace());
                } catch (IOException e) {
                    ErrorLog.logError(e.getStackTrace());
                } catch (HttpException e) {
                    ErrorLog.logError(e.getStackTrace());
                } catch (Exception e) {
                    ErrorLog.logError(e.getStackTrace());
                }
            }
        }
    } catch (InterruptedException e) {
        ErrorLog.logError(e.getStackTrace());
    } catch (Exception e) {
        ErrorLog.logError(e.getStackTrace());
    }
}

From source file:com.comcast.cns.io.HTTPEndpointAsyncPublisher.java

@Override
public void send() throws Exception {

    HttpAsyncRequester requester = new HttpAsyncRequester(httpProcessor, new DefaultConnectionReuseStrategy(),
            httpParams);/* w  ww .  j  a va2  s  .  co  m*/
    final URL url = new URL(endpoint);
    final HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());

    BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
            url.getPath() + (url.getQuery() == null ? "" : "?" + url.getQuery()));
    composeHeader(request);

    String msg = null;

    if (message.getMessageStructure() == CNSMessageStructure.json) {
        msg = message.getProtocolSpecificMessage(CnsSubscriptionProtocol.http);
    } else {
        msg = message.getMessage();
    }

    if (!rawMessageDelivery && message.getMessageType() == CNSMessageType.Notification) {
        msg = com.comcast.cns.util.Util.generateMessageJson(message, CnsSubscriptionProtocol.http);
    }

    logger.debug("event=send_async_http_request endpoint=" + endpoint + "\" message=\"" + msg + "\"");

    request.setEntity(new NStringEntity(msg));

    requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(),
            connectionPool, new BasicHttpContext(), new FutureCallback<HttpResponse>() {

                public void completed(final HttpResponse response) {

                    int statusCode = response.getStatusLine().getStatusCode();

                    // accept all 2xx status codes

                    if (statusCode >= 200 && statusCode < 300) {
                        callback.onSuccess();
                    } else {
                        logger.warn(target + "://" + url.getPath() + "?" + url.getQuery() + " -> "
                                + response.getStatusLine());
                        callback.onFailure(statusCode);
                    }
                }

                public void failed(final Exception ex) {
                    logger.warn(target + " " + url.getPath() + " " + url.getQuery(), ex);
                    callback.onFailure(0);
                }

                public void cancelled() {
                    logger.warn(target + " " + url.getPath() + " " + url.getQuery() + " -> " + "cancelled");
                    callback.onFailure(1);
                }
            });
}

From source file:com.floragunn.searchguard.HeaderAwareJestHttpClient.java

@Override
public <T extends JestResult> void executeAsync(final Action<T> clientRequest,
        final JestResultHandler<T> resultHandler) throws ExecutionException, InterruptedException, IOException {

    synchronized (this) {
        if (!asyncClient.isRunning()) {
            asyncClient.start();/*from w  w  w  .  j a v  a  2s.  c o  m*/
        }
    }

    final String elasticSearchRestUrl = getRequestURL(getElasticSearchServer(), clientRequest.getURI());

    final HttpUriRequest request = constructHttpMethod(clientRequest.getRestMethodName(), elasticSearchRestUrl,
            clientRequest.getData(gson));

    // add headers added to action
    if (!clientRequest.getHeaders().isEmpty()) {
        for (final Entry<String, Object> header : clientRequest.getHeaders().entrySet()) {
            request.addHeader(header.getKey(), header.getValue() + "");
        }
    }

    asyncClient.execute(request, new FutureCallback<HttpResponse>() {
        @Override
        public void completed(final HttpResponse response) {
            try {
                final T jestResult = deserializeResponse(response, clientRequest);
                resultHandler.completed(jestResult);
            } catch (final IOException e) {
                log.error("Exception occurred while serializing the response. Exception: " + e.getMessage());
            }
        }

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

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

}

From source file:com.petalmd.armor.HeaderAwareJestHttpClient.java

@Override
//    <T extends JestResult> void executeAsync(Action<T> var1, JestResultHandler<? super T> var2);
public <T extends JestResult> void executeAsync(final Action<T> clientRequest,
        final JestResultHandler<? super T> resultHandler) {

    synchronized (this) {
        if (!asyncClient.isRunning()) {
            asyncClient.start();//from w w  w . j a  v  a  2 s . c  o m
        }
    }

    final String elasticSearchRestUrl = getRequestURL(getNextServer(), clientRequest.getURI());

    try {
        final HttpUriRequest request = constructHttpMethod(clientRequest.getRestMethodName(),
                elasticSearchRestUrl, clientRequest.getData(gson));

        // add headers added to action
        if (!clientRequest.getHeaders().isEmpty()) {
            for (final Entry<String, Object> header : clientRequest.getHeaders().entrySet()) {
                request.addHeader(header.getKey(), header.getValue() + "");
            }
        }

        asyncClient.execute(request, new FutureCallback<HttpResponse>() {
            @Override
            public void completed(final HttpResponse response) {
                try {
                    final T jestResult = deserializeResponse(response, clientRequest);
                    resultHandler.completed(jestResult);
                } catch (final IOException e) {
                    log.error(
                            "Exception occurred while serializing the response. Exception: " + e.getMessage());
                }
            }

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

            @Override
            public void cancelled() {
            }
        });
    } catch (Exception e) {
    }
}

From source file:com.ysheng.auth.common.restful.BaseClient.java

/**
 * Performs an asynchronous GET operation.
 *
 * @param path The path of the RESTful operation.
 * @param expectedHttpStatus The expected HTTP status of the operation.
 * @param responseHandler The asynchronous response handler.
 * @param <T> The type of the response.
 * @throws IOException The error that contains detail information.
 *///from ww  w.j a va 2 s.  c  o  m
public final <T> void getAsync(final String path, final int expectedHttpStatus,
        final FutureCallback<T> responseHandler) throws IOException {
    restClient.performAsync(RestClient.Method.GET, path, null, new FutureCallback<HttpResponse>() {
        @Override
        public void completed(HttpResponse httpResponse) {
            T response = null;
            try {
                restClient.checkResponse(httpResponse, expectedHttpStatus);
                response = JsonSerializer.deserialize(httpResponse.getEntity(), new TypeReference<T>() {
                });
            } catch (Exception e) {
                responseHandler.failed(e);
            }

            responseHandler.completed(response);
        }

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

        @Override
        public void cancelled() {
            responseHandler.cancelled();
        }
    });
}