Simplify message serialization and payload scheme

This commit is contained in:
William committed 2022-08-18 14:10:24 +01:00
1 parent 2325fd9220
commit 25975a4de6
5 files changed
+156 -100

No files matched your search

@@ -24,10 +24,11 @@ public class Message {
public MessageType type;
/**
* The kind of message this is - {@link MessageKind#MESSAGE} or a {@link MessageKind#REPLY} to a message.
* The kind of message this is - {@link RelayType#MESSAGE} or a {@link RelayType#REPLY} to a message.
*/
@SerializedName("relay_type")
@NotNull
public MessageKind kind;
public RelayType relayType;
/**
* Username of the target player the message is bound for
@@ -53,34 +54,41 @@ public class Message {
* Data to send in the message
*/
@NotNull
public String payload;
public MessagePayload payload;
public Message(@NotNull MessageType type, @NotNull String sender, @NotNull String targetPlayer,
@NotNull MessageSerializable payload, @NotNull MessageKind messageKind, @NotNull String clusterId) {
@NotNull MessagePayload payload, @NotNull Message.RelayType relayType, @NotNull String clusterId) {
this.type = type;
this.sender = sender;
this.targetPlayer = targetPlayer;
this.payload = payload.toJson();
this.kind = messageKind;
this.payload = payload;
this.relayType = relayType;
this.clusterId = clusterId;
this.uuid = UUID.randomUUID();
}
@NotNull
public String toJson() {
return new GsonBuilder().setPrettyPrinting().create().toJson(this);
return new GsonBuilder().create().toJson(this);
}
public static Message fromJson(String json) {
return new GsonBuilder().setPrettyPrinting().create().fromJson(json, Message.class);
@NotNull
public static Message fromJson(@NotNull String json) {
return new GsonBuilder().create().fromJson(json, Message.class);
}
/**
* Identifies the type of message or reply
*/
public enum MessageType {
TP_REQUEST,
POSITION_REQUEST
}
public enum MessageKind {
/**
* Identifies the source of the message being relayed - a {@link RelayType#MESSAGE} or a {@link RelayType#REPLY} to a message.
*/
public enum RelayType {
MESSAGE,
REPLY
}
@@ -0,0 +1,44 @@
package net.william278.huskhomes.messenger;
import net.william278.huskhomes.position.Position;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Represents a payload sent in a cross-server {@link Message}
*/
public class MessagePayload {
/**
* A position field
*/
@Nullable
public Position position;
/**
* Returns an empty cross-server message payload
*
* @return an empty payload
*/
@NotNull
public static MessagePayload empty() {
return new MessagePayload();
}
/**
* Returns a payload containing a {@link Position}
*
* @param position the position to send
* @return a payload containing the position
*/
@NotNull
public static MessagePayload withPosition(@NotNull Position position) {
final MessagePayload payload = new MessagePayload();
payload.position = position;
return payload;
}
private MessagePayload() {
}
}
@@ -1,10 +0,0 @@
package net.william278.huskhomes.messenger;
/**
* Represents data that can be sent as a payload in a {@link Message}
*/
public interface MessageSerializable {
String toJson();
}
@@ -1,20 +1,14 @@
package net.william278.huskhomes.position;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import net.william278.huskhomes.messenger.MessageSerializable;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.Optional;
import java.util.UUID;
/**
* Represents a position - a {@link Location} somewhere on the proxy network or server
*/
public class Position extends Location implements MessageSerializable {
public class Position extends Location {
/**
* The {@link Server} the position is on
@@ -27,81 +21,48 @@ public class Position extends Location implements MessageSerializable {
this.server = server;
}
@SuppressWarnings("unused")
public Position() {
}
public String toJson() {
return new GsonBuilder().setPrettyPrinting().create().toJson(this);
/**
* Parses the position from a set of values
*
* @param values The values to parse
* @return The position if it could be parsed, otherwise an empty optional
*/
public static Optional<Position> parse(@NotNull Position currentPosition, @NotNull String... values) {
// Validate argument length
if (values.length < 3 || values.length > 5) {
return Optional.empty();
}
// Parse, handle relatives, and return, catching NumberFormatExceptions and returning an empty optional
try {
final double x = parseCoordinate(values[0], currentPosition.x);
final double y = parseCoordinate(values[1], currentPosition.y);
final double z = parseCoordinate(values[2], currentPosition.z);
final World world = values.length > 3 ? new World(values[3], UUID.randomUUID()) : currentPosition.world;
final Server server = values.length > 4 ? new Server(values[4]) : currentPosition.server;
return Optional.of(new Position(x, y, z, currentPosition.yaw, currentPosition.pitch, world, server));
} catch (NumberFormatException ignored) {
return Optional.empty();
}
}
public static Position fromJson(String json) {
return new GsonBuilder().setPrettyPrinting()
.registerTypeAdapter(World.class, new TypeAdapter<World>() {
@Override
public void write(JsonWriter jsonWriter, World world) throws IOException {
jsonWriter.beginObject();
jsonWriter.name("name");
jsonWriter.value(world.name);
jsonWriter.name("uuid");
jsonWriter.value(world.uuid.toString());
jsonWriter.endObject();
}
@Override
public World read(JsonReader jsonReader) throws IOException {
final World readWorld = new World();
jsonReader.beginObject();
String fieldName = null;
while (jsonReader.hasNext()) {
JsonToken token = jsonReader.peek();
if (token.equals(JsonToken.NAME)) {
fieldName = jsonReader.nextName();
}
if (fieldName != null) {
if (fieldName.equals("name")) {
jsonReader.peek();
readWorld.name = jsonReader.nextString();
}
if (fieldName.equals("uuid")) {
jsonReader.peek();
readWorld.uuid = UUID.fromString(jsonReader.nextString());
}
}
}
jsonReader.endObject();
return readWorld;
}
})
.registerTypeAdapter(Server.class, new TypeAdapter<Server>() {
@Override
public void write(JsonWriter jsonWriter, Server world) throws IOException {
jsonWriter.beginObject();
jsonWriter.name("name");
jsonWriter.value(world.name);
jsonWriter.endObject();
}
@Override
public Server read(JsonReader jsonReader) throws IOException {
final Server readServer = new Server();
jsonReader.beginObject();
String fieldName = null;
while (jsonReader.hasNext()) {
JsonToken token = jsonReader.peek();
if (token.equals(JsonToken.NAME)) {
fieldName = jsonReader.nextName();
}
if (fieldName != null) {
if (fieldName.equals("name")) {
jsonReader.peek();
readServer.name = jsonReader.nextString();
}
}
}
jsonReader.endObject();
return readServer;
}
})
.create().fromJson(json, Position.class);
/**
* Parses a coordinate double value from a string
*
* @param value The string to parse
* @param currentValue The current value of the coordinate, for handling relatives
* @return The parsed coordinate
* @throws NumberFormatException If the string could not be parsed
*/
private static double parseCoordinate(@NotNull String value, double currentValue) throws NumberFormatException {
if (value.startsWith("~")) {
return currentValue + Double.parseDouble(value.substring(1));
} else {
return Double.parseDouble(value);
}
}
}
@@ -0,0 +1,53 @@
package net.william278.huskhomes.messenger;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.Server;
import net.william278.huskhomes.position.World;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.UUID;
public class MessageTests {
@Test
public void testMessageSerializationWithEmptyPayload() {
final Message message = new Message(
Message.MessageType.TP_REQUEST,
"TestSender",
"TestTarget",
MessagePayload.empty(),
Message.RelayType.MESSAGE,
"TestClusterId");
Assertions.assertNotNull(message.toJson());
final Message readMessage = Message.fromJson(message.toJson());
Assertions.assertEquals(message.uuid, readMessage.uuid);
Assertions.assertEquals(message.sender, readMessage.sender);
Assertions.assertEquals(message.targetPlayer, readMessage.targetPlayer);
Assertions.assertEquals(message.type, readMessage.type);
}
@Test
public void testMessageSerializationWithPositionPayload() {
final Message message = new Message(
Message.MessageType.POSITION_REQUEST,
"TestSender",
"TestTarget",
MessagePayload.withPosition(new Position(63.25, 127.43, -32, 180f, -94.3f,
new World("TestWorld", UUID.randomUUID()), new Server("TestServer"))),
Message.RelayType.REPLY,
"TestClusterId");
Assertions.assertNotNull(message.toJson());
final Message readMessage = Message.fromJson(message.toJson());
Assertions.assertEquals(message.uuid, readMessage.uuid);
Assertions.assertNotNull(readMessage.payload.position);
assert message.payload.position != null;
Assertions.assertEquals(message.payload.position.x, readMessage.payload.position.x);
Assertions.assertEquals(message.payload.position.y, readMessage.payload.position.y);
Assertions.assertEquals(message.payload.position.z, readMessage.payload.position.z);
}
}