1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.ws.security.util;
21
22 import java.net.InetAddress;
23 import java.net.UnknownHostException;
24 import java.security.MessageDigest;
25 import java.security.NoSuchAlgorithmException;
26 import java.util.Random;
27
28
29
30
31 public final class UUIDGenerator {
32
33 private static final org.apache.commons.logging.Log LOG =
34 org.apache.commons.logging.LogFactory.getLog(UUIDGenerator.class);
35
36 private static String baseUUID = null;
37 private static long incrementingValue = 0;
38
39
40 private static Random myRand = null;
41
42 private UUIDGenerator() {
43
44 }
45
46
47
48
49
50
51
52 public static synchronized String getUUID() {
53 if (baseUUID == null) {
54 getInitialUUID();
55 }
56 long i = ++incrementingValue;
57 if (i >= Long.MAX_VALUE || i < 0) {
58 incrementingValue = 0;
59 i = 0;
60 }
61 return baseUUID + System.currentTimeMillis() + i;
62 }
63
64 protected static synchronized void getInitialUUID() {
65 if (baseUUID != null) {
66 return;
67 }
68 if (myRand == null) {
69 myRand = new Random();
70 }
71 long rand = myRand.nextLong();
72 String sid;
73 try {
74 sid = InetAddress.getLocalHost().toString();
75 } catch (UnknownHostException e) {
76 sid = Thread.currentThread().getName();
77 }
78 StringBuilder sb = new StringBuilder();
79 sb.append(sid);
80 sb.append(":");
81 sb.append(Long.toString(rand));
82 MessageDigest md5 = null;
83 try {
84 md5 = MessageDigest.getInstance("MD5");
85 } catch (NoSuchAlgorithmException e) {
86 if (LOG.isDebugEnabled()) {
87 LOG.debug(e.getMessage(), e);
88 }
89
90 }
91 md5.update(sb.toString().getBytes());
92 byte[] array = md5.digest();
93 StringBuilder sb2 = new StringBuilder();
94 for (int j = 0; j < array.length; ++j) {
95 int b = array[j] & 0xFF;
96 sb2.append(Integer.toHexString(b));
97 }
98 int begin = myRand.nextInt();
99 if (begin < 0) {
100 begin = begin * -1;
101 }
102 begin = begin % 8;
103 baseUUID = sb2.toString().substring(begin, begin + 18).toUpperCase();
104 }
105
106 }