Search in sources :

Example 56 with Routing

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

the class MetricsIT method startWebServer.

/**
 * Start the Web Server listening on an ephemeral port.
 *
 * @throws Exception in case of an error
 */
private static void startWebServer() throws Exception {
    // Add metrics to the web server routing
    Routing routing = Routing.builder().register(MetricsSupport.create()).build();
    // Web server picks a free ephemeral port by default
    webServer = WebServer.create(routing).start().toCompletableFuture().get(10, TimeUnit.SECONDS);
    LOGGER.info("Started web server at: http://localhost:" + webServer.port());
}
Also used : GrpcRouting(io.helidon.grpc.server.GrpcRouting) Routing(io.helidon.webserver.Routing)

Example 57 with Routing

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

the class WebSocketCdiExtension method registerWebSockets.

private void registerWebSockets() {
    try {
        WebSocketApplication app = toWebSocketApplication();
        // If application present call its methods
        TyrusSupport.Builder builder = TyrusSupport.builder();
        Optional<Class<? extends ServerApplicationConfig>> appClass = app.applicationClass();
        Optional<String> contextRoot = appClass.flatMap(c -> findContextRoot(config, c));
        Optional<String> namedRouting = appClass.flatMap(c -> findNamedRouting(config, c));
        boolean routingNameRequired = appClass.map(c -> isNamedRoutingRequired(config, c)).orElse(false);
        Routing.Builder routing;
        if (appClass.isPresent()) {
            Class<? extends ServerApplicationConfig> c = appClass.get();
            // Attempt to instantiate via CDI
            ServerApplicationConfig instance = null;
            try {
                instance = CDI.current().select(c).get();
            } catch (UnsatisfiedResolutionException e) {
            // falls through
            }
            // Otherwise, we create instance directly
            if (instance == null) {
                try {
                    instance = c.getDeclaredConstructor().newInstance();
                } catch (Exception e) {
                    throw new RuntimeException("Unable to instantiate websocket application " + c, e);
                }
            }
            // Call methods in application class
            Set<ServerEndpointConfig> endpointConfigs = instance.getEndpointConfigs(app.programmaticEndpoints());
            Set<Class<?>> endpointClasses = instance.getAnnotatedEndpointClasses(app.annotatedEndpoints());
            // Register classes and configs
            endpointClasses.forEach(builder::register);
            endpointConfigs.forEach(builder::register);
            // Create routing builder
            routing = serverCdiExtension.routingBuilder(namedRouting, routingNameRequired, c.getName());
        } else {
            // Direct registration without calling application class
            app.annotatedEndpoints().forEach(builder::register);
            app.programmaticEndpoints().forEach(builder::register);
            app.extensions().forEach(builder::register);
            // Create routing builder
            routing = serverCdiExtension.serverRoutingBuilder();
        }
        // Finally register WebSockets in Helidon routing
        String rootPath = contextRoot.orElse(DEFAULT_WEBSOCKET_PATH);
        LOGGER.info("Registering websocket application at " + rootPath);
        routing.register(rootPath, new TyrusSupportMp(builder.build()));
    } catch (IllegalArgumentException e) {
        throw new RuntimeException("Unable to load WebSocket extension", e);
    }
}
Also used : CDI(jakarta.enterprise.inject.spi.CDI) ServerEndpointConfig(jakarta.websocket.server.ServerEndpointConfig) Observes(jakarta.enterprise.event.Observes) ApplicationScoped(jakarta.enterprise.context.ApplicationScoped) RuntimeStart(io.helidon.microprofile.cdi.RuntimeStart) ServerApplicationConfig(jakarta.websocket.server.ServerApplicationConfig) Extension(jakarta.enterprise.inject.spi.Extension) ProcessAnnotatedType(jakarta.enterprise.inject.spi.ProcessAnnotatedType) PLATFORM_AFTER(jakarta.interceptor.Interceptor.Priority.PLATFORM_AFTER) TyrusSupport(io.helidon.webserver.tyrus.TyrusSupport) Priority(jakarta.annotation.Priority) Initialized(jakarta.enterprise.context.Initialized) BeanManager(jakarta.enterprise.inject.spi.BeanManager) UnsatisfiedResolutionException(jakarta.enterprise.inject.UnsatisfiedResolutionException) Config(io.helidon.config.Config) RoutingPath(io.helidon.microprofile.server.RoutingPath) Set(java.util.Set) ServerCdiExtension(io.helidon.microprofile.server.ServerCdiExtension) Logger(java.util.logging.Logger) RoutingName(io.helidon.microprofile.server.RoutingName) Endpoint(jakarta.websocket.Endpoint) WithAnnotations(jakarta.enterprise.inject.spi.WithAnnotations) Optional(java.util.Optional) ServerEndpoint(jakarta.websocket.server.ServerEndpoint) Routing(io.helidon.webserver.Routing) ServerEndpointConfig(jakarta.websocket.server.ServerEndpointConfig) Routing(io.helidon.webserver.Routing) UnsatisfiedResolutionException(jakarta.enterprise.inject.UnsatisfiedResolutionException) ServerApplicationConfig(jakarta.websocket.server.ServerApplicationConfig) UnsatisfiedResolutionException(jakarta.enterprise.inject.UnsatisfiedResolutionException) TyrusSupport(io.helidon.webserver.tyrus.TyrusSupport)

Example 58 with Routing

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

the class ApplMain method startServer.

private static WebServer startServer(final String configFile) {
    final Config config = Config.create(ConfigSources.classpath(configFile));
    final Config dbConfig = config.get("db");
    // Client services are added through a service loader - see mongoDB example for explicit services
    final DbClient dbClient = DbClient.builder(dbConfig).addService(DbClientMetrics.counter().statementNames("select-pokemon-named-arg", "select-pokemon-order-arg", "insert-pokemon")).addService(DbClientMetrics.timer().statementTypes(DbStatementType.GET)).build();
    final HealthSupport health = HealthSupport.builder().addLiveness(DbClientHealthCheck.builder(dbClient).statementName("ping").build()).build();
    final Map<String, String> statements = dbConfig.get("statements").detach().asMap().get();
    final ExitService exitResource = new ExitService();
    final DbClientService interceptorTestService = new InterceptorService.TestClientService();
    final Routing routing = Routing.builder().register(// Metrics at "/metrics"
    MetricsSupport.create()).register(// Health at "/health"
    health).register("/Init", new InitService(dbClient, dbConfig)).register("/Exit", exitResource).register("/Verify", new VerifyService(dbClient, config)).register("/SimpleGet", new SimpleGetService(dbClient, statements)).register("/SimpleQuery", new SimpleQueryService(dbClient, statements)).register("/SimpleUpdate", new SimpleUpdateService(dbClient, statements)).register("/SimpleInsert", new SimpleInsertService(dbClient, statements)).register("/SimpleDelete", new SimpleDeleteService(dbClient, statements)).register("/TransactionGet", new TransactionGetService(dbClient, statements)).register("/TransactionQueries", new TransactionQueriesService(dbClient, statements)).register("/TransactionUpdate", new TransactionUpdateService(dbClient, statements)).register("/TransactionInsert", new TransactionInsertService(dbClient, statements)).register("/TransactionDelete", new TransactionDeleteService(dbClient, statements)).register("/DmlStatement", new DmlStatementService(dbClient, statements)).register("/GetStatement", new GetStatementService(dbClient, statements)).register("/QueryStatement", new QueryStatementService(dbClient, statements)).register("/FlowControl", new FlowControlService(dbClient, statements)).register("/Mapper", new MapperService(dbClient, statements)).register("/Interceptor", new InterceptorService(DbClient.builder(dbConfig).addService(interceptorTestService).build(), statements, interceptorTestService)).register("/HealthCheck", new HealthCheckService(dbClient, dbConfig, statements)).build();
    // Prepare routing for the server
    final WebServer.Builder serverBuilder = WebServer.builder().routing(routing).config(config.get("server"));
    final WebServer server = serverBuilder.addMediaSupport(JsonpSupport.create()).addMediaSupport(JsonbSupport.create()).build();
    exitResource.setServer(server);
    // Start the server and print some info.
    server.start().thenAccept(ws -> {
        System.out.println("WEB server is up! http://localhost:" + ws.port() + "/");
    });
    // Server threads are not daemon. NO need to block. Just react.
    server.whenShutdown().thenRun(() -> System.out.println("WEB server is DOWN. Good bye!"));
    return server;
}
Also used : TransactionGetService(io.helidon.tests.integration.dbclient.appl.transaction.TransactionGetService) LogConfig(io.helidon.common.LogConfig) Config(io.helidon.config.Config) HealthSupport(io.helidon.health.HealthSupport) TransactionQueriesService(io.helidon.tests.integration.dbclient.appl.transaction.TransactionQueriesService) DmlStatementService(io.helidon.tests.integration.dbclient.appl.statement.DmlStatementService) TransactionUpdateService(io.helidon.tests.integration.dbclient.appl.transaction.TransactionUpdateService) SimpleQueryService(io.helidon.tests.integration.dbclient.appl.simple.SimpleQueryService) TransactionInsertService(io.helidon.tests.integration.dbclient.appl.transaction.TransactionInsertService) GetStatementService(io.helidon.tests.integration.dbclient.appl.statement.GetStatementService) QueryStatementService(io.helidon.tests.integration.dbclient.appl.statement.QueryStatementService) DbClient(io.helidon.dbclient.DbClient) HealthCheckService(io.helidon.tests.integration.dbclient.appl.health.HealthCheckService) SimpleInsertService(io.helidon.tests.integration.dbclient.appl.simple.SimpleInsertService) Routing(io.helidon.webserver.Routing) SimpleGetService(io.helidon.tests.integration.dbclient.appl.simple.SimpleGetService) SimpleDeleteService(io.helidon.tests.integration.dbclient.appl.simple.SimpleDeleteService) ExitService(io.helidon.tests.integration.dbclient.appl.tools.ExitService) DbClientService(io.helidon.dbclient.DbClientService) WebServer(io.helidon.webserver.WebServer) TransactionDeleteService(io.helidon.tests.integration.dbclient.appl.transaction.TransactionDeleteService) InterceptorService(io.helidon.tests.integration.dbclient.appl.interceptor.InterceptorService) SimpleUpdateService(io.helidon.tests.integration.dbclient.appl.simple.SimpleUpdateService) FlowControlService(io.helidon.tests.integration.dbclient.appl.result.FlowControlService) MapperService(io.helidon.tests.integration.dbclient.appl.mapping.MapperService)

Example 59 with Routing

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

the class OutboundOverrideJwtExample method startClientService.

static CompletionStage<Void> startClientService(int port) {
    Config config = createConfig("client-service-jwt");
    Routing routing = Routing.builder().register(WebSecurity.create(config.get("security"))).get("/override", OutboundOverrideJwtExample::override).get("/propagate", OutboundOverrideJwtExample::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 60 with Routing

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

the class GoogleConfigMain method start.

static int start(int port) {
    Config config = buildConfig();
    Routing.Builder routing = Routing.builder().register(WebSecurity.create(config.get("security"))).get("/rest/profile", (req, res) -> {
        Optional<SecurityContext> securityContext = req.context().get(SecurityContext.class);
        res.headers().contentType(MediaType.TEXT_PLAIN.withCharset("UTF-8"));
        res.send("Response from config based service, you are: \n" + securityContext.flatMap(SecurityContext::user).map(Subject::toString).orElse("Security context is null"));
    }).register(StaticContentSupport.create("/WEB"));
    theServer = GoogleUtil.startIt(port, routing);
    return theServer.port();
}
Also used : ConfigSources.file(io.helidon.config.ConfigSources.file) StaticContentSupport(io.helidon.webserver.staticcontent.StaticContentSupport) 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) Subject(io.helidon.security.Subject) ConfigSources.classpath(io.helidon.config.ConfigSources.classpath) Routing(io.helidon.webserver.Routing) MediaType(io.helidon.common.http.MediaType) Optional(java.util.Optional) Config(io.helidon.config.Config) SecurityContext(io.helidon.security.SecurityContext) Routing(io.helidon.webserver.Routing) Subject(io.helidon.security.Subject)

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