Search in sources :

Example 31 with WebClient

use of io.helidon.webclient.WebClient in project helidon by oracle.

the class OidcSupport method processCode.

private void processCode(String code, ServerRequest req, ServerResponse res) {
    WebClient webClient = oidcConfig.appWebClient();
    FormParams.Builder form = FormParams.builder().add("grant_type", "authorization_code").add("code", code).add("redirect_uri", redirectUri(req));
    WebClientRequestBuilder post = webClient.post().uri(oidcConfig.tokenEndpointUri()).accept(io.helidon.common.http.MediaType.APPLICATION_JSON);
    oidcConfig.updateRequest(OidcConfig.RequestType.CODE_TO_TOKEN, post, form);
    OidcConfig.postJsonResponse(post, form.build(), json -> processJsonResponse(req, res, json), (status, errorEntity) -> processError(res, status, errorEntity), (t, message) -> processError(res, t, message)).ignoreElement();
}
Also used : Security(io.helidon.security.Security) WebClient(io.helidon.webclient.WebClient) HashMap(java.util.HashMap) Level(java.util.logging.Level) OidcCookieHandler(io.helidon.security.providers.oidc.common.OidcCookieHandler) Matcher(java.util.regex.Matcher) OidcConfig(io.helidon.security.providers.oidc.common.OidcConfig) Map(java.util.Map) FormParams(io.helidon.common.http.FormParams) ServerResponse(io.helidon.webserver.ServerResponse) JsonObject(jakarta.json.JsonObject) WebSecurity(io.helidon.security.integration.webserver.WebSecurity) URI(java.net.URI) Service(io.helidon.webserver.Service) Http(io.helidon.common.http.Http) Config(io.helidon.config.Config) CrossOriginConfig(io.helidon.webserver.cors.CrossOriginConfig) Logger(java.util.logging.Logger) ServerRequest(io.helidon.webserver.ServerRequest) List(java.util.List) ResponseHeaders(io.helidon.webserver.ResponseHeaders) CorsSupport(io.helidon.webserver.cors.CorsSupport) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) Routing(io.helidon.webserver.Routing) WebClientRequestBuilder(io.helidon.webclient.WebClientRequestBuilder) FormParams(io.helidon.common.http.FormParams) WebClient(io.helidon.webclient.WebClient) WebClientRequestBuilder(io.helidon.webclient.WebClientRequestBuilder)

Example 32 with WebClient

use of io.helidon.webclient.WebClient in project helidon by oracle.

the class PrematureConnectionCutTest method cutConnectionBefore100Continue.

@Test
void cutConnectionBefore100Continue() {
    List<Exception> exceptions = Collections.synchronizedList(new ArrayList<>());
    TestAsyncRunner asyncRunner = null;
    WebServer webServer = null;
    try {
        final TestAsyncRunner async = asyncRunner = new TestAsyncRunner(CALL_NUM);
        webServer = WebServer.builder().host("localhost").port(0).routing(Routing.builder().post((req, res) -> req.content().as(InputStream.class).thenAccept(is -> async.run(() -> {
            try {
                // this is where thread could get blocked indefinitely
                is.readAllBytes();
            } catch (IOException e) {
                exceptions.add(e);
            } finally {
                res.send();
            }
        })))).build().start().await(TIMEOUT);
        WebClient webClient = WebClient.builder().baseUri("http://localhost:" + webServer.port()).build();
        for (int i = 0; i < CALL_NUM; i++) {
            // Sending request with fake content length, but not continuing after 100 code
            incomplete100Call(webClient);
        }
        // Wait for all threads to finish
        asyncRunner.await();
        assertThat("All threads didn't finish in time, probably deadlocked.", asyncRunner.finishedThreads.get(), is(CALL_NUM));
        assertThat("All exceptions were not delivered, when connection closed.", exceptions.size(), is(CALL_NUM));
        exceptions.forEach(e -> {
            assertThat(e.getCause(), anyOf(// ISE: Channel closed prematurely by other side! - on Linux
            instanceOf(IllegalStateException.class), instanceOf(IOException.class)));
        });
    } finally {
        Optional.ofNullable(webServer).ifPresent(ws -> ws.shutdown().await(TIMEOUT));
        Optional.ofNullable(asyncRunner).ifPresent(TestAsyncRunner::shutdown);
    }
}
Also used : WebClient(io.helidon.webclient.WebClient) WebClientResponse(io.helidon.webclient.WebClientResponse) IOException(java.io.IOException) Logger(java.util.logging.Logger) Executors(java.util.concurrent.Executors) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) ChronoUnit(java.time.temporal.ChronoUnit) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) Optional(java.util.Optional) Matchers.is(org.hamcrest.Matchers.is) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Matchers.anyOf(org.hamcrest.Matchers.anyOf) Collections(java.util.Collections) ExecutorService(java.util.concurrent.ExecutorService) InputStream(java.io.InputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) WebClient(io.helidon.webclient.WebClient) IOException(java.io.IOException) Test(org.junit.jupiter.api.Test)

Example 33 with WebClient

use of io.helidon.webclient.WebClient in project helidon by oracle.

the class ResponseOrderingTest method testContentOrdering.

@Test
public void testContentOrdering() throws Exception {
    WebClient webClient = WebClient.builder().baseUri("http://0.0.0.0:" + webServer.port() + "/stream").build();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 10000; i++) {
        sb.append(i).append("\n");
    }
    webClient.post().contentType(MediaType.APPLICATION_OCTET_STREAM).submit(sb.toString().getBytes(), String.class).thenAccept(it -> assertThat(it, is(sb.toString())));
}
Also used : WebClient(io.helidon.webclient.WebClient) Test(org.junit.jupiter.api.Test)

Example 34 with WebClient

use of io.helidon.webclient.WebClient in project helidon by oracle.

the class MainTest method routing.

@ParameterizedTest
@ValueSource(strings = { "se", "mp" })
void routing(String edition) throws Exception {
    HelidonApplication application = startTheApplication(editionToJarPath(edition), Collections.emptyList());
    WebClient webClient = WebClient.builder().baseUri(application.getBaseUrl()).addMediaSupport(JsonpSupport.create()).build();
    webClient.get().accept(MediaType.APPLICATION_JSON).skipUriEncoding().path("/boo%6bs").request().thenAccept(it -> {
        if ("se".equals(edition)) {
            assertThat("Checking encode URL response SE", it.status(), is(Http.Status.OK_200));
        } else {
            // JAXRS does not decode URLs before matching
            assertThat("Checking encode URL response MP", it.status(), is(Http.Status.NOT_FOUND_404));
        }
    }).toCompletableFuture().get();
    webClient.get().accept(MediaType.APPLICATION_JSON).path("/badurl").request().thenAccept(it -> assertThat("Checking encode URL response", it.status(), is(Http.Status.NOT_FOUND_404))).toCompletableFuture().get();
    application.stop();
}
Also used : WebClient(io.helidon.webclient.WebClient) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 35 with WebClient

use of io.helidon.webclient.WebClient in project helidon by oracle.

the class MainTest method runJsonFunctionalTest.

/**
 * Run some basic CRUD operations on the server. The server supports
 * running with any of our three JSON libraries: jsonp, jsonb, jackson.
 * So we set a system property to select the library to use before starting
 * the server
 *
 * @param edition     "mp", "se"
 * @param jsonLibrary "jsonp", "jsonb" or "jackson"
 * @throws Exception on test failure
 */
private void runJsonFunctionalTest(String edition, String jsonLibrary) throws Exception {
    JsonObject json = getBookAsJsonObject();
    int numberOfBooks = 1000;
    List<String> systemPropertyArgs = new LinkedList<>();
    systemPropertyArgs.add("-Dbookstore.size=" + numberOfBooks);
    if (jsonLibrary != null && !jsonLibrary.isEmpty()) {
        systemPropertyArgs.add("-Dapp.json-library=" + jsonLibrary);
    }
    HelidonApplication application = startTheApplication(editionToJarPath(edition), systemPropertyArgs);
    WebClient webClient = WebClient.builder().baseUri(application.getBaseUrl()).addMediaSupport(JsonpSupport.create()).build();
    webClient.get().path("/books").request(JsonArray.class).thenAccept(bookArray -> assertThat("Number of books", bookArray.size(), is(numberOfBooks))).toCompletableFuture().get();
    webClient.post().path("/books").submit(json).thenAccept(it -> assertThat("HTTP response POST", it.status(), is(Http.Status.OK_200))).thenCompose(it -> webClient.get().path("/books/123456").request(JsonObject.class)).thenAccept(it -> assertThat("Checking if correct ISBN", it.getString("isbn"), is("123456"))).toCompletableFuture().get();
    webClient.get().path("/books/0000").request().thenAccept(it -> assertThat("HTTP response GET bad ISBN", it.status(), is(Http.Status.NOT_FOUND_404))).toCompletableFuture().get();
    webClient.get().path("/books").request().thenApply(it -> {
        assertThat("HTTP response list books", it.status(), is(Http.Status.OK_200));
        return it;
    }).thenCompose(WebClientResponse::close).toCompletableFuture().get();
    webClient.delete().path("/books/123456").request().thenAccept(it -> assertThat("HTTP response delete book", it.status(), is(Http.Status.OK_200))).toCompletableFuture().get();
    application.stop();
}
Also used : JsonArray(jakarta.json.JsonArray) HttpURLConnection(java.net.HttpURLConnection) CoreMatchers.is(org.hamcrest.CoreMatchers.is) CapturingApplicationConsole(com.oracle.bedrock.runtime.console.CapturingApplicationConsole) WebClient(io.helidon.webclient.WebClient) WebClientResponse(io.helidon.webclient.WebClientResponse) URL(java.net.URL) CoreMatchers.startsWith(org.hamcrest.CoreMatchers.startsWith) Disabled(org.junit.jupiter.api.Disabled) ArrayList(java.util.ArrayList) MediaType(io.helidon.common.http.MediaType) JsonpSupport(io.helidon.media.jsonp.JsonpSupport) Console(com.oracle.bedrock.runtime.options.Console) BeforeAll(org.junit.jupiter.api.BeforeAll) JsonObject(jakarta.json.JsonObject) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) LinkedList(java.util.LinkedList) Http(io.helidon.common.http.Http) Application(com.oracle.bedrock.runtime.Application) ValueSource(org.junit.jupiter.params.provider.ValueSource) LocalPlatform(com.oracle.bedrock.runtime.LocalPlatform) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) Logger(java.util.logging.Logger) File(java.io.File) Arguments(com.oracle.bedrock.runtime.options.Arguments) Json(jakarta.json.Json) Test(org.junit.jupiter.api.Test) List(java.util.List) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Paths(java.nio.file.Paths) Assertions(org.junit.jupiter.api.Assertions) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) Queue(java.util.Queue) Collections(java.util.Collections) JsonArray(jakarta.json.JsonArray) InputStream(java.io.InputStream) WebClientResponse(io.helidon.webclient.WebClientResponse) JsonObject(jakarta.json.JsonObject) WebClient(io.helidon.webclient.WebClient) LinkedList(java.util.LinkedList)

Aggregations

WebClient (io.helidon.webclient.WebClient)58 Test (org.junit.jupiter.api.Test)42 WebClientResponse (io.helidon.webclient.WebClientResponse)21 JsonObject (jakarta.json.JsonObject)15 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)13 Http (io.helidon.common.http.Http)11 Config (io.helidon.config.Config)11 Collections (java.util.Collections)10 WebClientRequestBuilder (io.helidon.webclient.WebClientRequestBuilder)9 WebClientService (io.helidon.webclient.spi.WebClientService)9 Json (jakarta.json.Json)9 JsonBuilderFactory (jakarta.json.JsonBuilderFactory)8 IOException (java.io.IOException)8 DataChunk (io.helidon.common.http.DataChunk)7 JsonpSupport (io.helidon.media.jsonp.JsonpSupport)7 CompletionException (java.util.concurrent.CompletionException)7 Context (io.helidon.common.context.Context)6 List (java.util.List)6 TimeUnit (java.util.concurrent.TimeUnit)6 Counter (org.eclipse.microprofile.metrics.Counter)6