Search in sources :

Example 11 with Routing

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

the class Main method advancedRouting.

/**
 * Routing rules (routes) are limited on two criteria - <i>HTTP method and path</i>. {@link RequestPredicate} can be used
 * to specify more complex criteria.
 */
public void advancedRouting() {
    Routing routing = Routing.builder().get("/foo", RequestPredicate.create().accepts(MediaType.TEXT_PLAIN).containsHeader("bar").thenApply((req, res) -> res.send())).build();
    startServer(routing);
}
Also used : Routing(io.helidon.webserver.Routing)

Example 12 with Routing

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

the class Main method supports.

/**
 * Combination of filtering {@link Handler} pattern with {@link io.helidon.webserver.Service Service} registration capabilities
 * can be used by other frameworks for the integration. WebServer is shipped with several integrated libraries (supports)
 * including <i>static content</i>, JSON and Jersey. See {@code POM.xml} for requested dependencies.
 */
public void supports() {
    Routing routing = Routing.builder().register(StaticContentSupport.create("/static")).get("/hello/{what}", (req, res) -> res.send(JSON.createObjectBuilder().add("message", "Hello " + req.path().param("what")).build())).register("/api", JerseySupport.builder().register(HelloWorldResource.class).build()).build();
    MediaContext mediaContext = MediaContext.builder().addWriter(JsonpSupport.writer()).build();
    startServer(routing, mediaContext);
}
Also used : MediaContext(io.helidon.media.common.MediaContext) Routing(io.helidon.webserver.Routing)

Example 13 with Routing

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

the class Main method errorHandling.

/**
 * Request processing can cause error represented by {@link Throwable}. It is possible to register custom
 * {@link io.helidon.webserver.ErrorHandler ErrorHandlers} for specific processing.
 * <p>
 * If error is not processed by a custom {@link io.helidon.webserver.ErrorHandler ErrorHandler} than default one is used.
 * It respond with <i>HTTP 500 code</i> unless error is not represented
 * by {@link HttpException HttpException}. In such case it reflects its content.
 */
public void errorHandling() {
    Routing routing = Routing.builder().post("/compute", Handler.create(String.class, (req, res, str) -> {
        int result = 100 / Integer.parseInt(str);
        res.send(String.valueOf("100 / " + str + " = " + result));
    })).error(Throwable.class, (req, res, ex) -> {
        ex.printStackTrace(System.out);
        req.next();
    }).error(NumberFormatException.class, (req, res, ex) -> res.status(Http.Status.BAD_REQUEST_400).send()).error(ArithmeticException.class, (req, res, ex) -> res.status(Http.Status.PRECONDITION_FAILED_412).send()).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)

Example 14 with Routing

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

the class Main method parametersAndHeaders.

/**
 * {@link io.helidon.webserver.ServerRequest ServerRequest} provides access to three types of "parameters":
 * <ul>
 *     <li>Headers</li>
 *     <li>Query parameters</li>
 *     <li>Path parameters - <i>Evaluated from provided {@code path pattern}</i></li>
 * </ul>
 * <p>
 * {@link java.util.Optional Optional} API is heavily used to represent parameters optionality.
 * <p>
 * WebServer {@link Parameters Parameters} API is used to represent fact, that <i>headers</i> and
 * <i>query parameters</i> can contain multiple values.
 */
public void parametersAndHeaders() {
    Routing routing = Routing.builder().get("/context/{id}", (req, res) -> {
        StringBuilder sb = new StringBuilder();
        // Request headers
        req.headers().first("foo").ifPresent(v -> sb.append("foo: ").append(v).append("\n"));
        // Request parameters
        req.queryParams().first("bar").ifPresent(v -> sb.append("bar: ").append(v).append("\n"));
        // Path parameters
        sb.append("id: ").append(req.path().param("id"));
        // Response headers
        res.headers().contentType(MediaType.TEXT_PLAIN);
        // Response entity (payload)
        res.send(sb.toString());
    }).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)

Example 15 with Routing

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

the class OutboundOverrideExample method startServingService.

static CompletionStage<Void> startServingService(int port) {
    Config config = createConfig("serving-service");
    Routing routing = Routing.builder().register(WebSecurity.create(config.get("security"))).get("/hello", (req, res) -> {
        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) HttpBasicAuthProvider(io.helidon.security.providers.httpauth.HttpBasicAuthProvider) Config(io.helidon.config.Config) OutboundOverrideUtil.createConfig(io.helidon.security.examples.outbound.OutboundOverrideUtil.createConfig) 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