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 specified.</p>
115      *
116      * <p>Characters will be chosen from the set of characters which match the POSIX [:graph:]
117      * regular expression character class. This class contains all visible ASCII characters 
118      * (i.e. anything except spaces and control characters).</p>
119      *
120      * @param count  the length of random string to create
121      * @return the random string
122      * @since 3.5
123      */
124     public static String randomGraph(final int count) {
125         return random(count, 33, 126, false, false);
126     }
127     
128     /**
129      * <p>Creates a random string whose length is the number of characters
130      * specified.</p>
131      *
132      * <p>Characters will be chosen from the set of numeric
133      * characters.</p>
134      *
135      * @param count  the length of random string to create
136      * @return the random string
137      */
138     public static String randomNumeric(final int count) {
139         return random(count, false, true);
140     }
141 
142     /**
143      * <p>Creates a random string whose length is the number of characters specified.</p>
144      *
145      * <p>Characters will be chosen from the set of characters which match the POSIX [:print:]
146      * regular expression character class. This class includes all visible ASCII characters and spaces
147      * (i.e. anything except control characters).</p>
148      *
149      * @param count  the length of random string to create
150      * @return the random string
151      * @since 3.5
152      */
153     public static String randomPrint(final int count) {
154         return random(count, 32, 126, false, false);
155     }
156 
157     /**
158      * <p>Creates a random string whose length is the number of characters
159      * specified.</p>
160      *
161      * <p>Characters will be chosen from the set of alpha-numeric
162      * characters as indicated by the arguments.</p>
163      *
164      * @param count  the length of random string to create
165      * @param letters  if {@code true}, generated string may include
166      *  alphabetic characters
167      * @param numbers  if {@code true}, generated string may include
168      *  numeric characters
169      * @return the random string
170      */
171     public static String random(final int count, final boolean letters, final boolean numbers) {
172         return random(count, 0, 0, letters, numbers);
173     }
174     
175     /**
176      * <p>Creates a random string whose length is the number of characters
177      * specified.</p>
178      *
179      * <p>Characters will be chosen from the set of alpha-numeric
180      * characters as indicated by the arguments.</p>
181      *
182      * @param count  the length of random string to create
183      * @param start  the position in set of chars to start at
184      * @param end  the position in set of chars to end before
185      * @param letters  if {@code true}, generated string may include
186      *  alphabetic characters
187      * @param numbers  if {@code true}, generated string may include
188      *  numeric characters
189      * @return the random string
190      */
191     public static String random(final int count, final int start, final int end, final boolean letters, final boolean numbers) {
192         return random(count, start, end, letters, numbers, null, RANDOM);
193     }
194 
195     /**
196      * <p>Creates a random string based on a variety of options, using
197      * default source of randomness.</p>
198      *
199      * <p>This method has exactly the same semantics as
200      * {@link #random(int,int,int,boolean,boolean,char[],Random)}, but
201      * instead of using an externally supplied source of randomness, it uses
202      * the internal static {@link Random} instance.</p>
203      *
204      * @param count  the length of random string to create
205      * @param start  the position in set of chars to start at
206      * @param end  the position in set of chars to end before
207      * @param letters  only allow letters?
208      * @param numbers  only allow numbers?
209      * @param chars  the set of chars to choose randoms from.
210      *  If {@code null}, then it will use the set of all chars.
211      * @return the random string
212      * @throws ArrayIndexOutOfBoundsException if there are not
213      *  {@code (end - start) + 1} characters in the set array.
214      */
215     public static String random(final int count, final int start, final int end, final boolean letters, final boolean numbers, final char... chars) {
216         return random(count, start, end, letters, numbers, chars, RANDOM);
217     }
218 
219     /**
220      * <p>Creates a random string based on a variety of options, using
221      * supplied source of randomness.</p>
222      *
223      * <p>If start and end are both {@code 0}, start and end are set
224      * to {@code ' '} and {@code 'z'}, the ASCII printable
225      * characters, will be used, unless letters and numbers are both
226      * {@code false}, in which case, start and end are set to
227      * {@code 0} and {@code Integer.MAX_VALUE}.
228      *
229      * <p>If set is not {@code null}, characters between start and
230      * end are chosen.</p>
231      *
232      * <p>This method accepts a user-supplied {@link Random}
233      * instance to use as a source of randomness. By seeding a single 
234      * {@link Random} instance with a fixed seed and using it for each call,
235      * the same random sequence of strings can be generated repeatedly
236      * and predictably.</p>
237      *
238      * @param count  the length of random string to create
239      * @param start  the position in set of chars to start at
240      * @param end  the position in set of chars to end before
241      * @param letters  only allow letters?
242      * @param numbers  only allow numbers?
243      * @param chars  the set of chars to choose randoms from, must not be empty.
244      *  If {@code null}, then it will use the set of all chars.
245      * @param random  a source of randomness.
246      * @return the random string
247      * @throws ArrayIndexOutOfBoundsException if there are not
248      *  {@code (end - start) + 1} characters in the set array.
249      * @throws IllegalArgumentException if {@code count} &lt; 0 or the provided chars array is empty.
250      * @since 2.0
251      */
252     public static String random(int count, int start, int end, final boolean letters, final boolean numbers,
253                                 final char[] chars, final Random random) {
254         if (count == 0) {
255             return StringUtils.EMPTY;
256         } else if (count < 0) {
257             throw new IllegalArgumentException("Requested random string length " + count + " is less than 0.");
258         }
259         if (chars != null && chars.length == 0) {
260             throw new IllegalArgumentException("The chars array must not be empty");
261         }
262 
263         if (start == 0 && end == 0) {
264             if (chars != null) {
265                 end = chars.length;
266             } else {
267                 if (!letters && !numbers) {
268                     end = Integer.MAX_VALUE;
269                 } else {
270                     end = 'z' + 1;
271                     start = ' ';                
272                 }
273             }
274         } else {
275             if (end <= start) {
276                 throw new IllegalArgumentException("Parameter end (" + end + ") must be greater than start (" + start + ")");
277             }
278         }
279 
280         final char[] buffer = new char[count];
281         final int gap = end - start;
282 
283         while (count-- != 0) {
284             char ch;
285             if (chars == null) {
286                 ch = (char) (random.nextInt(gap) + start);
287             } else {
288                 ch = chars[random.nextInt(gap) + start];
289             }
290             if (letters && Character.isLetter(ch)
291                     || numbers && Character.isDigit(ch)
292                     || !letters && !numbers) {
293                 if(ch >= 56320 && ch <= 57343) {
294                     if(count == 0) {
295                         count++;
296                     } else {
297                         // low surrogate, insert high surrogate after putting it in
298                         buffer[count] = ch;
299                         count--;
300                         buffer[count] = (char) (55296 + random.nextInt(128));
301                     }
302                 } else if(ch >= 55296 && ch <= 56191) {
303                     if(count == 0) {
304                         count++;
305                     } else {
306                         // high surrogate, insert low surrogate before putting it in
307                         buffer[count] = (char) (56320 + random.nextInt(128));
308                         count--;
309                         buffer[count] = ch;
310                     }
311                 } else if(ch >= 56192 && ch <= 56319) {
312                     // private high surrogate, no effing clue, so skip it
313                     count++;
314                 } else {
315                     buffer[count] = ch;
316                 }
317             } else {
318                 count++;
319             }
320         }
321         return new String(buffer);
322     }
323 
324     /**
325      * <p>Creates a random string whose length is the number of characters
326      * specified.</p>
327      *
328      * <p>Characters will be chosen from the set of characters
329      * specified by the string, must not be empty. 
330      * If null, the set of all characters is used.</p>
331      *
332      * @param count  the length of random string to create
333      * @param chars  the String containing the set of characters to use,
334      *  may be null, but must not be empty
335      * @return the random string
336      * @throws IllegalArgumentException if {@code count} &lt; 0 or the string is empty.
337      */
338     public static String random(final int count, final String chars) {
339         if (chars == null) {
340             return random(count, 0, 0, false, false, null, RANDOM);
341         }
342         return random(count, chars.toCharArray());
343     }
344 
345     /**
346      * <p>Creates a random string whose length is the number of characters
347      * specified.</p>
348      *
349      * <p>Characters will be chosen from the set of characters specified.</p>
350      *
351      * @param count  the length of random string to create
352      * @param chars  the character array containing the set of characters to use,
353      *  may be null
354      * @return the random string
355      * @throws IllegalArgumentException if {@code count} &lt; 0.
356      */
357     public static String random(final int count, final char... chars) {
358         if (chars == null) {
359             return random(count, 0, 0, false, false, null, RANDOM);
360         }
361         return random(count, 0, chars.length, false, false, chars, RANDOM);
362     }
363     
364 }