Search in sources :

Example 21 with Http

use of io.helidon.common.http.Http in project helidon by oracle.

the class AbstractCorsTest method test2PreFlightForbiddenOrigin.

@Test
void test2PreFlightForbiddenOrigin() throws ExecutionException, InterruptedException {
    WebClientRequestBuilder reqBuilder = client().options().path(path(SERVICE_2));
    Headers headers = reqBuilder.headers();
    headers.add(ORIGIN, "http://not.allowed");
    headers.add(ACCESS_CONTROL_REQUEST_METHOD, "PUT");
    WebClientResponse res = reqBuilder.request().toCompletableFuture().get();
    Http.ResponseStatus status = res.status();
    assertThat(status.code(), is(Http.Status.FORBIDDEN_403.code()));
    assertThat(status.reasonPhrase(), is("CORS origin is not in allowed list"));
}
Also used : WebClientResponse(io.helidon.webclient.WebClientResponse) Headers(io.helidon.common.http.Headers) Http(io.helidon.common.http.Http) WebClientRequestBuilder(io.helidon.webclient.WebClientRequestBuilder) Test(org.junit.jupiter.api.Test)

Example 22 with Http

use of io.helidon.common.http.Http in project helidon by oracle.

the class AbstractCorsTest method test2PreFlightForbiddenMethod.

@Test
void test2PreFlightForbiddenMethod() throws ExecutionException, InterruptedException {
    WebClientRequestBuilder reqBuilder = client().options().path(path(SERVICE_2));
    Headers headers = reqBuilder.headers();
    headers.add(ORIGIN, "http://foo.bar");
    headers.add(ACCESS_CONTROL_REQUEST_METHOD, "POST");
    WebClientResponse res = reqBuilder.request().toCompletableFuture().get();
    Http.ResponseStatus status = res.status();
    assertThat(status.code(), is(Http.Status.FORBIDDEN_403.code()));
    assertThat(status.reasonPhrase(), is("CORS origin is denied"));
}
Also used : WebClientResponse(io.helidon.webclient.WebClientResponse) Headers(io.helidon.common.http.Headers) Http(io.helidon.common.http.Http) WebClientRequestBuilder(io.helidon.webclient.WebClientRequestBuilder) Test(org.junit.jupiter.api.Test)

Example 23 with Http

use of io.helidon.common.http.Http in project helidon by oracle.

the class NettyClientHandler method channelRead0.

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws IOException {
    Channel channel = ctx.channel();
    if (msg instanceof HttpResponse) {
        channel.config().setAutoRead(false);
        HttpResponse response = (HttpResponse) msg;
        this.requestId = channel.attr(REQUEST_ID).get();
        channel.attr(RESPONSE_RECEIVED).set(true);
        WebClientRequestImpl clientRequest = channel.attr(REQUEST).get();
        RequestConfiguration requestConfiguration = clientRequest.configuration();
        LOGGER.finest(() -> "(client reqID: " + requestId + ") Initial http response message received");
        this.publisher = new HttpResponsePublisher(ctx);
        channel.attr(PUBLISHER).set(this.publisher);
        this.responseCloser = new ResponseCloser(ctx);
        WebClientResponseImpl.Builder responseBuilder = WebClientResponseImpl.builder();
        responseBuilder.contentPublisher(publisher).readerContext(requestConfiguration.readerContext()).status(helidonStatus(response.status())).httpVersion(Http.Version.create(response.protocolVersion().toString())).responseCloser(responseCloser).lastEndpointURI(requestConfiguration.requestURI());
        HttpHeaders nettyHeaders = response.headers();
        for (String name : nettyHeaders.names()) {
            List<String> values = nettyHeaders.getAll(name);
            responseBuilder.addHeader(name, values);
        }
        String connection = nettyHeaders.get(Http.Header.CONNECTION, HttpHeaderValues.CLOSE.toString());
        if (connection.equals(HttpHeaderValues.CLOSE.toString())) {
            ctx.channel().attr(WILL_CLOSE).set(true);
        }
        // we got a response, we can safely complete the future
        // all errors are now fed only to the publisher
        WebClientResponse clientResponse = responseBuilder.build();
        channel.attr(RESPONSE).set(clientResponse);
        for (HttpInterceptor interceptor : HTTP_INTERCEPTORS) {
            if (interceptor.shouldIntercept(response.status(), requestConfiguration)) {
                boolean continueAfter = !interceptor.continueAfterInterception();
                if (continueAfter) {
                    responseCloser.close().thenAccept(future -> LOGGER.finest(() -> "Response closed due to redirection"));
                }
                interceptor.handleInterception(response, clientRequest, channel.attr(RESULT).get());
                if (continueAfter) {
                    return;
                }
            }
        }
        requestConfiguration.cookieManager().put(requestConfiguration.requestURI(), clientResponse.headers().toMap());
        WebClientServiceResponse clientServiceResponse = new WebClientServiceResponseImpl(requestConfiguration.context().get(), clientResponse.headers(), clientResponse.status());
        channel.attr(SERVICE_RESPONSE).set(clientServiceResponse);
        List<WebClientService> services = requestConfiguration.services();
        CompletionStage<WebClientServiceResponse> csr = CompletableFuture.completedFuture(clientServiceResponse);
        for (WebClientService service : services) {
            csr = csr.thenCompose(clientSerResponse -> service.response(clientRequest, clientSerResponse));
        }
        CompletableFuture<WebClientServiceResponse> responseReceived = channel.attr(RECEIVED).get();
        CompletableFuture<WebClientResponse> responseFuture = channel.attr(RESULT).get();
        csr.whenComplete((clientSerResponse, throwable) -> {
            if (throwable != null) {
                responseReceived.completeExceptionally(throwable);
                responseFuture.completeExceptionally(throwable);
                responseCloser.close();
            } else {
                responseReceived.complete(clientServiceResponse);
                responseReceived.thenRun(() -> {
                    if (shouldResponseAutomaticallyClose(clientResponse)) {
                        responseCloser.close().thenAccept(aVoid -> {
                            LOGGER.finest(() -> "Response automatically closed. No entity expected");
                        });
                    }
                    responseFuture.complete(clientResponse);
                });
            }
        });
    }
    if (responseCloser.isClosed()) {
        if (!channel.attr(WILL_CLOSE).get() && channel.hasAttr(RETURN)) {
            if (msg instanceof LastHttpContent) {
                LOGGER.finest(() -> "(client reqID: " + requestId + ") Draining finished");
                if (channel.isActive()) {
                    channel.attr(RETURN).get().set(true);
                }
            } else {
                LOGGER.finest(() -> "(client reqID: " + requestId + ") Draining not finished, requesting new chunk");
            }
            channel.read();
        }
        return;
    }
    // never "else-if" - msg may be an instance of more than one type, we must process all of them
    if (msg instanceof HttpContent) {
        HttpContent content = (HttpContent) msg;
        publisher.emit(content.content());
    }
    if (msg instanceof LastHttpContent) {
        LOGGER.finest(() -> "(client reqID: " + requestId + ") Last http content received");
        if (channel.hasAttr(RETURN)) {
            channel.attr(RETURN).get().set(true);
            responseCloser.close();
            channel.read();
        } else {
            responseCloser.close();
        }
    }
}
Also used : BufferedEmittingPublisher(io.helidon.common.reactive.BufferedEmittingPublisher) AttributeKey(io.netty.util.AttributeKey) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) COMPLETED(io.helidon.webclient.WebClientRequestBuilderImpl.COMPLETED) RECEIVED(io.helidon.webclient.WebClientRequestBuilderImpl.RECEIVED) DataChunk(io.helidon.common.http.DataChunk) RESULT(io.helidon.webclient.WebClientRequestBuilderImpl.RESULT) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) HttpObject(io.netty.handler.codec.http.HttpObject) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) RESPONSE(io.helidon.webclient.WebClientRequestBuilderImpl.RESPONSE) ByteBuf(io.netty.buffer.ByteBuf) Single(io.helidon.common.reactive.Single) Http(io.helidon.common.http.Http) REQUEST(io.helidon.webclient.WebClientRequestBuilderImpl.REQUEST) HttpContent(io.netty.handler.codec.http.HttpContent) WILL_CLOSE(io.helidon.webclient.WebClientRequestBuilderImpl.WILL_CLOSE) WebClientService(io.helidon.webclient.spi.WebClientService) HttpHeaderValues(io.netty.handler.codec.http.HttpHeaderValues) REQUEST_ID(io.helidon.webclient.WebClientRequestBuilderImpl.REQUEST_ID) IOException(java.io.IOException) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) Logger(java.util.logging.Logger) Channel(io.netty.channel.Channel) IN_USE(io.helidon.webclient.WebClientRequestBuilderImpl.IN_USE) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) HttpResponse(io.netty.handler.codec.http.HttpResponse) RETURN(io.helidon.webclient.WebClientRequestBuilderImpl.RETURN) RESPONSE_RECEIVED(io.helidon.webclient.WebClientRequestBuilderImpl.RESPONSE_RECEIVED) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) Channel(io.netty.channel.Channel) HttpResponse(io.netty.handler.codec.http.HttpResponse) WebClientService(io.helidon.webclient.spi.WebClientService) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent)

Example 24 with Http

use of io.helidon.common.http.Http 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)

Example 25 with Http

use of io.helidon.common.http.Http in project helidon by oracle.

the class GreetService method contextCheck.

/**
 * Checks the existence of a {@code Context} object in a WebClient thread.
 *
 * @param request the request
 * @param response the response
 */
private void contextCheck(ServerRequest request, ServerResponse response) {
    WebClient webClient = WebClient.builder().baseUri("http://localhost:" + Main.serverPort + "/").build();
    Optional<Context> context = Contexts.context();
    // Verify that context was propagated with auth enabled
    if (context.isEmpty()) {
        response.status(Http.Status.INTERNAL_SERVER_ERROR_500).send();
        return;
    }
    // Register instance in context
    context.get().register(this);
    // Ensure context is available in webclient threads
    webClient.get().request().thenAccept(clientResponse -> {
        Context singleContext = Contexts.context().orElseThrow();
        Objects.requireNonNull(singleContext.get(GreetService.class));
        response.status(Http.Status.OK_200);
        response.send();
    }).exceptionally(throwable -> {
        response.status(Http.Status.INTERNAL_SERVER_ERROR_500);
        response.send();
        return null;
    });
}
Also used : Context(io.helidon.common.context.Context) SecurityContext(io.helidon.security.SecurityContext) WebClient(io.helidon.webclient.WebClient) DataChunk(io.helidon.common.http.DataChunk) Context(io.helidon.common.context.Context) JsonBuilderFactory(jakarta.json.JsonBuilderFactory) AtomicReference(java.util.concurrent.atomic.AtomicReference) Level(java.util.logging.Level) FormParams(io.helidon.common.http.FormParams) ServerResponse(io.helidon.webserver.ServerResponse) JsonObject(jakarta.json.JsonObject) Service(io.helidon.webserver.Service) JsonException(jakarta.json.JsonException) Http(io.helidon.common.http.Http) Multi(io.helidon.common.reactive.Multi) Config(io.helidon.config.Config) WebClientSecurity(io.helidon.webclient.security.WebClientSecurity) SecurityContext(io.helidon.security.SecurityContext) Logger(java.util.logging.Logger) Contexts(io.helidon.common.context.Contexts) Executors(java.util.concurrent.Executors) ServerRequest(io.helidon.webserver.ServerRequest) Json(jakarta.json.Json) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) Principal(java.security.Principal) Optional(java.util.Optional) Routing(io.helidon.webserver.Routing) Collections(java.util.Collections) WebClient(io.helidon.webclient.WebClient)

Aggregations

Http (io.helidon.common.http.Http)27 WebClient (io.helidon.webclient.WebClient)16 DataChunk (io.helidon.common.http.DataChunk)12 Config (io.helidon.config.Config)12 WebClientResponse (io.helidon.webclient.WebClientResponse)12 Routing (io.helidon.webserver.Routing)11 WebServer (io.helidon.webserver.WebServer)10 Test (org.junit.jupiter.api.Test)10 MediaType (io.helidon.common.http.MediaType)9 Optional (java.util.Optional)9 Single (io.helidon.common.reactive.Single)8 WebClientRequestBuilder (io.helidon.webclient.WebClientRequestBuilder)8 Logger (java.util.logging.Logger)8 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)8 Json (jakarta.json.Json)7 JsonBuilderFactory (jakarta.json.JsonBuilderFactory)7 Collections (java.util.Collections)7 JsonpSupport (io.helidon.media.jsonp.JsonpSupport)6 SecurityContext (io.helidon.security.SecurityContext)6 JsonObject (jakarta.json.JsonObject)5