1 7 package org.jboss.remoting; 8 9 import java.util.ArrayList ; 10 import java.util.List ; 11 import java.util.ListIterator ; 12 import java.util.Timer ; 13 import java.util.TimerTask ; 14 import org.jboss.remoting.transport.ClientInvoker; 15 16 19 public class ConnectionValidator extends TimerTask 20 { 21 private List listeners = new ArrayList (); 22 private Client client = null; 23 24 private Timer validatorTimer = null; 25 private long pingPeriod = DEFAULT_PING_PERIOD; 26 27 30 public static final long DEFAULT_PING_PERIOD = 2000; 31 32 public ConnectionValidator(Client client) 33 { 34 this.client = client; 35 } 36 37 private void start() 38 { 39 validatorTimer = new Timer (false); 40 validatorTimer.schedule(this, pingPeriod, pingPeriod); 41 } 42 43 private void stop() 44 { 45 this.cancel(); 46 validatorTimer.cancel(); 47 validatorTimer = null; 48 } 49 50 51 public void addConnectionListener(ConnectionListener listener) 52 { 53 if(listener != null) 54 { 55 synchronized(listener) 56 { 57 if(listeners.size() == 0) 58 { 59 start(); 60 } 61 listeners.add(listener); 62 } 63 } 64 } 65 66 public boolean removeConnectionListener(ConnectionListener listener) 67 { 68 boolean isRemoved = false; 69 if(listener != null) 70 { 71 synchronized(listeners) 72 { 73 isRemoved = listeners.remove(listener); 74 if(listeners.size() == 0) 75 { 76 stop(); 77 } 78 } 79 } 80 return isRemoved; 81 } 82 83 86 public void run() 87 { 88 try 89 { 90 boolean isValid = checkConnection(client.getInvoker()); 91 if(!isValid) 92 { 93 notifyListeners(new Exception ("Could not connect to server.")); 94 } 95 } 96 catch(Throwable thr) 97 { 98 notifyListeners(thr); 99 } 100 } 101 102 private void notifyListeners(Throwable thr) 103 { 104 final Throwable t = thr; 105 synchronized(listeners) 106 { 107 ListIterator itr = listeners.listIterator(); 108 while(itr.hasNext()) 109 { 110 final ConnectionListener listener = (ConnectionListener) itr.next(); 111 new Thread () 112 { 113 public void run() 114 { 115 listener.handlerConnectionException(t, client); 116 } 117 }.start(); 118 } 119 } 120 } 121 122 public static boolean checkConnection(ClientInvoker clientInvoker) throws Throwable 123 { 124 Object o = clientInvoker.invoke(new InvocationRequest(ConnectionValidator.class.getName(), 125 Subsystem.SELF, "$PING$", null, null, null)); 126 InvocationResponse resp = (InvocationResponse) o; 127 Boolean b = (Boolean ) resp.getResult(); 128 return b.booleanValue(); 129 } 130 131 132 } | Popular Tags |