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:com.vanillasource.gerec.httpclient.AsyncApacheHttpClientITTests.java

@BeforeMethod
protected void setUp() {
    change = mock(HttpRequest.HttpRequestChange.class);
    httpClient = HttpAsyncClients.createDefault();
    httpClient.start();// w  ww . ja  v  a 2 s . c  o  m
    client = new AsyncApacheHttpClient(httpClient);
    WireMock.reset();
}

From source file:com.controller.CTraderOrderMANIAC.java

public static List<Block> updateBlockOrderHistory()
        throws InterruptedException, ExecutionException, IOException, JSONException {
    String currUsername = CMAIN.reportUser().getUsername();
    HttpResponse<JsonNode> resp;/*from  ww  w.  j av a2 s.c  o  m*/

    //INIT CLIENT
    CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
    client.start();

    //REQUEST
    HttpGet request = new HttpGet("http://139.59.17.119:8080/api/trader/blocks/" + 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());
    JSONArray arrJson = new JSONArray(json_string);
    System.out.println("ASYNC JSONARRAY IS : " + arrJson.toString());

    //PARSE ARRAY INTO SINGLE ORDERS
    ArrayList<Block> arrayBlock = new ArrayList<>();
    for (int i = 0; i < arrJson.length(); i++) {
        JSONObject currentBlock = new JSONObject();
        try {
            currentBlock = arrJson.getJSONObject(i);
        } catch (JSONException ex) {
            Logger.getLogger(CTraderOrderMANIAC.class.getName()).log(Level.SEVERE, null, ex);
        }
        Block currBlock = JsonParsing.parseJsonToBlockObject(currentBlock.toString());
        arrayBlock.add(currBlock);
    }
    blockHistory = arrayBlock;

    //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 (!blockHistory.isEmpty()) {
        return blockHistory;
    } else {
        System.out.println("ASYNC BLOCK HISTORY IS EMPTY.");
        return null;
    }
}

From source file:com.snowplowanalytics.snowplow.tracker.emitter.Emitter.java

/**
 * Sets whether requests should be sent synchronously or asynchronously.
 * @param option The HTTP request method
 *///from   w  w w. j  a va2  s  .  c  o  m
public void setRequestMethod(RequestMethod option) {
    this.requestMethod = option;
    this.httpAsyncClient = HttpAsyncClients.createDefault();
    this.httpAsyncClient.start();
}

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

/**
 * Make http call to specified endpoint with events
 * @param inEvents//w  w  w .  j a va2s.co  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:com.vmware.photon.controller.nsxclient.RestClientTest.java

@Test
public void testCheckResponseMatch() {
    RestClient restClient = new RestClient(target, username, password, HttpAsyncClients.createDefault());

    HttpResponse httpResponse = mock(HttpResponse.class);
    StatusLine statusLine = mock(StatusLine.class);
    when(httpResponse.getStatusLine()).thenReturn(statusLine);
    when(statusLine.getStatusCode()).thenReturn(404);

    restClient.check(httpResponse, 404);
}

From source file:com.vmware.photon.controller.nsxclient.RestClientTest.java

@Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "HTTP request failed with: 404")
public void testCheckResponseMismatch() {
    RestClient restClient = new RestClient(target, username, password, HttpAsyncClients.createDefault());

    HttpResponse httpResponse = mock(HttpResponse.class);
    StatusLine statusLine = mock(StatusLine.class);
    when(httpResponse.getStatusLine()).thenReturn(statusLine);
    when(statusLine.getStatusCode()).thenReturn(404);

    restClient.check(httpResponse, 200);
}

From source file:UnitTest4.java

public static void execute()
        throws ClientProtocolException, IOException, InterruptedException, ExecutionException {
    /*/*from  w  w  w.  ja  va2s  .com*/
      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");
    */

    /*
    try (CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault()) {
        httpclient.start();
        HttpPost request = new HttpPost(addr);
        StringEntity entity = new StringEntity(event, ContentType.create("application/json", Consts.UTF_8));
        request.setEntity(entity);
        httpclient.execute(request, null);
    } catch (Exception e) {
        LOG.error("Failed to sending event", e);
    }
    */
    //Asserts a;
    CloseableHttpAsyncClient m_httpClient = HttpAsyncClients.createDefault();

    m_httpClient.start();

    HttpHost m_target = new HttpHost("localhost", 5000, "http");
    //HttpPost postRequest = new HttpPost("http://localhost:5000/hello");
    HttpPost postRequest = new HttpPost("/");

    StringEntity params = new StringEntity("");

    postRequest.addHeader("content-type", "application/json");
    postRequest.setEntity(params);

    log.debug("execute() executing request to " + m_target);

    //HttpAsyncRequestConsumer<HttpRequest> gh;

    // works HttpResponse httpResponse = httpClient.execute(target, getRequest);
    Future<HttpResponse> future = m_httpClient.execute(m_target, postRequest, null);
    //Future<HttpResponse> future = m_httpClient.execute(postRequest, null);
    //HttpResponse httpResponse = future.get();
    while (future.isDone() == false) {
        log.debug("Inside while");
    }
    HttpResponse httpResponse = null;
    try {
        httpResponse = future.get(100, TimeUnit.NANOSECONDS);
    } catch (TimeoutException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    HttpEntity entity = httpResponse.getEntity();

    log.debug("execute()----------------------------------------");
    log.debug("execute() {}", httpResponse.getStatusLine());
    Header[] headers = httpResponse.getAllHeaders();
    for (int i = 0; i < headers.length; i++) {
        log.debug("execute() {}", headers[i]);
    }
    log.debug("execute()----------------------------------------");

    String jsonString = null;
    if (entity != null) {
        jsonString = EntityUtils.toString(entity);
        log.debug("execute() {}", jsonString);
    }

}

From source file:com.vmware.photon.controller.client.RestClientTest.java

@Test
public void testCheckResponseMatch() {
    RestClient restClient = new RestClient(endpoint, HttpAsyncClients.createDefault());

    HttpResponse httpResponse = mock(HttpResponse.class);
    StatusLine statusLine = mock(StatusLine.class);
    when(httpResponse.getStatusLine()).thenReturn(statusLine);
    when(statusLine.getStatusCode()).thenReturn(404);

    restClient.checkResponse(httpResponse, 404);
}

From source file:org.apache.camel.component.olingo2.api.impl.Olingo2AppImpl.java

/**
 * Create Olingo2 Application with custom HTTP client builder.
 *
 * @param serviceUri Service Application base URI.
 * @param builder custom HTTP client builder.
 *///from   w  w  w.j av  a 2 s  .c  o m
public Olingo2AppImpl(String serviceUri, HttpAsyncClientBuilder builder) {
    setServiceUri(serviceUri);

    if (builder == null) {
        this.client = HttpAsyncClients.createDefault();
    } else {
        this.client = builder.build();
    }
    this.client.start();
    this.contentType = ContentType.create("application/json", Consts.UTF_8);
}