Skip to content

Commit

Permalink
- Add a simple UI to the WebServer SSE example.
Browse files Browse the repository at this point in the history
- Update README.md (align with multipart)
- Update endpoints and test to add count and delay parameters
- Add logging provider and logging.properties
  • Loading branch information
romain-grecourt committed Oct 25, 2024
1 parent 39db5d7 commit 33f2d78
Show file tree
Hide file tree
Showing 8 changed files with 271 additions and 102 deletions.
11 changes: 5 additions & 6 deletions examples/webserver/sse/README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# Helidon SE SSE Example

This is a very simple example showing how to use the Helidon SSE API to send events from the
server to a client. It defines a couple of SSE "hello world" endpoints that send either
text or JSON messages. It also uses the SSE extensions to the Helidon WebClient API to test
these endpoints.
This example demonstrates how to use Server Sent Events (SSE) with both the WebServer and WebClient APIs.

This project implements a couple of SSE endpoints that send either text or JSON messages.
The unit test uses the WebClient API to test the endpoints.

## Build, run and test

Expand All @@ -13,5 +13,4 @@ mvn package
java -jar target/helidon-examples-webserver-sse.jar
```

See `SseServiceTest` for additional information on the tests that are executed during
the build process.
Then open http://localhost:8080 in your browser.
22 changes: 12 additions & 10 deletions examples/webserver/sse/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,13 @@
<version>4.2.0-SNAPSHOT</version>
<relativePath/>
</parent>

<groupId>io.helidon.examples.webserver</groupId>
<artifactId>helidon-examples-webserver-sse</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>Helidon Examples WebServer SSE</name>

<properties>
<mainClass>io.helidon.examples.webserver.sse.SseMain</mainClass>
<mainClass>io.helidon.examples.webserver.sse.Main</mainClass>
</properties>

<dependencies>
Expand All @@ -44,22 +43,25 @@
<artifactId>helidon-webserver-sse</artifactId>
</dependency>
<dependency>
<groupId>io.helidon.webclient</groupId>
<artifactId>helidon-webclient-sse</artifactId>
<scope>test</scope>
<groupId>io.helidon.webserver</groupId>
<artifactId>helidon-webserver-static-content</artifactId>
</dependency>
<dependency>
<groupId>jakarta.json</groupId>
<artifactId>jakarta.json-api</artifactId>
</dependency>
<dependency>
<groupId>io.helidon.http.media</groupId>
<artifactId>helidon-http-media-jsonp</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>jakarta.json</groupId>
<artifactId>jakarta.json-api</artifactId>
<groupId>io.helidon.logging</groupId>
<artifactId>helidon-logging-jul</artifactId>
</dependency>
<dependency>
<groupId>io.helidon.http.media</groupId>
<artifactId>helidon-http-media-jsonb</artifactId>
<groupId>io.helidon.webclient</groupId>
<artifactId>helidon-webclient-sse</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.helidon.webserver.testing.junit5</groupId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* Copyright (c) 2024 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.helidon.examples.webserver.sse;

import io.helidon.logging.common.LogConfig;
import io.helidon.webserver.WebServer;
import io.helidon.webserver.http.HttpRules;
import io.helidon.webserver.staticcontent.StaticContentService;

/**
* This application provides a simple service with a UI to exercise Server Sent Events (SSE).
*/
class Main {

private Main() {
}

/**
* Executes the example.
*
* @param args command line arguments, ignored
*/
public static void main(String[] args) {
// load logging configuration
LogConfig.configureRuntime();

WebServer server = WebServer.builder()
.routing(Main::routing)
.port(8080)
.build()
.start();

System.out.println("WEB server is up! http://localhost:" + server.port());
}

/**
* Updates the routing rules.
*
* @param rules routing rules
*/
static void routing(HttpRules rules) {
rules.register("/", StaticContentService.builder("WEB")
.welcomeFileName("index.html")
.build())
.register("/api", new SseService());
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -15,44 +15,62 @@
*/
package io.helidon.examples.webserver.sse;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

import io.helidon.http.sse.SseEvent;
import io.helidon.webserver.http.HttpRules;
import io.helidon.webserver.http.HttpService;
import io.helidon.webserver.http.ServerRequest;
import io.helidon.webserver.http.ServerResponse;
import io.helidon.webserver.sse.SseSink;

import jakarta.json.Json;
import jakarta.json.JsonObject;
import jakarta.json.spi.JsonProvider;

/**
* An HTTP that sends SSE.
*/
class SseService implements HttpService {

private static final JsonProvider JSON_PROVIDER = JsonProvider.provider();

@Override
public void routing(HttpRules httpRules) {
httpRules.get("/sse_text", this::sseText)
.get("/sse_json", this::sseJson);
}

void sseText(ServerRequest req, ServerResponse res) {
void sseText(ServerRequest req, ServerResponse res) throws InterruptedException {
int count = req.query().first("count").asInt().orElse(1);
int delay = req.query().first("delay").asInt().orElse(0);
try (SseSink sseSink = res.sink(SseSink.TYPE)) {
sseSink.emit(SseEvent.builder()
.comment("first line")
.name("first")
.data("hello")
.build())
.emit(SseEvent.builder()
.name("second")
.data("world")
.build());
for (int i = 0; i < count; i++) {
sseSink.emit(SseEvent.builder()
.comment("comment#" + i)
.name("my-event")
.data("data#" + i)
.build());

if (delay > 0) {
Thread.sleep(Duration.ofSeconds(delay));
}
}
}
}

void sseJson(ServerRequest req, ServerResponse res) {
JsonObject json = Json.createObjectBuilder()
.add("hello", "world")
.build();
void sseJson(ServerRequest req, ServerResponse res) throws InterruptedException {
int count = req.query().first("count").asInt().orElse(1);
int delay = req.query().first("delay").asInt().orElse(0);
try (SseSink sseSink = res.sink(SseSink.TYPE)) {
sseSink.emit(SseEvent.create(json));
for (int i = 0; i < count; i++) {
sseSink.emit(SseEvent.create(JSON_PROVIDER.createObjectBuilder()
.add("data", "data#" + i)
.build()));

if (delay > 0) {
Thread.sleep(Duration.ofSeconds(delay));
}
}
}
}
}
107 changes: 107 additions & 0 deletions examples/webserver/sse/src/main/resources/WEB/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
<!DOCTYPE html>
<!--
Copyright (c) 2024 Oracle and/or its affiliates.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<html lang="en">
<meta charset="utf-8"/>
<head>
<title>Helidon Examples WebServer SSE</title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<style>
.container {
width: 400px;
}
.controls {
display: flex;
flex-direction: row;
justify-content: space-between;
}
.controls input {
flex-grow: 1;
}
.controls input:not(:first-child) {
margin-left: 10px;
}
.events {
overflow-y: auto;
height: 400px;
margin: 10px 0 10px 0;
background-color: #f3f4f9;
color: #2F4F4F;
}
.events span {
display: block;
}
</style>
</head>
<body>
<h1>Text events</h1>
<div id="text_events" class="container">
<div class="controls">
<input type="button" value="start" />
<input type="button" value="stop" disabled/>
</div>
<div class="events"></div>
</div>
<h1>JSON events</h1>
<div id="json_events" class="container">
<div class="controls">
<input type="button" value="start" />
<input type="button" value="stop" disabled/>
</div>
<div class="events"></div>
</div>
<script type="text/javascript">
$(document).ready(() => {
class Events {
constructor(rootEltId, uri, eventType) {
this.uri = uri;
this.eventSource = null;
this.rootElt = $(rootEltId);
this.eventsElt = this.rootElt.find('.events');
this.startButton = this.rootElt.find('input[value="start"]');
this.stopButton = this.rootElt.find('input[value="stop"]');
this.startButton.click(() => {
this.eventsElt.empty();
this.eventSource = new EventSource(this.uri);
this.eventSource.addEventListener('error', () => {
// server side stops after count
// prevent restart
this.eventSource.close();
this.toggle(false);
});
this.eventSource.addEventListener(eventType, event => {
this.eventsElt.append(`<span>${event.data}</span>`);
});
this.toggle(true);
});
this.stopButton.click(() => {
this.eventSource.close();
this.toggle(false);
});
}
toggle(active) {
this.startButton[0].disabled = active;
this.stopButton[0].disabled = !active;
}
}
new Events('#text_events', '/api/sse_text?count=30&delay=1', 'my-event');
new Events('#json_events', '/api/sse_json?count=10&delay=1', 'message');
});
</script>
</body>
</html>
21 changes: 21 additions & 0 deletions examples/webserver/sse/src/main/resources/logging.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#
# Copyright (c) 2018, 2024 Oracle and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

handlers=java.util.logging.ConsoleHandler
java.util.logging.SimpleFormatter.format=%1$tY.%1$tm.%1$td %1$tH:%1$tM:%1$tS.%1$tL %5$s%6$s%n
# Global logging level. Can be overridden by specific loggers
.level=INFO
io.helidon.webserver.level=INFO
Loading

0 comments on commit 33f2d78

Please sign in to comment.