View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    * 
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   * 
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.lang3;
18  
19  import java.util.Random;
20  
21  /**
22   * <p>Operations for random {@code String}s.</p>
23   * <p>Currently <em>private high surrogate</em> characters are ignored. 
24   * These are Unicode characters that fall between the values 56192 (db80)
25   * and 56319 (dbff) as we don't know how to handle them. 
26   * High and low surrogates are correctly dealt with - that is if a 
27   * high surrogate is randomly chosen, 55296 (d800) to 56191 (db7f) 
28   * then it is followed by a low surrogate. If a low surrogate is chosen, 
29   * 56320 (dc00) to 57343 (dfff) then it is placed after a randomly 
30   * chosen high surrogate. </p>
31   *
32   * <p>#ThreadSafe#</p>
33   * @since 1.0
34   */
35  public class RandomStringUtils {
36  
37      /**
38       * <p>Random object used by random method. This has to be not local
39       * to the random method so as to not return the same value in the 
40       * same millisecond.</p>
41       */
42      private static final Random RANDOM = new Random();
43  
44      /**
45       * <p>{@code RandomStringUtils} instances should NOT be constructed in
46       * standard programming. Instead, the class should be used as
47       * {@code RandomStringUtils.random(5);}.</p>
48       *
49       * <p>This constructor is public to permit tools that require a JavaBean instance
50       * to operate.</p>
51       */
52      public RandomStringUtils() {
53        super();
54      }
55  
56      // Random
57      //-----------------------------------------------------------------------
58      /**
59       * <p>Creates a random string whose length is the number of characters
60       * specified.</p>
61       *
62       * <p>Characters will be chosen from the set of all characters.</p>
63       *
64       * @param count  the length of random string to create
65       * @return the random string
66       */
67      public static String random(final int count) {
68          return random(count, false, false);
69      }
70  
71      /**
72       * <p>Creates a random string whose length is the number of characters
73       * specified.</p>
74       *
75       * <p>Characters will be chosen from the set of characters whose
76       * ASCII value is between {@code 32} and {@code 126} (inclusive).</p>
77       *
78       * @param count  the length of random string to create
79       * @return the random string
80       */
81      public static String randomAscii(final int count) {
82          return random(count, 32, 127, false, false);
83      }
84      
85      /**
86       * <p>Creates a random string whose length is the number of characters
87       * specified.</p>
88       *
89       * <p>Characters will be chosen from the set of alphabetic
90       * characters.</p>
91       *
92       * @param count  the length of random string to create
93       * @return the random string
94       */
95      public static String randomAlphabetic(final int count) {
96          return random(count, true, false);
97      }
98      
99      /**
100      * <p>Creates a random string whose length is the number of characters
101      * specified.</p>
102      *
103      * <p>Characters will be chosen from the set of alpha-numeric
104      * characters.</p>
105      *
106      * @param count  the length of random string to create
107      * @return the random string
108      */
109     public static String randomAlphanumeric(final int count) {
110         return random(count, true, true);
111     }
112     
113     /**
114      * <p>Creates a random string whose length is the number of characters
115      * specified.</p>
116      *
117      * <p>Characters will be chosen from the set of numeric
118      * characters.</p>
119      *
120      * @param count  the length of random string to create
121      * @return the random string
122      */
123     public static String randomNumeric(final int count) {
124         return random(count, false, true);
125     }
126 
127     /**
128      * <p>Creates a random string whose length is the number of characters
129      * specified.</p>
130      *
131      * <p>Characters will be chosen from the set of alpha-numeric
132      * characters as indicated by the arguments.</p>
133      *
134      * @param count  the length of random string to create
135      * @param letters  if {@code true}, generated string may include
136      *  alphabetic characters
137      * @param numbers  if {@code true}, generated string may include
138      *  numeric characters
139      * @return the random string
140      */
141     public static String random(final int count, final boolean letters, final boolean numbers) {
142         return random(count, 0, 0, letters, numbers);
143     }
144     
145     /**
146      * <p>Creates a random string whose length is the number of characters
147      * specified.</p>
148      *
149      * <p>Characters will be chosen from the set of alpha-numeric
150      * characters as indicated by the arguments.</p>
151      *
152      * @param count  the length of random string to create
153      * @param start  the position in set of chars to start at
154      * @param end  the position in set of chars to end before
155      * @param letters  if {@code true}, generated string may include
156      *  alphabetic characters
157      * @param numbers  if {@code true}, generated string may include
158      *  numeric characters
159      * @return the random string
160      */
161     public static String random(final int count, final int start, final int end, final boolean letters, final boolean numbers) {
162         return random(count, start, end, letters, numbers, null, RANDOM);
163     }
164 
165     /**
166      * <p>Creates a random string based on a variety of options, using
167      * default source of randomness.</p>
168      *
169      * <p>This method has exactly the same semantics as
170      * {@link #random(int,int,int,boolean,boolean,char[],Random)}, but
171      * instead of using an externally supplied source of randomness, it uses
172      * the internal static {@link Random} instance.</p>
173      *
174      * @param count  the length of random string to create
175      * @param start  the position in set of chars to start at
176      * @param end  the position in set of chars to end before
177      * @param letters  only allow letters?
178      * @param numbers  only allow numbers?
179      * @param chars  the set of chars to choose randoms from.
180      *  If {@code null}, then it will use the set of all chars.
181      * @return the random string
182      * @throws ArrayIndexOutOfBoundsException if there are not
183      *  {@code (end - start) + 1} characters in the set array.
184      */
185     public static String random(final int count, final int start, final int end, final boolean letters, final boolean numbers, final char... chars) {
186         return random(count, start, end, letters, numbers, chars, RANDOM);
187     }
188 
189     /**
190      * <p>Creates a random string based on a variety of options, using
191      * supplied source of randomness.</p>
192      *
193      * <p>If start and end are both {@code 0}, start and end are set
194      * to {@code ' '} and {@code 'z'}, the ASCII printable
195      * characters, will be used, unless letters and numbers are both
196      * {@code false}, in which case, start and end are set to
197      * {@code 0} and {@code Integer.MAX_VALUE}.
198      *
199      * <p>If set is not {@code null}, characters between start and
200      * end are chosen.</p>
201      *
202      * <p>This method accepts a user-supplied {@link Random}
203      * instance to use as a source of randomness. By seeding a single 
204      * {@link Random} instance with a fixed seed and using it for each call,
205      * the same random sequence of strings can be generated repeatedly
206      * and predictably.</p>
207      *
208      * @param count  the length of random string to create
209      * @param start  the position in set of chars to start at
210      * @param end  the position in set of chars to end before
211      * @param letters  only allow letters?
212      * @param numbers  only allow numbers?
213      * @param chars  the set of chars to choose randoms from, must not be empty.
214      *  If {@code null}, then it will use the set of all chars.
215      * @param random  a source of randomness.
216      * @return the random string
217      * @throws ArrayIndexOutOfBoundsException if there are not
218      *  {@code (end - start) + 1} characters in the set array.
219      * @throws IllegalArgumentException if {@code count} &lt; 0 or the provided chars array is empty.
220      * @since 2.0
221      */
222     public static String random(int count, int start, int end, final boolean letters, final boolean numbers,
223                                 final char[] chars, final Random random) {
224         if (count == 0) {
225             return "";
226         } else if (count < 0) {
227             throw new IllegalArgumentException("Requested random string length " + count + " is less than 0.");
228         }
229         if (chars != null && chars.length == 0) {
230             throw new IllegalArgumentException("The chars array must not be empty");
231         }
232 
233         if (start == 0 && end == 0) {
234             if (chars != null) {
235                 end = chars.length;
236             } else {
237                 if (!letters && !numbers) {
238                     end = Integer.MAX_VALUE;
239                 } else {
240                     end = 'z' + 1;
241                     start = ' ';                
242                 }
243             }
244         } else {
245             if (end <= start) {
246                 throw new IllegalArgumentException("Parameter end (" + end + ") must be greater than start (" + start + ")");
247             }
248         }
249 
250         final char[] buffer = new char[count];
251         final int gap = end - start;
252 
253         while (count-- != 0) {
254             char ch;
255             if (chars == null) {
256                 ch = (char) (random.nextInt(gap) + start);
257             } else {
258                 ch = chars[random.nextInt(gap) + start];
259             }
260             if (letters && Character.isLetter(ch)
261                     || numbers && Character.isDigit(ch)
262                     || !letters && !numbers) {
263                 if(ch >= 56320 && ch <= 57343) {
264                     if(count == 0) {
265                         count++;
266                     } else {
267                         // low surrogate, insert high surrogate after putting it in
268                         buffer[count] = ch;
269                         count--;
270                         buffer[count] = (char) (55296 + random.nextInt(128));
271                     }
272                 } else if(ch >= 55296 && ch <= 56191) {
273                     if(count == 0) {
274                         count++;
275                     } else {
276                         // high surrogate, insert low surrogate before putting it in
277                         buffer[count] = (char) (56320 + random.nextInt(128));
278                         count--;
279                         buffer[count] = ch;
280                     }
281                 } else if(ch >= 56192 && ch <= 56319) {
282                     // private high surrogate, no effing clue, so skip it
283                     count++;
284                 } else {
285                     buffer[count] = ch;
286                 }
287             } else {
288                 count++;
289             }
290         }
291         return new String(buffer);
292     }
293 
294     /**
295      * <p>Creates a random string whose length is the number of characters
296      * specified.</p>
297      *
298      * <p>Characters will be chosen from the set of characters
299      * specified by the string, must not be empty. 
300      * If null, the set of all characters is used.</p>
301      *
302      * @param count  the length of random string to create
303      * @param chars  the String containing the set of characters to use,
304      *  may be null, but must not be empty
305      * @return the random string
306      * @throws IllegalArgumentException if {@code count} &lt; 0 or the string is empty.
307      */
308     public static String random(final int count, final String chars) {
309         if (chars == null) {
310             return random(count, 0, 0, false, false, null, RANDOM);
311         }
312         return random(count, chars.toCharArray());
313     }
314 
315     /**
316      * <p>Creates a random string whose length is the number of characters
317      * specified.</p>
318      *
319      * <p>Characters will be chosen from the set of characters specified.</p>
320      *
321      * @param count  the length of random string to create
322      * @param chars  the character array containing the set of characters to use,
323      *  may be null
324      * @return the random string
325      * @throws IllegalArgumentException if {@code count} &lt; 0.
326      */
327     public static String random(final int count, final char... chars) {
328         if (chars == null) {
329             return random(count, 0, 0, false, false, null, RANDOM);
330         }
331         return random(count, 0, chars.length, false, false, chars, RANDOM);
332     }
333     
334 }