View Javadoc

1   package nl.tudelft.goal.ut2004.visualizer.connection.client;
2   
3   import java.net.URI;
4   import java.rmi.NotBoundException;
5   import java.rmi.RemoteException;
6   import java.rmi.registry.LocateRegistry;
7   import java.rmi.registry.Registry;
8   
9   import nl.tudelft.goal.ut2004.visualizer.connection.VisualizerService;
10  import nl.tudelft.pogamut.base.server.ServerDefinition;
11  import cz.cuni.amis.utils.exception.PogamutException;
12  import cz.cuni.amis.utils.flag.FlagListener;
13  
14  public class VisualizerServiceDefinition extends ServerDefinition<RemoteVisualizer> {
15  
16  	/**
17  	 * Serial version UID. Date of last modification.
18  	 */
19  	private static final long serialVersionUID = 201212041520L;
20  
21  	public static final String serviceName = "UnrealVisualizerService";
22  
23  	private final FlagListener<Boolean> connectionListener = new FlagListener<Boolean>() {
24  
25  		@Override
26  		public void flagChanged(Boolean connected) {
27  			if (!connected)
28  				startServer(); 
29  		}
30  	};
31  
32  	private RemoteVisualizer visualizer;
33  
34  	/**
35  	 * Starts a connection to the Visualizer server. Throws a Pogamut exception if the connection fails.
36  	 * 
37  	 */
38  	@Override
39  	public void startServer() {
40  
41  		try {
42  			URI uri = getUri();
43  
44  			assert uri.getHost() != null;
45  			assert uri.getPort() != -1;
46  
47  			Registry registry = LocateRegistry.getRegistry(uri.getHost(), uri.getPort());
48  			VisualizerService service = (VisualizerService) registry.lookup(serviceName);
49  			visualizer = new RemoteVisualizer();
50  			visualizer.setVisualizerService(service);
51  			visualizer.getConnectedFlag().addListener(connectionListener);
52  			setNewServer(visualizer);
53  
54  		} catch (RemoteException e) {
55  			throw new PogamutException("Problem marshalling remote visualizer.", e);
56  		} catch (NotBoundException e) {
57  			throw new PogamutException("UnrealVisualizer is not running", e);
58  		}
59  	}
60  
61  	@Override
62  	public void stopServer() {
63  		if (visualizer != null) {
64  			visualizer.getConnectedFlag().removeListener(connectionListener);
65  			visualizer.disconnect();
66  			visualizer = null;
67  			setNewServer(null);
68  		}
69  	}
70  
71  }