1 package org.apache.turbine.util;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.util.Random;
23
24 /***
25 * This class generates a unique 10+ character id. This is good for
26 * authenticating users or tracking users around.
27 *
28 * <p>This code was borrowed from Apache
29 * JServ.JServServletManager.java. It is what Apache JServ uses to
30 * generate session ids for users. Unfortunately, it was not included
31 * in Apache JServ as a class, so I had to create one here in order to
32 * use it.
33 *
34 * @author <a href="mailto:jon@clearink.com">Jon S. Stevens</a>
35 * @author <a href="mailto:neeme@one.lv">Neeme Praks</a>
36 * @version $Id: GenerateUniqueId.java 534527 2007-05-02 16:10:59Z tv $
37 */
38 public class GenerateUniqueId
39 {
40
41
42
43
44
45
46
47
48 static private int session_count = 0;
49 static private long lastTimeVal = 0;
50 static private Random randomSource = new java.util.Random();
51
52
53
54
55
56
57
58
59 public final static long maxRandomLen = 2176782336L;
60
61
62
63
64
65
66
67 public final static long maxSessionLifespanTics = 46656;
68
69
70
71
72
73 public final static long ticDifference = 2000;
74
75 /***
76 * Get the unique id.
77 *
78 * <p>NOTE: This must work together with
79 * get_jserv_session_balance() in jserv_balance.c
80 *
81 * @return A String with the new unique id.
82 */
83 static synchronized public String getIdentifier()
84 {
85 StringBuffer sessionId = new StringBuffer();
86
87
88 long n = randomSource.nextLong();
89 if (n < 0) n = -n;
90 n %= maxRandomLen;
91
92
93
94 n += maxRandomLen;
95 sessionId.append(Long.toString(n, Character.MAX_RADIX)
96 .substring(1));
97
98 long timeVal = (System.currentTimeMillis() / ticDifference);
99
100
101 timeVal %= maxSessionLifespanTics;
102
103
104 timeVal += maxSessionLifespanTics;
105
106 sessionId.append(Long.toString(timeVal, Character.MAX_RADIX)
107 .substring(1));
108
109
110
111
112
113
114
115
116 if (lastTimeVal != timeVal)
117 {
118 lastTimeVal = timeVal;
119 session_count = 0;
120 }
121 sessionId.append(Long.toString(++session_count,
122 Character.MAX_RADIX));
123
124 return sessionId.toString();
125 }
126
127 /***
128 * Get the unique id.
129 *
130 * @param jsIdent A String.
131 * @return A String with the new unique id.
132 */
133 synchronized public String getIdentifier(String jsIdent)
134 {
135 if (jsIdent != null && jsIdent.length() > 0)
136 {
137 return getIdentifier() + "." + jsIdent;
138 }
139 return getIdentifier();
140 }
141
142 /***
143 * Simple test of the functionality.
144 *
145 * @param args A String[] with the command line arguments.
146 */
147 public static void main(String[] args)
148 {
149 System.out.println(GenerateUniqueId.getIdentifier());
150 System.out.println(GenerateUniqueId.getIdentifier());
151 System.out.println(GenerateUniqueId.getIdentifier());
152 System.out.println(GenerateUniqueId.getIdentifier());
153 }
154 }