- *
+ * This {@link ObjectProcessor} handles incoming {@link Message}s.
+ *
* Project: envoy-server-standalone
* File: MessageProcessor.java
* Created: 30.12.2019
@@ -26,6 +27,8 @@ import envoy.util.EnvoyLog;
*/
public class MessageProcessor implements ObjectProcessor {
+ private static final PersistenceManager persistenceManager = PersistenceManager.getInstance();
+ private static final ConnectionManager connectionManager = ConnectionManager.getInstance();
private static final Logger logger = EnvoyLog.getLogger(MessageProcessor.class);
@Override
@@ -35,26 +38,32 @@ public class MessageProcessor implements ObjectProcessor {
return;
}
message.nextStatus();
- ConnectionManager connectionManager = ConnectionManager.getInstance();
- sendToUser(connectionManager, message, writeProxy);
+ // Convert to server message
+ final var serverMessage = new envoy.server.data.Message(message);
+
try {
- PersistenceManager.getInstance().addMessage(new envoy.server.data.Message(message));
- } catch (EntityExistsException e) {
- logger.warning("Received a message with an id that already exists");
- }
- }
- private void sendToUser(ConnectionManager connectionManager, Message message, ObjectWriteProxy writeProxy) {
- if (connectionManager.isOnline(message.getRecipientID())) try {
- // If recipient is online, send the message directly
- writeProxy.write(connectionManager.getSocketID(message.getRecipientID()), message);
- // Update the message status to RECEIVED
- message.setReceivedDate(LocalDateTime.now());
- message.nextStatus();
+ // Persist the message
+ persistenceManager.addMessage(serverMessage);
+
+ // Send the message to the recipient if online
+ if (connectionManager.isOnline(message.getRecipientID())) {
+ writeProxy.write(connectionManager.getSocketID(message.getRecipientID()), message);
+
+ // Increment status
+ message.nextStatus();
+ serverMessage.received();
+ persistenceManager.updateMessage(serverMessage);
+
+ // Notify the sender about the delivery
+ // Note that the exact time stamp might differ slightly
+ writeProxy.write(socketID, new MessageStatusChange(message));
+ }
+ } catch (EntityExistsException e) {
+ logger.log(Level.WARNING, "Received " + message + " with an ID that already exists!");
} catch (IOException e) {
- logger.warning("Recipient online. Failed to send message" + message.getID());
- e.printStackTrace();
+ logger.log(Level.WARNING, "Failed to deliver " + message + ":", e);
}
}