aula08tRMICallbacks

TemperatureListener.java

import java.rmi.Remote;
import java.rmi.RemoteException;

//A interface remota associada aos listeners define apenas o método temperatureChanged()
interface TemperatureListener extends Remote {
    public void temperatureChanged(double temperature) throws RemoteException;
}

TemperatureMonitorCliente.java

import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

//Monitor de mudança de temperatura (listener)
public class TemperatureMonitorCliente extends UnicastRemoteObject implements TemperatureListener {

    public TemperatureMonitorCliente() throws RemoteException {
        // NO CODE REQUIRED
        //nao precisamos do construtor mas todos os serviços RMi precisam por causa do throws RemoteException
    }

    public static void main(String args[]) {
        System.out.println("Looking for temperature sensor");

        // ONLY REQUIRED FOR DYNAMIC CLASS LOADING
        // SYSTEM.SETSECURITYMANAGER ( NEW RMISECURITYMANAGER() );
        try {
            String registry = "localhost";
            if (args.length >= 1) {
                registry = args[0];
            }
            // LOOKUP THE SERVICE IN THE REGISTRY, AND OBTAIN A REMOTE SERVICE
            String registration = "rmi://" + registry + "/TemperatureSensor";
            Remote remoteService = Naming.lookup(registration);
            TemperatureSensor sensor = (TemperatureSensor) remoteService;

            // GET AND DISPLAY CURRENT TEMPERATURE
            double reading = sensor.getTemperature();
            System.out.println("Original temp : " + reading);

            // CREATE A NEW MONITOR AND REGISTER IT AS A LISTENER WITH REMOTE SENSOR
            TemperatureMonitorCliente monitor = new TemperatureMonitorCliente(); //criar o serviço
            sensor.addTemperatureListener(monitor); //registo o sensor
        } catch (NotBoundException e) {
            System.out.println("No sensors available");
        } catch (RemoteException e) {
            System.out.println("RMI Error - " + e);
        } catch (Exception e) {
            System.out.println("Error - " + e);
        }
    } //MAIN

    public void temperatureChanged(double temperature) throws java.rmi.RemoteException {
        System.out.println("Temperature change event : " + temperature);
    }
}

TemperatureSensor.java

//Interface associada ao serviço de medição de temperatura (i.e., fonte do evento mudança de temperatura)
interface TemperatureSensor extends java.rmi.Remote {
    public double getTemperature() throws java.rmi.RemoteException;

    public void addTemperatureListener(TemperatureListener listener) throws java.rmi.RemoteException;

    public void removeTemperatureListener(TemperatureListener listener) throws java.rmi.RemoteException;
}

TemperatureSensorServer.java

import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

//Serviço + Servidor sensor de temperatura
public class TemperatureSensorServer extends UnicastRemoteObject implements TemperatureSensor, Runnable {
    private volatile double temp; //THE VALUE OF THIS VARIABLE WILL NEVER BE

    //CACHED THREAD-LOCALLY
    private List<TemperatureListener> list;

    public TemperatureSensorServer() throws java.rmi.RemoteException {
        temp = 20.0;
        list = new ArrayList<TemperatureListener>();
    }

    //parte de comunicação gerada autmaticamente
    public synchronized double getTemperature() throws java.rmi.RemoteException {
        return temp;
    }

    public synchronized void addTemperatureListener(TemperatureListener listener) throws RemoteException {
        System.out.println("adding listener -" + listener);
        list.add(listener);
    }

    public synchronized void removeTemperatureListener(TemperatureListener listener) throws java.rmi.RemoteException {
        System.out.println("removing listener -" + listener);
        list.remove(listener);
    }

    public synchronized void changeTemp(Random r) {
        int num = r.nextInt();
        if (num < 0) temp += 0.5;
        else temp -= 0.5;

        // NOTIFY REGISTERED LISTENERS
        notifyListeners();
    }

    //run é acessorio
    public void run() {
        Random r = new Random();
        while (true) {
            try {
                // SLEEP FOR A RANDOM AMOUNT OF TIME
                int duration = r.nextInt() % 10000 + 2000;
                if (duration < 0)
                    duration = -1 * duration;
                Thread.sleep(duration);
            } catch (InterruptedException e) {

            }
            // COMPUTE NEW VALUE FOR TEMP
            changeTemp(r);
        }
    } //WHILE

    private synchronized void notifyListeners() {
        for (int i = 0; i < list.size(); i++) {
            TemperatureListener listener = list.get(i);
            try {
                listener.temperatureChanged(temp);
                //temperatureChanged vai ser executado do lado do cliente
            } catch (RemoteException e) { //UNABLE TO CONTACT LISTENER
                System.out.println("removing listener -" + listener);
                list.remove(listener);
                i--;
            }
        }
    }

    public static void main(String args[]) {
        System.out.println("Loading temperature service");
        // ONLY REQUIRED FOR DYNAMIC CLASS LOADING
        //System.setSecurityManager ( new RMISecurityManager() );
        try {
            // LOAD THE SERVICE
            TemperatureSensorServer sensor = new TemperatureSensorServer(); //criar o serviço

            // REGISTER WITH SERVICE SO THAT CLIENTS CAN FIND US
            String registry = "localhost";
            if (args.length >= 1) {
                registry = args[0];
            }

            String registration = "rmi://" + registry + "/TemperatureSensor";
            Naming.rebind(registration, sensor); //referencia remota ficar registada no registry
            //para os clientes depois obterem essa referencia remota

            // CREATE A THREAD TO TRIGGER REGULAR TEMPERATURE CHANGES
            //serve apenas para simular as diferentes temperaturas
            Thread thread = new Thread(sensor);
            thread.start();

        } catch (RemoteException re) {
            System.err.println("Remote Error - " + re);
        } catch (Exception e) {
            System.err.println("Error - " + e);
        }
    } //MAIN
}
Tags : ,

0 thoughts on “aula08tRMICallbacks”

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.