Search in sources :

Example 11 with Callback

use of org.apache.hc.core5.function.Callback in project httpcomponents-core by apache.

the class TestHttpRequestExecutor method testExecutionSkipIntermediateResponses.

@Test
public void testExecutionSkipIntermediateResponses() throws Exception {
    final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class);
    final HttpClientConnection conn = Mockito.mock(HttpClientConnection.class);
    final HttpRequestExecutor executor = new HttpRequestExecutor();
    final HttpCoreContext context = HttpCoreContext.create();
    final ClassicHttpRequest request = new BasicClassicHttpRequest(Method.GET, "/");
    executor.preProcess(request, httprocessor, context);
    Mockito.verify(httprocessor).process(request, request.getEntity(), context);
    Mockito.when(conn.receiveResponseHeader()).thenReturn(new BasicClassicHttpResponse(100, "Continue"), new BasicClassicHttpResponse(110, "Huh?"), new BasicClassicHttpResponse(111, "Huh?"), new BasicClassicHttpResponse(200, "OK"));
    final HttpResponseInformationCallback callback = Mockito.mock(HttpResponseInformationCallback.class);
    final ClassicHttpResponse response = executor.execute(request, conn, callback, context);
    Mockito.verify(conn).sendRequestHeader(request);
    Mockito.verify(conn).flush();
    Mockito.verify(conn, Mockito.times(4)).receiveResponseHeader();
    Mockito.verify(conn, Mockito.times(1)).receiveResponseEntity(response);
    final ArgumentCaptor<HttpResponse> responseCaptor = ArgumentCaptor.forClass(HttpResponse.class);
    Mockito.verify(callback, Mockito.times(2)).execute(responseCaptor.capture(), ArgumentMatchers.eq(conn), ArgumentMatchers.eq(context));
    final List<HttpResponse> infos = responseCaptor.getAllValues();
    Assertions.assertNotNull(infos);
    Assertions.assertEquals(2, infos.size());
    final HttpResponse info1 = infos.get(0);
    Assertions.assertNotNull(info1);
    Assertions.assertEquals(110, info1.getCode());
    final HttpResponse info2 = infos.get(1);
    Assertions.assertNotNull(info2);
    Assertions.assertEquals(111, info2.getCode());
    executor.postProcess(response, httprocessor, context);
    Mockito.verify(httprocessor).process(response, response.getEntity(), context);
    Assertions.assertSame(request, context.getRequest());
    Assertions.assertSame(response, context.getResponse());
}
Also used : BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpResponseInformationCallback(org.apache.hc.core5.http.io.HttpResponseInformationCallback) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) HttpProcessor(org.apache.hc.core5.http.protocol.HttpProcessor) HttpClientConnection(org.apache.hc.core5.http.io.HttpClientConnection) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) Test(org.junit.jupiter.api.Test)

Example 12 with Callback

use of org.apache.hc.core5.function.Callback in project httpcomponents-core by apache.

the class TestBasicFuture method testCancelled.

@Test
public void testCancelled() throws Exception {
    final FutureCallback<Object> callback = Mockito.mock(FutureCallback.class);
    final BasicFuture<Object> future = new BasicFuture<>(callback);
    final Object result = new Object();
    final Exception boom = new Exception();
    future.cancel(true);
    future.failed(boom);
    future.completed(result);
    Mockito.verify(callback, Mockito.never()).completed(Mockito.any());
    Mockito.verify(callback, Mockito.never()).failed(Mockito.any());
    Mockito.verify(callback).cancelled();
    Assertions.assertThrows(CancellationException.class, future::get);
    Assertions.assertTrue(future.isDone());
    Assertions.assertTrue(future.isCancelled());
}
Also used : ExecutionException(java.util.concurrent.ExecutionException) CancellationException(java.util.concurrent.CancellationException) TimeoutException(java.util.concurrent.TimeoutException) TimeoutValueException(org.apache.hc.core5.util.TimeoutValueException) Test(org.junit.jupiter.api.Test)

Example 13 with Callback

use of org.apache.hc.core5.function.Callback in project httpcomponents-core by apache.

the class TestBasicFuture method testCompleted.

@Test
public void testCompleted() throws Exception {
    final FutureCallback<Object> callback = Mockito.mock(FutureCallback.class);
    final BasicFuture<Object> future = new BasicFuture<>(callback);
    Assertions.assertFalse(future.isDone());
    final Object result = new Object();
    final Exception boom = new Exception();
    future.completed(result);
    future.failed(boom);
    Mockito.verify(callback).completed(result);
    Mockito.verify(callback, Mockito.never()).failed(Mockito.any());
    Mockito.verify(callback, Mockito.never()).cancelled();
    Assertions.assertSame(result, future.get());
    Assertions.assertTrue(future.isDone());
    Assertions.assertFalse(future.isCancelled());
}
Also used : ExecutionException(java.util.concurrent.ExecutionException) CancellationException(java.util.concurrent.CancellationException) TimeoutException(java.util.concurrent.TimeoutException) TimeoutValueException(org.apache.hc.core5.util.TimeoutValueException) Test(org.junit.jupiter.api.Test)

Example 14 with Callback

use of org.apache.hc.core5.function.Callback in project para by Erudika.

the class TwitterAuthFilter method stepOne.

private boolean stepOne(HttpServletResponse response, String redirectURI, String[] keys) throws IOException {
    String callback = Utils.urlEncode(redirectURI);
    Map<String, String[]> params = new HashMap<>();
    params.put("oauth_callback", new String[] { callback });
    HttpPost tokenPost = new HttpPost(FLOW_URL1);
    tokenPost.setHeader(HttpHeaders.AUTHORIZATION, OAuth1HmacSigner.sign("POST", FLOW_URL1, params, keys[0], keys[1], null, null));
    tokenPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    try (CloseableHttpResponse resp1 = httpclient.execute(tokenPost)) {
        if (resp1.getCode() == HttpServletResponse.SC_OK) {
            String decoded = EntityUtils.toString(resp1.getEntity());
            EntityUtils.consumeQuietly(resp1.getEntity());
            for (String pair : decoded.split("&")) {
                if (pair.startsWith("oauth_token")) {
                    response.sendRedirect(FLOW_URL2 + pair);
                    return true;
                } else {
                    logger.info("Authentication request failed, token not found in response - " + decoded);
                }
            }
        } else {
            logger.info("Authentication request failed with status '" + resp1.getReasonPhrase() + "' and empty response body.");
        }
    } catch (ParseException e) {
        logger.error(null, e);
    }
    return false;
}
Also used : HttpPost(org.apache.hc.client5.http.classic.methods.HttpPost) HashMap(java.util.HashMap) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) ParseException(org.apache.hc.core5.http.ParseException)

Example 15 with Callback

use of org.apache.hc.core5.function.Callback in project easeagent by megaease.

the class HttpClient5AsyncTracingInterceptorTest method runOne.

private static ReportSpan runOne(final Consumer<FutureCallback<HttpResponse>> consumer) throws InterruptedException {
    SimpleHttpRequest simpleHttpRequest = SimpleHttpRequest.create("GET", "http://127.0.0.1:8080");
    SimpleRequestProducer simpleRequestProducer = SimpleRequestProducer.create(simpleHttpRequest);
    FutureCallback<HttpResponse> callback = new FutureCallback<HttpResponse>() {

        @Override
        public void completed(HttpResponse httpResponse) {
        }

        @Override
        public void failed(Exception e) {
        }

        @Override
        public void cancelled() {
        }
    };
    MethodInfo methodInfo = MethodInfo.builder().args(new Object[] { simpleRequestProducer, null, null, null, callback }).build();
    MockEaseAgent.cleanLastSpan();
    HttpClient5AsyncTracingInterceptor httpClient5AsyncTracingInterceptor = new HttpClient5AsyncTracingInterceptor();
    httpClient5AsyncTracingInterceptor.doBefore(methodInfo, EaseAgent.getContext());
    assertNotNull(EaseAgent.getContext().get(HttpClient5AsyncTracingInterceptor.class));
    httpClient5AsyncTracingInterceptor.doAfter(methodInfo, EaseAgent.getContext());
    assertNull(EaseAgent.getContext().get(HttpClient5AsyncTracingInterceptor.class));
    AtomicReference<FutureCallback<HttpResponse>> newCallBack = new AtomicReference<>();
    for (Object o : methodInfo.getArgs()) {
        if (o instanceof FutureCallback) {
            newCallBack.set((FutureCallback<HttpResponse>) o);
        }
    }
    assertNotNull(newCallBack.get());
    assertNull(MockEaseAgent.getLastSpan());
    Thread thread = new Thread(() -> consumer.accept(newCallBack.get()));
    thread.start();
    thread.join();
    return MockEaseAgent.getLastSpan();
}
Also used : SimpleRequestProducer(org.apache.hc.client5.http.async.methods.SimpleRequestProducer) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) MethodInfo(com.megaease.easeagent.plugin.interceptor.MethodInfo) AtomicReference(java.util.concurrent.atomic.AtomicReference) FutureCallback(org.apache.hc.core5.concurrent.FutureCallback)

Aggregations

Test (org.junit.jupiter.api.Test)10 IOException (java.io.IOException)6 FutureCallback (org.apache.hc.core5.concurrent.FutureCallback)6 CancellationException (java.util.concurrent.CancellationException)5 TimeoutException (java.util.concurrent.TimeoutException)5 HttpResponse (org.apache.hc.core5.http.HttpResponse)5 ExecutionException (java.util.concurrent.ExecutionException)4 ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)4 StringEntity (org.apache.hc.core5.http.io.entity.StringEntity)4 TimeoutValueException (org.apache.hc.core5.util.TimeoutValueException)4 Stopwatch (com.google.common.base.Stopwatch)3 SimpleHttpRequest (org.apache.hc.client5.http.async.methods.SimpleHttpRequest)3 SimpleHttpResponse (org.apache.hc.client5.http.async.methods.SimpleHttpResponse)3 ContentType (org.apache.hc.core5.http.ContentType)3 BasicHeader (org.apache.hc.core5.http.message.BasicHeader)3 BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)2 HttpGet (org.apache.hc.client5.http.classic.methods.HttpGet)2 HttpPost (org.apache.hc.client5.http.classic.methods.HttpPost)2