KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > caucho > util > RandomUtil


1 /*
2  * Copyright (c) 1998-2006 Caucho Technology -- all rights reserved
3  *
4  * This file is part of Resin(R) Open Source
5  *
6  * Each copy or derived work must preserve the copyright notice and this
7  * notice unmodified.
8  *
9  * Resin Open Source is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * Resin Open Source is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
17  * of NON-INFRINGEMENT. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with Resin Open Source; if not, write to the
22  *
23  * Free Software Foundation, Inc.
24  * 59 Temple Place, Suite 330
25  * Boston, MA 02111-1307 USA
26  *
27  * @author Scott Ferguson
28  */

29
30 package com.caucho.util;
31
32 import java.security.SecureRandom JavaDoc;
33 import java.util.Random JavaDoc;
34
35 /**
36  * System-wide random number generator.
37  */

38 public class RandomUtil {
39   static private long _seed = System.currentTimeMillis();
40   static private Random JavaDoc _random;
41   static private boolean _isTest;
42
43   /**
44    * Returns the next random long.
45    */

46   public synchronized static long getRandomLong()
47   {
48     return getRandom().nextLong();
49   }
50
51   /**
52    * Returns the next random int.
53    */

54   public synchronized static int nextInt(int n)
55   {
56     return getRandom().nextInt(n);
57   }
58
59   /**
60    * Adds a random number based on a string.
61    */

62   public static void addRandom(String JavaDoc random)
63   {
64     if (random == null)
65       return;
66     
67     for (int i = 0; i < random.length(); i++)
68       addRandom(random.charAt(i));
69   }
70
71   /**
72    * Adds a random number to the server seed.
73    */

74   public static void addRandom(long seed)
75   {
76     Random JavaDoc random = getRandom();
77     if (random instanceof SecureRandom JavaDoc)
78       ((SecureRandom JavaDoc) random).setSeed(seed);
79   }
80
81   /**
82    * Returns the random generator.
83    */

84   private static Random JavaDoc getRandom()
85   {
86     if (_random == null) {
87       _random = new SecureRandom JavaDoc();
88       _random.setSeed(_seed);
89     }
90
91     return _random;
92   }
93
94   /**
95    * Sets the specific seed. Only for testing.
96    */

97   public static void setTestSeed(long seed)
98   {
99     _seed = seed;
100     _isTest = true;
101     _random = new Random JavaDoc(seed);
102   }
103 }
104
Popular Tags