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.coffeeking.controller.service.util.ConnectedCupServiceUtils.java

public static String sendCommandViaHTTP(final String deviceHTTPEndpoint, String urlContext,
        boolean fireAndForgot) throws DeviceManagementException {

    String responseMsg = "";
    String urlString = ConnectedCupConstants.URL_PREFIX + deviceHTTPEndpoint + urlContext;

    if (log.isDebugEnabled()) {
        log.debug(urlString);//from www  . j  a  v a2 s .  co  m
    }

    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;
}

From source file:co.paralleluniverse.fibers.httpasyncclient.FiberCloseableHttpAsyncClient.java

private static <T> FutureCallback<T> wrapCallbackWithFuture(final SettableFuture<T> future,
        final FutureCallback<T> callback) {
    return new FutureCallback<T>() {

        @Override/* w  w w  . j  a v a  2s .  c o  m*/
        public void completed(T result) {
            future.set(result);
            callback.completed(result);
        }

        @Override
        public void failed(Exception ex) {
            future.setException(ex);
            callback.failed(ex);
        }

        @Override
        public void cancelled() {
            future.cancel(true);
            callback.cancelled();
        }
    };
}

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

/**
 * Performs an asynchronous POST operation.
 *
 * @param path The path of the RESTful operation.
 * @param payload The payload 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.
 *///  w  w w .  j  a  v  a  2s  .  c  o  m
public final <T> void postAsync(final String path, final Object payload, final int expectedHttpStatus,
        final FutureCallback<T> responseHandler) throws IOException {
    restClient.performAsync(RestClient.Method.POST, path, JsonSerializer.serialize(payload),
            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();
                }
            });
}

From source file:org.mobicents.slee.ra.httpclient.nio.ra.HttpClientNIORequestActivityImpl.java

private FutureCallback<HttpResponse> getFutureCallback(final Object applicationData) {
    return new FutureCallback<HttpResponse>() {
        public void failed(Exception exception) {
            final HttpClientNIOResponseEventImpl event = new HttpClientNIOResponseEventImpl(null, exception,
                    applicationData);/*from   w  ww .j a va 2 s .co m*/
            ra.processResponseEvent(event, HttpClientNIORequestActivityImpl.this);
            ra.endActivity(HttpClientNIORequestActivityImpl.this);
        }

        public void completed(HttpResponse response) {
            final HttpClientNIOResponseEventImpl event = new HttpClientNIOResponseEventImpl(response, null,
                    applicationData);
            ra.processResponseEvent(event, HttpClientNIORequestActivityImpl.this);
            ra.endActivity(HttpClientNIORequestActivityImpl.this);
        }

        public void cancelled() {
            ra.endActivity(HttpClientNIORequestActivityImpl.this);
        }
    };
}

From source file:com.spotify.helios.serviceregistration.skydns.MiniEtcdClient.java

Future<HttpResponse> get(final String key) {
    final URI uri = URI.create(baseUri + key);
    return httpClient.execute(new HttpGet(uri), new FutureCallback<HttpResponse>() {
        @Override/*  w  w  w  .  j  a va 2  s .c  o m*/
        public void cancelled() {
            log.warn("Attempt to get {} to was cancelled", key);
        }

        @Override
        public void completed(HttpResponse arg0) {
            log.info("Succeeded getting {}", key);
        }

        @Override
        public void failed(Exception e) {
            log.warn("Failed getting {}", key, e);
        }
    });
}

From source file:net.ychron.unirestinst.http.HttpClientHelper.java

private <T> FutureCallback<org.apache.http.HttpResponse> prepareCallback(final Class<T> responseClass,
        final Callback<T> callback) {
    if (callback == null)
        return null;

    return new FutureCallback<org.apache.http.HttpResponse>() {

        public void cancelled() {
            callback.cancelled();/*from   w w  w  .j a v a  2 s .c  om*/
        }

        public void completed(org.apache.http.HttpResponse arg0) {
            callback.completed(new HttpResponse<T>(options, arg0, responseClass));
        }

        public void failed(Exception arg0) {
            callback.failed(new UnirestException(arg0));
        }

    };
}

From source file:com.google.cloud.metrics.AsyncMetricsSender.java

/**
 * Translates an encapsulated event into a request to the Google Analytics API and asynchronously
 * sends the resulting request. Note that errors will only be caught in the asynchronous execution
 * thread and therefore will not result in an exception, unlike {@link MetricsSender}.
 *//* w w  w  . jav a  2 s  .c  o  m*/
public void send(Event event) {
    HttpPost request = new HttpPost(MetricsUtils.GA_ENDPOINT_URL);
    request.setEntity(MetricsUtils.buildPostBody(event, analyticsId, random));
    client.execute(request, new FutureCallback<HttpResponse>() {
        @Override
        public void completed(HttpResponse result) {
            try {
                // Let BasicResponseHandler do the work of checking the status
                // code. The actual response body is irrelevant.
                RESPONSE_HANDLER.handleResponse(result);
            } catch (IOException e) {
                // For our purposes, this is exactly identical to a failure.
                failed(e);
            }
        }

        @Override
        public void failed(Exception ex) {
            // Can't really do anything but log the problem.
            LOGGER.warning("Problem sending request to server: " + ex);
        }

        @Override
        public void cancelled() {
            LOGGER.warning("Metrics-reporting HTTP request was cancelled.");
        }
    });
}

From source file:httpasync.AsyncClientPipelinedStreaming.java

public static void a() {
    long start = System.currentTimeMillis();
    CloseableHttpPipeliningClient httpclient = HttpAsyncClients.createPipelining();
    try {// ww  w  . jav a  2s . com
        httpclient.start();

        HttpHost targetHost = new HttpHost("globalquotes.xignite.com", 80);
        //            HttpGet[] resquests = {
        //                    new HttpGet("/docs/index.html"),
        //                    new HttpGet("/docs/introduction.html"),
        //                    new HttpGet("/docs/setup.html"),
        //                    new HttpGet("/docs/config/index.html")
        //            };

        List<MyRequestProducer> requestProducers = new ArrayList<MyRequestProducer>();
        List<MyResponseConsumer> responseConsumers = new ArrayList<MyResponseConsumer>();
        String[] codes = StockParser.stockCodeList.split(",");
        //            500 * 17  ~~~~~~~~~~~~~~~ Shutting down : 12660
        //              avg=17348.1

        //            400 * 21  ~~~~~~~~~~~~~~~ Shutting down : 27476
        //              avg=18923.8

        int take = 400;
        for (int i = 0; i < codes.length / take; i++) {
            String code = Arrays.asList(codes).stream().skip(i * take).limit(take)
                    .collect(Collectors.joining(","));
            HttpGet request = new HttpGet(StockParser.uri + URLEncoder.encode(code.trim()));
            requestProducers.add(new MyRequestProducer(targetHost, request));
            responseConsumers.add(new MyResponseConsumer(request));
        }
        //            System.out.println("? = "+ responseConsumers.size());
        //            for (HttpGet request: resquests) {
        //                requestProducers.add(new MyRequestProducer(targetHost, request));
        //                responseConsumers.add(new MyResponseConsumer(request));
        //            }

        Future<List<Boolean>> future = httpclient.execute(targetHost, requestProducers, responseConsumers,
                new FutureCallback<List<Boolean>>() {
                    @Override
                    public void completed(List<Boolean> result) {
                    }

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

                    @Override
                    public void cancelled() {

                    }
                });
        future.get();
        System.out.println(take + " * " + responseConsumers.size()
                + "  ~~~~~~~~~~~~~~~ Shutting down : "
                + (System.currentTimeMillis() - start));
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //        System.out.println("Done");
}

From source file:com.imagesleuth.imagesleuthclient2.Getter.java

public void get(final String id, final File result)
        throws InterruptedException, IOException, URISyntaxException {

    Test.testNull(id);/*from   w ww .  j a va  2s.  c o  m*/
    Test.testNull(result);
    final CountDownLatch latch = new CountDownLatch(1);

    try (CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultHeaders(harray)
            .setDefaultCredentialsProvider(credsProvider).setDefaultRequestConfig(requestConfig).build()) {
        httpclient.start();
        URIBuilder builder = new URIBuilder();
        if (url.startsWith("https://")) {
            String baseURL = url.substring(8);
            builder.setScheme("https").setHost(baseURL).setPath("/api/v1/results").setParameter("id", id);
        } else if (url.startsWith("http://")) {
            String baseURL = url.substring(7);
            builder.setScheme("http").setHost(baseURL).setPath("/api/v1/results").setParameter("id", id);
        } else {
            builder.setScheme("http").setHost(url).setPath("/api/v1/results").setParameter("id", id);
        }
        URI uri = builder.build();
        final HttpGet request = new HttpGet(uri);
        httpclient.execute(request, new FutureCallback<HttpResponse>() {

            @Override
            public void completed(final HttpResponse response) {

                int code = response.getStatusLine().getStatusCode();
                latch.countDown();
                if (code == 200) {
                    if (response.getEntity() != null) {
                        StringWriter writer = new StringWriter();
                        try {
                            IOUtils.copy(response.getEntity().getContent(), writer);
                            //System.out.println("result: " + writer.toString());
                            JsonNode json = mapper.readTree(writer.toString());
                            String s = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
                            try (FileWriter fw = new FileWriter(result)) {
                                fw.write(s);
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            }

            @Override
            public void failed(final Exception ex) {
                latch.countDown();
                System.out.println(request.getRequestLine() + "->" + ex);
            }

            @Override
            public void cancelled() {
                latch.countDown();
                System.out.println(request.getRequestLine() + " cancelled");
            }

        });
        latch.await();
    }
    //System.out.println("Shutting down");
}

From source file:com.uber.jaeger.httpclient.JaegerRequestAndResponseInterceptorIntegrationTest.java

@Test
public void testAsyncHttpClientTracing() throws Exception {
    HttpAsyncClientBuilder clientBuilder = HttpAsyncClients.custom();
    CloseableHttpAsyncClient client = TracingInterceptors.addTo(clientBuilder, tracer).build();

    client.start();//w ww .  j av  a 2s.c o  m

    //Make a request to the async client and wait for response
    client.execute(new HttpHost("localhost", mockServerRule.getPort()), new BasicHttpRequest("GET", "/testing"),
            new FutureCallback<org.apache.http.HttpResponse>() {
                @Override
                public void completed(org.apache.http.HttpResponse result) {
                }

                @Override
                public void failed(Exception ex) {
                }

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

    verifyTracing(parentSpan);
}