Java Code Examples for org.apache.http.impl.nio.client.HttpAsyncClients#createDefault()

The following examples show how to use org.apache.http.impl.nio.client.HttpAsyncClients#createDefault() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConnectorCommon.java    From nextcloud-java-api with GNU General Public License v3.0 6 votes vote down vote up
public static CloseableHttpAsyncClient getInstance(ServerConfig serverConfig)
	throws IOException{
	if (HTTPC_CLIENT == null) {
		if (serverConfig.isTrustAllCertificates()) {
			try {
				SSLContext sslContext = SSLContexts.custom()
					.loadTrustMaterial(null, TrustAllStrategy.INSTANCE).build();
				HTTPC_CLIENT = HttpAsyncClients.custom()
					.setSSLHostnameVerifier((NoopHostnameVerifier.INSTANCE))
					.setSSLContext(sslContext)
					.build();
			} catch (KeyManagementException | NoSuchAlgorithmException
					| KeyStoreException e) {
				throw new IOException(e);
			} 
			
		} else {
			HTTPC_CLIENT = HttpAsyncClients.createDefault();
		}
		
		HTTPC_CLIENT.start();
	}
	return HTTPC_CLIENT;
}
 
Example 2
Source File: ApacheHttpAsyncClientPluginIT.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
    httpClient.start();
    HttpHost httpHost = new HttpHost("localhost", getPort());
    HttpPost httpPost = new HttpPost("/hello4");
    SimpleFutureCallback callback = new SimpleFutureCallback();
    Future<HttpResponse> future = httpClient.execute(httpHost, httpPost, callback);
    callback.latch.await();
    httpClient.close();
    int responseStatusCode = future.get().getStatusLine().getStatusCode();
    if (responseStatusCode != 200) {
        throw new IllegalStateException(
                "Unexpected response status code: " + responseStatusCode);
    }
}
 
Example 3
Source File: ApacheHttpAsyncClientPluginIT.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
    httpClient.start();
    HttpHost httpHost = new HttpHost("localhost", getPort());
    HttpGet httpGet = new HttpGet("/hello2");
    SimpleFutureCallback callback = new SimpleFutureCallback();
    Future<HttpResponse> future = httpClient.execute(httpHost, httpGet, callback);
    callback.latch.await();
    httpClient.close();
    int responseStatusCode = future.get().getStatusLine().getStatusCode();
    if (responseStatusCode != 200) {
        throw new IllegalStateException(
                "Unexpected response status code: " + responseStatusCode);
    }
}
 
Example 4
Source File: AsyncClientExecuteProxy.java    From yunpian-java-sdk with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    try {
        httpclient.start();
        HttpHost proxy = new HttpHost("someproxy", 8080);
        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        HttpGet request = new HttpGet("https://issues.apache.org/");
        request.setConfig(config);
        Future<HttpResponse> future = httpclient.execute(request, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
}
 
Example 5
Source File: AsyncClientHttpExchangeStreaming.java    From yunpian-java-sdk with MIT License 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    try {
        httpclient.start();
        Future<Boolean> future = httpclient.execute(HttpAsyncMethods.createGet("http://localhost:8080/"),
                new MyResponseConsumer(), null);
        Boolean result = future.get();
        if (result != null && result.booleanValue()) {
            System.out.println("Request successfully executed");
        } else {
            System.out.println("Request failed");
        }
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}
 
Example 6
Source File: AsyncClientHttpExchange.java    From yunpian-java-sdk with MIT License 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    try {
        httpclient.start();
        HttpGet request = new HttpGet("http://www.apache.org/");
        Future<HttpResponse> future = httpclient.execute(request, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}
 
Example 7
Source File: HttpAsyncClientLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenUseProxyWithHttpClient_thenCorrect() throws Exception {
    final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
    client.start();
    final HttpHost proxy = new HttpHost("127.0.0.1", 8080);
    final RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
    final HttpGet request = new HttpGet(HOST_WITH_PROXY);
    request.setConfig(config);
    final Future<HttpResponse> future = client.execute(request, null);
    final HttpResponse response = future.get();
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}
 
Example 8
Source File: HttpAsyncClientLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException {
    final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
    client.start();
    final HttpGet request = new HttpGet(HOST);

    final Future<HttpResponse> future = client.execute(request, null);
    final HttpResponse response = future.get();

    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}
 
Example 9
Source File: ApacheHttpAsyncClientPluginIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
    httpClient.start();
    HttpPost httpPost = new HttpPost("http://localhost:" + getPort() + "/hello3");
    SimpleFutureCallback callback = new SimpleFutureCallback();
    Future<HttpResponse> future = httpClient.execute(httpPost, callback);
    callback.latch.await();
    httpClient.close();
    int responseStatusCode = future.get().getStatusLine().getStatusCode();
    if (responseStatusCode != 200) {
        throw new IllegalStateException(
                "Unexpected response status code: " + responseStatusCode);
    }
}
 
Example 10
Source File: ApacheHttpAsyncClientPluginIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
    httpClient.start();
    HttpGet httpGet = new HttpGet("http://localhost:" + getPort() + "/hello1");
    SimpleFutureCallback callback = new SimpleFutureCallback();
    Future<HttpResponse> future = httpClient.execute(httpGet, callback);
    callback.latch.await();
    httpClient.close();
    int responseStatusCode = future.get().getStatusLine().getStatusCode();
    if (responseStatusCode != 200) {
        throw new IllegalStateException(
                "Unexpected response status code: " + responseStatusCode);
    }
}
 
Example 11
Source File: ImportRunner.java    From newts with Apache License 2.0 5 votes vote down vote up
private Observable<Boolean> restPoster(Observable<List<Sample>> samples,  MetricRegistry metrics) {

        final CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
        httpClient.start();


        return samples

                // turn each batch into json
                .map(toJSON())

                // meter them as the go into the post code
                .map(meter(metrics.meter("posts"), String.class))

                // post the json to the REST server
                .mergeMap(postJSON(m_restUrl, httpClient))

                // meter the responses
                .map(meter(metrics.meter("responses"), ObservableHttpResponse.class))
                
                // count sample completions
                .map(meter(metrics.meter("samples-completed"), m_samplesPerBatch, ObservableHttpResponse.class))

                // make sure every request has a successful return code
                .all(successful())
                
                .doOnCompleted(new Action0() {

                    @Override
                    public void call() {
                        try {
                            httpClient.close();
                        } catch (IOException e) {
                            System.err.println("Failed to close httpClient!");
                            e.printStackTrace();
                        }
                    }
                    
                });
    }
 
Example 12
Source File: InterruptibleHttpClient.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
/** An InterruptibleHttpClient usign {@code HttpAsyncClients.createDefault()}
 * as HttpAsyncClientProducer. */
public InterruptibleHttpClient ()
{
   clientProducer = new HttpAsyncClientProducer ()
   {
      @Override
      public CloseableHttpAsyncClient generateClient ()
      {
         CloseableHttpAsyncClient res = HttpAsyncClients.createDefault ();
         res.start ();
         return res;
      }
   };
}
 
Example 13
Source File: HttpPostDeliverService.java    From cicada with MIT License 5 votes vote down vote up
public HttpPostDeliverService(final String postUrl, final int connectTimeout, final int soTimeout) {
  httpClient = HttpAsyncClients.createDefault();
  httpClient.start();

  httpPost = new HttpPost(postUrl);
  final RequestConfig requestConfig =
      RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(soTimeout).build();
  httpPost.setConfig(requestConfig);

  httpPost.setHeader("Content-type", "application/json");
  httpPost.setHeader("Content-Type", "text/html;charset=UTF-8");
}
 
Example 14
Source File: TestRpcClient.java    From kbear with Apache License 2.0 5 votes vote down vote up
public TestRpcClient(String serviceUrl, Map<String, String> procedureRestPathMap) {
    _serviceUrl = serviceUrl;
    _procedureRestPathMap = procedureRestPathMap;

    _syncClient = HttpClients.createDefault();
    _asyncClient = HttpAsyncClients.createDefault();
}
 
Example 15
Source File: ZeroCopyHttpExchange.java    From yunpian-java-sdk with MIT License 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    try {
        httpclient.start();
        File upload = new File(args[0]);
        File download = new File(args[1]);
        ZeroCopyPost httpost = new ZeroCopyPost("http://localhost:8080/", upload, ContentType.create("text/plain"));
        ZeroCopyConsumer<File> consumer = new ZeroCopyConsumer<File>(download) {

            @Override
            protected File process(final HttpResponse response, final File file, final ContentType contentType)
                    throws Exception {
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    throw new ClientProtocolException("Upload failed: " + response.getStatusLine());
                }
                return file;
            }

        };
        Future<File> future = httpclient.execute(httpost, consumer, null);
        File result = future.get();
        System.out.println("Response file length: " + result.length());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}
 
Example 16
Source File: AsyncClientCustomContext.java    From yunpian-java-sdk with MIT License 5 votes vote down vote up
public final static void main(String[] args) throws Exception {
	CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
	try {
		// Create a local instance of cookie store
		CookieStore cookieStore = new BasicCookieStore();

		// Create local HTTP context
		HttpClientContext localContext = HttpClientContext.create();
		// Bind custom cookie store to the local context
		localContext.setCookieStore(cookieStore);

           HttpGet httpget = new HttpGet("http://localhost/");
		System.out.println("Executing request " + httpget.getRequestLine());

		httpclient.start();

		// Pass local context as a parameter
		Future<HttpResponse> future = httpclient.execute(httpget, localContext, null);

		// Please note that it may be unsafe to access HttpContext instance
		// while the request is still being executed

		HttpResponse response = future.get();
		System.out.println("Response: " + response.getStatusLine());
		List<Cookie> cookies = cookieStore.getCookies();
		for (int i = 0; i < cookies.size(); i++) {
			System.out.println("Local cookie: " + cookies.get(i));
		}
		System.out.println("Shutting down");
	} finally {
		httpclient.close();
	}
}
 
Example 17
Source File: TestHttpAsyncClient.java    From aliyun-tsdb-java-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpAsyncClient() throws InterruptedException, IOException {
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();

    final CountDownLatch latch1 = new CountDownLatch(1);
    final HttpGet request2 = new HttpGet("http://www.apache.org/");
    httpclient.execute(request2, new FutureCallback<HttpResponse>() {

        public void completed(final HttpResponse response2) {
            latch1.countDown();
            System.out.println(request2.getRequestLine() + "->" + response2.getStatusLine());
        }

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

        public void cancelled() {
            latch1.countDown();
            System.out.println(request2.getRequestLine() + " cancelled");
        }

    });

    latch1.await();
}
 
Example 18
Source File: MDEAnalysisUsingIterables.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
public void runSearch() {
	try {

		// Cache cache = new Cache(new File("cache/"), 1000 * 1024 * 1024);
		// // 1GB cache
		// OkHttpClient client = new OkHttpClient().setCache(cache);
		// OkUrlFactory urlFactory = new OkUrlFactory(client);
		// HttpConnector connector = new ImpatientHttpConnector(new
		// OkHttpConnector(urlFactory),
		// DEFAULT_CONNECTION_TIMEOUT_IN_MILLI_SECONDS,
		// DEFAULT_READ_TIMEOUT_IN_MILLI_SECONDS);

		// GitHub github = new GitHubBuilder().withPassword(githubUserName,
		// githubUserPass).withConnector(connector).withAbuseLimitHandler(AbuseLimitHandler.WAIT).withRateLimitHandler(RateLimitHandler.WAIT).build();

		//

		localApi = GitHubUtils.getOAuthClient();
		asyncClient = HttpAsyncClients.createDefault();

		LOG.info("DAEMON? " + Thread.currentThread().isDaemon());
		
		String query = currentMDE.query();
		LOG.info(query);
		IDataSet<SearchCode> searchCode = localApi.getSearchCode("asc", query, null);

		List<SearchCode> searchCodeList = searchCode.observe().toList().blockingGet();

		totalCount = searchCodeList.size();
		logger.info("TOTAL RESULT COUNT: " + Integer.toString(totalCount));

		int currResNo = 1;

		HashSet<String> repoNameSet = new HashSet<>();
		// files
		for (SearchCode initialResultItem : searchCodeList) {
			Repository initialResultRepo = initialResultItem.getRepository();
			String initialResultItemFullRepoName = initialResultRepo.getFullName();

			if (!repoNameSet.contains(initialResultItemFullRepoName)) {

				String q = new CodeSearchQuery().create(currentMDE.getKeyword())
						.extension(currentMDE.getExtension()).repo(initialResultItemFullRepoName).build()
						.getQuery();
				// System.err.println(q);
				IDataSet<SearchCode> ret = GitHubUtils.getOAuthClient().getSearchCode("asc", q, null);

				List<SearchCode> repoFiles = ret.observe().toList().blockingGet();

				// files in current repo
				for (SearchCode resultItem : repoFiles) {

					Repository resultRepo = resultItem.getRepository();
					String resultItemPath = java.net.URLDecoder.decode(resultItem.getPath(), "UTF-8");
					String resultItemFullRepoName = resultRepo.getFullName();
					// String resultItemDownloadUrl =
					// java.net.URLDecoder.decode(resultItem.getDownloadUrl(),"UTF-8");

					// commits of file
					List<Commits> commits = GitHubUtils
							.getOAuthClient().getReposCommits(resultRepo.getOwner().getLogin(),
									resultRepo.getName(), null, null, resultItem.getPath(), null, null)
							.observe().toList().blockingGet();

					for (Commits commit : commits) {
						String authorEmail = commit.getCommit().getCommitterInner().getEmail();
						int count = 0;
						String tableKey = resultItemFullRepoName + ";" + commit.getCommit().getUrl();
						if (resultTable.get(tableKey, authorEmail) != null) {
							count = resultTable.get(tableKey, authorEmail);
						}
						resultTable.put(tableKey, authorEmail, count + 1);
						++totalCommitCount;
					} // commits of file

					logger.info("ADDED (" + currResNo + " of " + totalCount + "): " + resultItemFullRepoName);
					++currResNo;

				}

			} // files in current repo

		} // files end

		logger.info("TOTAL COMMIT COUNT: " + totalCommitCount);
		logger.info("=============== RESULT TABLE PRINTOUT ===============");
		logger.info(resultTable.toString());
		logger.info("=============== RESULT TABLE PRINTOUT (END) =========");

	} catch (Exception e1) {
		logger.info("Failed to connect to GitHub (bad credentials or timeout).");
		e1.printStackTrace();
	}
}
 
Example 19
Source File: TestHttpAsyncClient.java    From aliyun-tsdb-java-sdk with Apache License 2.0 4 votes vote down vote up
@Before
public void init() {
    httpclient = HttpAsyncClients.createDefault();
}
 
Example 20
Source File: ApacheHttpAsyncClientInstrumentationTest.java    From apm-agent-java with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void setUp() {
    client = HttpAsyncClients.createDefault();
    client.start();
}