Example usage for org.apache.http.impl.nio.client HttpAsyncClientBuilder create

List of usage examples for org.apache.http.impl.nio.client HttpAsyncClientBuilder create

Introduction

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

Prototype

public static HttpAsyncClientBuilder create() 

Source Link

Usage

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

public static void main(String[] args) throws IOException, InterruptedException, ExecutionException {
    CloseableHttpAsyncClient asyncClient = HttpAsyncClientBuilder.create().build();
    asyncClient.start();//  w w w. jav a  2 s .c  om
    HttpGet request = new HttpGet("http://www.google.com");
    request.addHeader("Accept", "text/html");
    Future f = asyncClient.execute(request, new FutureCallback<HttpResponse>() {
        @Override
        public void completed(HttpResponse t) {
            System.out.println("completed");

            try {
                String result = new BufferedReader(new InputStreamReader(t.getEntity().getContent())).lines()
                        .collect(Collectors.joining("\n"));
                System.out.println(result);
            } catch (IOException ex) {
                Logger.getLogger(JPDIClientFactory.class.getName()).log(Level.SEVERE, null, ex);
            } catch (UnsupportedOperationException ex) {
                Logger.getLogger(JPDIClientFactory.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        @Override
        public void failed(Exception excptn) {
            System.out.println("failed");
        }

        @Override
        public void cancelled() {
            System.out.println("cancelled");
        }
    });
    f.get();
    asyncClient.close();
}

From source file:co.paralleluniverse.photon.Photon.java

public static void main(final String[] args) throws InterruptedException, IOException {

    final Options options = new Options();
    options.addOption("rate", true, "Requests per second (default " + rateDefault + ")");
    options.addOption("duration", true,
            "Minimum test duration in seconds: will wait for <duration> * <rate> requests to terminate or, if progress check enabled, no progress after <duration> (default "
                    + durationDefault + ")");
    options.addOption("maxconnections", true,
            "Maximum number of open connections (default " + maxConnectionsDefault + ")");
    options.addOption("timeout", true,
            "Connection and read timeout in millis (default " + timeoutDefault + ")");
    options.addOption("print", true,
            "Print cycle in millis, 0 to disable intermediate statistics (default " + printCycleDefault + ")");
    options.addOption("check", true,
            "Progress check cycle in millis, 0 to disable progress check (default " + checkCycleDefault + ")");
    options.addOption("stats", false, "Print full statistics when finish (default false)");
    options.addOption("minmax", false, "Print min/mean/stddev/max stats when finish (default false)");
    options.addOption("name", true, "Test name to print in the statistics (default '" + testNameDefault + "')");
    options.addOption("help", false, "Print help");

    try {/* w ww. jav a  2 s .  c om*/
        final CommandLine cmd = new BasicParser().parse(options, args);
        final String[] ar = cmd.getArgs();
        if (cmd.hasOption("help") || ar.length != 1)
            printUsageAndExit(options);

        final String url = ar[0];

        final int timeout = Integer.parseInt(cmd.getOptionValue("timeout", timeoutDefault));
        final int maxConnections = Integer
                .parseInt(cmd.getOptionValue("maxconnections", maxConnectionsDefault));
        final int duration = Integer.parseInt(cmd.getOptionValue("duration", durationDefault));
        final int printCycle = Integer.parseInt(cmd.getOptionValue("print", printCycleDefault));
        final int checkCycle = Integer.parseInt(cmd.getOptionValue("check", checkCycleDefault));
        final String testName = cmd.getOptionValue("name", testNameDefault);
        final int rate = Integer.parseInt(cmd.getOptionValue("rate", rateDefault));

        final MetricRegistry metrics = new MetricRegistry();
        final Meter requestMeter = metrics.meter("request");
        final Meter responseMeter = metrics.meter("response");
        final Meter errorsMeter = metrics.meter("errors");
        final Logger log = LoggerFactory.getLogger(Photon.class);
        final ConcurrentHashMap<String, AtomicInteger> errors = new ConcurrentHashMap<>();
        final HttpGet request = new HttpGet(url);
        final StripedTimeSeries<Long> sts = new StripedTimeSeries<>(30000, false);
        final StripedHistogram sh = new StripedHistogram(60000, 5);

        log.info("name: " + testName + " url:" + url + " rate:" + rate + " duration:" + duration
                + " maxconnections:" + maxConnections + ", " + "timeout:" + timeout);
        final DefaultConnectingIOReactor ioreactor = new DefaultConnectingIOReactor(IOReactorConfig.custom()
                .setConnectTimeout(timeout).setIoThreadCount(10).setSoTimeout(timeout).build());

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            final List<ExceptionEvent> events = ioreactor.getAuditLog();
            if (events != null)
                events.stream().filter(event -> event != null).forEach(event -> {
                    System.err.println(
                            "Apache Async HTTP Client I/O Reactor Error Time: " + event.getTimestamp());
                    //noinspection ThrowableResultOfMethodCallIgnored
                    if (event.getCause() != null)
                        //noinspection ThrowableResultOfMethodCallIgnored
                        event.getCause().printStackTrace();
                });
            if (cmd.hasOption("stats"))
                printFinishStatistics(errorsMeter, sts, sh, testName);
            if (!errors.keySet().isEmpty())
                errors.entrySet().stream()
                        .forEach(p -> log.info(testName + " " + p.getKey() + " " + p.getValue() + "ms"));
            System.out.println(
                    testName + " responseTime(90%): " + sh.getHistogramData().getValueAtPercentile(90) + "ms");
            if (cmd.hasOption("minmax")) {
                final HistogramData hd = sh.getHistogramData();
                System.out.format("%s %8s%8s%8s%8s\n", testName, "min", "mean", "sd", "max");
                System.out.format("%s %8d%8.2f%8.2f%8d\n", testName, hd.getMinValue(), hd.getMean(),
                        hd.getStdDeviation(), hd.getMaxValue());
            }
        }));

        final PoolingNHttpClientConnectionManager mngr = new PoolingNHttpClientConnectionManager(ioreactor);
        mngr.setDefaultMaxPerRoute(maxConnections);
        mngr.setMaxTotal(maxConnections);
        final CloseableHttpAsyncClient ahc = HttpAsyncClientBuilder.create().setConnectionManager(mngr)
                .setDefaultRequestConfig(RequestConfig.custom().setLocalAddress(null).build()).build();
        try (final CloseableHttpClient client = new FiberHttpClient(ahc)) {
            final int num = duration * rate;

            final CountDownLatch cdl = new CountDownLatch(num);
            final Semaphore sem = new Semaphore(maxConnections);
            final RateLimiter rl = RateLimiter.create(rate);

            spawnStatisticsThread(printCycle, cdl, log, requestMeter, responseMeter, errorsMeter, testName);

            for (int i = 0; i < num; i++) {
                rl.acquire();
                if (sem.availablePermits() == 0)
                    log.debug("Maximum connections count reached, waiting...");
                sem.acquireUninterruptibly();

                new Fiber<Void>(() -> {
                    requestMeter.mark();
                    final long start = System.nanoTime();
                    try {
                        try (final CloseableHttpResponse ignored = client.execute(request)) {
                            responseMeter.mark();
                        } catch (final Throwable t) {
                            markError(errorsMeter, errors, t);
                        }
                    } catch (final Throwable t) {
                        markError(errorsMeter, errors, t);
                    } finally {
                        final long now = System.nanoTime();
                        final long millis = TimeUnit.NANOSECONDS.toMillis(now - start);
                        sts.record(start, millis);
                        sh.recordValue(millis);
                        sem.release();
                        cdl.countDown();
                    }
                }).start();
            }
            spawnProgressCheckThread(log, duration, checkCycle, cdl);
            cdl.await();
        }
    } catch (final ParseException ex) {
        System.err.println("Parsing failed.  Reason: " + ex.getMessage());
    }
}

From source file:com.ysheng.auth.sdk.api.ApiClient.java

/**
 * Constructs an ApiClient object./*from w  ww  .  j a  v  a2  s.  com*/
 *
 * @param target The address of the RESTful endpoint.
 */
public ApiClient(String target) {
    this(target, HttpAsyncClientBuilder.create().build());
}

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

@PostConstruct
public void init() {
    CloseableHttpAsyncClient asyncClient = HttpAsyncClientBuilder.create().build();
    this.client = new JPDIClientImpl(asyncClient, serializer, featureHandler,
            ResourceBundle.getBundle("config").getString("ServerBasePath"));
}

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

/**
 * Non-injected constructor for clients that do not want to use dependency injection.
 *
 * @param analyticsId The Google Analytics ID to which reports will be sent.
 *//*  w ww  .  j  a va 2s .  c om*/
public AsyncMetricsSender(String analyticsId) {
    this(analyticsId, HttpAsyncClientBuilder.create(), new Random());
}

From source file:io.getlime.push.service.fcm.FcmClient.java

/**
 * Set information about proxy.//from   w  w w  . j a  v a 2  s. co  m
 * @param host Proxy host URL.
 * @param port Proxy port.
 * @param username Proxy username, use 'null' for proxy without authentication.
 * @param password Proxy user password, ignored in case username is 'null'
 */
public void setProxy(String host, int port, String username, String password) {

    HttpAsyncClientBuilder clientBuilder = HttpAsyncClientBuilder.create();
    clientBuilder.useSystemProperties();
    clientBuilder.setProxy(new HttpHost(host, port));

    if (username != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        UsernamePasswordCredentials user = new UsernamePasswordCredentials(username, password);
        credsProvider.setCredentials(new AuthScope(host, port), user);
        clientBuilder.setDefaultCredentialsProvider(credsProvider);
        clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
    }

    CloseableHttpAsyncClient client = clientBuilder.build();

    HttpComponentsAsyncClientHttpRequestFactory factory = new HttpComponentsAsyncClientHttpRequestFactory();
    factory.setAsyncClient(client);

    restTemplate.setAsyncRequestFactory(factory);
}

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

/**
 * Refreshes the options, and restores defaults.
 *//*  w  w  w.java 2 s  .  co  m*/
public static void refresh() {
    // Load timeouts
    Object connectionTimeout = Options.getOption(Option.CONNECTION_TIMEOUT);
    if (connectionTimeout == null) {
        connectionTimeout = CONNECTION_TIMEOUT;
    }

    Object socketTimeout = Options.getOption(Option.SOCKET_TIMEOUT);
    if (socketTimeout == null) {
        socketTimeout = SOCKET_TIMEOUT;
    }

    // Create common default configuration
    final BasicCookieStore store = new BasicCookieStore();
    RequestConfig clientConfig = RequestConfig.custom()
            .setConnectTimeout(((Long) connectionTimeout).intValue() * TimeUtils.TIME_FACTOR)
            .setSocketTimeout(((Long) socketTimeout).intValue() * TimeUtils.TIME_FACTOR)
            .setConnectionRequestTimeout(((Long) socketTimeout).intValue() * TimeUtils.TIME_FACTOR)
            .setCookieSpec(CookieSpecs.STANDARD).build();

    // Create clients
    setOption(Option.HTTPCLIENT, HttpClientBuilder.create().setDefaultRequestConfig(clientConfig)
            .setDefaultCookieStore(store).build());

    setOption(Option.COOKIES, store);

    CloseableHttpAsyncClient asyncClient = HttpAsyncClientBuilder.create().setDefaultRequestConfig(clientConfig)
            .setDefaultCookieStore(store).build();
    setOption(Option.ASYNCHTTPCLIENT, asyncClient);
}

From source file:HCNIOEngine.java

private CloseableHttpAsyncClient createCloseableHttpAsyncClient() throws Exception {
    HttpAsyncClientBuilder builder = HttpAsyncClientBuilder.create();
    builder.useSystemProperties();//from   ww w .  j  ava  2 s.  c  om
    builder.setSSLContext(SSLContext.getDefault());
    builder.setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE);
    builder.setMaxConnPerRoute(2);
    builder.setMaxConnTotal(2);
    builder.setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(1000)
            .setConnectTimeout(2000).setSocketTimeout(2000).build());
    //        builder.setHttpProcessor()
    CloseableHttpAsyncClient hc = builder.build();
    hc.start();
    return hc;
}

From source file:com.linecorp.platform.channel.sample.ApiHttpClient.java

public ApiHttpClient(final String channelAccessToken) {

    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeoutInMillis)
            .setConnectTimeout(timeoutInMillis).build();

    CloseableHttpAsyncClient asyncClient = HttpAsyncClientBuilder.create()
            .setDefaultRequestConfig(requestConfig)
            .addInterceptorLast((HttpRequest httpRequest, HttpContext httpContext) -> {
                httpRequest.addHeader("X-Line-ChannelToken", channelAccessToken);
                httpRequest.addHeader("Content-Type", "application/json; charser=UTF-8");
                httpRequest.removeHeaders("Accept");
                httpRequest.addHeader("Accept", "application/json; charset=UTF-8");
            }).setMaxConnTotal(maxConnections).setMaxConnPerRoute(maxConnections).disableCookieManagement()
            .build();/* w ww  .  ja v a2s .  co m*/

    asyncRestTemplate = new AsyncRestTemplate(new HttpComponentsAsyncClientHttpRequestFactory(asyncClient));
    asyncRestTemplate.setErrorHandler(new ApiResponseErrorHandler());

    httpHeaders = new HttpHeaders();
    httpHeaders.set("X-Line-ChannelToken", channelAccessToken);
    httpHeaders.setContentType(new MediaType("application", "json", Charset.forName("UTF-8")));
    List<MediaType> list = new ArrayList<>();
    list.add(new MediaType("application", "json", Charset.forName("UTF-8")));
    httpHeaders.setAccept(list);

    objectMapper = new ObjectMapper();
    objectMapper.configure(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME, true);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    objectMapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()));
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}

From source file:com.pinterest.jbender.executors.http.FiberApacheHttpClientRequestExecutor.java

public FiberApacheHttpClientRequestExecutor(final Validator<CloseableHttpResponse> resValidator,
        final int maxConnections, final int timeout, final int parallelism) throws IOReactorException {
    final DefaultConnectingIOReactor ioreactor = new DefaultConnectingIOReactor(IOReactorConfig.custom()
            .setConnectTimeout(timeout).setIoThreadCount(parallelism).setSoTimeout(timeout).build());

    final PoolingNHttpClientConnectionManager mngr = new PoolingNHttpClientConnectionManager(ioreactor);
    mngr.setDefaultMaxPerRoute(maxConnections);
    mngr.setMaxTotal(maxConnections);//from  w w  w .jav  a 2s.c  om

    final CloseableHttpAsyncClient ahc = HttpAsyncClientBuilder.create().setConnectionManager(mngr)
            .setDefaultRequestConfig(RequestConfig.custom().setLocalAddress(null).build()).build();

    client = new FiberHttpClient(ahc);
    validator = resValidator;
}