Search in sources :

Example 11 with WebServer

use of io.helidon.webserver.WebServer 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 12 with WebServer

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

the class ServerMain method startServer.

/**
 * Start the server.
 *
 * @return the created {@link WebServer} instance
 */
static Single<WebServer> startServer() {
    // By default this will pick up application.yaml from the classpath
    Config config = Config.create();
    WebServer server = WebServer.builder(createRouting(config)).config(config.get("server")).addMediaSupport(JsonpSupport.create()).build();
    // Server threads are not daemon. No need to block. Just react.
    return server.start().peek(ws -> {
        serverPort = ws.port();
        System.out.println("WEB server is up! http://localhost:" + ws.port() + "/greet");
        ws.whenShutdown().thenRun(() -> System.out.println("WEB server is DOWN. Good bye!"));
    }).onError(t -> {
        System.err.println("Startup failed: " + t.getMessage());
        t.printStackTrace(System.err);
    });
}
Also used : JsonpSupport(io.helidon.media.jsonp.JsonpSupport) Config(io.helidon.config.Config) WebServer(io.helidon.webserver.WebServer) Single(io.helidon.common.reactive.Single) MetricsSupport(io.helidon.metrics.MetricsSupport) Routing(io.helidon.webserver.Routing) WebServer(io.helidon.webserver.WebServer) Config(io.helidon.config.Config)

Example 13 with WebServer

use of io.helidon.webserver.WebServer 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 14 with WebServer

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

the class VaultsExampleMain method main.

/**
 * Start the server.
 *
 * @param args ignored
 */
public static void main(String[] args) {
    LogConfig.configureRuntime();
    // as I cannot share my configuration of OCI, let's combine the configuration
    // from my home directory with the one compiled into the jar
    // when running this example, you can either update the application.yaml in resources directory
    // or use the same approach
    Config config = buildConfig();
    System.out.println("This example requires a valid OCI Vault, Secret and keys configured. It also requires " + "a Hashicorp Vault running with preconfigured data. Please see README.md");
    Security security = Security.create(config.get("security"));
    WebServer server = WebServer.builder().config(config.get("server")).routing(Routing.builder().register("/secrets", new SecretsService(security)).register("/encryption", new EncryptionService(security)).register("/digests", new DigestService(security))).build().start().await(10, TimeUnit.SECONDS);
    System.out.println("Server started on port: " + server.port());
    String baseAddress = "http://localhost:" + server.port() + "/";
    System.out.println("Secrets endpoints:");
    System.out.println();
    System.out.println("OCI secret:");
    System.out.println("\t" + baseAddress + "secrets/password");
    System.out.println("Config secret:");
    System.out.println("\t" + baseAddress + "secrets/token");
    System.out.println("HCP Vault secret:");
    System.out.println("\t" + baseAddress + "secrets/username");
    System.out.println();
    System.out.println("Encryption endpoints:");
    System.out.println("OCI encrypted:");
    System.out.println("\t" + baseAddress + "encryption/encrypt/crypto-1/text");
    System.out.println("\t" + baseAddress + "encryption/decrypt/crypto-1/cipherText");
    System.out.println("Config encrypted:");
    System.out.println("\t" + baseAddress + "encryption/encrypt/crypto-2/text");
    System.out.println("\t" + baseAddress + "encryption/decrypt/crypto-2/cipherText");
    System.out.println("HCP Vault encrypted:");
    System.out.println("\t" + baseAddress + "encryption/encrypt/crypto-3/text");
    System.out.println("\t" + baseAddress + "encryption/decrypt/crypto-3/cipherText");
    System.out.println();
    System.out.println("Signature/HMAC endpoints:");
    System.out.println("OCI Signature:");
    System.out.println("\t" + baseAddress + "digests/digest/sig-1/text");
    System.out.println("\t" + baseAddress + "digests/verify/sig-1/text/signature");
    System.out.println("HCP Vault Signature:");
    System.out.println("\t" + baseAddress + "digests/digest/sig-2/text");
    System.out.println("\t" + baseAddress + "digests/digest/sig-2/text/signature");
    System.out.println("HCP Vault HMAC:");
    System.out.println("\t" + baseAddress + "digests/digest/hmac-1/text");
    System.out.println("\t" + baseAddress + "digests/digest/hmac-2/text/hmac");
}
Also used : WebServer(io.helidon.webserver.WebServer) Config(io.helidon.config.Config) LogConfig(io.helidon.common.LogConfig) Security(io.helidon.security.Security)

Example 15 with WebServer

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

the class ConfigTest method runWithConfig.

private JsonObject runWithConfig(String configKey, int expectedStatus) throws InterruptedException, ExecutionException, TimeoutException {
    HealthSupport healthSupport = HealthSupport.builder().addLiveness(HealthChecks.healthChecks(testConfig.get(configKey + ".helidon.health"))).build();
    WebServer webServer = null;
    try {
        webServer = startServer(healthSupport);
        WebClientResponse response = webClientBuilder(webServer).build().get().accept(MediaType.APPLICATION_JSON).path("health/live").submit().await();
        assertThat("Normal health URL HTTP response", response.status().code(), is(expectedStatus));
        return response.content().as(JsonObject.class).await();
    } finally {
        if (webServer != null) {
            shutdownServer(webServer);
        }
    }
}
Also used : WebClientResponse(io.helidon.webclient.WebClientResponse) WebServer(io.helidon.webserver.WebServer) HealthSupport(io.helidon.health.HealthSupport) JsonObject(jakarta.json.JsonObject)

Aggregations

WebServer (io.helidon.webserver.WebServer)88 Config (io.helidon.config.Config)49 Routing (io.helidon.webserver.Routing)48 LogConfig (io.helidon.common.LogConfig)34 Single (io.helidon.common.reactive.Single)17 JsonpSupport (io.helidon.media.jsonp.JsonpSupport)16 MetricsSupport (io.helidon.metrics.MetricsSupport)16 HealthSupport (io.helidon.health.HealthSupport)15 HealthChecks (io.helidon.health.checks.HealthChecks)13 ConfigSources (io.helidon.config.ConfigSources)10 TimeUnit (java.util.concurrent.TimeUnit)10 WebClient (io.helidon.webclient.WebClient)9 WebClientResponse (io.helidon.webclient.WebClientResponse)9 CountDownLatch (java.util.concurrent.CountDownLatch)9 Test (org.junit.jupiter.api.Test)9 Http (io.helidon.common.http.Http)8 MediaType (io.helidon.common.http.MediaType)8 IOException (java.io.IOException)8 SecurityContext (io.helidon.security.SecurityContext)7 StaticContentSupport (io.helidon.webserver.staticcontent.StaticContentSupport)7