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:interoperabilite.webservice.client.ClientWithRequestFuture.java

public static void main(String[] args) throws Exception {
    // the simplest way to create a HttpAsyncClientWithFuture
    HttpClient httpclient = HttpClientBuilder.create().setMaxConnPerRoute(5).setMaxConnTotal(5).build();
    ExecutorService execService = Executors.newFixedThreadPool(5);
    FutureRequestExecutionService requestExecService = new FutureRequestExecutionService(httpclient,
            execService);//from   w  w w  .java 2s. c o  m
    try {
        // Because things are asynchronous, you must provide a ResponseHandler
        ResponseHandler<Boolean> handler = new ResponseHandler<Boolean>() {
            @Override
            public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                // simply return true if the status was OK
                return response.getStatusLine().getStatusCode() == 200;
            }
        };

        // Simple request ...
        HttpGet request1 = new HttpGet("http://httpbin.org/get");
        HttpRequestFutureTask<Boolean> futureTask1 = requestExecService.execute(request1,
                HttpClientContext.create(), handler);
        Boolean wasItOk1 = futureTask1.get();
        System.out.println("It was ok? " + wasItOk1);

        // Cancel a request
        try {
            HttpGet request2 = new HttpGet("http://httpbin.org/get");
            HttpRequestFutureTask<Boolean> futureTask2 = requestExecService.execute(request2,
                    HttpClientContext.create(), handler);
            futureTask2.cancel(true);
            Boolean wasItOk2 = futureTask2.get();
            System.out.println("It was cancelled so it should never print this: " + wasItOk2);
        } catch (CancellationException e) {
            System.out.println("We cancelled it, so this is expected");
        }

        // Request with a timeout
        HttpGet request3 = new HttpGet("http://httpbin.org/get");
        HttpRequestFutureTask<Boolean> futureTask3 = requestExecService.execute(request3,
                HttpClientContext.create(), handler);
        Boolean wasItOk3 = futureTask3.get(10, TimeUnit.SECONDS);
        System.out.println("It was ok? " + wasItOk3);

        FutureCallback<Boolean> callback = new FutureCallback<Boolean>() {
            @Override
            public void completed(Boolean result) {
                System.out.println("completed with " + result);
            }

            @Override
            public void failed(Exception ex) {
                System.out.println("failed with " + ex.getMessage());
            }

            @Override
            public void cancelled() {
                System.out.println("cancelled");
            }
        };

        // Simple request with a callback
        HttpGet request4 = new HttpGet("http://httpbin.org/get");
        // using a null HttpContext here since it is optional
        // the callback will be called when the task completes, fails, or is cancelled
        HttpRequestFutureTask<Boolean> futureTask4 = requestExecService.execute(request4,
                HttpClientContext.create(), handler, callback);
        Boolean wasItOk4 = futureTask4.get(10, TimeUnit.SECONDS);
        System.out.println("It was ok? " + wasItOk4);
    } finally {
        requestExecService.close();
    }
}

From source file:com.yulore.demo.NHttpClient.java

public static void main(String[] args) throws Exception {
    // Create HTTP protocol processing chain
    HttpProcessor httpproc = HttpProcessorBuilder.create()
            // Use standard client-side protocol interceptors
            .add(new RequestContent()).add(new RequestTargetHost()).add(new RequestConnControl())
            .add(new RequestUserAgent("Test/1.1")).add(new RequestExpectContinue(true)).build();
    // Create client-side HTTP protocol handler
    HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor();
    // Create client-side I/O event dispatch
    final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler,
            ConnectionConfig.DEFAULT);//from   w  w w. j  a  v  a 2 s .  c  om
    // Create client-side I/O reactor
    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
    // Create HTTP connection pool
    BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, ConnectionConfig.DEFAULT);
    // Limit total number of connections to just two
    pool.setDefaultMaxPerRoute(2);
    pool.setMaxTotal(2);
    // Run the I/O reactor in a separate thread
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                // Ready to go!
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }
            System.out.println("Shutdown");
        }

    });
    // Start the client thread
    t.start();
    // Create HTTP requester
    HttpAsyncRequester requester = new HttpAsyncRequester(httpproc);
    // Execute HTTP GETs to the following hosts and
    HttpHost[] targets = new HttpHost[] { new HttpHost("www.apache.org", 80, "http"),
            new HttpHost("www.verisign.com", 443, "https"), new HttpHost("www.google.com", 80, "http") };
    final CountDownLatch latch = new CountDownLatch(targets.length);
    for (final HttpHost target : targets) {
        BasicHttpRequest request = new BasicHttpRequest("GET", "/");
        HttpCoreContext coreContext = HttpCoreContext.create();
        requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(),
                pool, coreContext,
                // Handle HTTP response from a callback
                new FutureCallback<HttpResponse>() {

                    public void completed(final HttpResponse response) {
                        latch.countDown();
                        System.out.println(target + "->" + response.getStatusLine());
                    }

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

                    public void cancelled() {
                        latch.countDown();
                        System.out.println(target + " cancelled");
                    }

                });
    }
    latch.await();
    System.out.println("Shutting down I/O reactor");
    ioReactor.shutdown();
    System.out.println("Done");

}

From source file:framework.httpclient.nio.NHttpClient.java

public static void main(String[] args) throws Exception {
    // Create HTTP protocol processing chain
    HttpProcessor httpproc = HttpProcessorBuilder.create()
            // Use standard client-side protocol interceptors
            .add(new RequestContent()).add(new RequestTargetHost()).add(new RequestConnControl())
            .add(new RequestUserAgent("LinkedHashSetVsTreeSet/1.1")).add(new RequestExpectContinue(true))
            .build();/*from www  . j a v  a 2  s  .  c  o  m*/

    // Create client-side HTTP protocol handler
    HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor();

    // Create client-side I/O event dispatch
    //   IO 
    final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler,
            ConnectionConfig.DEFAULT);

    // Create client-side I/O reactor
    //   IO reactor
    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();

    // Create HTTP connection pool
    //  HTTP 
    BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, ConnectionConfig.DEFAULT);

    // Limit total number of connections to just two
    pool.setDefaultMaxPerRoute(2);
    pool.setMaxTotal(2);

    // Run the I/O reactor in a separate thread
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                // Ready to go!
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }
            System.out.println("Shutdown");
        }

    });
    // Start the client thread
    t.start();

    // Create HTTP requester
    //  HTTP 
    HttpAsyncRequester requester = new HttpAsyncRequester(httpproc);

    // Execute HTTP GETs to the following hosts and
    HttpHost[] targets = new HttpHost[] { new HttpHost("www.baidu.org", -1, "https"),
            //            new HttpHost("www.zhihu.com", -1, "https"),
            new HttpHost("www.bilibili.com", -1, "https") };

    final CountDownLatch latch = new CountDownLatch(targets.length);

    for (final HttpHost target : targets) {
        BasicHttpRequest request = new BasicHttpRequest("GET", "/");
        HttpCoreContext coreContext = HttpCoreContext.create();
        requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(),
                pool, coreContext,
                // Handle HTTP response from a callback
                new FutureCallback<HttpResponse>() {

                    public void completed(final HttpResponse response) {
                        latch.countDown();
                        System.out.println(target + "->" + response.getStatusLine());
                    }

                    public void failed(final Exception ex) {
                        latch.countDown();
                        System.err.println(target + "->" + ex);
                        ex.printStackTrace();
                    }

                    public void cancelled() {
                        latch.countDown();
                        System.out.println(target + " cancelled");
                    }

                });
    }
    latch.await();
    System.out.println("Shutting down I/O reactor");
    ioReactor.shutdown();
    System.out.println("Done");
}

From source file:com.weibo.wesync.client.NHttpClient2.java

public static void main(String[] args) throws Exception {
    RSAPublicKey publicKey = RSAEncrypt.loadPublicKey("D:\\weibo\\meyou_gw\\conf\\public.pem");
    //  /*from w w w . j  a  v  a2  s .c om*/
    byte[] cipher = RSAEncrypt.encrypt(publicKey, password.getBytes());
    password = RSAEncrypt.toHexString(cipher);

    // HTTP parameters for the client
    HttpParams params = new SyncBasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);

    // Create HTTP protocol processing chain
    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Use standard client-side protocol interceptors
            new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(),
            new RequestExpectContinue() });
    // Create client-side HTTP protocol handler
    HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor();
    // Create client-side I/O event dispatch
    final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, params);
    // Create client-side I/O reactor
    IOReactorConfig config = new IOReactorConfig();
    config.setIoThreadCount(1);
    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(config);
    // Create HTTP connection pool
    BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, params);
    // Limit total number of connections to just two
    pool.setDefaultMaxPerRoute(2);
    pool.setMaxTotal(1);

    // Run the I/O reactor in a separate thread
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                // Ready to go!
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }
            System.out.println("Shutdown");
        }

    });
    // Start the client thread
    t.start();
    // Create HTTP requester
    //        HttpAsyncRequester requester = new HttpAsyncRequester(
    //                httpproc, new DefaultConnectionReuseStrategy(), params);
    // Execute HTTP GETs to the following hosts and
    HttpHost[] targets = new HttpHost[] {
            //              new HttpHost("123.125.106.28", 8093, "http"),
            //              new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            new HttpHost("123.125.106.28", 8082, "http") };

    final CountDownLatch latch = new CountDownLatch(targets.length);
    int callbackId = 0;

    for (int i = 0; i < 1; i++) {
        for (final HttpHost target : targets) {
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/wesync");

            //              String usrpwd = Base64.encodeBase64String((username + ":" + password).getBytes());
            //              request.setHeader("authorization", "Basic " + usrpwd);
            request.setHeader("uid", "2565640713");
            Meyou.MeyouPacket packet = null;

            if (callbackId == 0) {
                packet = Meyou.MeyouPacket.newBuilder().setCallbackId(String.valueOf(callbackId++))
                        .setSort(MeyouSort.notice).build();
            } else {
                packet = Meyou.MeyouPacket.newBuilder().setCallbackId(String.valueOf(callbackId++))
                        .setSort(MeyouSort.wesync).build();
            }

            ByteArrayEntity entity = new ByteArrayEntity(packet.toByteArray());
            request.setEntity(entity);
            //           BasicHttpRequest request = new BasicHttpRequest("GET", "/test.html");

            System.out.println("send ...");
            HttpAsyncRequester requester = new HttpAsyncRequester(httpproc,
                    new DefaultConnectionReuseStrategy(), params);
            requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(),
                    pool, new BasicHttpContext(),
                    // Handle HTTP response from a callback
                    new FutureCallback<HttpResponse>() {
                        public void completed(final HttpResponse response) {
                            StatusLine status = response.getStatusLine();
                            int code = status.getStatusCode();

                            if (code == 200) {
                                try {
                                    latch.countDown();
                                    DataInputStream in;
                                    in = new DataInputStream(response.getEntity().getContent());
                                    int packetLength = in.readInt();
                                    int start = 0;

                                    while (packetLength > 0) {
                                        ByteArrayOutputStream outstream = new ByteArrayOutputStream(
                                                packetLength);
                                        byte[] buffer = new byte[1024];
                                        int len = 0;

                                        while (start < packetLength
                                                && (len = in.read(buffer, start, packetLength)) > 0) {
                                            outstream.write(buffer, 0, len);
                                            start += len;
                                        }

                                        Meyou.MeyouPacket packet0 = Meyou.MeyouPacket
                                                .parseFrom(outstream.toByteArray());
                                        System.out.println(target + "->" + packet0);

                                        if ((len = in.read(buffer, start, 4)) > 0) {
                                            packetLength = Util.readPacketLength(buffer);
                                        } else {
                                            break;
                                        }
                                    }
                                } catch (IllegalStateException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            } else {
                                System.out.println("error code=" + code + "|" + status.getReasonPhrase());
                            }
                        }

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

                        public void cancelled() {
                            latch.countDown();
                            System.out.println(target + " cancelled");
                        }

                    });

            Thread.sleep((long) (Math.random() * 10000));
        }
    }
    //        latch.await();
    //        System.out.println("Shutting down I/O reactor");
    //        ioReactor.shutdown();
    //        System.out.println("Done");
}

From source file:com.hcspider.platypusjs.asynchttp.AsyncHTTPCallbacks.java

public static FutureCallback<HttpResponse> asCallback(BiConsumer<Object, Throwable> aWrapped) {
    return new FutureCallback<HttpResponse>() {
        @Override/*from   w ww .  j a va 2s .  co  m*/
        public void completed(final HttpResponse response) {
            aWrapped.accept(response, null);
        }

        @Override
        public void failed(final Exception ex) {
            aWrapped.accept(null, ex);
        }

        @Override
        public void cancelled() {
            aWrapped.accept(null, new Exception("Async HTTP requst was cancelled."));
        }
    };
}

From source file:org.wisdom.test.http.HttpClientHelper.java

private static <T> FutureCallback<org.apache.http.HttpResponse> prepareCallback(final Class<T> responseClass,
        final Callback<T> callback) {
    if (callback == null) {
        return null;
    }//from  ww w. j  ava 2 s . c  o  m

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

        /**
         * Cancels the request.
         */
        public void cancelled() {
            callback.cancelled();
        }

        /**
         * Completes the request.
         * @param arg0 the HTTP Response
         */
        public void completed(org.apache.http.HttpResponse arg0) {
            callback.completed(new HttpResponse<>(arg0, responseClass));
        }

        /**
         * Marks the request as failed.
         * @param arg0 the error
         */
        public void failed(Exception arg0) {
            callback.failed(arg0);
        }

    };
}

From source file:im.dadoo.logger.client.impl.DefaultLoggerClient.java

@Override
public void send(final Log log) {
    logger.info(String.format("??,:%s", log.toString()));
    try {//ww w.j a  v  a 2  s .  c o  m
        this.post.setEntity(new StringEntity(this.mapper.writeValueAsString(log)));
        if (!this.httpClient.isRunning()) {
            this.httpClient.start();
        }
        this.httpClient.execute(this.post, new FutureCallback<HttpResponse>() {
            @Override
            public void completed(HttpResponse response) {
                HttpEntity entity = response.getEntity();
                try {
                    String rs = EntityUtils.toString(entity);
                    logger.info(rs);
                    Boolean result = mapper.readValue(rs, Boolean.class);
                    if (result) {
                        logger.info(String.format(",?:%s", log.toPropertyString()));
                    } else {
                        logger.warn(
                                String.format(",?:%s", log.toPropertyString()));
                    }
                } catch (IOException ex) {
                    logger.error(String.format("IO,?:%s", log.toPropertyString()),
                            ex);
                } catch (ParseException ex) {
                    logger.error(String.format("???,?:%s",
                            log.toPropertyString()), ex);
                } finally {
                    EntityUtils.consumeQuietly(entity);
                }
            }

            @Override
            public void failed(Exception ex) {
                logger.error(String.format("??,?:%s", log.toPropertyString()), ex);
            }

            @Override
            public void cancelled() {
                logger.warn(String.format("???,?:%s", log.toPropertyString()));
            }
        });
    } catch (JsonProcessingException ex) {
        logger.error(
                String.format("??json,?:%s", log.toPropertyString()),
                ex);
    } catch (UnsupportedEncodingException ex) {
        logger.error(String.format("????,?:%s", log.toPropertyString()), ex);
    }
}

From source file:org.wso2.carbon.device.mgt.iot.arduino.service.impl.util.ArduinoServiceUtils.java

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

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

    if (log.isDebugEnabled()) {
        log.debug(urlString);//from w  w  w.  j  a  v a2s . com
    }

    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:net.data.technology.jraft.extensions.http.HttpRpcClient.java

@Override
public CompletableFuture<RaftResponseMessage> send(RaftRequestMessage request) {
    CompletableFuture<RaftResponseMessage> future = new CompletableFuture<RaftResponseMessage>();
    String payload = this.gson.toJson(request);
    HttpPost postRequest = new HttpPost(this.serverUrl);
    postRequest.setEntity(new StringEntity(payload, StandardCharsets.UTF_8));
    this.httpClient.execute(postRequest, new FutureCallback<HttpResponse>() {

        @Override//from ww w  .j a v a2  s . c om
        public void completed(HttpResponse result) {
            if (result.getStatusLine().getStatusCode() != 200) {
                logger.info("receive an response error code "
                        + String.valueOf(result.getStatusLine().getStatusCode()) + " from server");
                future.completeExceptionally(new IOException("Service Error"));
            }

            try {
                InputStreamReader reader = new InputStreamReader(result.getEntity().getContent());
                RaftResponseMessage response = gson.fromJson(reader, RaftResponseMessage.class);
                future.complete(response);
            } catch (Throwable error) {
                logger.info("fails to parse the response from server due to errors", error);
                future.completeExceptionally(error);
            }
        }

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

        @Override
        public void cancelled() {
            future.completeExceptionally(new IOException("request cancelled"));
        }
    });
    return future;
}

From source file:io.github.bckfnn.reactstreams.arangodb.AsyncHttpClient.java

@Override
public <T extends Result> Stream<T> process(Operation<T> req) {
    LOG.debug("req -> " + req.getUri());
    return Stream.asOne(subscription -> {
        HttpRequest request = null;//w  w  w .j  a v a  2  s.  c o m
        if (req.getMethod().equals("POST")) {
            HttpPost post = new HttpPost(req.getUri());
            post.setEntity(
                    new ByteArrayEntity(mapper.writeValueAsBytes(req.getBody()), ContentType.APPLICATION_JSON));
            request = post;
        } else if (req.getMethod().equals("GET")) {
            request = new HttpGet(req.getUri());
        }

        httpClient.execute(new HttpHost(host, port), request, new FutureCallback<HttpResponse>() {
            public void completed(HttpResponse result) {
                LOG.debug("res <- " + result.getStatusLine().getStatusCode());
                HttpEntity ent = result.getEntity();
                System.out.println(result.getStatusLine().getStatusCode() + " " + ent.isRepeatable());

                try {
                    T val = mapper.readValue(ent.getContent(), req.getResponseClass());
                    subscription.sendNext(val);
                    subscription.sendComplete();
                } catch (Exception e) {
                    subscription.sendError(e);
                }
            }

            public void failed(Exception ex) {
                subscription.sendError(ex);
            }

            public void cancelled() {
                subscription.sendError(new Throwable("cancelled"));
            }
        });
    });
}