package envoy.client.net; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import envoy.client.data.Cache; import envoy.client.data.LocalDB; import envoy.data.Message; import envoy.event.MessageStatusChange; import envoy.util.EnvoyLog; /** * Implements methods to send {@link Message}s and * {@link MessageStatusChange}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.getCacheMap().get(Message.class).setProcessor(msg -> {
try {
logger.log(Level.FINER, "Sending cached " + msg);
client.sendMessage(msg);
} catch (final IOException e) {
logger.log(Level.SEVERE, "Could not send cached message: ", e);
}
});
localDB.getCacheMap().get(MessageStatusChange.class).setProcessor(evt -> {
logger.log(Level.FINER, "Sending cached " + evt);
try {
client.sendEvent(evt);
} catch (final IOException e) {
logger.log(Level.SEVERE, "Could not send cached message status change event: ", e);
}
});
}
/**
* Sends cached {@link Message}s and {@link MessageStatusChange}s to the
* server.
*
* @since Envoy Client v0.3-alpha
*/
public void flushCache() {
localDB.getCacheMap().getMap().values().forEach(Cache::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.getCacheMap().getApplicable(Message.class).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 writeMessageStatusChange(MessageStatusChange evt) throws IOException {
if (client.isOnline()) client.sendEvent(evt);
else localDB.getCacheMap().getApplicable(MessageStatusChange.class).accept(evt);
}
}