Files
ProcessControl/SIN.04028-From-Calling-to-Eventing/supplemental-java/06-mqtt/src/main/java/MqttRot13.java
T

173 lines
5.2 KiB
Java

import java.nio.charset.StandardCharsets;
import java.util.UUID;
import org.eclipse.paho.mqttv5.client.IMqttAsyncClient;
import org.eclipse.paho.mqttv5.client.IMqttToken;
import org.eclipse.paho.mqttv5.client.MqttAsyncClient;
import org.eclipse.paho.mqttv5.client.MqttCallback;
import org.eclipse.paho.mqttv5.client.MqttConnectionOptions;
import org.eclipse.paho.mqttv5.client.MqttDisconnectResponse;
import org.eclipse.paho.mqttv5.client.persist.MemoryPersistence;
import org.eclipse.paho.mqttv5.common.MqttException;
import org.eclipse.paho.mqttv5.common.MqttMessage;
import org.eclipse.paho.mqttv5.common.packet.MqttProperties;
record Rot13Message(String value) {}
record Rot13Subscription(String topic) {}
record Rot13Intent(
Rot13Subscription subscribe,
Rot13Message text
) {}
MqttAsyncClient client;
String intentTopic;
String eventTopic;
String subscriptionStatusTopic;
String dynamicTextTopic;
void publish(
IMqttAsyncClient client,
String topic,
String content,
int qos,
boolean retained)
throws Exception {
var message = new MqttMessage(
content.getBytes(StandardCharsets.UTF_8)
);
message.setQos(qos);
message.setRetained(retained);
client.publish(topic, message).waitForCompletion();
}
MqttConnectionOptions connectionOptions(String lastWillTopic) {
var options = new MqttConnectionOptions();
options.setAutomaticReconnect(true);
var will = new MqttMessage(
"{\"value\":false}".getBytes(StandardCharsets.UTF_8),
1,
true,
new MqttProperties()
);
options.setWill(lastWillTopic, will);
return options;
}
String rot13(String text) {
var result = new StringBuilder();
for (var character : text.toCharArray()) {
if (character >= 'a' && character <= 'z')
character = (char) ('a' + (character - 'a' + 13) % 26);
else if (character >= 'A' && character <= 'Z')
character = (char) ('A' + (character - 'A' + 13) % 26);
result.append(character);
}
return result.toString();
}
void cryptAndPublish(String text) throws Exception {
var json = JsonTools.serializationObjectMapper
.writeValueAsString(new Rot13Message(rot13(text)));
publish(client, eventTopic, json, 1, false);
}
void handleIntent(MqttMessage message) throws Exception {
var intent = JsonTools.deserializationObjectMapper.readValue(
message.getPayload(),
Rot13Intent.class
);
if (intent.subscribe() != null) {
var requestedTopic = intent.subscribe().topic();
if (!MqttTools.isValidFilter(requestedTopic)) {
IO.println("Rejected invalid topic filter: " + requestedTopic);
return;
}
if (dynamicTextTopic != null)
client.unsubscribe(dynamicTextTopic).waitForCompletion();
dynamicTextTopic = requestedTopic;
client.subscribe(dynamicTextTopic, 1).waitForCompletion();
var status = JsonTools.serializationObjectMapper
.writeValueAsString(new Rot13Message(dynamicTextTopic));
publish(
client,
subscriptionStatusTopic,
status,
1,
true
);
IO.println("ROT13 now listens to " + dynamicTextTopic);
}
if (intent.text() != null)
cryptAndPublish(intent.text().value());
}
void handlePublication(String topic, MqttMessage message) throws Exception {
if (topic.equals(intentTopic)) {
handleIntent(message);
} else if (dynamicTextTopic != null
&& MqttTools.isTopicMatchingFilter(topic, dynamicTextTopic)) {
var input = JsonTools.deserializationObjectMapper.readValue(
message.getPayload(),
Rot13Message.class
);
cryptAndPublish(input.value());
}
}
void main(String[] arguments) throws Exception {
var unit = arguments.length == 0 ? "alice" : arguments[0];
var broker = System.getProperty("mqtt.broker", "tcp://localhost:1883");
var root = "Tutorial/ROT13/U/" + unit;
intentTopic = root + "/I";
eventTopic = root + "/E/crypted";
subscriptionStatusTopic = root + "/S/subscriptions/text";
var onlineTopic = root + "/S/online";
client = new MqttAsyncClient(
broker,
"rot13-" + unit + "-" + UUID.randomUUID(),
new MemoryPersistence()
);
client.setCallback(new MqttCallback() {
public void messageArrived(String topic, MqttMessage message)
throws Exception {
handlePublication(topic, message);
}
public void disconnected(MqttDisconnectResponse response) {}
public void mqttErrorOccurred(MqttException exception) {
exception.printStackTrace();
}
public void deliveryComplete(IMqttToken token) {}
public void connectComplete(boolean reconnect, String serverURI) {}
public void authPacketArrived(
int reasonCode,
MqttProperties properties) {}
});
client.connect(connectionOptions(onlineTopic)).waitForCompletion();
client.subscribe(intentTopic, 1).waitForCompletion();
publish(client, onlineTopic, "{\"value\":true}", 1, true);
IO.println("ROT13 waits for Intent on " + intentTopic);
Thread.currentThread().join();
}