Search in sources :

Example 51 with Routing

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

the class Main method mediaReader.

/**
 * Use a custom {@link MessageBodyReader reader} to convert the request content into an object of a given type.
 */
public void mediaReader() {
    Routing routing = Routing.builder().post("/create-record", Handler.create(Name.class, (req, res, name) -> {
        System.out.println("Name: " + name);
        res.status(Http.Status.CREATED_201).send(name.toString());
    })).build();
    // Create a media support that contains the defaults and our custom Name reader
    MediaContext mediaContext = MediaContext.builder().addReader(NameReader.create()).build();
    startServer(routing, mediaContext);
}
Also used : MediaContext(io.helidon.media.common.MediaContext) Routing(io.helidon.webserver.Routing)

Example 52 with Routing

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

the class DigestExampleBuilderMain method main.

/**
 * Starts this example. Programmatical configuration. See standard output for instructions.
 *
 * @param args ignored
 */
public static void main(String[] args) {
    // load logging configuration
    LogConfig.configureRuntime();
    // build routing (same as done in application.conf)
    Routing routing = Routing.builder().register(buildWebSecurity().securityDefaults(WebSecurity.authenticate())).get("/noRoles", WebSecurity.enforce()).get("/user[/{*}]", WebSecurity.rolesAllowed("user")).get("/admin", WebSecurity.rolesAllowed("admin")).get("/deny", WebSecurity.rolesAllowed("deny").audit()).any("/noAuthn", WebSecurity.rolesAllowed("admin").authenticationOptional().audit()).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();
    // start server (blocks until started)
    server = DigestExampleUtil.startServer(routing);
}
Also used : Arrays(java.util.Arrays) Security(io.helidon.security.Security) MessageDigest(java.security.MessageDigest) Set(java.util.Set) HashMap(java.util.HashMap) SecurityContext(io.helidon.security.SecurityContext) StandardCharsets(java.nio.charset.StandardCharsets) HttpDigest(io.helidon.security.providers.httpauth.HttpDigest) MediaType(io.helidon.common.http.MediaType) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Map(java.util.Map) WebServer(io.helidon.webserver.WebServer) Optional(java.util.Optional) WebSecurity(io.helidon.security.integration.webserver.WebSecurity) HttpDigestAuthProvider(io.helidon.security.providers.httpauth.HttpDigestAuthProvider) LogConfig(io.helidon.common.LogConfig) Routing(io.helidon.webserver.Routing) SecureUserStore(io.helidon.security.providers.httpauth.SecureUserStore) Optional(java.util.Optional) SecurityContext(io.helidon.security.SecurityContext) Routing(io.helidon.webserver.Routing)

Example 53 with Routing

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

the class CommentsServiceTest method testRouting.

@Test
public void testRouting() throws Exception {
    Routing routing = Routing.builder().register(new CommentsService()).build();
    TestResponse response = TestClient.create(routing).path("one").get();
    assertEquals(Http.Status.OK_200, response.status());
    response = TestClient.create(routing).path("one").post(MediaPublisher.create(MediaType.TEXT_PLAIN, "aaa"));
    assertEquals(Http.Status.OK_200, response.status());
    response = TestClient.create(routing).path("one").get();
    assertEquals(Http.Status.OK_200, response.status());
    byte[] data = response.asBytes().toCompletableFuture().join();
    assertEquals("anonymous: aaa", new String(data, StandardCharsets.UTF_8));
}
Also used : TestResponse(io.helidon.webserver.testsupport.TestResponse) Routing(io.helidon.webserver.Routing) Test(org.junit.jupiter.api.Test)

Example 54 with Routing

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

the class ServerBuilderMain method startServer.

static Single<WebServer> startServer(int unsecured, int secured) {
    SocketConfiguration socketConf = SocketConfiguration.builder().name("secured").port(secured).tls(tlsConfig()).build();
    Single<WebServer> webServer = WebServer.builder().port(unsecured).routing(createPlainRouting()).addSocket(socketConf, createMtlsRouting()).build().start();
    webServer.thenAccept(ws -> {
        System.out.println("WebServer is up!");
        System.out.println("Unsecured: http://localhost:" + ws.port() + "/");
        System.out.println("Secured: https://localhost:" + ws.port("secured") + "/");
        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;
    });
    return webServer;
}
Also used : SocketConfiguration(io.helidon.webserver.SocketConfiguration) KeyConfig(io.helidon.common.pki.KeyConfig) WebServer(io.helidon.webserver.WebServer) Single(io.helidon.common.reactive.Single) ClientAuthentication(io.helidon.webserver.ClientAuthentication) Resource(io.helidon.common.configurable.Resource) Http(io.helidon.common.http.Http) Routing(io.helidon.webserver.Routing) WebServerTls(io.helidon.webserver.WebServerTls) WebServer(io.helidon.webserver.WebServer) SocketConfiguration(io.helidon.webserver.SocketConfiguration)

Example 55 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 io.helidon.webserver.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();
    // Ignore the "gets" timer.
    RegistryFilterSettings.Builder registryFilterSettingsBuilder = RegistryFilterSettings.builder().exclude(GreetService.TIMER_FOR_GETS);
    RegistrySettings.Builder registrySettingsBuilder = RegistrySettings.builder().filterSettings(registryFilterSettingsBuilder);
    MetricsSettings.Builder metricsSettingsBuilder = MetricsSettings.builder().registrySettings(MetricRegistry.Type.APPLICATION, registrySettingsBuilder.build());
    WebServer server = WebServer.builder().routing(createRouting(config, metricsSettingsBuilder)).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) Config(io.helidon.config.Config) RegistryFactory(io.helidon.metrics.api.RegistryFactory) WebServer(io.helidon.webserver.WebServer) Single(io.helidon.common.reactive.Single) RegistryFilterSettings(io.helidon.metrics.api.RegistryFilterSettings) RegistrySettings(io.helidon.metrics.api.RegistrySettings) MetricsSupport(io.helidon.metrics.MetricsSupport) MetricRegistry(org.eclipse.microprofile.metrics.MetricRegistry) LogConfig(io.helidon.common.LogConfig) Routing(io.helidon.webserver.Routing) MetricsSettings(io.helidon.metrics.api.MetricsSettings) WebServer(io.helidon.webserver.WebServer) Config(io.helidon.config.Config) LogConfig(io.helidon.common.LogConfig) RegistryFilterSettings(io.helidon.metrics.api.RegistryFilterSettings) RegistrySettings(io.helidon.metrics.api.RegistrySettings) MetricsSettings(io.helidon.metrics.api.MetricsSettings)

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