1 18 package org.apache.activemq.util; 19 import java.net.InetAddress ; 20 import java.net.ServerSocket ; 21 import java.util.logging.Level ; 22 import java.util.logging.Logger ; 23 24 27 28 public class IdGenerator{ 29 30 private static final Logger log = Logger.getLogger(IdGenerator.class.getName()); 31 private static final String UNIQUE_STUB; 32 private static int instanceCount; 33 private static String hostName; 34 private String seed; 35 private long sequence; 36 37 static { 38 String stub = ""; 39 boolean canAccessSystemProps = true; 40 try{ 41 SecurityManager sm = System.getSecurityManager(); 42 if(sm != null){ 43 sm.checkPropertiesAccess(); 44 } 45 }catch(SecurityException se){ 46 canAccessSystemProps = false; 47 } 48 49 if ( canAccessSystemProps) { 50 try { 51 hostName = InetAddress.getLocalHost().getHostName(); 52 ServerSocket ss = new ServerSocket (0); 53 stub="-" + ss.getLocalPort() + "-" + System.currentTimeMillis() + "-"; 54 Thread.sleep(100); 55 ss.close(); 56 }catch(Exception ioe){ 57 log.log(Level.WARNING, "could not generate unique stub",ioe); 58 } 59 }else{ 60 hostName="localhost"; 61 stub = "-1-" +System.currentTimeMillis() +"-"; 62 } 63 UNIQUE_STUB = stub; 64 } 65 66 71 72 public static String getHostName(){ 73 return hostName; 74 } 75 76 80 81 public IdGenerator(String prefix){ 82 synchronized(UNIQUE_STUB){ 83 this.seed = prefix + UNIQUE_STUB +(instanceCount++) +":"; 84 } 85 } 86 87 public IdGenerator(){ 88 this("ID:" + hostName); 89 } 90 91 95 96 public synchronized String generateId(){ 97 return this.seed + (this.sequence++); 98 } 99 100 104 public String generateSanitizedId(){ 105 String result = generateId(); 106 result = result.replace(':', '-'); 107 result = result.replace('_', '-'); 108 result = result.replace('.', '-'); 109 return result; 110 } 111 112 } 113 | Popular Tags |