View Javadoc

1   package org.apache.turbine.util;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
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       * Create a suitable string for session identification.  Use
42       * synchronized count and time to ensure uniqueness.  Use random
43       * string to ensure the timestamp cannot be guessed by programmed
44       * attack.
45       *
46       * Format of id is <6 chars random><3 chars time><1+ char count>
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      // MAX_RADIX is 36
53  
54      /*
55       * We want to have a random string with a length of 6 characters.
56       * Since we encode it BASE 36, we've to modulo it with the
57       * following value:
58       */
59      public final static long maxRandomLen = 2176782336L; // 36 ** 6
60  
61      /*
62       * The session identifier must be unique within the typical
63       * lifespan of a Session; the value can roll over after that.  3
64       * characters: (this means a roll over after over a day, which is
65       * much larger than a typical lifespan)
66       */
67      public final static long maxSessionLifespanTics = 46656; // 36 ** 3
68  
69      /*
70       * Millisecons between different tics.  So this means that the
71       * 3-character time string has a new value every 2 seconds:
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          // Random value.
88          long n = randomSource.nextLong();
89          if (n < 0) n = -n;
90          n %= maxRandomLen;
91  
92          // Add maxLen to pad the leading characters with '0'; remove
93          // first digit with substring.
94          n += maxRandomLen;
95          sessionId.append(Long.toString(n, Character.MAX_RADIX)
96                  .substring(1));
97  
98          long timeVal = (System.currentTimeMillis() / ticDifference);
99  
100         // Cut.
101         timeVal %= maxSessionLifespanTics;
102 
103         // Padding, see above.
104         timeVal += maxSessionLifespanTics;
105 
106         sessionId.append(Long.toString(timeVal, Character.MAX_RADIX)
107                 .substring(1));
108 
109         /*
110          * Make the string unique: append the session count since last
111          * time flip.
112          */
113 
114         // Count sessions only within tics.  So the 'real' session
115         // count isn't exposed to the public.
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 }