Skip to content
Snippets Groups Projects
TransferControllerImpl.java 1.85 KiB
Newer Older
package ufrn.imd.controller.impl;

import lombok.extern.java.Log;
import ufrn.imd.controller.Controller;
import ufrn.imd.service.impl.TransferServiceImpl;
import ufrn.imd.utils.ServerResponse;
import ufrn.imd.utils.message.TransferMessage;

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.Optional;

import static ufrn.imd.utils.NameSpace.HOST_TRANSFER_SERVICE;
import static ufrn.imd.utils.NameSpace.PORT_TRANSFER_SERVICE;

@Log
public class TransferControllerImpl extends UnicastRemoteObject implements Controller {
    private final TransferServiceImpl service;

    public TransferControllerImpl(TransferServiceImpl service) throws RemoteException, MalformedURLException, AlreadyBoundException {
        super();
        log.info("Starting Transfer service!");
        this.service = service;
        log.info(String.format("Initializing server in %s", HOST_TRANSFER_SERVICE));
        LocateRegistry.createRegistry(PORT_TRANSFER_SERVICE);
        Naming.bind(HOST_TRANSFER_SERVICE, this);
    }

    @Override
    public ServerResponse getResponse(Object client) throws RemoteException {
        TransferMessage transferMessage = (TransferMessage) client;
        ServerResponse response;
        try {
            response = this.service.transfer(transferMessage.getValue(), Optional.of(transferMessage.getFrom()),
                    Optional.of(transferMessage.getTo()));
        } catch (RuntimeException e) {
            e.printStackTrace();
            response = ServerResponse.builder()
                    .status(500)
                    .message(e.getMessage())
                    .body(transferMessage.getFrom())
                    .build();
        }
        return response;
    }
}