Search in sources :

Example 1 with RedirectConfigBuilder

use of io.servicetalk.http.api.RedirectConfigBuilder in project servicetalk by apple.

the class MultiAddressUrlRedirectClient method main.

public static void main(String... args) throws Exception {
    try (HttpClient client = HttpClients.forMultiAddressUrl().followRedirects(new RedirectConfigBuilder().maxRedirects(3).allowNonRelativeRedirects(true).allowedMethods(GET, POST).redirectPredicate((relative, redirectCount, prevRequest, redirectResponse) -> // allow only relative redirects
    relative || // OR non-relative redirects to a trusted server:
    redirectResponse.headers().get(LOCATION, "").toString().startsWith("https://localhost:" + SECURE_SERVER_PORT)).headersToRedirect(CUSTOM_HEADER).redirectPayloadBody(true).redirectRequestTransformer((relative, prevRequest, redirectResponse, redirectedRequest) -> {
        // prevRequest and redirectResponse: check/copy other headers, modify request method, etc.
        return redirectedRequest;
    }).build()).initializer((scheme, address, builder) -> {
        // already provides default SSL configuration and this step may be skipped.
        if ("https".equalsIgnoreCase(scheme)) {
            builder.sslConfig(new ClientSslConfigBuilder(DefaultTestCerts::loadServerCAPem).build());
        }
    }).build()) {
        final String serverThatRedirects = "http://localhost:" + NON_SECURE_SERVER_PORT;
        System.out.println("- Simple GET request:");
        client.request(client.get(serverThatRedirects + "/relative")).whenOnSuccess(resp -> {
            System.out.println(resp.toString((name, value) -> value));
            System.out.println(resp.payloadBody(textSerializerAscii()));
            System.out.println();
        }).toFuture().get();
        System.out.println("- Relative redirect for POST request with headers and payload body:");
        client.request(client.post(serverThatRedirects + "/relative").addHeader(CUSTOM_HEADER, "value").payloadBody(client.executionContext().bufferAllocator().fromAscii("some_content"))).whenOnSuccess(resp -> {
            System.out.println(resp.toString((name, value) -> value));
            System.out.println(resp.payloadBody(textSerializerAscii()));
            System.out.println();
        }).toFuture().get();
        System.out.println("- Non-relative redirect for POST request with headers and payload body:");
        client.request(client.post(serverThatRedirects + "/non-relative").addHeader(CUSTOM_HEADER, "value").payloadBody(client.executionContext().bufferAllocator().fromAscii("some_content"))).whenOnSuccess(resp -> {
            System.out.println(resp.toString((name, value) -> value));
            System.out.println(resp.payloadBody(textSerializerAscii()));
            System.out.println();
        }).toFuture().get();
    }
}
Also used : HttpSerializers.textSerializerAscii(io.servicetalk.http.api.HttpSerializers.textSerializerAscii) HttpRequestMethod(io.servicetalk.http.api.HttpRequestMethod) CUSTOM_HEADER(io.servicetalk.examples.http.redirects.RedirectingServer.CUSTOM_HEADER) LOCATION(io.servicetalk.http.api.HttpHeaderNames.LOCATION) POST(io.servicetalk.http.api.HttpRequestMethod.POST) MultiAddressHttpClientBuilder(io.servicetalk.http.api.MultiAddressHttpClientBuilder) RedirectConfigBuilder(io.servicetalk.http.api.RedirectConfigBuilder) GET(io.servicetalk.http.api.HttpRequestMethod.GET) SECURE_SERVER_PORT(io.servicetalk.examples.http.redirects.RedirectingServer.SECURE_SERVER_PORT) NON_SECURE_SERVER_PORT(io.servicetalk.examples.http.redirects.RedirectingServer.NON_SECURE_SERVER_PORT) RedirectConfig(io.servicetalk.http.api.RedirectConfig) HttpClient(io.servicetalk.http.api.HttpClient) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) HttpClients(io.servicetalk.http.netty.HttpClients) HttpClient(io.servicetalk.http.api.HttpClient) RedirectConfigBuilder(io.servicetalk.http.api.RedirectConfigBuilder) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder)

Example 2 with RedirectConfigBuilder

use of io.servicetalk.http.api.RedirectConfigBuilder in project servicetalk by apple.

the class ExpectContinueTest method serverRespondsWithRedirect.

@ParameterizedTest(name = "protocol={0} withCL={1}")
@MethodSource("arguments")
void serverRespondsWithRedirect(HttpProtocol protocol, boolean withCL) throws Exception {
    try (HttpServerContext serverContext = startServer(protocol, (ctx, request, response) -> {
        if ("/redirect".equals(request.requestTarget())) {
            response.status(PERMANENT_REDIRECT);
            response.setHeader(LOCATION, "/");
            response.sendMetaData().close();
            return;
        }
        requestReceived.countDown();
        sendContinue.await();
        StringBuilder sb = new StringBuilder();
        request.payloadBody().forEach(chunk -> sb.append(chunk.toString(US_ASCII)));
        returnResponse.await();
        try (HttpPayloadWriter<Buffer> writer = response.sendMetaData()) {
            writer.write(ctx.executionContext().bufferAllocator().fromAscii(sb));
        }
    });
        StreamingHttpClient client = createClient(serverContext, protocol, new RedirectingHttpRequesterFilter(new RedirectConfigBuilder().allowedMethods(POST).headersToRedirect(CONTENT_LENGTH, TRANSFER_ENCODING, EXPECT).redirectPayloadBody(true).build()));
        StreamingHttpConnection connection = client.reserveConnection(client.get("/")).toFuture().get()) {
        BufferAllocator allocator = connection.executionContext().bufferAllocator();
        TestPublisher<Buffer> payload = new TestPublisher.Builder<Buffer>().singleSubscriber().build();
        connection.request(newRequest(connection, withCL, false, payload).requestTarget("/redirect")).subscribe(responses::add);
        requestReceived.await();
        assertThat("Unexpected subscribe to payload body before 100 (Continue)", payload.isSubscribed(), is(false));
        sendContinue.countDown();
        sendRequestPayload(payload, allocator);
        returnResponse.countDown();
        assertResponse(OK, PAYLOAD + PAYLOAD);
        sendFollowUpRequest(connection, withCL, allocator, OK);
    }
}
Also used : Buffer(io.servicetalk.buffer.api.Buffer) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) RedirectConfigBuilder(io.servicetalk.http.api.RedirectConfigBuilder) SingleAddressHttpClientBuilder(io.servicetalk.http.api.SingleAddressHttpClientBuilder) HttpServerContext(io.servicetalk.http.api.HttpServerContext) RedirectConfigBuilder(io.servicetalk.http.api.RedirectConfigBuilder) StreamingHttpConnection(io.servicetalk.http.api.StreamingHttpConnection) RedirectingHttpRequesterFilter(io.servicetalk.http.utils.RedirectingHttpRequesterFilter) BufferAllocator(io.servicetalk.buffer.api.BufferAllocator) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 3 with RedirectConfigBuilder

use of io.servicetalk.http.api.RedirectConfigBuilder in project servicetalk by apple.

the class RedirectingHttpRequesterFilterTest method shouldRedirectThrows.

@Test
void shouldRedirectThrows() {
    when(httpClient.request(any())).thenReturn(redirectResponse(MOVED_PERMANENTLY), okResponse());
    StreamingHttpClient client = newClient(new RedirectConfigBuilder().redirectPredicate((relative, count, request, response) -> {
        throw DELIBERATE_EXCEPTION;
    }).build());
    ExecutionException e = assertThrows(ExecutionException.class, () -> client.request(newRequest(client, GET)).toFuture().get());
    assertThat(e.getCause(), sameInstance(DELIBERATE_EXCEPTION));
}
Also used : StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) RedirectConfigBuilder(io.servicetalk.http.api.RedirectConfigBuilder) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 4 with RedirectConfigBuilder

use of io.servicetalk.http.api.RedirectConfigBuilder in project servicetalk by apple.

the class RedirectingHttpRequesterFilterTest method overrideAllowedMethods.

@Test
void overrideAllowedMethods() throws Exception {
    RedirectConfig config = new RedirectConfigBuilder().allowedMethods(POST).build();
    testRedirected(POST, MOVED_PERMANENTLY, config);
    testNoRedirectWasDone(GET, MOVED_PERMANENTLY, config);
    testNoRedirectWasDone(HEAD, MOVED_PERMANENTLY, config);
}
Also used : RedirectConfig(io.servicetalk.http.api.RedirectConfig) RedirectConfigBuilder(io.servicetalk.http.api.RedirectConfigBuilder) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 5 with RedirectConfigBuilder

use of io.servicetalk.http.api.RedirectConfigBuilder in project servicetalk by apple.

the class RedirectingHttpRequesterFilterTest method redirectForOnlyRelativeWithAbsoluteFormRelativeLocationWithPort.

@Test
void redirectForOnlyRelativeWithAbsoluteFormRelativeLocationWithPort() throws Exception {
    when(httpClient.request(any())).thenReturn(redirectResponse(MOVED_PERMANENTLY, "http://servicetalk.io:80"), okResponse());
    StreamingHttpClient client = newClient(new RedirectConfigBuilder().allowNonRelativeRedirects(false).build());
    verifyRedirected(client, newRequest(client, GET).setHeader(HOST, "servicetalk.io:80"), true, false);
}
Also used : StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) RedirectConfigBuilder(io.servicetalk.http.api.RedirectConfigBuilder) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Aggregations

RedirectConfigBuilder (io.servicetalk.http.api.RedirectConfigBuilder)27 StreamingHttpClient (io.servicetalk.http.api.StreamingHttpClient)24 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)23 Test (org.junit.jupiter.api.Test)17 StreamingHttpRequest (io.servicetalk.http.api.StreamingHttpRequest)10 ValueSource (org.junit.jupiter.params.provider.ValueSource)6 ExecutionException (java.util.concurrent.ExecutionException)5 CUSTOM_HEADER (io.servicetalk.examples.http.redirects.RedirectingServer.CUSTOM_HEADER)2 NON_SECURE_SERVER_PORT (io.servicetalk.examples.http.redirects.RedirectingServer.NON_SECURE_SERVER_PORT)2 HttpClient (io.servicetalk.http.api.HttpClient)2 LOCATION (io.servicetalk.http.api.HttpHeaderNames.LOCATION)2 GET (io.servicetalk.http.api.HttpRequestMethod.GET)2 POST (io.servicetalk.http.api.HttpRequestMethod.POST)2 RedirectConfig (io.servicetalk.http.api.RedirectConfig)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 Buffer (io.servicetalk.buffer.api.Buffer)1 BufferAllocator (io.servicetalk.buffer.api.BufferAllocator)1 ServiceDiscoverer (io.servicetalk.client.api.ServiceDiscoverer)1 ServiceDiscovererEvent (io.servicetalk.client.api.ServiceDiscovererEvent)1 AsyncCloseables.newCompositeCloseable (io.servicetalk.concurrent.api.AsyncCloseables.newCompositeCloseable)1