vs.pu02 durch lokale Version ersetzen, BOM korrekt kodieren
TextMessage.toString() stellt den BOM als drei Latin-1-Zeichen voran, die im UTF-8-Websocket als "" ankamen. MqttAdapter.format() ersetzt dieses Präfix durch U+FEFF (UTF-8: EF BB BF), Test in MqttAdapterTest. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>marwe
parent
b9a17a82af
commit
f452920026
|
|
@ -0,0 +1,17 @@
|
|||
# vs.pu02 – Syslog-Adapter MQTT → Websocket
|
||||
|
||||
Java 17, Servlet 5.0 / Websocket 2.0 (Tomcat ≥ 10, Jetty ≥ 11), MQTT über Eclipse Paho (Maven-Dependency).
|
||||
|
||||
```
|
||||
mvn package
|
||||
```
|
||||
`target/vs.pu02-1.0-SNAPSHOT.war` als `webapps/ROOT.war` deployen (Kontextpfad "/"), dann http://localhost:8080/ öffnen.
|
||||
|
||||
| Datei | Aufgabe |
|
||||
|---|---|
|
||||
| `vs/adapter/MqttAdapter.java` | eine Instanz, zwei MqttClients (je ein Broker + Topic), Deserialisierung, Filter sev ≥ WARNING |
|
||||
| `vs/adapter/SyslogEndpoint.java` | Websocket `/syslog`, sendet an alle Clients |
|
||||
| `vs/adapter/ConfigServlet.java` | `/config`, nimmt das Formular entgegen, hält die Adapter-Instanz |
|
||||
| `webapp/index.html` | Formular + Websocket-Client |
|
||||
|
||||
Die vorgegebenen Klassen (`AsciiChars`, `StructuredData`, `SyslogMessage`) sind unverändert.
|
||||
|
|
@ -9,33 +9,31 @@
|
|||
<maven.compiler.release>17</maven.compiler.release>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>jakarta.servlet</groupId>
|
||||
<artifactId>jakarta.servlet-api</artifactId>
|
||||
<version>5.0.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>jakarta.websocket</groupId>
|
||||
<artifactId>jakarta.websocket-api</artifactId>
|
||||
<version>2.0.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<!-- NEU: MQTT-Client, kommt mit ins WAR -->
|
||||
<dependency>
|
||||
<groupId>org.eclipse.paho</groupId>
|
||||
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
|
||||
<version>1.2.5</version>
|
||||
</dependency>
|
||||
<!-- Ende NEU -->
|
||||
<dependency><!-- für Unit-Tests -->
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>5.10.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>jakarta.servlet</groupId>
|
||||
<artifactId>jakarta.servlet-api</artifactId>
|
||||
<version>5.0.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>jakarta.websocket</groupId>
|
||||
<artifactId>jakarta.websocket-api</artifactId>
|
||||
<version>2.0.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency><!-- MQTT-Client (Eclipse Paho), wird ins WAR gepackt -->
|
||||
<groupId>org.eclipse.paho</groupId>
|
||||
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
|
||||
<version>1.2.5</version>
|
||||
</dependency>
|
||||
<dependency><!-- für Unit-Tests -->
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>5.10.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
|
|
|||
|
|
@ -1,11 +0,0 @@
|
|||
package vs;
|
||||
|
||||
|
||||
import org.eclipse.paho.client.mqttv3.MqttClient;
|
||||
|
||||
public class Adapter {
|
||||
MqttClient a;
|
||||
MqttClient b;
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -1,5 +1,4 @@
|
|||
package vs;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* helper class for RFC 5424 (https://datatracker.ietf.org/doc/html/rfc5424)
|
||||
|
|
@ -9,7 +8,7 @@ import java.io.Serializable;
|
|||
* @author Sandro Leuchter
|
||||
*
|
||||
*/
|
||||
public abstract class AsciiChars implements Serializable{
|
||||
public abstract class AsciiChars {
|
||||
private final String value;
|
||||
|
||||
public String value() {
|
||||
|
|
|
|||
|
|
@ -1,16 +0,0 @@
|
|||
package vs;
|
||||
|
||||
import jakarta.servlet.annotation.WebServlet;
|
||||
import jakarta.servlet.http.*;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
@WebServlet("/hello")
|
||||
public class MainServlet extends HttpServlet {
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
response.setContentType("text/html");
|
||||
PrintWriter writer = response.getWriter();
|
||||
writer.println("<html><body>Hello World</body></html>");
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,5 @@
|
|||
package vs;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
|
|
@ -13,8 +12,8 @@ import java.util.List;
|
|||
* @author Sandro Leuchter
|
||||
*
|
||||
*/
|
||||
public class StructuredData implements Serializable {
|
||||
static public class Element implements Serializable {
|
||||
public class StructuredData {
|
||||
static public class Element {
|
||||
private final String name;
|
||||
private List<Param> parameters;
|
||||
|
||||
|
|
@ -102,7 +101,7 @@ public class StructuredData implements Serializable {
|
|||
}
|
||||
}
|
||||
|
||||
static public class Param implements Serializable {
|
||||
static public class Param {
|
||||
private final String name;
|
||||
// name: printable US-ASCII string ^[@=\]\"\s]+
|
||||
// "@" + private enterpise number "@\d+(\.\d+)*"
|
||||
|
|
|
|||
|
|
@ -84,7 +84,7 @@ public class SyslogMessage implements Serializable {
|
|||
DEBUG;
|
||||
}
|
||||
|
||||
public static interface Message extends Serializable {
|
||||
public static interface Message {
|
||||
public Object message();
|
||||
|
||||
public int length();
|
||||
|
|
|
|||
|
|
@ -1,53 +0,0 @@
|
|||
package vs;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectOutputStream;
|
||||
|
||||
import org.eclipse.paho.client.mqttv3.MqttClient;
|
||||
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
|
||||
|
||||
import vs.StructuredData.Element;
|
||||
import vs.SyslogMessage.Facility;
|
||||
import vs.SyslogMessage.Severity;
|
||||
import vs.SyslogMessage.TextMessage;
|
||||
|
||||
public class SyslogSender {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
String[][] ziele = {
|
||||
{ "tcp://localhost:1883", "vs/a" },
|
||||
{ "tcp://localhost:1884", "vs/b" } };
|
||||
|
||||
for (String[] z : ziele) {
|
||||
MqttClient client = new MqttClient(z[0],
|
||||
MqttClient.generateClientId(), new MemoryPersistence());
|
||||
client.connect();
|
||||
|
||||
for (Severity sev : Severity.values()) {
|
||||
SyslogMessage msg = new SyslogMessage(
|
||||
Facility.SECURITY1, sev,
|
||||
new AsciiChars.L255("mymachine.example.com"),
|
||||
new AsciiChars.L048("su"),
|
||||
new AsciiChars.L128(""),
|
||||
new AsciiChars.L032("ID47"),
|
||||
new StructuredData().add(Element.newTimeQuality(true, true)),
|
||||
new TextMessage(sev + " über " + z[1]));
|
||||
client.publish(z[1], serialisieren(msg), 1, false);
|
||||
}
|
||||
client.publish(z[1], "nur Text".getBytes(), 1, false);
|
||||
System.out.println("gesendet an " + z[0] + " / " + z[1]);
|
||||
|
||||
client.disconnect();
|
||||
client.close();
|
||||
}
|
||||
}
|
||||
|
||||
static byte[] serialisieren(Object o) throws IOException {
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
try (ObjectOutputStream out = new ObjectOutputStream(bos)) {
|
||||
out.writeObject(o);
|
||||
}
|
||||
return bos.toByteArray();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,33 +0,0 @@
|
|||
package vs.adapter;
|
||||
|
||||
import jakarta.servlet.ServletContext;
|
||||
import jakarta.servlet.ServletContextEvent;
|
||||
import jakarta.servlet.ServletContextListener;
|
||||
import jakarta.servlet.annotation.WebListener;
|
||||
|
||||
@WebListener
|
||||
public class AdapterLifecycle implements ServletContextListener {
|
||||
|
||||
static final String ATTR = "mqttAdapter";
|
||||
|
||||
/** Holt den Adapter aus dem ServletContext. */
|
||||
static MqttAdapter adapter(ServletContext ctx) {
|
||||
return (MqttAdapter) ctx.getAttribute(ATTR);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void contextInitialized(ServletContextEvent sce) {
|
||||
MqttAdapter adapter = new MqttAdapter(SyslogEndpoint::broadcast);
|
||||
sce.getServletContext().setAttribute(ATTR, adapter);
|
||||
System.out.println("MqttAdapter erzeugt");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void contextDestroyed(ServletContextEvent sce) {
|
||||
MqttAdapter adapter = adapter(sce.getServletContext());
|
||||
if (adapter != null) {
|
||||
adapter.close();
|
||||
}
|
||||
System.out.println("MqttAdapter geschlossen");
|
||||
}
|
||||
}
|
||||
|
|
@ -7,43 +7,50 @@ import jakarta.servlet.http.HttpServlet;
|
|||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.eclipse.paho.client.mqttv3.MqttException;
|
||||
|
||||
/**
|
||||
* Nimmt das Web-Formular (server1/topic1, server2/topic2) entgegen und
|
||||
* konfiguriert damit die eine Adapter-Instanz. Der Container erzeugt genau
|
||||
* eine Instanz dieses Servlets, daher gibt es auch genau einen Adapter.
|
||||
* Ein leeres Server-Feld trennt die jeweilige Verbindung.
|
||||
*/
|
||||
@WebServlet("/config")
|
||||
public class ConfigServlet extends HttpServlet {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private final transient MqttAdapter adapter = new MqttAdapter();
|
||||
|
||||
@Override
|
||||
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
|
||||
throws IOException {
|
||||
req.setCharacterEncoding("UTF-8");
|
||||
MqttAdapter adapter = AdapterLifecycle.adapter(getServletContext());
|
||||
StringBuilder status = new StringBuilder();
|
||||
|
||||
for (int slot = 0; slot < MqttAdapter.SLOTS; slot++) {
|
||||
String server = trim(req.getParameter("server" + (slot + 1)));
|
||||
String topic = trim(req.getParameter("topic" + (slot + 1)));
|
||||
|
||||
if (server.isEmpty()) {
|
||||
adapter.disconnect(slot);
|
||||
status.append("Broker ").append(slot + 1).append(": getrennt\n");
|
||||
var result = new StringBuilder();
|
||||
for (int i = 0; i < 2; i++) {
|
||||
var server = req.getParameter("server" + (i + 1));
|
||||
var topic = req.getParameter("topic" + (i + 1));
|
||||
if (server == null || server.isBlank()) {
|
||||
adapter.disconnect(i);
|
||||
result.append("Broker ").append(i + 1).append(": getrennt\n");
|
||||
continue;
|
||||
}
|
||||
if (!server.contains("://")) {
|
||||
server = "tcp://" + server; // "localhost:1883" -> "tcp://localhost:1883"
|
||||
}
|
||||
try {
|
||||
adapter.connect(slot, server, topic.isEmpty() ? "#" : topic);
|
||||
status.append("Broker ").append(slot + 1).append(": verbunden mit ")
|
||||
.append(server).append(" (").append(topic).append(")\n");
|
||||
} catch (Exception e) {
|
||||
status.append("Broker ").append(slot + 1).append(": FEHLER ")
|
||||
.append(e.getMessage()).append("\n");
|
||||
adapter.connect(i, server.strip(), topic.strip());
|
||||
result.append("Broker ").append(i + 1).append(": verbunden mit ")
|
||||
.append(server.strip()).append(", Topic ")
|
||||
.append(topic.strip()).append('\n');
|
||||
} catch (MqttException | IllegalArgumentException e) {
|
||||
result.append("Broker ").append(i + 1).append(": Fehler: ")
|
||||
.append(e).append('\n');
|
||||
}
|
||||
}
|
||||
|
||||
resp.setContentType("text/plain; charset=UTF-8");
|
||||
resp.getWriter().print(status);
|
||||
resp.setContentType("text/plain");
|
||||
resp.setCharacterEncoding("UTF-8");
|
||||
resp.getWriter().write(result.toString());
|
||||
}
|
||||
|
||||
private static String trim(String s) {
|
||||
return s == null ? "" : s.strip();
|
||||
/** Beim Herunterfahren der Web-Anwendung alle MQTT-Verbindungen trennen. */
|
||||
@Override
|
||||
public void destroy() {
|
||||
adapter.disconnectAll();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package vs.adapter;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ObjectInputStream;
|
||||
|
||||
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
|
||||
import org.eclipse.paho.client.mqttv3.MqttCallback;
|
||||
|
|
@ -9,51 +10,38 @@ import org.eclipse.paho.client.mqttv3.MqttException;
|
|||
import org.eclipse.paho.client.mqttv3.MqttMessage;
|
||||
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
|
||||
|
||||
public class MqttAdapter {
|
||||
import vs.SyslogMessage;
|
||||
import vs.SyslogMessage.Severity;
|
||||
|
||||
public static final int SLOTS = 2;
|
||||
/**
|
||||
* Adapter MQTT -> Websocket. Eine Instanz kann gleichzeitig mit zwei
|
||||
* MQTT-Brokern verbunden sein (ein MqttClient pro Broker) und abonniert je
|
||||
* Broker genau ein Topic.
|
||||
*/
|
||||
public class MqttAdapter implements MqttCallback {
|
||||
|
||||
private final MqttClient[] clients = new MqttClient[SLOTS];
|
||||
private final Consumer<String> ziel;
|
||||
private final MqttClient[] clients = new MqttClient[2];
|
||||
|
||||
/** @param ziel bekommt den Text jeder weitergeleiteten Nachricht */
|
||||
public MqttAdapter(Consumer<String> ziel) {
|
||||
this.ziel = ziel;
|
||||
}
|
||||
|
||||
/** Verbindet Slot 0 oder 1 mit einem Broker und abonniert ein Topic. */
|
||||
public synchronized void connect(int slot, String server, String topic)
|
||||
/**
|
||||
* Verbindet Broker {@code nr} (0 oder 1) mit {@code server} und abonniert
|
||||
* {@code topic}. Eine bestehende Verbindung dieses Brokers wird vorher
|
||||
* getrennt.
|
||||
*/
|
||||
public synchronized void connect(int nr, String server, String topic)
|
||||
throws MqttException {
|
||||
disconnect(slot); // alte Verbindung in diesem Slot vorher schließen
|
||||
|
||||
MqttClient client = new MqttClient(server,
|
||||
MqttClient.generateClientId(), new MemoryPersistence());
|
||||
|
||||
client.setCallback(new MqttCallback() {
|
||||
@Override
|
||||
public void messageArrived(String t, MqttMessage message) {
|
||||
verarbeite(message.getPayload());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connectionLost(Throwable cause) {
|
||||
System.err.println("Slot " + slot + ": Verbindung verloren: " + cause);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deliveryComplete(IMqttDeliveryToken token) {
|
||||
}
|
||||
});
|
||||
|
||||
disconnect(nr);
|
||||
var client = new MqttClient(server, MqttClient.generateClientId(),
|
||||
new MemoryPersistence());
|
||||
client.setCallback(this);
|
||||
client.connect();
|
||||
client.subscribe(topic, 1);
|
||||
clients[slot] = client;
|
||||
client.subscribe(topic);
|
||||
clients[nr] = client;
|
||||
}
|
||||
|
||||
/** Trennt die Verbindung in diesem Slot (falls vorhanden). */
|
||||
public synchronized void disconnect(int slot) {
|
||||
MqttClient client = clients[slot];
|
||||
clients[slot] = null;
|
||||
/** Trennt die Verbindung zu Broker {@code nr}, falls vorhanden. */
|
||||
public synchronized void disconnect(int nr) {
|
||||
var client = clients[nr];
|
||||
clients[nr] = null;
|
||||
if (client == null) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -63,36 +51,84 @@ public class MqttAdapter {
|
|||
}
|
||||
client.close();
|
||||
} catch (MqttException e) {
|
||||
System.err.println("Fehler beim Trennen: " + e);
|
||||
// Verbindung ist ohnehin weg
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized boolean isConnected(int slot) {
|
||||
return clients[slot] != null && clients[slot].isConnected();
|
||||
public void disconnectAll() {
|
||||
disconnect(0);
|
||||
disconnect(1);
|
||||
}
|
||||
|
||||
/** Alle Verbindungen schließen (z.B. beim Herunterfahren). */
|
||||
public synchronized void close() {
|
||||
for (int i = 0; i < SLOTS; i++) {
|
||||
disconnect(i);
|
||||
/** Wird von Paho für jede empfangene Nachricht (beider Broker) aufgerufen. */
|
||||
@Override
|
||||
public void messageArrived(String topic, MqttMessage message) {
|
||||
var msg = deserialize(message.getPayload());
|
||||
if (msg != null && isRelevant(msg)) {
|
||||
try {
|
||||
SyslogEndpoint.broadcast(format(msg));
|
||||
} catch (RuntimeException e) {
|
||||
// toString() nicht möglich (z.B. host == null) -> verwerfen
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Auspacken, filtern, weitergeben. */
|
||||
void verarbeite(byte[] payload) {
|
||||
SyslogDecoder.decode(payload)
|
||||
.filter(SyslogDecoder::isRelevant)
|
||||
.ifPresent(m -> {
|
||||
String text;
|
||||
try {
|
||||
text = m.toString();
|
||||
} catch (RuntimeException e) {
|
||||
// z.B. host == null -> NullPointerException; ohne catch
|
||||
// würde Paho die Broker-Verbindung trennen
|
||||
System.err.println("SyslogMessage nicht darstellbar: " + e);
|
||||
return;
|
||||
}
|
||||
ziel.accept(text);
|
||||
});
|
||||
/** BOM als drei einzelne Latin-1-Zeichen, wie TextMessage.toString() ihn erzeugt. */
|
||||
private static final String BROKEN_BOM = "";
|
||||
/** Der echte BOM (U+FEFF); als UTF-8 kodiert ergibt er genau EF BB BF. */
|
||||
private static final String BOM = "";
|
||||
|
||||
/**
|
||||
* Wie {@link SyslogMessage#toString()}, aber mit korrekt kodiertem BOM vor
|
||||
* der Textnachricht. TextMessage.toString() stellt die UTF-8-Bytes des BOM
|
||||
* als drei Zeichen voran, die im (UTF-8-)Websocket als "" ankommen. Es
|
||||
* wird nur dieses Präfix ersetzt, der Nachrichtentext selbst bleibt
|
||||
* unverändert.
|
||||
*/
|
||||
static String format(SyslogMessage m) {
|
||||
var s = m.toString();
|
||||
if (m.message() instanceof SyslogMessage.TextMessage
|
||||
&& m.message().message() instanceof String text
|
||||
&& s.endsWith(BROKEN_BOM + text)) {
|
||||
return s.substring(0, s.length() - BROKEN_BOM.length() - text.length())
|
||||
+ BOM + text;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return die enthaltene SyslogMessage (oder ein Untertyp) oder null, wenn
|
||||
* die Payload kein serialisiertes SyslogMessage-Objekt ist
|
||||
*/
|
||||
static SyslogMessage deserialize(byte[] payload) {
|
||||
try (var in = new ObjectInputStream(new ByteArrayInputStream(payload))) {
|
||||
// instanceof gilt auch für alle Untertypen von SyslogMessage
|
||||
if (in.readObject() instanceof SyslogMessage m) {
|
||||
return m;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// kein serialisiertes Java-Objekt bzw. unbekannte Klasse
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Severity ist nach Schwere geordnet (EMERGENCY = 0 ... DEBUG = 7), daher
|
||||
* reicht ein Vergleich der Ordinalwerte.
|
||||
*
|
||||
* @return true bei EMERGENCY, ALERT, CRITICAL, ERROR und WARNING
|
||||
*/
|
||||
static boolean isRelevant(SyslogMessage m) {
|
||||
return m.sev() != null && m.sev().ordinal() <= Severity.WARNING.ordinal();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connectionLost(Throwable cause) {
|
||||
// keine automatische Wiederverbindung gefordert
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deliveryComplete(IMqttDeliveryToken token) {
|
||||
// der Adapter publiziert nicht
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,39 +0,0 @@
|
|||
package vs.adapter;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.util.Optional;
|
||||
|
||||
import vs.SyslogMessage;
|
||||
import vs.SyslogMessage.Severity;
|
||||
|
||||
public final class SyslogDecoder {
|
||||
|
||||
private SyslogDecoder() {
|
||||
// nur statische Methoden, keine Objekte nötig
|
||||
}
|
||||
|
||||
/** Bytes -> SyslogMessage, oder leer, wenn keine drinsteckt. */
|
||||
public static Optional<SyslogMessage> decode(byte[] payload) {
|
||||
if (payload == null || payload.length == 0) {
|
||||
return Optional.empty();
|
||||
}
|
||||
try (ObjectInputStream in = new ObjectInputStream(
|
||||
new ByteArrayInputStream(payload))) {
|
||||
Object o = in.readObject();
|
||||
if (o instanceof SyslogMessage m) {
|
||||
return Optional.of(m);
|
||||
}
|
||||
return Optional.empty();
|
||||
} catch (Exception e) {
|
||||
System.err.println("Decode-Fehler: " + e);
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
/** true für EMERGENCY, ALERT, CRITICAL, ERROR, WARNING */
|
||||
public static boolean isRelevant(SyslogMessage m) {
|
||||
return m.sev() != null
|
||||
&& m.sev().ordinal() <= Severity.WARNING.ordinal();
|
||||
}
|
||||
}
|
||||
|
|
@ -5,21 +5,24 @@ import java.util.Set;
|
|||
import java.util.concurrent.CopyOnWriteArraySet;
|
||||
|
||||
import jakarta.websocket.OnClose;
|
||||
import jakarta.websocket.OnError;
|
||||
import jakarta.websocket.OnOpen;
|
||||
import jakarta.websocket.Session;
|
||||
import jakarta.websocket.server.ServerEndpoint;
|
||||
|
||||
/**
|
||||
* Websocket relativ zum Kontextpfad unter "/syslog". Jeder verbundene Client
|
||||
* erhält alle weitergeleiteten Syslog-Nachrichten als Text.
|
||||
*/
|
||||
@ServerEndpoint("/syslog")
|
||||
public class SyslogEndpoint {
|
||||
|
||||
// alle offenen Browser-Verbindungen (für alle Endpoint-Objekte gemeinsam)
|
||||
// pro Client erzeugt der Container eine eigene Endpoint-Instanz,
|
||||
// daher sind die Sessions statisch für alle gemeinsam gespeichert
|
||||
private static final Set<Session> SESSIONS = new CopyOnWriteArraySet<>();
|
||||
|
||||
@OnOpen
|
||||
public void onOpen(Session session) {
|
||||
SESSIONS.add(session);
|
||||
System.out.println("WebSocket geöffnet, jetzt " + SESSIONS.size() + " Clients");
|
||||
}
|
||||
|
||||
@OnClose
|
||||
|
|
@ -27,23 +30,18 @@ public class SyslogEndpoint {
|
|||
SESSIONS.remove(session);
|
||||
}
|
||||
|
||||
@OnError
|
||||
public void onError(Session session, Throwable t) {
|
||||
SESSIONS.remove(session);
|
||||
}
|
||||
|
||||
/** Schickt den Text an alle verbundenen Browser. */
|
||||
/** Sendet {@code text} an alle verbundenen Websocket-Clients. */
|
||||
public static void broadcast(String text) {
|
||||
for (Session s : SESSIONS) {
|
||||
for (var s : SESSIONS) {
|
||||
// beide MQTT-Verbindungen haben eigene Threads: nicht gleichzeitig
|
||||
// auf dieselbe Session schreiben
|
||||
synchronized (s) {
|
||||
try {
|
||||
if (s.isOpen()) {
|
||||
s.getBasicRemote().sendText(text);
|
||||
}
|
||||
} catch (IOException | IllegalStateException e) {
|
||||
s.getBasicRemote().sendText(text);
|
||||
} catch (IOException e) {
|
||||
SESSIONS.remove(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,52 +1,33 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Syslog-Adapter</title>
|
||||
<meta charset="UTF-8">
|
||||
<title>Syslog-Adapter</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Syslog-Adapter: MQTT → WebSocket</h1>
|
||||
<h1>Syslog-Adapter MQTT → Websocket</h1>
|
||||
|
||||
<h2>MQTT-Broker</h2>
|
||||
<form id="cfg">
|
||||
<p>Broker 1:
|
||||
<input name="server1" placeholder="tcp://localhost:1883" size="30">
|
||||
Topic: <input name="topic1" placeholder="vs/a">
|
||||
</p>
|
||||
<p>Broker 2:
|
||||
<input name="server2" placeholder="tcp://localhost:1884" size="30">
|
||||
Topic: <input name="topic2" placeholder="vs/b">
|
||||
</p>
|
||||
<button type="submit">Verbinden</button>
|
||||
<!-- Antwort des Servlets erscheint im iframe, damit der Websocket offen bleibt -->
|
||||
<form method="post" action="config" target="result">
|
||||
<p>Broker 1: <input name="server1" placeholder="tcp://localhost:1883" size="35">
|
||||
Topic: <input name="topic1" placeholder="vs/syslog"></p>
|
||||
<p>Broker 2: <input name="server2" placeholder="tcp://localhost:1884" size="35">
|
||||
Topic: <input name="topic2" placeholder="vs/syslog"></p>
|
||||
<p><button type="submit">Verbinden</button></p>
|
||||
</form>
|
||||
<pre id="cfgStatus"></pre>
|
||||
<iframe name="result" style="width:100%;height:4em"></iframe>
|
||||
|
||||
<h2>Empfangene Syslog-Nachrichten (≥ WARNING)</h2>
|
||||
<p id="status">Websocket: verbinde …</p>
|
||||
<h2>Syslog-Nachrichten</h2>
|
||||
<ul id="log"></ul>
|
||||
|
||||
<script>
|
||||
// ---------- Formular ----------
|
||||
document.getElementById('cfg').addEventListener('submit', async (e) => {
|
||||
e.preventDefault(); // Seite NICHT neu laden, sonst bricht der WebSocket ab
|
||||
const daten = new URLSearchParams(new FormData(e.target));
|
||||
document.getElementById('cfgStatus').textContent = 'verbinde …';
|
||||
const antwort = await fetch('config', { method: 'POST', body: daten });
|
||||
document.getElementById('cfgStatus').textContent = await antwort.text();
|
||||
});
|
||||
|
||||
// ---------- WebSocket-Client ----------
|
||||
const url = new URL('syslog', location.href);
|
||||
url.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const ws = new WebSocket(url);
|
||||
|
||||
ws.onopen = () => document.getElementById('status').textContent = 'Websocket: verbunden';
|
||||
ws.onclose = () => document.getElementById('status').textContent = 'Websocket: getrennt';
|
||||
ws.onmessage = (event) => {
|
||||
const li = document.createElement('li');
|
||||
li.textContent = event.data;
|
||||
document.getElementById('log').prepend(li);
|
||||
};
|
||||
// Kontextpfad "/" -> Websocket unter /syslog
|
||||
const ws = new WebSocket("ws://" + location.host + "/syslog");
|
||||
ws.onmessage = event => {
|
||||
const li = document.createElement("li");
|
||||
li.textContent = event.data; // als Text, nicht als HTML einfügen
|
||||
document.getElementById("log").append(li);
|
||||
};
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
</html>
|
||||
|
|
|
|||
|
|
@ -1,68 +0,0 @@
|
|||
package vs;
|
||||
|
||||
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
|
||||
import org.eclipse.paho.client.mqttv3.MqttCallback;
|
||||
import org.eclipse.paho.client.mqttv3.MqttClient;
|
||||
import org.eclipse.paho.client.mqttv3.MqttException;
|
||||
import org.eclipse.paho.client.mqttv3.MqttMessage;
|
||||
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ObjectInputStream;
|
||||
import vs.SyslogMessage.Severity;
|
||||
|
||||
public class MqttEmpfaenger {
|
||||
|
||||
public static void main(String[] args) throws MqttException {
|
||||
String broker = "tcp://localhost:1883";
|
||||
String topic = "vs/test";
|
||||
|
||||
// 1. Client-Objekt erzeugen
|
||||
MqttClient client = new MqttClient(
|
||||
broker,
|
||||
MqttClient.generateClientId(),
|
||||
new MemoryPersistence());
|
||||
|
||||
// 2. Festlegen, was bei eingehenden Nachrichten passiert
|
||||
client.setCallback(new MqttCallback() {
|
||||
@Override
|
||||
public void messageArrived(String t, MqttMessage message) {
|
||||
byte[] payload = message.getPayload();
|
||||
try (ObjectInputStream in = new ObjectInputStream(
|
||||
new ByteArrayInputStream(payload))) {
|
||||
|
||||
Object o = in.readObject();
|
||||
|
||||
if (o instanceof SyslogMessage m) {
|
||||
if (m.sev().ordinal() <= Severity.WARNING.ordinal()) {
|
||||
System.out.println("WEITERLEITEN: " + m);
|
||||
} else {
|
||||
System.out.println("ignoriert (zu unwichtig): " + m.sev());
|
||||
}
|
||||
} else {
|
||||
System.out.println("ignoriert: Objekt, aber keine SyslogMessage");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println("ignoriert: kein serialisiertes Objekt ("
|
||||
+ e.getClass().getSimpleName() + ")");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connectionLost(Throwable cause) {
|
||||
System.out.println("Verbindung verloren: " + cause);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deliveryComplete(IMqttDeliveryToken token) {
|
||||
// nur relevant, wenn wir selbst senden
|
||||
}
|
||||
});
|
||||
|
||||
// 3. Verbinden und abonnieren
|
||||
client.connect();
|
||||
client.subscribe(topic);
|
||||
System.out.println("Verbunden mit " + broker + ", warte auf " + topic + " ...");
|
||||
}
|
||||
}
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
package vs;
|
||||
|
||||
import vs.adapter.MqttAdapter;
|
||||
|
||||
public class ZweiBrokerTest {
|
||||
public static void main(String[] args) throws Exception {
|
||||
MqttAdapter adapter = new MqttAdapter(text -> System.out.println("→ " + text));
|
||||
|
||||
adapter.connect(0, "tcp://localhost:1883", "vs/a");
|
||||
adapter.connect(1, "tcp://localhost:1884", "vs/b");
|
||||
System.out.println("Slot 0 verbunden: " + adapter.isConnected(0));
|
||||
System.out.println("Slot 1 verbunden: " + adapter.isConnected(1));
|
||||
System.out.println("Warte 60 Sekunden auf Nachrichten ...");
|
||||
|
||||
Thread.sleep(60_000);
|
||||
adapter.close();
|
||||
System.out.println("Beendet.");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
package vs.adapter;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import vs.AsciiChars;
|
||||
import vs.StructuredData;
|
||||
import vs.SyslogMessage;
|
||||
import vs.SyslogMessage.Facility;
|
||||
import vs.SyslogMessage.Severity;
|
||||
import vs.SyslogMessage.TextMessage;
|
||||
|
||||
class MqttAdapterTest {
|
||||
|
||||
@Test
|
||||
void formatWritesRealBom() {
|
||||
var m = new SyslogMessage(Facility.SECURITY1, Severity.WARNING,
|
||||
new AsciiChars.L255("mymachine.example.com"),
|
||||
new AsciiChars.L048("su"), new AsciiChars.L128(""),
|
||||
new AsciiChars.L032("ID47"),
|
||||
new StructuredData().add(StructuredData.Element.newTimeQuality(true, true)),
|
||||
new TextMessage("WARNING über vs/b"));
|
||||
var s = MqttAdapter.format(m);
|
||||
assertFalse(s.contains(""));
|
||||
assertTrue(s.endsWith("[timeQuality tzKnown=\"1\" isSynced=\"1\"] WARNING über vs/b"));
|
||||
// UTF-8 on the wire: EF BB BF exactly once before the text
|
||||
var bytes = s.getBytes(StandardCharsets.UTF_8);
|
||||
var expected = "WARNING über vs/b".getBytes(StandardCharsets.UTF_8);
|
||||
assertTrue(Arrays.equals(Arrays.copyOfRange(bytes, bytes.length - expected.length, bytes.length), expected));
|
||||
assertTrue(expected[0] == (byte) 0xEF && expected[1] == (byte) 0xBB && expected[2] == (byte) 0xBF);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue