X-Git-Url: https://git.nmode.ca/signal-cli/blobdiff_plain/1d98e5307ad42052b1463df1f7f3744828a04c5a..a780be70dd98679b732baa9ef0a4645126d31b08:/src/main/java/org/asamk/signal/http/ServerSentEventSender.java diff --git a/src/main/java/org/asamk/signal/http/ServerSentEventSender.java b/src/main/java/org/asamk/signal/http/ServerSentEventSender.java new file mode 100644 index 00000000..b33d3310 --- /dev/null +++ b/src/main/java/org/asamk/signal/http/ServerSentEventSender.java @@ -0,0 +1,55 @@ +package org.asamk.signal.http; + +import java.io.BufferedWriter; +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.nio.charset.StandardCharsets; +import java.util.List; + +/** + * This class send Server-sent events payload to an OutputStream. + * See spec + */ +public class ServerSentEventSender { + + private final BufferedWriter writer; + + public ServerSentEventSender(final OutputStream outputStream) { + this.writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)); + } + + /** + * @param id Event id + * @param event Event type + * @param data Event data, each entry must not contain newline chars. + */ + public synchronized void sendEvent(String id, String event, List data) throws IOException { + if (id != null) { + writer.write("id:"); + writer.write(id); + writer.write("\n"); + } + if (event != null) { + writer.write("event:"); + writer.write(event); + writer.write("\n"); + } + if (data.size() == 0) { + writer.write("data\n"); + } else { + for (final var d : data) { + writer.write("data:"); + writer.write(d); + writer.write("\n"); + } + } + writer.write("\n"); + writer.flush(); + } + + public synchronized void sendKeepAlive() throws IOException { + writer.write(":\n"); + writer.flush(); + } +}