1 package org.objectweb.proactive.p2p.registry; 2 3 import java.rmi.RemoteException ; 4 import java.util.Enumeration ; 5 import java.util.Hashtable ; 6 7 import net.jini.discovery.LookupDiscovery; 8 import net.jini.discovery.DiscoveryListener; 9 import net.jini.discovery.DiscoveryEvent; 10 import net.jini.core.lookup.ServiceItem; 11 import net.jini.core.lookup.ServiceRegistrar; 12 import net.jini.core.lookup.ServiceRegistration; 13 import net.jini.core.lease.Lease; 14 import net.jini.core.lease.LeaseDeniedException; 15 import net.jini.core.lease.UnknownLeaseException; 16 17 20 21 public class ServerListener implements DiscoveryListener, Runnable { 22 23 private Hashtable leases = new Hashtable (); 25 private ServiceItem item; private static final long ltime = Lease.FOREVER; 27 private static final int mtime = 30*1000; 29 private LookupDiscovery ld; 31 public ServerListener(LookupDiscovery ld, Object object) { 32 item = new ServiceItem(null, object, null); 33 this.ld = ld; 34 new Thread (this).start(); 36 } 37 38 public synchronized void discovered(DiscoveryEvent dev) { 40 ServiceRegistrar[] lookup = dev.getRegistrars(); 41 for (int i = 0; i < lookup.length; i++) { 44 if (leases.containsKey(lookup[i]) == false) { 45 try { 47 ServiceRegistration ret = lookup[i].register(item, ltime); 49 if (item.serviceID == null) { 52 item.serviceID = ret.getServiceID(); 53 } 54 leases.put(lookup[i], ret); 56 notify(); 58 } catch (RemoteException ex) { 59 System.out.println("ServerListener error: " + ex); 60 } 61 } 62 } 64 } 65 66 public synchronized void discarded(DiscoveryEvent dev) { 68 ServiceRegistrar[] lookup = dev.getRegistrars(); 69 for (int i = 0; i < lookup.length; i++) { 70 if (leases.containsKey(lookup[i]) == true) { 71 leases.remove(lookup[i]); 74 } 75 } 76 } 77 78 public synchronized void run() { 79 while (true) { 80 long nextRenewal = Long.MAX_VALUE; 81 long now = System.currentTimeMillis(); 82 83 Enumeration e = leases.keys(); 84 while (e.hasMoreElements()) { 88 ServiceRegistrar lookup = (ServiceRegistrar) e.nextElement(); 89 ServiceRegistration sr = (ServiceRegistration) leases.get(lookup); 90 Lease l = sr.getLease(); 91 long expire = l.getExpiration(); 92 93 try { 98 if (expire <= now + mtime) { 99 l.renew(ltime); 100 expire = l.getExpiration(); 101 } 102 if (nextRenewal > expire - mtime) { 103 nextRenewal = expire - mtime; 104 } 105 } catch (LeaseDeniedException lex) { 106 } catch (UnknownLeaseException lex) { 107 ld.discard(lookup); 108 } catch (RemoteException ex) { 109 ld.discard(lookup); 110 } 111 } 112 try { 113 wait(nextRenewal - now); 117 } catch (InterruptedException ex) {}; 118 } 119 } 120 } 121 | Popular Tags |