package ufrn.imd.controller.impl; import ufrn.imd.controller.Controller; import ufrn.imd.domain.Client; import ufrn.imd.service.impl.BalanceServiceImpl; 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.*; import static ufrn.imd.utils.NameSpace.HOST_BALANCE_SERVICE; import static ufrn.imd.utils.NameSpace.PORT_BALANCE_SERVICE; @lombok.extern.java.Log public class BalanceControllerImpl extends UnicastRemoteObject implements Controller { private volatile Queue<Client> clients = new ArrayDeque<>(); public BalanceControllerImpl(BalanceServiceImpl service) throws RemoteException, MalformedURLException, AlreadyBoundException { super(); LocateRegistry.createRegistry(PORT_BALANCE_SERVICE); Naming.bind(HOST_BALANCE_SERVICE, this); log.info("Starting Deposit service!"); new Notify(service).start(); log.info(String.format("Initializing server in %s", HOST_BALANCE_SERVICE)); } @Override public void registerClient(Client client) throws RemoteException { clients.add(client); log.info("new client registred"); log.info(String.format("total users: %d", clients.size())); } private class Notify extends Thread{ private final BalanceServiceImpl service; public Notify(BalanceServiceImpl service) { super(); this.service = service; } public void run() { for(;;) { if(clients.size() > 0) { log.info("notyfing the clients!"); int i = 0; clients.stream().forEach(client -> { try { log.info(String.format("Clients waiting %d", clients.size())); this.service.balance(Optional.of(client)); clients.remove(); log.info(String.format("Clients waiting %d", clients.size())); } catch (RemoteException e) { e.printStackTrace(); } }); try { Thread.sleep(15 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } } }