View Javadoc

1   /*
2    * Created by IntelliJ IDEA.
3    * User: mike
4    * Date: Jan 23, 2002
5    * Time: 6:10:02 PM
6    * To change template for new class use
7    * Code Style | Class Templates options (Tools | IDE Options).
8    */
9   package com.atlassian.core.util;
10  
11  public class RandomGenerator {
12      /**
13       * Generate a random password (length 6)
14       */
15      public static String randomPassword() {
16          return randomString(6);
17      }
18  
19      /**
20       * Generate a random string of characters - including numbers
21       */
22      public static String randomString(int length) {
23          return randomString(length, true);
24      }
25  
26      /**
27       * Generate a random string of characters
28       */
29      public static String randomString(int length, boolean includeNumbers) {
30          StringBuilder b = new StringBuilder(length);
31  
32          for (int i = 0; i < length; i++) {
33              if (includeNumbers)
34                  b.append(randomCharacter());
35              else
36                  b.append(randomAlpha());
37          }
38  
39          return b.toString();
40      }
41  
42      /**
43       * Generate a random alphanumeric character.
44       *
45       * 3/4rs of the time this will generate a letter, 1/4 a number
46       */
47      public static char randomCharacter() {
48          int i = (int) (Math.random() * 3);
49          if (i < 2)
50              return randomAlpha();
51          else
52              return randomDigit();
53      }
54  
55      /**
56       * Generate a random character from the alphabet - either a-z or A-Z
57       */
58      public static char randomAlpha() {
59          int i = (int) (Math.random() * 52);
60  
61          if (i > 25)
62              return (char) (97 + i - 26);
63          else
64              return (char) (65 + i);
65      }
66  
67      /**
68       * Generate a random digit - from 0 - 9
69       */
70      public static char randomDigit() {
71          int i = (int) (Math.random() * 10);
72          return (char) (48 + i);
73      }
74  }