package envoy.client.net; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import envoy.client.data.LocalDB; import envoy.data.Message; import envoy.event.MessageStatusChangeEvent; import envoy.util.EnvoyLog; /** * Implements methods to send {@link Message}s and * {@link MessageStatusChangeEvent}s to the server or cache them inside a * {@link LocalDB} depending on the online status.
*
* Project: envoy-client
* File: WriteProxy.java
* Created: 6 Feb 2020
* * @author Kai S. K. Engelbart * @since Envoy Client v0.3-alpha */ public class WriteProxy { private final Client client; private final LocalDB localDB; private static final Logger logger = EnvoyLog.getLogger(WriteProxy.class); /** * Initializes a write proxy using a client and a local database. The * corresponding cache processors are injected into the caches. * * @param client the client used to send messages and message status change * events * @param localDB the local database used to cache messages and message status * change events * @since Envoy Client v0.3-alpha */ public WriteProxy(Client client, LocalDB localDB) { this.client = client; this.localDB = localDB; // Initialize cache processors for messages and message status change events localDB.getMessageCache().setProcessor(msg -> { try { logger.finer("Sending cached " + msg); client.sendMessage(msg); // Update message state to SENT in localDB localDB.getMessage(msg.getID()).ifPresent(Message::nextStatus); } catch (IOException e) { logger.log(Level.SEVERE, "Could not send cached message", e); } }); localDB.getStatusCache().setProcessor(evt -> { logger.finer("Sending cached " + evt); try { client.sendEvent(evt); } catch (IOException e) { logger.log(Level.SEVERE, "Could not send cached message status change event", e); } }); } /** * Sends cached {@link Message}s and {@link MessageStatusChangeEvent}s to the * server. * * @since Envoy Client v0.3-alpha */ public void flushCache() { // Send messages localDB.getMessageCache().relay(); // Send message status change events localDB.getStatusCache().relay(); } /** * Delivers a message to the server if online. Otherwise the message is cached * inside the local database. * * @param message the message to send * @throws IOException if the message could not be sent * @since Envoy Client v0.3-alpha */ public void writeMessage(Message message) throws IOException { if (client.isOnline()) client.sendMessage(message); else localDB.getMessageCache().accept(message); } /** * Delivers a message status change event to the server if online. Otherwise the * event is cached inside the local database. * * @param evt the event to send * @throws IOException if the event could not be sent * @since Envoy Client v0.3-alpha */ public void writeMessageStatusChangeEvent(MessageStatusChangeEvent evt) throws IOException { if (client.isOnline()) client.sendEvent(evt); else localDB.getStatusCache().accept(evt); } }