1 17 package org.apache.servicemix.id; 18 19 22 23 24 import java.net.InetAddress ; 25 import java.net.ServerSocket ; 26 import java.util.logging.Level ; 27 import java.util.logging.Logger ; 28 29 32 33 public class IdGenerator{ 34 35 private static final Logger log = Logger.getLogger(IdGenerator.class.getName()); 36 private static final String UNIQUE_STUB; 37 private static int instanceCount; 38 private static String hostName; 39 private String seed; 40 private long sequence; 41 42 static { 43 String stub = ""; 44 boolean canAccessSystemProps = true; 45 try{ 46 SecurityManager sm = System.getSecurityManager(); 47 if(sm != null){ 48 sm.checkPropertiesAccess(); 49 } 50 }catch(SecurityException se){ 51 canAccessSystemProps = false; 52 } 53 54 if ( canAccessSystemProps) { 55 try { 56 hostName = InetAddress.getLocalHost().getHostName(); 57 ServerSocket ss = new ServerSocket (0); 58 stub=hostName + "-" + ss.getLocalPort() + "-" + System.currentTimeMillis() + "-"; 59 Thread.sleep(100); 60 ss.close(); 61 }catch(Exception ioe){ 62 log.log(Level.WARNING, "could not generate unique stub",ioe); 63 } 64 }else{ 65 hostName="localhost"; 66 stub = hostName + "-1-" +System.currentTimeMillis() +"-"; 67 } 68 UNIQUE_STUB = stub; 69 } 70 71 76 77 public static String getHostName(){ 78 return hostName; 79 } 80 81 85 86 public IdGenerator(String prefix){ 87 synchronized(UNIQUE_STUB){ 88 this.seed = prefix + UNIQUE_STUB +(instanceCount++) +":"; 89 } 90 } 91 92 public IdGenerator(){ 93 this("ID:"); 94 } 95 96 100 101 public synchronized String generateId(){ 102 return this.seed + (this.sequence++); 103 } 104 105 109 public String generateSanitizedId(){ 110 String result = generateId(); 111 result = result.replace(':', '-'); 112 result = result.replace('_', '-'); 113 result = result.replace('.', '-'); 114 return result; 115 } 116 117 } 118 | Popular Tags |