Search in sources :

Example 6 with Http

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

the class RestApiBase method handleBytesResponse.

/**
 * Handle bytes response for optional bytes entity.
 * This method checks if this was a success and if the response should contain an entity.
 * For success, it returns a response using the provided response builder.
 * For failures, returns an error.
 *
 * @param path requested path
 * @param request API request
 * @param method HTTP method
 * @param requestId request ID
 * @param response the web client response
 * @param responseBuilder builder to configure success response
 * @param <R> type of the optional part of the response
 * @param <T> type of the response
 *
 * @return future with response
 */
protected <R, T extends ApiOptionalResponse<R>> Single<T> handleBytesResponse(String path, ApiRequest<?> request, Http.RequestMethod method, String requestId, WebClientResponse response, ApiOptionalResponse.BuilderBase<?, T, byte[], R> responseBuilder) {
    Http.ResponseStatus status = response.status();
    boolean success = (Http.Status.Family.of(status.code()) == Http.ResponseStatus.Family.SUCCESSFUL) || isSuccess(path, request, method, requestId, status);
    boolean isEntityExpected = (Http.Status.Family.of(status.code()) == Http.ResponseStatus.Family.SUCCESSFUL) || isEntityExpected(path, request, method, requestId, status);
    if (success) {
        if (isEntityExpected) {
            return response.content().map(DataChunk::bytes).collect(new Collector<byte[], byte[]>() {

                private final ByteArrayOutputStream baos = new ByteArrayOutputStream();

                @Override
                public void collect(byte[] item) {
                    baos.writeBytes(item);
                }

                @Override
                public byte[] value() {
                    return baos.toByteArray();
                }
            }).map(it -> responseBuilder.headers(response.headers()).status(status).requestId(requestId).entity(it).build());
        } else {
            return emptyResponse(path, request, method, requestId, response, responseBuilder);
        }
    } else {
        return errorResponse(path, request, method, requestId, response);
    }
}
Also used : Collector(io.helidon.common.reactive.Collector) Http(io.helidon.common.http.Http) DataChunk(io.helidon.common.http.DataChunk) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 7 with Http

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

the class RestApiBase method errorResponse.

/**
 * Create an error response.
 * This method attempts to read the response entity as a string, parse it into a JsonObject and
 * depending on result, calls methods to create a proper exception.
 *
 * @param path requested path
 * @param request original request
 * @param method HTTP method
 * @param requestId ID of the request
 * @param response actual response where we do not expect an entity
 * @param <T> type of the response
 *
 * @return future with error
 */
protected <T extends ApiResponse> Single<T> errorResponse(String path, ApiRequest<?> request, Http.RequestMethod method, String requestId, WebClientResponse response) {
    if (response.headers().contentLength().orElse(-1L) == 0) {
        // explicitly no content
        return Single.error(readError(path, request, method, requestId, response));
    } else {
        AtomicBoolean processedError = new AtomicBoolean();
        return response.content().as(String.class).flatMapSingle(string -> {
            try {
                JsonObject json = jsonReaderFactory.createReader(new StringReader(string)).readObject();
                Single<T> error = Single.error(readError(path, request, method, requestId, response, json));
                processedError.set(true);
                return error;
            } catch (Exception e) {
                Single<T> error = Single.error(readError(path, request, method, requestId, response, string));
                processedError.set(true);
                return error;
            }
        }).onErrorResumeWithSingle(it -> {
            if (processedError.get()) {
                return Single.error(it);
            }
            return Single.error(readErrorFailedEntity(path, request, method, requestId, response, it));
        });
    }
}
Also used : JsonWriterFactory(jakarta.json.JsonWriterFactory) ByteArrayOutputStream(java.io.ByteArrayOutputStream) WebClient(io.helidon.webclient.WebClient) WebClientResponse(io.helidon.webclient.WebClientResponse) JsonReaderFactory(jakarta.json.JsonReaderFactory) DataChunk(io.helidon.common.http.DataChunk) JsonBuilderFactory(jakarta.json.JsonBuilderFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Supplier(java.util.function.Supplier) MediaType(io.helidon.common.http.MediaType) Flow(java.util.concurrent.Flow) JsonObject(jakarta.json.JsonObject) Single(io.helidon.common.reactive.Single) Http(io.helidon.common.http.Http) Multi(io.helidon.common.reactive.Multi) FtHandler(io.helidon.faulttolerance.FtHandler) Collector(io.helidon.common.reactive.Collector) UUID(java.util.UUID) Logger(java.util.logging.Logger) WebClientRequestHeaders(io.helidon.webclient.WebClientRequestHeaders) Contexts(io.helidon.common.context.Contexts) SpanContext(io.opentracing.SpanContext) StringReader(java.io.StringReader) Optional(java.util.Optional) WebClientRequestBuilder(io.helidon.webclient.WebClientRequestBuilder) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Single(io.helidon.common.reactive.Single) StringReader(java.io.StringReader) JsonObject(jakarta.json.JsonObject)

Example 8 with Http

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

the class WebSecurityBuilderGateDefaultsTest method initClass.

@BeforeAll
public static void initClass() throws InterruptedException {
    WebSecurityTestUtil.auditLogFinest();
    myAuditProvider = new UnitTestAuditProvider();
    Config config = Config.create();
    Security security = Security.builder(config.get("security")).addAuditProvider(myAuditProvider).build();
    Routing routing = Routing.builder().register(WebSecurity.create(security).securityDefaults(WebSecurity.rolesAllowed("admin").audit())).get("/noRoles", WebSecurity.enforce()).get("/user[/{*}]", WebSecurity.rolesAllowed("user")).get("/admin", WebSecurity.rolesAllowed("admin")).get("/deny", WebSecurity.rolesAllowed("deny")).get("/auditOnly", WebSecurity.enforce().skipAuthentication().skipAuthorization().auditEventType("unit_test").auditMessageFormat(WebSecurityTests.AUDIT_MESSAGE_FORMAT)).get("/{*}", (req, res) -> {
        Optional<SecurityContext> securityContext = req.context().get(SecurityContext.class);
        res.headers().contentType(MediaType.TEXT_PLAIN.withCharset("UTF-8"));
        res.send("Hello, you are: \n" + securityContext.map(ctx -> ctx.user().orElse(SecurityContext.ANONYMOUS).toString()).orElse("Security context is null"));
    }).build();
    server = WebServer.create(routing);
    long t = System.currentTimeMillis();
    CountDownLatch cdl = new CountDownLatch(1);
    server.start().thenAccept(webServer -> {
        long time = System.currentTimeMillis() - t;
        System.out.println("Started server on localhost:" + webServer.port() + " in " + time + " millis");
        cdl.countDown();
    });
    // we must wait for server to start, so other tests are not triggered until it is ready!
    assertThat("Timeout while waiting for server to start!", cdl.await(5, TimeUnit.SECONDS), is(true));
    serverBaseUri = "http://localhost:" + server.port();
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) Security(io.helidon.security.Security) WebClient(io.helidon.webclient.WebClient) WebClientResponse(io.helidon.webclient.WebClientResponse) CoreMatchers.not(org.hamcrest.CoreMatchers.not) MediaType(io.helidon.common.http.MediaType) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) AfterAll(org.junit.jupiter.api.AfterAll) AuditEvent(io.helidon.security.AuditEvent) BeforeAll(org.junit.jupiter.api.BeforeAll) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Http(io.helidon.common.http.Http) HttpBasicAuthProvider(io.helidon.security.providers.httpauth.HttpBasicAuthProvider) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Config(io.helidon.config.Config) WebClientSecurity(io.helidon.webclient.security.WebClientSecurity) Set(java.util.Set) SecurityContext(io.helidon.security.SecurityContext) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) WebServer(io.helidon.webserver.WebServer) Optional(java.util.Optional) Routing(io.helidon.webserver.Routing) Optional(java.util.Optional) Config(io.helidon.config.Config) SecurityContext(io.helidon.security.SecurityContext) Routing(io.helidon.webserver.Routing) Security(io.helidon.security.Security) WebClientSecurity(io.helidon.webclient.security.WebClientSecurity) CountDownLatch(java.util.concurrent.CountDownLatch) BeforeAll(org.junit.jupiter.api.BeforeAll)

Example 9 with Http

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

the class WebSecurityProgrammaticTest method initClass.

@BeforeAll
public static void initClass() throws InterruptedException {
    WebSecurityTestUtil.auditLogFinest();
    myAuditProvider = new UnitTestAuditProvider();
    Config config = Config.create();
    Security security = Security.builder(config.get("security")).addAuditProvider(myAuditProvider).build();
    Routing routing = Routing.builder().register(WebSecurity.create(security).securityDefaults(SecurityHandler.create().queryParam("jwt", TokenHandler.builder().tokenHeader("BEARER_TOKEN").tokenPattern(Pattern.compile("bearer (.*)")).build()).queryParam("name", TokenHandler.builder().tokenHeader("NAME_FROM_REQUEST").build()))).get("/noRoles", WebSecurity.secure()).get("/user[/{*}]", WebSecurity.rolesAllowed("user")).get("/admin", WebSecurity.rolesAllowed("admin")).get("/deny", WebSecurity.rolesAllowed("deny"), (req, res) -> {
        res.status(Http.Status.INTERNAL_SERVER_ERROR_500);
        res.send("Should not get here, this role doesn't exist");
    }).get("/auditOnly", WebSecurity.audit().auditEventType("unit_test").auditMessageFormat(AUDIT_MESSAGE_FORMAT)).get("/{*}", (req, res) -> {
        Optional<SecurityContext> securityContext = req.context().get(SecurityContext.class);
        res.headers().contentType(MediaType.TEXT_PLAIN.withCharset("UTF-8"));
        res.send("Hello, you are: \n" + securityContext.map(ctx -> ctx.user().orElse(SecurityContext.ANONYMOUS).toString()).orElse("Security context is null"));
    }).build();
    server = WebServer.create(routing);
    long t = System.currentTimeMillis();
    CountDownLatch cdl = new CountDownLatch(1);
    server.start().thenAccept(webServer -> {
        long time = System.currentTimeMillis() - t;
        System.out.println("Started server on localhost:" + webServer.port() + " in " + time + " millis");
        cdl.countDown();
    });
    // we must wait for server to start, so other tests are not triggered until it is ready!
    assertThat("Timeout while waiting for server to start!", cdl.await(5, TimeUnit.SECONDS), is(true));
    baseUri = "http://localhost:" + server.port();
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) Security(io.helidon.security.Security) Config(io.helidon.config.Config) SecurityContext(io.helidon.security.SecurityContext) TokenHandler(io.helidon.security.util.TokenHandler) MediaType(io.helidon.common.http.MediaType) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) BeforeAll(org.junit.jupiter.api.BeforeAll) WebServer(io.helidon.webserver.WebServer) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Http(io.helidon.common.http.Http) Routing(io.helidon.webserver.Routing) Optional(java.util.Optional) Config(io.helidon.config.Config) SecurityContext(io.helidon.security.SecurityContext) Routing(io.helidon.webserver.Routing) Security(io.helidon.security.Security) CountDownLatch(java.util.concurrent.CountDownLatch) BeforeAll(org.junit.jupiter.api.BeforeAll)

Example 10 with Http

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

the class GreetService method basicAuthOutbound.

private void basicAuthOutbound(ServerRequest serverRequest, ServerResponse response) {
    WebClient webClient = WebClient.builder().baseUri("http://localhost:" + Main.serverPort + "/greet/secure/basic").addService(WebClientSecurity.create()).build();
    webClient.get().request().thenAccept(clientResponse -> {
        response.status(clientResponse.status());
        response.send(clientResponse.content());
    }).exceptionally(throwable -> {
        response.status(Http.Status.INTERNAL_SERVER_ERROR_500);
        response.send();
        return null;
    });
}
Also used : 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