package ufrn.imd.controller.impl; import ufrn.imd.controller.Controller; import ufrn.imd.utils.Log; import ufrn.imd.domain.Client; import ufrn.imd.service.DepositService; import java.net.MalformedURLException; import java.rmi.AlreadyBoundException; import java.rmi.Naming; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import java.util.List; import static ufrn.imd.utils.NameSpace.HOST_DEPOSIT_SERVICE; import static ufrn.imd.utils.NameSpace.PORT_DEPOSIT_SERVICE; public class DepositControllerImpl extends UnicastRemoteObject implements Controller { private volatile List<Client> clients = new ArrayList<>(); public DepositControllerImpl(DepositService service) throws RemoteException, MalformedURLException, AlreadyBoundException { super(); Log.info(DepositControllerImpl.class, "Starting Deposit service!"); new Notify(service).start(); Log.info(DepositControllerImpl.class, String.format("Initializing server in %s", HOST_DEPOSIT_SERVICE)); LocateRegistry.createRegistry(PORT_DEPOSIT_SERVICE); Naming.bind(HOST_DEPOSIT_SERVICE, this); } @Override public void registerClient(Client client) throws RemoteException { clients.add(client); Log.info(DepositControllerImpl.class, "new client registred"); Log.info(DepositControllerImpl.class, String.format("total users: %d", clients.size())); } private class Notify extends Thread{ private final DepositService service; public Notify(DepositService service) { super(); this.service = service; } public void run() { for(;;) { if(clients.size() > 0) { Log.info( DepositControllerImpl.class, "notyfing the clients!" ); int i = 0; for (Client client : clients) { try { this.service.deposit(client.getBalance(), client.getAccount()); } catch (RemoteException e) { e.printStackTrace(); } } try { Thread.sleep(15 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } else { try { Thread.sleep(15 * 1000); } catch (InterruptedException e) { throw new RuntimeException(e); } Log.info(DepositControllerImpl.class, "No there's clients!"); } } } } }