Example usage for org.apache.http.impl.nio.client HttpAsyncClients createDefault

List of usage examples for org.apache.http.impl.nio.client HttpAsyncClients createDefault

Introduction

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

Prototype

public static CloseableHttpAsyncClient createDefault() 

Source Link

Document

Creates CloseableHttpAsyncClient instance with default configuration.

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);/*  w  ww .j  ava  2s . c  om*/
    }

    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:com.controller.CTraderOrderMANIAC.java

public static List<SingleOrder> updateOrders()
        throws InterruptedException, IOException, JSONException, ExecutionException {

    String currUsername = CMAIN.reportUser().getUsername();
    HttpResponse<JsonNode> resp;//from  ww  w  . ja v a 2  s .  c o m
    System.out.println("Username in update orders is: " + currUsername);
    //INIT CLIENT
    CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
    client.start();

    //REQUEST
    HttpGet request = new HttpGet("http://139.59.17.119:8080/api/trader/orders/" + currUsername);

    //GET AND PARSE RESPONSE
    Future<org.apache.http.HttpResponse> future = client.execute(request, null);
    org.apache.http.HttpResponse response = future.get();
    String json_string = EntityUtils.toString(response.getEntity());
    System.out.println("ASYNC JSON STRING IS : " + json_string);
    JSONArray arrJson = new JSONArray(json_string);
    System.out.println("ASYNC JSONARRAY IS : " + arrJson.toString());

    //PARSE ARRAY INTO SINGLE ORDERS
    List<SingleOrder> arrayOrders = new ArrayList<>();
    for (int i = 0; i < arrJson.length(); i++) {
        JSONObject currentOrder = new JSONObject();
        try {
            currentOrder = arrJson.getJSONObject(i);
        } catch (JSONException ex) {
            Logger.getLogger(CTraderOrderMANIAC.class.getName()).log(Level.SEVERE, null, ex);
        }
        SingleOrder currentSingleOrder = JsonParsing.parseJsonToSingleOrderObject(currentOrder.toString());

        arrayOrders.add(currentSingleOrder);
    }
    arrayOrdersMaster = arrayOrders;
    System.out.println("-----------------> THIS ARRAY IS: " + arrayOrdersMaster.size());
    //DONT FORGET TO KILL CLIENT
    try {
        client.close();
    } catch (IOException ex) {
        Logger.getLogger(CPMOrderMANIAC.class.getName()).log(Level.SEVERE, null, ex);
    }

    //RETURN ORDERS RETRIEVED
    if (!arrayOrdersMaster.isEmpty()) {
        return arrayOrdersMaster;
    } else {
        System.out.println("ASYNC ORDERS IS EMPTY.");
        return null;
    }
}

From source file:tech.beshu.ror.httpclient.ApacheHttpCoreClient.java

public ApacheHttpCoreClient(ESContext esContext, boolean validate) {
    AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
        this.hcHttpClient = validate ? HttpAsyncClients.createDefault() : getNonValidatedHttpClient();
        this.hcHttpClient.start();
        return null;
    });/*ww  w.  java2  s .  c  o  m*/
    this.logger = esContext.logger(getClass());
    this.context = esContext;
    esContext.getShutDownObservable().addObserver((x, y) -> {
        try {
            hcHttpClient.close();
        } catch (IOException e) {
            logger.error("cannot shut down Apache HTTP Core client.. ", e);
        }
    });
}

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  w  w  w.  j  ava  2s . c o  m*/
        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:org.edgexfoundry.EdgeXConfigWatcherApplication.java

public static void registerWatcher(List<CatalogService> services, String notificationPath) {
    try (CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();) {
        httpClient.start();/*from   w w w  .  ja  v  a2  s  . c  o m*/
        for (CatalogService service : services) {
            LOGGER.info("Attempting registration of {} to: {}", service.getServiceName(), notificationPath);
            URL serviceNotificationURL = new URL(notificationProtocol, service.getAddress(),
                    service.getServicePort(), notificationPath);
            HttpGet request = new HttpGet(serviceNotificationURL.toURI());
            Future<HttpResponse> future = httpClient.execute(request, null);
            future.get();
            LOGGER.info("Registered {} @ {}", service.getServiceName(), notificationPath);
        }
    } catch (URISyntaxException e) {
        LOGGER.error("URI Syntax issue: " + e.getMessage());
    } catch (InterruptedException e) {
        LOGGER.error("Interrupted process: " + e.getMessage());
        Thread.currentThread().interrupt();
    } catch (ExecutionException e) {
        LOGGER.error("Execution problem: " + e.getMessage());
    } catch (IOException e) {
        LOGGER.error("IO problem: " + e.getMessage());
    }
}

From source file:io.galeb.services.healthchecker.testers.ApacheHttpClientTester.java

public boolean connect() throws RuntimeException, InterruptedException, ExecutionException {
    if (url == null || returnType == null || expectedReturn == null) {
        return false;
    }/*from  w  w  w .j  a  va2 s.com*/
    final CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    try {
        httpclient.start();
        final CountDownLatch latch = new CountDownLatch(1);
        final HttpGet request = new HttpGet(url);
        request.setHeader(HttpHeaders.HOST, host);
        final HttpAsyncRequestProducer producer = HttpAsyncMethods.create(request);
        final RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT)
                .setSocketTimeout(defaultTimeout).setConnectTimeout(defaultTimeout)
                .setConnectionRequestTimeout(defaultTimeout).build();
        request.setConfig(requestConfig);
        final AsyncCharConsumer<HttpResponse> consumer = new AsyncCharConsumer<HttpResponse>() {

            HttpResponse response;

            @Override
            protected void onCharReceived(CharBuffer buf, IOControl iocontrol) throws IOException {
                return;
            }

            @Override
            protected HttpResponse buildResult(HttpContext context) throws Exception {
                return response;
            }

            @Override
            protected void onResponseReceived(HttpResponse response) throws HttpException, IOException {
                this.response = response;
            }

        };
        httpclient.execute(producer, consumer, new FutureCallback<HttpResponse>() {

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

            @Override
            public void completed(HttpResponse response) {
                latch.countDown();

                final int statusCode = response.getStatusLine().getStatusCode();
                InputStream contentIS = null;
                String content = "";
                try {
                    contentIS = response.getEntity().getContent();
                    content = IOUtils.toString(contentIS);

                } catch (IllegalStateException | IOException e) {
                    logger.ifPresent(log -> log.debug(e));
                }

                if (returnType.startsWith("httpCode")) {
                    returnType = returnType.replaceFirst("httpCode", "");
                }
                // isOk = statusCode == Integer.parseInt(returnType); // Disable temporarily statusCode check
                isOk = true;
            }

            @Override
            public void failed(Exception e) {
                latch.countDown();
                isOk = false;
                logger.ifPresent(log -> log.debug(e));
            }

        });
        latch.await();

    } catch (final RuntimeException e) {
        isOk = false;
        logger.ifPresent(log -> log.error(e));
    } finally {
        try {
            httpclient.close();
        } catch (final IOException e) {
            logger.ifPresent(log -> log.debug(e));
        }
    }
    return isOk;
}

From source file:tech.beshu.ror.httpclient.ApacheHttpCoreClient.java

private CloseableHttpAsyncClient getNonValidatedHttpClient() {
    try {//from   www  . j ava2  s  .  c  o m
        return HttpAsyncClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier())
                .setSSLContext(SSLContexts.custom()
                        .loadTrustMaterial(null, (X509Certificate[] chain, String authType) -> true).build())
                .build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        logger.error("cannot create non-validating Apache HTTP Core client.. ", e);
        return HttpAsyncClients.createDefault();
    }
}

From source file:com.kixeye.janus.client.http.async.AsyncHttpClient.java

/**
 * Creates an async http client./*from   w w w  .  j  a  v  a 2s .  c  o  m*/
 *
 * @param janus reference to Janus
 * @param numRetries number of retry attempts that should be made in the event of http request error. requests that fail to complete
 *                   are considered errors (ie. IOExceptions) and are eligible for retry. Requests that receive a response (regardless of http status) are
 *                   considered successful and are not eligible for retry.
 */
public AsyncHttpClient(Janus janus, int numRetries) {
    Preconditions.checkNotNull(janus, "'janus' is required but was null");
    Preconditions.checkArgument(numRetries >= 0, "'numRetries' must be >= 0");

    this.janus = janus;
    this.numRetries = numRetries;
    this.executor = Executors.newCachedThreadPool();
    this.httpClient = HttpAsyncClients.createDefault();

    this.httpClient.start();
}

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

private SAPResponse[] callSAP(String[] urls) throws Exception {
    log(urls);/* w  w  w .  ja v  a 2 s .  c  o 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.amazonaws.services.dynamodbv2.http.HttpClientFactory.java

/**
 * Creates a new HttpClient object using the specified AWS
 * ClientConfiguration to configure the client.
 *
 * @param config//  ww  w  .j  ava2  s  . c o m
 *            Client configuration options (ex: proxy settings, connection
 *            limits, etc).
 *
 * @return The new, configured HttpClient.
 */
public CloseableHttpAsyncClient createHttpClient(ClientConfiguration config) {
    /* Set HTTP client parameters */
    HttpParams httpClientParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout());
    HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, true);
    HttpConnectionParams.setTcpNoDelay(httpClientParams, true);
    HttpConnectionParams.setSoKeepalive(httpClientParams, config.useTcpKeepAlive());

    int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0];
    int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1];
    if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) {
        HttpConnectionParams.setSocketBufferSize(httpClientParams,
                Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint));
    }

    PoolingClientConnectionManager connectionManager = ConnectionManagerFactory
            .createPoolingClientConnManager(config, httpClientParams);

    CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();

    /* httpClient.setHttpRequestRetryHandler(HttpRequestNoRetryHandler.Singleton);
     httpClient.setRedirectStrategy(new NeverFollowRedirectStrategy());
            
     if (config.getConnectionMaxIdleMillis() > 0) {
    httpClient.setKeepAliveStrategy(new SdkConnectionKeepAliveStrategy(
            config.getConnectionMaxIdleMillis()));
     }*/

    if (config.getLocalAddress() != null) {
        ConnRouteParams.setLocalAddress(httpClientParams, config.getLocalAddress());
    }

    try {
        Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
        SSLSocketFactory sf = config.getApacheHttpClientConfig().getSslSocketFactory();
        if (sf == null) {
            sf = new SdkTLSSocketFactory(SSLContext.getDefault(), SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        }
        Scheme https = new Scheme("https", 443, sf);
        SchemeRegistry sr = connectionManager.getSchemeRegistry();
        sr.register(http);
        sr.register(https);
    } catch (NoSuchAlgorithmException e) {
        throw new AmazonClientException("Unable to access default SSL context", e);
    }

    /*
     * If SSL cert checking for endpoints has been explicitly disabled,
     * register a new scheme for HTTPS that won't cause self-signed certs to
     * error out.
     */
    if (System.getProperty(DISABLE_CERT_CHECKING_SYSTEM_PROPERTY) != null) {
        Scheme sch = new Scheme("https", 443, new TrustingSocketFactory());
        //httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    }

    /* Set proxy if configured */
    String proxyHost = config.getProxyHost();
    int proxyPort = config.getProxyPort();
    /*if (proxyHost != null && proxyPort > 0) {
    AmazonHttpClient.log.info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort);
    HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort);
    httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost);
            
    String proxyUsername    = config.getProxyUsername();
    String proxyPassword    = config.getProxyPassword();
    String proxyDomain      = config.getProxyDomain();
    String proxyWorkstation = config.getProxyWorkstation();
            
    if (proxyUsername != null && proxyPassword != null) {
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(proxyHost, proxyPort),
                new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
    }
            
    // Add a request interceptor that sets up proxy authentication pre-emptively if configured
    if (config.isPreemptiveBasicProxyAuth()){
        httpClient.addRequestInterceptor(new PreemptiveProxyAuth(proxyHttpHost), 0);
    }
    }
    */
    /* Accept Gzip response if configured */
    if (config.useGzip()) {
        /*
                    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
                
        @Override
        public void process(final HttpRequest request,
                final HttpContext context) throws HttpException,
                IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
            }
        }
                
                    });
                
                    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
                
        @Override
        public void process(final HttpResponse response,
                final HttpContext context) throws HttpException,
                IOException {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                Header ceheader = entity.getContentEncoding();
                if (ceheader != null) {
                    HeaderElement[] codecs = ceheader.getElements();
                    for (int i = 0; i < codecs.length; i++) {
                        if (codecs[i].getName()
                                .equalsIgnoreCase("gzip")) {
                            response.setEntity(new GzipDecompressingEntity(
                                    response.getEntity()));
                            return;
                        }
                    }
                }
            }
        }
                
                    });*/
    }

    return httpClient;
}