Search in sources :

Example 16 with RequestBuilder

use of org.asynchttpclient.RequestBuilder in project async-http-client by AsyncHttpClient.

the class ChunkingTest method doTestWithInputStreamBodyGenerator.

public void doTestWithInputStreamBodyGenerator(InputStream is) throws Throwable {
    try (AsyncHttpClient c = asyncHttpClient(httpClientBuilder())) {
        RequestBuilder builder = post(getTargetUrl()).setBody(new InputStreamBodyGenerator(is));
        Request r = builder.build();
        final ListenableFuture<Response> responseFuture = c.executeRequest(r);
        waitForAndAssertResponse(responseFuture);
    }
}
Also used : Response(org.asynchttpclient.Response) RequestBuilder(org.asynchttpclient.RequestBuilder) InputStreamBodyGenerator(org.asynchttpclient.request.body.generator.InputStreamBodyGenerator) Request(org.asynchttpclient.Request) AsyncHttpClient(org.asynchttpclient.AsyncHttpClient)

Example 17 with RequestBuilder

use of org.asynchttpclient.RequestBuilder in project async-http-client by AsyncHttpClient.

the class AsyncHttpClientCallFactoryTest method shouldApplyAllConsumersToCallBeingConstructed.

@Test
void shouldApplyAllConsumersToCallBeingConstructed() {
    // given
    val httpClient = mock(AsyncHttpClient.class);
    val rewriteUrl = "http://foo.bar.com/";
    val headerName = "X-Header";
    val headerValue = UUID.randomUUID().toString();
    val numCustomized = new AtomicInteger();
    val numRequestStart = new AtomicInteger();
    val numRequestSuccess = new AtomicInteger();
    val numRequestFailure = new AtomicInteger();
    Consumer<RequestBuilder> requestCustomizer = requestBuilder -> {
        requestBuilder.setUrl(rewriteUrl).setHeader(headerName, headerValue);
        numCustomized.incrementAndGet();
    };
    Consumer<AsyncHttpClientCall.AsyncHttpClientCallBuilder> callCustomizer = callBuilder -> callBuilder.requestCustomizer(requestCustomizer).requestCustomizer(rb -> log.warn("I'm customizing: {}", rb)).onRequestSuccess(createConsumer(numRequestSuccess)).onRequestFailure(createConsumer(numRequestFailure)).onRequestStart(createConsumer(numRequestStart));
    // create factory
    val factory = AsyncHttpClientCallFactory.builder().callCustomizer(callCustomizer).httpClient(httpClient).build();
    // when
    val call = (AsyncHttpClientCall) factory.newCall(REQUEST);
    val callRequest = call.createRequest(call.request());
    // then
    assertTrue(numCustomized.get() == 1);
    assertTrue(numRequestStart.get() == 0);
    assertTrue(numRequestSuccess.get() == 0);
    assertTrue(numRequestFailure.get() == 0);
    // let's see whether request customizers did their job
    // final async-http-client request should have modified URL and one
    // additional header value.
    assertEquals(callRequest.getUrl(), rewriteUrl);
    assertEquals(callRequest.getHeaders().get(headerName), headerValue);
    // final call should have additional consumers set
    assertNotNull(call.getOnRequestStart());
    assertTrue(call.getOnRequestStart().size() == 1);
    assertNotNull(call.getOnRequestSuccess());
    assertTrue(call.getOnRequestSuccess().size() == 1);
    assertNotNull(call.getOnRequestFailure());
    assertTrue(call.getOnRequestFailure().size() == 1);
    assertNotNull(call.getRequestCustomizers());
    assertTrue(call.getRequestCustomizers().size() == 2);
}
Also used : lombok.val(lombok.val) Request(okhttp3.Request) AsyncHttpClient(org.asynchttpclient.AsyncHttpClient) lombok.val(lombok.val) Test(org.testng.annotations.Test) UUID(java.util.UUID) AsyncHttpClientCallTest.createConsumer(org.asynchttpclient.extras.retrofit.AsyncHttpClientCallTest.createConsumer) Consumer(java.util.function.Consumer) REQUEST(org.asynchttpclient.extras.retrofit.AsyncHttpClientCallTest.REQUEST) Slf4j(lombok.extern.slf4j.Slf4j) Assert(org.testng.Assert) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Response(okhttp3.Response) RequestBuilder(org.asynchttpclient.RequestBuilder) Mockito.mock(org.mockito.Mockito.mock) RequestBuilder(org.asynchttpclient.RequestBuilder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.testng.annotations.Test)

Example 18 with RequestBuilder

use of org.asynchttpclient.RequestBuilder in project async-http-client by AsyncHttpClient.

the class ProxyUnauthorized407Interceptor method exitAfterHandling407.

public boolean exitAfterHandling407(Channel channel, NettyResponseFuture<?> future, HttpResponse response, Request request, ProxyServer proxyServer, HttpRequest httpRequest) {
    if (future.isAndSetInProxyAuth(true)) {
        LOGGER.info("Can't handle 407 as auth was already performed");
        return false;
    }
    Realm proxyRealm = future.getProxyRealm();
    if (proxyRealm == null) {
        LOGGER.debug("Can't handle 407 as there's no proxyRealm");
        return false;
    }
    List<String> proxyAuthHeaders = response.headers().getAll(PROXY_AUTHENTICATE);
    if (proxyAuthHeaders.isEmpty()) {
        LOGGER.info("Can't handle 407 as response doesn't contain Proxy-Authenticate headers");
        return false;
    }
    // FIXME what's this???
    future.setChannelState(ChannelState.NEW);
    HttpHeaders requestHeaders = new DefaultHttpHeaders(false).add(request.getHeaders());
    switch(proxyRealm.getScheme()) {
        case BASIC:
            if (getHeaderWithPrefix(proxyAuthHeaders, "Basic") == null) {
                LOGGER.info("Can't handle 407 with Basic realm as Proxy-Authenticate headers don't match");
                return false;
            }
            if (proxyRealm.isUsePreemptiveAuth()) {
                // FIXME do we need this, as future.getAndSetAuth
                // was tested above?
                // auth was already performed, most likely auth
                // failed
                LOGGER.info("Can't handle 407 with Basic realm as auth was preemptive and already performed");
                return false;
            }
            // FIXME do we want to update the realm, or directly
            // set the header?
            Realm newBasicRealm = realm(proxyRealm).setUsePreemptiveAuth(true).build();
            future.setProxyRealm(newBasicRealm);
            break;
        case DIGEST:
            String digestHeader = getHeaderWithPrefix(proxyAuthHeaders, "Digest");
            if (digestHeader == null) {
                LOGGER.info("Can't handle 407 with Digest realm as Proxy-Authenticate headers don't match");
                return false;
            }
            Realm newDigestRealm = realm(proxyRealm).setUri(request.getUri()).setMethodName(request.getMethod()).setUsePreemptiveAuth(true).parseProxyAuthenticateHeader(digestHeader).build();
            future.setProxyRealm(newDigestRealm);
            break;
        case NTLM:
            String ntlmHeader = getHeaderWithPrefix(proxyAuthHeaders, "NTLM");
            if (ntlmHeader == null) {
                LOGGER.info("Can't handle 407 with NTLM realm as Proxy-Authenticate headers don't match");
                return false;
            }
            ntlmProxyChallenge(ntlmHeader, requestHeaders, proxyRealm, future);
            Realm newNtlmRealm = realm(proxyRealm).setUsePreemptiveAuth(true).build();
            future.setProxyRealm(newNtlmRealm);
            break;
        case KERBEROS:
        case SPNEGO:
            if (getHeaderWithPrefix(proxyAuthHeaders, NEGOTIATE) == null) {
                LOGGER.info("Can't handle 407 with Kerberos or Spnego realm as Proxy-Authenticate headers don't match");
                return false;
            }
            try {
                kerberosProxyChallenge(proxyServer, requestHeaders);
            } catch (SpnegoEngineException e) {
                // FIXME
                String ntlmHeader2 = getHeaderWithPrefix(proxyAuthHeaders, "NTLM");
                if (ntlmHeader2 != null) {
                    LOGGER.warn("Kerberos/Spnego proxy auth failed, proceeding with NTLM");
                    ntlmProxyChallenge(ntlmHeader2, requestHeaders, proxyRealm, future);
                    Realm newNtlmRealm2 = realm(proxyRealm).setScheme(AuthScheme.NTLM).setUsePreemptiveAuth(true).build();
                    future.setProxyRealm(newNtlmRealm2);
                } else {
                    requestSender.abort(channel, future, e);
                    return false;
                }
            }
            break;
        default:
            throw new IllegalStateException("Invalid Authentication scheme " + proxyRealm.getScheme());
    }
    RequestBuilder nextRequestBuilder = new RequestBuilder(future.getCurrentRequest()).setHeaders(requestHeaders);
    if (future.getCurrentRequest().getUri().isSecured()) {
        nextRequestBuilder.setMethod(CONNECT);
    }
    final Request nextRequest = nextRequestBuilder.build();
    LOGGER.debug("Sending proxy authentication to {}", request.getUri());
    if (future.isKeepAlive() && !HttpUtil.isTransferEncodingChunked(httpRequest) && !HttpUtil.isTransferEncodingChunked(response)) {
        future.setConnectAllowed(true);
        future.setReuseChannel(true);
        requestSender.drainChannelAndExecuteNextRequest(channel, future, nextRequest);
    } else {
        channelManager.closeChannel(channel);
        requestSender.sendNextRequest(nextRequest, future);
    }
    return true;
}
Also used : RequestBuilder(org.asynchttpclient.RequestBuilder) SpnegoEngineException(org.asynchttpclient.spnego.SpnegoEngineException) Request(org.asynchttpclient.Request) Realm(org.asynchttpclient.Realm)

Example 19 with RequestBuilder

use of org.asynchttpclient.RequestBuilder in project async-http-client by AsyncHttpClient.

the class TimeToLiveIssue method testTTLBug.

@Test(enabled = false, description = "https://github.com/AsyncHttpClient/async-http-client/issues/1113")
public void testTTLBug() throws Throwable {
    try (AsyncHttpClient client = asyncHttpClient(config().setKeepAlive(true).setConnectionTtl(1).setPooledConnectionIdleTimeout(1))) {
        for (int i = 0; i < 200000; ++i) {
            Request request = new RequestBuilder().setUrl(String.format("http://localhost:%d/", port1)).build();
            Future<Response> future = client.executeRequest(request);
            future.get(5, TimeUnit.SECONDS);
            // from sometimes winning over poll for the ownership of a connection.
            if (System.currentTimeMillis() % 100 == 0) {
                Thread.sleep(5);
            }
        }
    }
}
Also used : Response(org.asynchttpclient.Response) RequestBuilder(org.asynchttpclient.RequestBuilder) Request(org.asynchttpclient.Request) AsyncHttpClient(org.asynchttpclient.AsyncHttpClient) AbstractBasicTest(org.asynchttpclient.AbstractBasicTest) Test(org.testng.annotations.Test)

Example 20 with RequestBuilder

use of org.asynchttpclient.RequestBuilder in project async-http-client by AsyncHttpClient.

the class WebDavBasicTest method mkcolWebDavTest2.

@Test(groups = "standalone")
public void mkcolWebDavTest2() throws InterruptedException, IOException, ExecutionException {
    try (AsyncHttpClient c = asyncHttpClient()) {
        Request mkcolRequest = new RequestBuilder("MKCOL").setUrl(getTargetUrl() + "/folder2").build();
        Response response = c.executeRequest(mkcolRequest).get();
        assertEquals(response.getStatusCode(), 409);
    }
}
Also used : Response(org.asynchttpclient.Response) RequestBuilder(org.asynchttpclient.RequestBuilder) Request(org.asynchttpclient.Request) AsyncHttpClient(org.asynchttpclient.AsyncHttpClient) Test(org.testng.annotations.Test) AbstractBasicTest(org.asynchttpclient.AbstractBasicTest)

Aggregations

RequestBuilder (org.asynchttpclient.RequestBuilder)44 Request (org.asynchttpclient.Request)18 AsyncHttpClient (org.asynchttpclient.AsyncHttpClient)17 Test (org.testng.annotations.Test)17 Response (org.asynchttpclient.Response)14 AbstractBasicTest (org.asynchttpclient.AbstractBasicTest)9 Realm (org.asynchttpclient.Realm)4 SpnegoEngineException (org.asynchttpclient.spnego.SpnegoEngineException)4 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)3 Uri (org.asynchttpclient.uri.Uri)3 DefaultHttpHeaders (io.netty.handler.codec.http.DefaultHttpHeaders)2 HttpRequest (io.netty.handler.codec.http.HttpRequest)2 UUID (java.util.UUID)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 Consumer (java.util.function.Consumer)2 Slf4j (lombok.extern.slf4j.Slf4j)2 lombok.val (lombok.val)2 Request (okhttp3.Request)2 Response (okhttp3.Response)2 REQUEST (org.asynchttpclient.extras.retrofit.AsyncHttpClientCallTest.REQUEST)2