01: // Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved.
02: // Released under the terms of the GNU General Public License version 2 or later.
03: package fitnesse.wikitext.widgets;
04:
05: import java.security.MessageDigest;
06: import java.security.NoSuchAlgorithmException;
07: import java.util.Random;
08:
09: import fitnesse.wikitext.WikiWidget;
10:
11: public class RandomVariableWidget extends WikiWidget {
12:
13: public static final String REGEXP = "!random";
14:
15: private static String RandomValue = "";
16:
17: public RandomVariableWidget(ParentWidget parent, String text) {
18: super (parent);
19: RandomValue = randomValue();
20: }
21:
22: public String render() throws Exception {
23: return RandomValue;
24: }
25:
26: public String randomValue() {
27: try {
28: Random generator = new Random();
29: String randomNum = new Integer(generator.nextInt(100000))
30: .toString();
31: MessageDigest sha = MessageDigest.getInstance("SHA-1");
32: byte[] result = sha.digest(randomNum.getBytes());
33:
34: return hexEncode(result).toString().substring(0, 11);
35: } catch (NoSuchAlgorithmException ex) {
36: return "notrandom";
37: }
38: }
39:
40: private String hexEncode(byte[] aInput) {
41: StringBuffer result = new StringBuffer();
42: char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
43: '9', 'a', 'b', 'c', 'd', 'e', 'f' };
44: for (int idx = 0; idx < aInput.length; ++idx) {
45: byte b = aInput[idx];
46: result.append(digits[(b & 0xf0) >> 4]);
47: result.append(digits[b & 0x0f]);
48: }
49: return result.toString();
50: }
51:
52: }
|