1 19 package org.objectweb.carol.cmi; 20 21 import java.net.InetAddress ; 22 import java.net.UnknownHostException ; 23 24 32 public class ClusterIdFactory { 33 private static byte localIdArray[]; 34 private static ClusterId localId; 35 private static long date; 36 private static java.net.ServerSocket ss; 37 38 private ClusterIdFactory() { 39 } 40 41 public static synchronized void start() throws ClusterException { 42 startTypeIp(); 43 } 44 45 49 private static synchronized void startTypeIp() throws ClusterException { 50 if (localIdArray != null) { 51 return; 52 } 53 InetAddress a; 54 try { 55 a = InetAddress.getLocalHost(); 56 } catch (UnknownHostException e) { 57 throw new ClusterException("Error in getLocalHost() : " + e.toString()); 58 } 59 byte aa[] = a.getAddress(); 60 if (aa.length != 4) { 61 throw new ClusterException( 62 "IP Address of size " + aa.length + " not supported by ClusterIdFactory"); 63 } 64 if (aa[0] == 127) { 65 throw new ClusterException( 66 "Loopback IP address not allowed in ClusterIdFactory : fix /etc/hosts (or equivalent) so that java.net.InetAddress.getLocalHost() does not return 127.x.x.x"); 67 } 68 try { 69 ss = new java.net.ServerSocket (0, 1, a); 70 } catch (Exception e) { 71 throw new ClusterException(e.toString()); 72 } 73 int p = ss.getLocalPort(); 74 if ((p & 0xffff) != p) { 75 throw new ClusterException( 76 "Invalid port number (more than 16 bits) in ClusterIdFactory"); 77 } 78 date = System.currentTimeMillis() / 1000; 79 if (date >= 128L << 24) { 80 throw new ClusterException("Invalid date (too high) in ClusterIdFactory"); 81 } 82 localIdArray = new byte[10]; 83 localIdArray[0] = (byte) (p & 0xff); 84 localIdArray[1] = (byte) (p >> 8); 85 localIdArray[2] = aa[3]; 86 localIdArray[3] = aa[2]; 87 localIdArray[4] = aa[1]; 88 localIdArray[5] = aa[0]; 89 int n = 4; 90 long d = date; 91 while (n > 0) { 92 n--; 93 localIdArray[9 - n] = (byte) (d & 0xff); 94 d >>= 8; 95 } 96 localId = ClusterId.toClusterId(localIdArray); 97 SecureRandom.setSeed(localIdArray); 98 } 99 100 105 public static synchronized ClusterId getLocalId() throws ClusterException { 106 if (localIdArray == null) { 107 start(); 108 } 109 if (ss == null) { 110 return localId; 111 } 112 while (true) { 113 long d = System.currentTimeMillis(); 114 if ((d / 1000) > date) { 116 try { 117 ss.close(); 118 } catch (java.io.IOException e) { 119 } 121 ss = null; 122 return localId; 123 } 124 try { 125 synchronized (localIdArray) { 126 localIdArray.wait(1001 - (d % 1000)); 127 } 128 } catch (InterruptedException e) { 129 } 131 d = System.currentTimeMillis(); 132 } 133 } 134 } 135 | Popular Tags |