KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > idaremedia > antx > helpers > SIDs


1 /**
2  * $Id: SIDs.java 180 2007-03-15 12:56:38Z ssmc $
3  * Copyright 1997-2004 iDare Media, Inc. All rights reserved.
4  *
5  * Originally written by iDare Media, Inc. for release into the public domain. This
6  * library, source form and binary form, is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public License as published by the
8  * Free Software Foundation; either version 2.1 of the License, or (at your option) any
9  * later version.<p>
10  *
11  * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
12  * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13  * See the GNU LGPL (GNU Lesser General Public License) for more details.<p>
14  *
15  * You should have received a copy of the GNU Lesser General Public License along with this
16  * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite
17  * 330, Boston, MA 02111-1307 USA. The LGPL can be found online at
18  * http://www.fsf.org/copyleft/lesser.html
19  *
20  * This product has been influenced by several projects within the open-source community.
21  * The JWare developers wish to acknowledge the open-source community's support. For more
22  * information regarding the open-source products used within JWare, please visit the
23  * JWare website.
24  *----------------------------------------------------------------------------------------*
25  * WEBSITE- http://www.jware.info EMAIL- inquiries@jware.info
26  *----------------------------------------------------------------------------------------*
27  **/

28
29 package com.idaremedia.antx.helpers;
30
31 import java.security.NoSuchAlgorithmException JavaDoc;
32 import java.security.SecureRandom JavaDoc;
33
34 /**
35  * Administrator of a set of pseudo-unique numeric identifers. Components that need a
36  * context-specific, unique key identifier will find this class useful. If a test needs
37  * more secure ids it should look at the java.rmi.server package for VMIDs
38  * and/or GIDs.
39  * <p>
40  * The SIDs class uses a <span class="src">SecureRandom</span> as the foundation of
41  * of its implementation. By default it will try to locate one of two default secure
42  * random number generator algorithms ("<span class="src">SHA1PRNG</span>" and
43  * "<span class="src">IBMSecureRandom</span>"). These two algorithms represent the
44  * dominant JREs (Sun's and IBM's). To force SIDs to use another custom algorithm you
45  * must install the SPI for the algorithm and define the system property
46  * "<span class="src">jware.securerandom.algo</span>" to the algorithm's common name.
47  *
48  * @since JWare/core 0.2
49  * @author ssmc, &copy;1997-2004 <a HREF="http://www.jware.info">iDare&nbsp;Media,&nbsp;Inc.</a>
50  * @version 0.5
51  * @.safety multiple
52  * @.group impl,helper
53  **/

54
55 public final class SIDs
56 {
57     /** The system property that customizes the SecureRandom algorithm. **/
58     public static final String JavaDoc SECURERANDOM_ALGORITHM_PROPERTY=
59         "jware.securerandom.algo";
60
61
62     /** Check if a given SPI/algorithm is available. **/
63     private static SecureRandom JavaDoc getSRNG(String JavaDoc algo)
64     {
65         SecureRandom JavaDoc srng=null;
66         try {
67             srng= SecureRandom.getInstance(algo);
68         } catch (NoSuchAlgorithmException JavaDoc algox) {
69             return null;
70         }
71         srng.setSeed(System.currentTimeMillis());
72         return srng;
73     }
74
75
76     /** A secure pseudo-random number generator (PRNG). Tries to two main ones
77         automatically if not explicitly defined by application. **/

78     private static final SecureRandom JavaDoc PRNG;
79     static {
80         SecureRandom JavaDoc srng=null;
81         String JavaDoc preferred = System.getProperty(SECURERANDOM_ALGORITHM_PROPERTY);
82         if (preferred!=null) {
83             srng = getSRNG(preferred);
84             if (srng==null) {
85                 throw new RuntimeException JavaDoc("Missing SPRNG algorithm: "+preferred);
86             }
87         } else {
88             srng = getSRNG("SHA1PRNG");//Sun's jre
89
if (srng==null) {
90                 srng = getSRNG("IBMSecureRandom");//IBM's jre
91
if (srng==null) {
92                     throw new RuntimeException JavaDoc("Missing SPRNG algorithm: SHA1PRNG");
93                 }
94             }
95         }
96         PRNG= srng;
97     }
98
99
100     /** Shared scratch for generating string-based identifiers. **/
101     private static StringBuffer JavaDoc m_sb= new StringBuffer JavaDoc(32);
102
103
104     /**
105      * Strategy that determines if a SID is unique within some context.
106      **/

107     public interface Finder {
108         public boolean exists(String JavaDoc sid);
109     }
110
111
112     /**
113      * Returns the next pseudo-random SIDs long integer. Both
114      * positive and negative numbers are returned.
115      **/

116     public static long nextLong()
117     {
118         return PRNG.nextLong();
119     }
120
121
122     /**
123      * Returns the next pseudo-random SIDs integer. Both
124      * positive and negative numbers are returned.
125      **/

126     public static int nextInt()
127     {
128         return PRNG.nextInt();
129     }
130
131
132     /**
133      * Returns the next pseudo-random <em>positive</em> SIDs integer
134      * within a particular range. Only integers between 0(inclusive)
135      * and <i>limit</i> (exclusive) are returned.
136      * @return an integer (<i>0</i>..<i>limit</i>]
137      **/

138     public static int nextInt(int limit)
139     {
140         return PRNG.nextInt(limit);
141     }
142
143
144     /**
145      * Returns a new identifier with default prefix "<i>RUT</i>;" for example,
146      * "<i>RUT123456</i>".
147      **/

148     public static String JavaDoc next()
149     {
150         synchronized(PRNG) {
151             m_sb.setLength(0);
152             m_sb.append(o_SYSID);
153             m_sb.append(PRNG.nextInt(Integer.MAX_VALUE));//keep positive
154
m_sb.append(c_SYSID);
155             return m_sb.substring(0);//NB: a string with own copy of chars!
156
}
157     }
158
159
160     /**
161      * Returns a new identifier with a customized prefix. Prefix is
162      * typically at least three characters long.
163      * @param pfx custom prefix (non-null)
164      * @throws java.lang.IllegalArgumentException if prefix is <i>null</i>
165      **/

166     public static String JavaDoc next(String JavaDoc pfx)
167     {
168         if (pfx==null) {
169             throw new IllegalArgumentException JavaDoc();
170         }
171         synchronized(PRNG) {
172             m_sb.setLength(0);
173             m_sb.append(pfx);
174             m_sb.append(PRNG.nextInt(999999));
175             return m_sb.substring(0);//NB: a string with own copy of chars!
176
}
177     }
178
179
180     /**
181      * Returns a new identifier that doesn't already exist in caller's
182      * context.
183      * @param uv the uniqueness checker for caller's context (non-null)
184      * @throws java.lang.IllegalArgumentException if <i>uv</i> finder is <i>null</i>
185      **/

186     public static String JavaDoc next(Finder uv)
187     {
188         if (uv==null) {
189             throw new IllegalArgumentException JavaDoc();
190         }
191         synchronized(PRNG) {
192             String JavaDoc s;
193             do {
194                 s= null;
195                 m_sb.setLength(0);
196                 m_sb.append(PRNG.nextInt(999999999));
197                 s = m_sb.substring(0);
198             } while (uv.exists(s));
199             return s;//NB: a string with own copy of chars!
200
}
201     }
202
203
204     /**
205      * Returns a new custom-prefixed identifier that doesn't already
206      * exist in caller's context. Prefix is typically at least three
207      * (3) characters long.
208      * @param uv the uniqueness checker for caller's context (non-null)
209      * @param pfx the prefix to append before unique part
210      * @throws java.lang.IllegalArgumentException if either parameter is <i>null</i>
211      **/

212     public static String JavaDoc next(Finder uv, String JavaDoc pfx)
213     {
214         if (uv==null || pfx==null) {
215             throw new IllegalArgumentException JavaDoc();
216         }
217         synchronized(PRNG) {
218             String JavaDoc s;
219             do {
220                 s= null;
221                 m_sb.setLength(0);
222                 m_sb.append(pfx);
223                 m_sb.append(PRNG.nextInt(999999));
224                 s = m_sb.substring(0);
225             } while (uv.exists(s));
226             return s;//NB: a string with own copy of chars!
227
}
228     }
229
230
231     /**
232      * Returns a given number of seed bytes as defined by the SIDs
233      * underlying secure random implementation's seed generation algorithm.
234      * The returned bytes can be used to seed other generators. Never
235      * returns <i>null</i>
236      * @param numBytes the number of seed bytes to generate
237      * @since JWare/core 0.7
238      **/

239     public static final byte[] nextSeed(int numBytes)
240     {
241         return PRNG.generateSeed(numBytes);
242     }
243
244
245
246     private SIDs()
247     {/*not-allowed,algorithms-only*/}
248
249
250     private static final String JavaDoc o_SYSID= "RUT{";
251     private static final String JavaDoc c_SYSID= "}";
252 }
253
254 /* end-of-SIDs.java */
255
Popular Tags