Example usage for org.apache.http.impl.nio.client CloseableHttpAsyncClient execute

List of usage examples for org.apache.http.impl.nio.client CloseableHttpAsyncClient execute

Introduction

In this page you can find the example usage for org.apache.http.impl.nio.client CloseableHttpAsyncClient execute.

Prototype

@Override
    public Future<HttpResponse> execute(final HttpUriRequest request, final FutureCallback<HttpResponse> callback) 

Source Link

Usage

From source file:ua.privatbank.cryptonite.CryptoniteX.java

private static byte[] request(final String url, final byte[] data) throws IOException {
    final CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();

    try {//from ww  w  . j  a  v a 2 s.  c om
        httpclient.start();

        final HttpPost request = new HttpPost(url);
        request.setEntity(new ByteArrayEntity(data));
        request.setHeader("Content-type", "application/octet-stream");
        Future<HttpResponse> future = httpclient.execute(request, null);
        // and wait until a response is received

        HttpResponse response = null;
        byte[] tspAnswer = null;
        try {
            response = future.get();
            tspAnswer = IOUtils.toByteArray(response.getEntity().getContent());
        } catch (Exception e) {
            throw new RuntimeException("Error response for url:" + url, e);
        }

        return tspAnswer;
    } finally {
        httpclient.close();
    }
}

From source file:com.envision.envservice.service.SAPService.java

private SAPResponse[] callSAP(String[] urls) throws Exception {
    log(urls);/*from   ww  w  . j a  va 2s. co m*/

    SAPResponse[] lstSAPResponse = new SAPResponse[urls.length];

    CloseableHttpAsyncClient httpAsyncClient = HttpAsyncClients.createDefault();
    httpAsyncClient.start();

    List<Future<HttpResponse>> lstFuture = new LinkedList<Future<HttpResponse>>();
    for (int i = 0; i < urls.length; i++) {
        lstFuture.add(httpAsyncClient.execute(buildHttpGet(urls[i]), null));
    }

    for (int i = 0; i < lstFuture.size(); i++) {
        lstSAPResponse[i] = buildSAPResponse(lstFuture.get(i).get());
    }

    httpAsyncClient.close();

    return lstSAPResponse;
}

From source file:com.networknt.client.ClientTest.java

public String callApiAsync() throws Exception {
    String url = "http://localhost:8887/api";
    CloseableHttpAsyncClient client = Client.getInstance().getAsyncClient();
    HttpGet httpGet = new HttpGet(url);
    try {/*from w w  w  . ja va  2 s .  co  m*/
        Client.getInstance().addAuthorizationWithScopeToken(httpGet, "Bearer token");
        Future<HttpResponse> future = client.execute(httpGet, null);
        HttpResponse response = future.get();
        int status = response.getStatusLine().getStatusCode();
        Assert.assertEquals(200, status);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity);
        Assert.assertEquals("{\"message\":\"OK!\"}", result);
        logger.debug("message = " + result);
        return result;
    } catch (Exception e) {
        e.printStackTrace();
        return "{\"message\":\"Error!\"}";
    }
}

From source file:com.qwazr.cluster.manager.ClusterNode.java

void startCheck(CloseableHttpAsyncClient httpclient) {
    checkToken = UUID.randomUUID().toString();
    HttpHead httpHead = new HttpHead(checkURI);
    httpHead.setHeader(ClusterServiceInterface.HEADER_CHECK_NAME, checkToken);
    httpHead.setHeader(ClusterServiceInterface.HEADER_CHECK_ADDR, ClusterManager.INSTANCE.myAddress);
    httpHead.setHeader("Connection", "close");
    latencyStart = System.currentTimeMillis();
    httpclient.execute(httpHead, this);
}

From source file:org.wso2.devicemgt.raspberry.agent.SidhdhiQuery.java

/**
 * Make http call to specified endpoint with events
 * @param inEvents/*from   w  ww .j  av  a2 s .c o  m*/
 * @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:net.ychron.unirestinst.http.HttpClientHelper.java

public <T> Future<HttpResponse<T>> requestAsync(HttpRequest request, final Class<T> responseClass,
        Callback<T> callback) {
    HttpUriRequest requestObj = prepareRequest(request, true);

    CloseableHttpAsyncClient asyncHttpClient = options.getAsyncHttpClient();
    if (!asyncHttpClient.isRunning()) {
        asyncHttpClient.start();/*from  w  w  w .j  av a  2 s .  c  o m*/
        AsyncIdleConnectionMonitorThread asyncIdleConnectionMonitorThread = (AsyncIdleConnectionMonitorThread) options
                .getOption(Option.ASYNC_MONITOR);
        asyncIdleConnectionMonitorThread.start();
    }

    final Future<org.apache.http.HttpResponse> future = asyncHttpClient.execute(requestObj,
            prepareCallback(responseClass, callback));

    return new Future<HttpResponse<T>>() {

        public boolean cancel(boolean mayInterruptIfRunning) {
            return future.cancel(mayInterruptIfRunning);
        }

        public boolean isCancelled() {
            return future.isCancelled();
        }

        public boolean isDone() {
            return future.isDone();
        }

        public HttpResponse<T> get() throws InterruptedException, ExecutionException {
            org.apache.http.HttpResponse httpResponse = future.get();
            return new HttpResponse<T>(options, httpResponse, responseClass);
        }

        public HttpResponse<T> get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            org.apache.http.HttpResponse httpResponse = future.get(timeout, unit);
            return new HttpResponse<T>(options, httpResponse, responseClass);
        }
    };
}

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

@Test
public void testAsync() throws IOException, InterruptedException, ExecutionException, TimeoutException {
    final int concurrencyLevel = 20;
    // snippet client configuration
    final CloseableHttpAsyncClient client = FiberCloseableHttpAsyncClient.wrap(HttpAsyncClients.custom()
            .setMaxConnPerRoute(concurrencyLevel).setMaxConnTotal(concurrencyLevel).build());
    client.start();//from w  w w .j  a  v a2 s  . com
    // end of snippet
    new Fiber<Void>(new SuspendableRunnable() {
        @Override
        public void run() throws SuspendExecution, InterruptedException {
            try {
                // snippet future calls
                ArrayList<Future<HttpResponse>> futures = new ArrayList<>();
                for (int i = 0; i < concurrencyLevel; i++)
                    futures.add(client.execute(new HttpGet("http://localhost:8080"), null));
                for (Future<HttpResponse> future : futures)
                    assertEquals("testGet", EntityUtils.toString(future.get().getEntity()));
                // end of snippet
            } catch (ExecutionException | IOException | ParseException ex) {
                fail(ex.getMessage());
            }
        }
    }).start().join(5000, TimeUnit.MILLISECONDS);
    client.close();
}

From source file:com.mycompany.wolf.Room.java

public void removePlayer(String playerId) throws IOException {
    synchronized (mutex) {
        sessions.removeIf(equalityPredicate(playerId));
        List<Map<String, String>> roomInfo = sessions.stream()
                .map(s -> ImmutableMap.of("playerId", getPlayerId(s)))
                .collect(Collectors.toCollection(LinkedList::new));
        Map<String, Object> m = ImmutableMap.of("code", "exitResp", "properties", roomInfo);
        String json = new Gson().toJson(m);
        sessions.stream().forEach(s -> {
            s.getAsyncRemote().sendText(json);
        });// www  .ja v  a  2  s  .c om
    }
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig)
            .build();
    httpclient.start();
    try {
        String routerAddress = SpringContext.getBean("routerAddress");

        httpclient.execute(new HttpGet(routerAddress), new FutureCallback<HttpResponse>() {
            @Override
            public void completed(HttpResponse t) {
            }

            @Override
            public void failed(Exception excptn) {
            }

            @Override
            public void cancelled() {
            }
        });
    } finally {
        httpclient.close();
    }
}

From source file:net.tirasa.wink.client.asynchttpclient.ApacheHttpAsyncClientConnectionHandler.java

private Future<HttpResponse> processRequest(ClientRequest request, HandlerContext context)
        throws IOException, KeyManagementException, NoSuchAlgorithmException {

    final CloseableHttpAsyncClient client = openConnection(request);
    // TODO: move this functionality to the base class
    NonCloseableOutputStream ncos = new NonCloseableOutputStream();

    EntityWriter entityWriter = null;/*w  ww.  jav a2 s .co m*/
    if (request.getEntity() != null) {
        OutputStream os = adaptOutputStream(ncos, request, context.getOutputStreamAdapters());
        // cast is safe because we're on the client
        ApacheHttpClientConfig config = (ApacheHttpClientConfig) request.getAttribute(WinkConfiguration.class);
        // prepare the entity that will write our entity
        entityWriter = new EntityWriter(this, request, os, ncos, config.isChunked());
    }

    HttpRequestBase entityRequest = setupHttpRequest(request, entityWriter);

    try {
        return client.execute(entityRequest, new FutureCallback<HttpResponse>() {

            @Override
            public void completed(HttpResponse t) {
                LOG.debug("Client completed with response {}", t);
                try {
                    client.close();
                } catch (IOException e) {
                    LOG.error("While closing", e);
                }
            }

            @Override
            public void failed(Exception excptn) {
                LOG.error("Client failed with exception", excptn);
                try {
                    client.close();
                } catch (IOException e) {
                    LOG.error("While closing", e);
                }
            }

            @Override
            public void cancelled() {
                LOG.debug("Client execution cancelled");
                try {
                    client.close();
                } catch (IOException e) {
                    LOG.error("While closing", e);
                }
            }
        });
    } catch (Exception ex) {
        entityRequest.abort();
        throw new RuntimeException(ex);
    }
}