1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package ch.elca.el4j.services.persistence.generic.primarykey;
18
19 import java.net.InetAddress;
20 import java.net.UnknownHostException;
21 import java.security.SecureRandom;
22
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25
26 import ch.elca.el4j.util.codingsupport.annotations.FindBugsSuppressWarnings;
27
28
29
30
31
32
33
34
35
36
37
38
39
40 public class UuidPrimaryKeyGenerator implements PrimaryKeyGenerator {
41
42
43
44 private static Logger s_logger
45 = LoggerFactory.getLogger(UuidPrimaryKeyGenerator.class);
46
47
48
49
50 private String m_midValue;
51
52
53
54
55 private SecureRandom m_seeder;
56
57
58
59
60 private String[] m_zeros;
61
62
63
64
65 public UuidPrimaryKeyGenerator() {
66 init();
67 }
68
69
70
71
72 @FindBugsSuppressWarnings(value = "INT_VACUOUS_BIT_OPERATION",
73 justification = "Ensures that no rounding takes place")
74 public String getPrimaryKey() {
75 long time = System.currentTimeMillis();
76 int timeLow = (int) time & 0xFFFFFFFF;
77 int value = m_seeder.nextInt();
78 String keyString = toHexString(timeLow) + m_midValue
79 + toHexString(value);
80 return keyString;
81 }
82
83
84
85
86
87 private void init() {
88
89 final int ZERO_ARRAY_LENGTH = 8;
90 m_zeros = new String[ZERO_ARRAY_LENGTH];
91 m_zeros[0] = "";
92 for (int i = 1; i < ZERO_ARRAY_LENGTH; i++) {
93 m_zeros[i] = m_zeros[i - 1] + "0";
94 }
95
96
97 byte[] bytes = null;
98 try {
99 InetAddress inetAddress = InetAddress.getLocalHost();
100 bytes = inetAddress.getAddress();
101 } catch (UnknownHostException npe) {
102 s_logger.debug("Host ip could not be found. Following "
103 + "will be used: 127.0.0.1");
104 bytes = new byte[] {1, 0, 0, 127};
105 }
106 int intAddress = 0;
107 for (int i = 0; i < bytes.length; i++) {
108 int unsignedByte = bytes[i] & 0xFF;
109 intAddress = (intAddress + unsignedByte) << 8;
110 }
111 String hexInetAddress = toHexString(intAddress);
112
113 String thisHashCode = toHexString(System.identityHashCode(this));
114
115 m_midValue = hexInetAddress + thisHashCode;
116
117 m_seeder = new SecureRandom();
118 }
119
120
121
122
123
124
125
126 private String toHexString(int i) {
127 String hex = Integer.toHexString(i);
128 int hexLength = hex.length();
129 return m_zeros[8 - hexLength] + hex;
130 }
131
132 }
133