Search in sources :

Example 16 with Routing

use of io.helidon.webserver.Routing in project helidon by oracle.

the class OutboundOverrideExample method startClientService.

static CompletionStage<Void> startClientService(int port) {
    Config config = createConfig("client-service");
    Routing routing = Routing.builder().register(WebSecurity.create(config.get("security"))).get("/override", OutboundOverrideExample::override).get("/propagate", OutboundOverrideExample::propagate).build();
    return startServer(routing, port, server -> clientPort = server.port());
}
Also used : Config(io.helidon.config.Config) OutboundOverrideUtil.createConfig(io.helidon.security.examples.outbound.OutboundOverrideUtil.createConfig) Routing(io.helidon.webserver.Routing)

Example 17 with Routing

use of io.helidon.webserver.Routing in project helidon by oracle.

the class OutboundOverrideJwtExample method startServingService.

static CompletionStage<Void> startServingService(int port) {
    Config config = createConfig("serving-service-jwt");
    Routing routing = Routing.builder().register(WebSecurity.create(config.get("security"))).get("/hello", (req, res) -> {
        // This is the token. It should be bearer <signed JWT base64 encoded>
        req.headers().first("Authorization").ifPresent(System.out::println);
        res.send(req.context().get(SecurityContext.class).flatMap(SecurityContext::user).map(Subject::principal).map(Principal::getName).orElse("Anonymous"));
    }).build();
    return startServer(routing, port, server -> servingPort = server.port());
}
Also used : OutboundOverrideUtil.startServer(io.helidon.security.examples.outbound.OutboundOverrideUtil.startServer) Config(io.helidon.config.Config) OutboundOverrideUtil.sendError(io.helidon.security.examples.outbound.OutboundOverrideUtil.sendError) SecurityContext(io.helidon.security.SecurityContext) Principal(io.helidon.security.Principal) ServerRequest(io.helidon.webserver.ServerRequest) OutboundOverrideUtil.getSecurityContext(io.helidon.security.examples.outbound.OutboundOverrideUtil.getSecurityContext) CompletionStage(java.util.concurrent.CompletionStage) ServerResponse(io.helidon.webserver.ServerResponse) WebSecurity(io.helidon.security.integration.webserver.WebSecurity) Subject(io.helidon.security.Subject) Routing(io.helidon.webserver.Routing) OutboundOverrideUtil.createConfig(io.helidon.security.examples.outbound.OutboundOverrideUtil.createConfig) OutboundOverrideUtil.webTarget(io.helidon.security.examples.outbound.OutboundOverrideUtil.webTarget) JwtProvider(io.helidon.security.providers.jwt.JwtProvider) Config(io.helidon.config.Config) OutboundOverrideUtil.createConfig(io.helidon.security.examples.outbound.OutboundOverrideUtil.createConfig) Routing(io.helidon.webserver.Routing) Subject(io.helidon.security.Subject)

Example 18 with Routing

use of io.helidon.webserver.Routing in project helidon by oracle.

the class DigestExampleConfigMain method main.

/**
 * Starts this example. Loads configuration from src/main/resources/application.conf. See standard output for instructions.
 *
 * @param args ignored
 */
public static void main(String[] args) {
    // load logging configuration
    LogConfig.configureRuntime();
    // load configuration
    Config config = Config.create();
    // build routing (security is loaded from config)
    Routing routing = Routing.builder().register(WebSecurity.create(config.get("security"))).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 = DigestExampleUtil.startServer(routing);
}
Also used : Config(io.helidon.config.Config) WebServer(io.helidon.webserver.WebServer) Optional(java.util.Optional) WebSecurity(io.helidon.security.integration.webserver.WebSecurity) SecurityContext(io.helidon.security.SecurityContext) LogConfig(io.helidon.common.LogConfig) Routing(io.helidon.webserver.Routing) MediaType(io.helidon.common.http.MediaType) Optional(java.util.Optional) Config(io.helidon.config.Config) LogConfig(io.helidon.common.LogConfig) SecurityContext(io.helidon.security.SecurityContext) Routing(io.helidon.webserver.Routing)

Example 19 with Routing

use of io.helidon.webserver.Routing in project helidon by oracle.

the class MicrometerCdiExtension method registerService.

/**
 * Registers the service-related endpoint, after security and as CDI initializes the app scope, returning the default routing
 * for optional use by the caller.
 *
 * @param adv    app-scoped initialization event
 * @param bm     BeanManager
 * @return default routing
 */
@Override
public Routing.Builder registerService(@Observes @Priority(LIBRARY_BEFORE + 10) @Initialized(ApplicationScoped.class) Object adv, BeanManager bm, ServerCdiExtension serverCdiExtension) {
    Routing.Builder result = super.registerService(adv, bm, serverCdiExtension);
    MeterRegistry meterRegistry = serviceSupport().registry();
    annotationsForMeters.forEach(deferredAnnotation -> {
        Annotation annotation = deferredAnnotation.annotation;
        AnnotatedCallable<?> annotatedCallable = deferredAnnotation.annotatedCallable;
        Meter newMeter;
        boolean isOnlyOnException = false;
        if (annotation instanceof Counted) {
            Counter counter = MeterProducer.produceCounter(meterRegistry, (Counted) annotation);
            LOGGER.log(Level.FINE, () -> "Registered counter " + counter.getId().toString());
            newMeter = counter;
            isOnlyOnException = ((Counted) annotation).recordFailuresOnly();
        } else {
            Timed timed = (Timed) annotation;
            if (timed.longTask()) {
                LongTaskTimer longTaskTimer = MeterProducer.produceLongTaskTimer(meterRegistry, timed);
                LOGGER.log(Level.FINE, () -> "Registered long task timer " + longTaskTimer.getId().toString());
                newMeter = longTaskTimer;
            } else {
                Timer timer = MeterProducer.produceTimer(meterRegistry, timed);
                LOGGER.log(Level.FINE, () -> "Registered timer " + timer.getId().toString());
                newMeter = timer;
            }
        }
        workItemsManager.put(Executable.class.cast(annotatedCallable.getJavaMember()), annotation.annotationType(), MeterWorkItem.create(newMeter, isOnlyOnException));
    });
    return result;
}
Also used : Counted(io.micrometer.core.annotation.Counted) Meter(io.micrometer.core.instrument.Meter) Timed(io.micrometer.core.annotation.Timed) Routing(io.helidon.webserver.Routing) Annotation(java.lang.annotation.Annotation) MeterRegistry(io.micrometer.core.instrument.MeterRegistry) Counter(io.micrometer.core.instrument.Counter) LongTaskTimer(io.micrometer.core.instrument.LongTaskTimer) Timer(io.micrometer.core.instrument.Timer) LongTaskTimer(io.micrometer.core.instrument.LongTaskTimer) Executable(java.lang.reflect.Executable)

Example 20 with Routing

use of io.helidon.webserver.Routing in project helidon by oracle.

the class JsonSupportTest method acceptHeaders.

@Test
public void acceptHeaders() throws Exception {
    Routing routing = Routing.builder().post("/foo", Handler.create(JsonObject.class, (req, res, json) -> res.send(json))).build();
    JsonObject json = createJson();
    // Has accept
    TestResponse response = TestClient.create(routing, JsonpSupport.create()).path("/foo").header("Accept", "text/plain; q=.8, application/json; q=.1").post(MediaPublisher.create(MediaType.APPLICATION_JSON.withCharset("UTF-8"), json.toString()));
    assertThat(response.status(), is(equalTo(Http.Status.OK_200)));
    assertThat(response.headers().first(Http.Header.CONTENT_TYPE).orElse(null), is(equalTo(MediaType.APPLICATION_JSON.toString())));
    // Has accept with +json
    response = TestClient.create(routing, JsonpSupport.create()).path("/foo").header("Accept", "text/plain; q=.8, application/specific+json; q=.1").post(MediaPublisher.create(MediaType.APPLICATION_JSON.withCharset("UTF-8"), json.toString()));
    assertThat(response.status(), is(equalTo(Http.Status.OK_200)));
    assertThat(response.headers().first(Http.Header.CONTENT_TYPE).orElse(null), is(equalTo(MediaType.parse("application/specific+json").toString())));
    // With start
    response = TestClient.create(routing, JsonpSupport.create()).path("/foo").header("Accept", "text/plain; q=.8, application/*; q=.1").post(MediaPublisher.create(MediaType.APPLICATION_JSON.withCharset("UTF-8"), json.toString()));
    assertThat(response.status(), is(equalTo(Http.Status.OK_200)));
    assertThat(response.headers().first(Http.Header.CONTENT_TYPE).orElse(null), is(equalTo(MediaType.APPLICATION_JSON.toString())));
    // With JSONP standard application/javascript
    response = TestClient.create(routing, JsonpSupport.create()).path("/foo").header("Accept", "application/javascript").post(MediaPublisher.create(MediaType.APPLICATION_JSON.withCharset("UTF-8"), json.toString()));
    assertThat(response.status(), is(equalTo(Http.Status.INTERNAL_SERVER_ERROR_500)));
    // Without start
    response = TestClient.create(routing, JsonpSupport.create()).path("/foo").header("Accept", "text/plain; q=.8, application/specific; q=.1").post(MediaPublisher.create(MediaType.APPLICATION_JSON.withCharset("UTF-8"), json.toString()));
    assertThat(response.status(), is(equalTo(Http.Status.INTERNAL_SERVER_ERROR_500)));
}
Also used : TestResponse(io.helidon.webserver.testsupport.TestResponse) Routing(io.helidon.webserver.Routing) JsonObject(jakarta.json.JsonObject) Test(org.junit.jupiter.api.Test)

Aggregations

Routing (io.helidon.webserver.Routing)86 WebServer (io.helidon.webserver.WebServer)38 Config (io.helidon.config.Config)33 Test (org.junit.jupiter.api.Test)32 Http (io.helidon.common.http.Http)23 TimeUnit (java.util.concurrent.TimeUnit)21 LogConfig (io.helidon.common.LogConfig)19 MediaType (io.helidon.common.http.MediaType)19 CoreMatchers.is (org.hamcrest.CoreMatchers.is)17 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)17 SecurityContext (io.helidon.security.SecurityContext)16 HttpException (io.helidon.webserver.HttpException)15 Optional (java.util.Optional)15 CountDownLatch (java.util.concurrent.CountDownLatch)15 WebSecurity (io.helidon.security.integration.webserver.WebSecurity)13 SERVICE_UNAVAILABLE_503 (io.helidon.common.http.Http.Status.SERVICE_UNAVAILABLE_503)11 JsonpSupport (io.helidon.media.jsonp.JsonpSupport)11 Security (io.helidon.security.Security)11 StaticContentSupport (io.helidon.webserver.staticcontent.StaticContentSupport)10 TestResponse (io.helidon.webserver.testsupport.TestResponse)10