View Javadoc

1   package twcsckernel.clientKernel.utils;
2   
3   import java.rmi.RemoteException;
4   import java.util.Timer;
5   import java.util.TimerTask;
6   
7   import twcsckernel.projectbase.common.User;
8   
9   /***
10   * Klasa odpowiedzialna za podtrzymanie polączenia, tak, żeby user 
11   * nie został wylogowany przez UserGarbageCollector na serwerze.
12   * 
13   * @author VMD Group
14   * 
15   */
16  public class ConnectionSustainer {
17  
18  	private long interval;
19  
20  	private Timer timer = null;
21  	private User user;
22  	
23  	private TimerTask gcTask = new TimerTask() {
24  	
25  		@Override
26  		public void run() {
27  			try {
28  				
29  				ConnectionSustainer.this.user.ping();
30  			} catch (RemoteException e) {
31  				disable();
32  				e.printStackTrace();
33  				System.exit(0);
34  				
35  			}catch (Exception e){
36  				disable();
37  				e.printStackTrace();
38  				System.exit(0);
39  			}
40  		}
41  	};
42  
43  	
44  
45  	/***
46  	 * Metoda ustawiająca obiekt użytkownika na serwerze na ktorym bedzie 
47  	 * wywoływana metoda <code>ping()</code>
48  	 * @param userObject
49  	 *            obiekt użytkownika na serwerze
50  	 */
51  	public synchronized void setUser(User userObject) {
52  		boolean ifEnabled = timer != null;
53  		disable();
54  		this.user = userObject;
55  		if (ifEnabled)
56  			enable();
57  
58  	}
59  
60  	/***
61  	 * Metoda wyłącza działanie Sustainera
62  	 */
63  	public synchronized void disable() {
64  		if (timer != null) {
65  			timer.cancel();
66  			timer = null;
67  		}
68  	}
69  
70  	/***
71  	 * Metoda włącza działanie Sustainera o ile ustanowione są pola 
72  	 * <code>interval</code> i <code>user</code>
73  	 */
74  	public synchronized void enable() {
75  		System.out.println("Starting ping procedure...");
76  		if (user == null)
77  			return;
78  		if (interval == 0) {
79  			disable();
80  			return;
81  		}
82  		timer = new Timer(true);
83  		timer.schedule(gcTask, interval, interval);
84  	}
85  
86  	/***
87  	 * Metoda ustawia interwał czasowy co który bedzie następowało wywołanie ping
88  	 * @param interval - interwał czasowy w milisekundach
89  	 */
90  	public synchronized void setInterval(long interval) {
91  		boolean ifEnabled = timer != null;
92  		disable();
93  		this.interval = interval;
94  		if (ifEnabled)
95  			enable();
96  	}
97  
98  }