Search in sources :

Example 6 with Routing

use of io.helidon.webserver.Routing in project metro-jax-ws by eclipse-ee4j.

the class Main method startServer.

static WebServer startServer() {
    setupLogging();
    // By default this will pick up application.yaml from the classpath
    Config config = buildConfig();
    // Get webserver config from the "server" section of application.yaml
    WebServer server = WebServer.builder().config(config.get("server")).routing(buildRouting(config)).build();
    // Try to start the server. If successful, print some info and arrange to
    // print a message at shutdown. If unsuccessful, print the exception.
    server.start().thenAccept(ws -> {
        System.out.println("WEB server is up! http://localhost:" + ws.port());
        ws.whenShutdown().thenRun(() -> System.out.println("WEB server is DOWN. Good bye!"));
    }).exceptionally(t -> {
        System.err.println("Startup failed: " + t.getMessage());
        t.printStackTrace(System.err);
        return null;
    });
    // Server threads are not daemon. No need to block. Just react.
    return server;
}
Also used : Config(io.helidon.config.Config) LogManager(java.util.logging.LogManager) WebServer(io.helidon.webserver.WebServer) MetroSupport(org.eclipse.metro.helidon.MetroSupport) IOException(java.io.IOException) ConfigSources(io.helidon.config.ConfigSources) Routing(io.helidon.webserver.Routing) InputStream(java.io.InputStream) WebServer(io.helidon.webserver.WebServer) Config(io.helidon.config.Config)

Example 7 with Routing

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

the class Main method main.

/**
 * Start the example. Prints endpoints to standard output.
 *
 * @param args not used
 */
public static void main(String[] args) {
    serverStartTime = System.currentTimeMillis();
    HealthSupport health = HealthSupport.builder().addLiveness(HealthChecks.healthChecks()).addReadiness(() -> HealthCheckResponse.named("exampleHealthCheck").up().withData("time", System.currentTimeMillis()).build()).addStartup(() -> HealthCheckResponse.named("exampleStartCheck").status(isStarted()).withData("time", System.currentTimeMillis()).build()).build();
    Routing routing = Routing.builder().register(health).get("/hello", (req, res) -> res.send("Hello World!")).build();
    WebServer ws = WebServer.create(routing);
    ws.start().thenApply(webServer -> {
        String endpoint = "http://localhost:" + webServer.port();
        System.out.println("Hello World started on " + endpoint + "/hello");
        System.out.println("Health checks available on " + endpoint + "/health");
        return null;
    });
}
Also used : HealthCheckResponse(org.eclipse.microprofile.health.HealthCheckResponse) Duration(java.time.Duration) WebServer(io.helidon.webserver.WebServer) Routing(io.helidon.webserver.Routing) HealthSupport(io.helidon.health.HealthSupport) HealthChecks(io.helidon.health.checks.HealthChecks) WebServer(io.helidon.webserver.WebServer) HealthSupport(io.helidon.health.HealthSupport) Routing(io.helidon.webserver.Routing)

Example 8 with Routing

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

the class Main method startServer.

/**
 * Start the server.
 * @return the created {@link WebServer} instance
 */
static Single<WebServer> startServer() {
    // load logging configuration
    LogConfig.configureRuntime();
    // By default this will pick up application.yaml from the classpath
    Config config = Config.create();
    WebServer server = WebServer.builder().routing(createRouting(config)).config(config.get("server")).addMediaSupport(JsonpSupport.create()).build();
    Single<WebServer> webserver = server.start();
    // Try to start the server. If successful, print some info and arrange to
    // print a message at shutdown. If unsuccessful, print the exception.
    webserver.thenAccept(ws -> {
        System.out.println("WEB server is up! http://localhost:" + ws.port() + "/greet");
        ws.whenShutdown().thenRun(() -> System.out.println("WEB server is DOWN. Good bye!"));
    }).exceptionallyAccept(t -> {
        System.err.println("Startup failed: " + t.getMessage());
        t.printStackTrace(System.err);
    });
    return webserver;
}
Also used : JsonpSupport(io.helidon.media.jsonp.JsonpSupport) KeyPerformanceIndicatorMetricsSettings(io.helidon.metrics.KeyPerformanceIndicatorMetricsSettings) Config(io.helidon.config.Config) WebServer(io.helidon.webserver.WebServer) Single(io.helidon.common.reactive.Single) MetricsSupport(io.helidon.metrics.MetricsSupport) LogConfig(io.helidon.common.LogConfig) Routing(io.helidon.webserver.Routing) WebServer(io.helidon.webserver.WebServer) Config(io.helidon.config.Config) LogConfig(io.helidon.common.LogConfig)

Example 9 with Routing

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

the class SignatureExampleUtil method startServer.

/**
 * Start a web server.
 *
 * @param routing routing to configre
 * @return started web server instance
 */
public static WebServer startServer(Routing routing, int port) {
    WebServer server = WebServer.builder(routing).port(port).build();
    long t = System.nanoTime();
    CountDownLatch cdl = new CountDownLatch(1);
    server.start().thenAccept(webServer -> {
        long time = System.nanoTime() - t;
        System.out.printf("Server started in %d ms ms%n", TimeUnit.MILLISECONDS.convert(time, TimeUnit.NANOSECONDS));
        System.out.printf("Started server on localhost:%d%n", webServer.port());
        System.out.println();
        cdl.countDown();
    }).exceptionally(throwable -> {
        throw new RuntimeException("Failed to start server", throwable);
    });
    try {
        cdl.await(START_TIMEOUT_SECONDS, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        throw new RuntimeException("Failed to start server within defined timeout: " + START_TIMEOUT_SECONDS + " seconds");
    }
    return server;
}
Also used : TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) WebClient(io.helidon.webclient.WebClient) WebClientSecurity(io.helidon.webclient.security.WebClientSecurity) ServerResponse(io.helidon.webserver.ServerResponse) WebServer(io.helidon.webserver.WebServer) Optional(java.util.Optional) SecurityContext(io.helidon.security.SecurityContext) Http(io.helidon.common.http.Http) Routing(io.helidon.webserver.Routing) MediaType(io.helidon.common.http.MediaType) ServerRequest(io.helidon.webserver.ServerRequest) WebServer(io.helidon.webserver.WebServer) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 10 with Routing

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

the class Main method routingAsFilter.

/**
 * All routing rules (routes) are evaluated in a definition order. The {@link Handler} assigned with the first valid route
 * for given request is called. It is a responsibility of each handler to process in one of the following ways:
 * <ul>
 *     <li>Respond using one of {@link io.helidon.webserver.ServerResponse#send() ServerResponse.send(...)} method.</li>
 *     <li>Continue to next valid route using {@link io.helidon.webserver.ServerRequest#next() ServerRequest.next()} method.
 *     <i>It is possible to define filtering handlers.</i></li>
 * </ul>
 * <p>
 * If no valid {@link Handler} is found then routing respond by {@code HTTP 404} code.
 * <p>
 * If selected {@link Handler} doesn't process request than the request <b>stacks</b>!
 * <p>
 * <b>Blocking operations:</b><br>
 * For performance reason, {@link Handler} can be called directly by a selector thread. It is not good idea to block
 * such thread. If request must be processed by a blocking operation then such processing should be deferred to another
 * thread.
 */
public void routingAsFilter() {
    Routing routing = Routing.builder().any((req, res) -> {
        System.out.println(req.method() + " " + req.path());
        // Filters are just routing handlers which calls next()
        req.next();
    }).post("/post-endpoint", (req, res) -> res.status(Http.Status.CREATED_201).send()).get("/get-endpoint", (req, res) -> res.status(Http.Status.NO_CONTENT_204).send("Hello World!")).build();
    startServer(routing);
}
Also used : JerseySupport(io.helidon.webserver.jersey.JerseySupport) DataChunk(io.helidon.common.http.DataChunk) RequestPredicate(io.helidon.webserver.RequestPredicate) JsonBuilderFactory(jakarta.json.JsonBuilderFactory) MediaContext(io.helidon.media.common.MediaContext) MessageBodyReader(io.helidon.media.common.MessageBodyReader) InvocationTargetException(java.lang.reflect.InvocationTargetException) MediaType(io.helidon.common.http.MediaType) Json(jakarta.json.Json) JsonpSupport(io.helidon.media.jsonp.JsonpSupport) Handler(io.helidon.webserver.Handler) StaticContentSupport(io.helidon.webserver.staticcontent.StaticContentSupport) Modifier(java.lang.reflect.Modifier) Parameters(io.helidon.common.http.Parameters) HttpException(io.helidon.webserver.HttpException) WebServer(io.helidon.webserver.WebServer) Http(io.helidon.common.http.Http) Routing(io.helidon.webserver.Routing) Method(java.lang.reflect.Method) Collections(java.util.Collections) Routing(io.helidon.webserver.Routing)

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