package envoy.server.net; import java.io.IOException; import java.util.Set; import java.util.logging.Logger; import java.util.stream.Stream; import com.jenkov.nioserver.*; import envoy.util.*; import envoy.server.data.Contact; /** * This class defines methods to send an object to a client. * * @author Kai S. K. Engelbart * @since Envoy Server Standalone v0.1-alpha */ public final class ObjectWriteProxy { private final WriteProxy writeProxy; private static final ConnectionManager connectionManager = ConnectionManager.getInstance(); private static final Logger logger = EnvoyLog.getLogger(ObjectWriteProxy.class); /** * Creates an instance of {@link ObjectWriteProxy}. * * @param writeProxy the {@link WriteProxy} to write objects to another client * @since Envoy Server Standalone v0.1-alpha */ public ObjectWriteProxy(WriteProxy writeProxy) { this.writeProxy = writeProxy; } /** * @param recipientSocketID the socket id of the recipient * @param obj the object to return to the client * @throws RuntimeException if the serialization of the object failed (this is highly unlikely) * @since Envoy Server Standalone v0.1-alpha */ public void write(long recipientSocketID, Object obj) { // Create message targeted at the client final Message response = writeProxy.getMessage(); response.socketId = recipientSocketID; logger.fine("Sending " + obj); try { // Serialize object to byte array final byte[] objBytes = SerializationUtils.writeToByteArray(obj); // Acquire object length in bytes final byte[] objLen = SerializationUtils.intToBytes(objBytes.length); response.writeToMessage(objLen); response.writeToMessage(objBytes); writeProxy.enqueue(response); } catch (IOException e) { throw new RuntimeException(e); } } /** * Sends an object to all contacts in a set that are online. * * @param contacts the contacts to send the object to * @param message the object to send * @since Envoy Server Standalone v0.1-beta */ public void writeToOnlineContacts(Set contacts, Object message) { writeToOnlineContacts(contacts.stream(), message); } /** * Sends an object to all contacts in a set that are online. * * @param contacts the contacts to send the object to * @param message the object to send * @since Envoy Server Standalone v0.1-beta */ public void writeToOnlineContacts(Stream contacts, Object message) { contacts.map(Contact::getID).filter(connectionManager::isOnline) .map(connectionManager::getSocketID).forEach(id -> write(id, message)); } }