package dslab.client; import dslab.ComponentFactory; import dslab.protocol.Message; import dslab.protocol.dmtp.InvalidMessageException; import dslab.protocol.dmtp.NoOpenMessageException; import dslab.rmi.channel.SocketChannel; import dslab.routing.AddressResolutionException; import dslab.routing.DeliveryService; import dslab.util.MessageClientConfig; import java.io.IOException; import java.net.Socket; import java.util.logging.Logger; import static java.util.logging.Level.WARNING; public class MessageClientDeliveryService implements DeliveryService { private static final Logger LOG = Logger.getLogger(MessageClientDeliveryService.class.getSimpleName()); private final MessageClientConfig config; private final ComponentFactory componentFactory; public MessageClientDeliveryService(MessageClientConfig config, ComponentFactory componentFactory) { this.config = config; this.componentFactory = componentFactory; } @Override public void deliver(Message message) throws IllegalArgumentException { SocketChannel channel; try { var socket = new Socket(config.transferHost(), config.transferPort()); channel = new SocketChannel(socket); } catch (IOException e) { throw new RuntimeException( "Couldn't establish a connection to the DMTP server. Are you sure it is running?"); } try (var dmtp = componentFactory.newDmtpInstance(channel)) { dmtp.begin(); dmtp.from(message.getSender()); dmtp.to(message.getRecipients()); dmtp.subject(message.getSubject()); dmtp.data(message.getData()); dmtp.hash(message.getHash()); dmtp.send(); } catch (AddressResolutionException | NoOpenMessageException | InvalidMessageException e) { throw new RuntimeException(e); //never happens } catch (IOException e) { LOG.log(WARNING, "Failed to close channel", e); } } }