001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 * 
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 * 
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.lang3;
018
019import java.util.Random;
020
021/**
022 * <p>Operations for random {@code String}s.</p>
023 * <p>Currently <em>private high surrogate</em> characters are ignored. 
024 * These are Unicode characters that fall between the values 56192 (db80)
025 * and 56319 (dbff) as we don't know how to handle them. 
026 * High and low surrogates are correctly dealt with - that is if a 
027 * high surrogate is randomly chosen, 55296 (d800) to 56191 (db7f) 
028 * then it is followed by a low surrogate. If a low surrogate is chosen, 
029 * 56320 (dc00) to 57343 (dfff) then it is placed after a randomly 
030 * chosen high surrogate. </p>
031 *
032 * <p>#ThreadSafe#</p>
033 * @since 1.0
034 */
035public class RandomStringUtils {
036
037    /**
038     * <p>Random object used by random method. This has to be not local
039     * to the random method so as to not return the same value in the 
040     * same millisecond.</p>
041     */
042    private static final Random RANDOM = new Random();
043
044    /**
045     * <p>{@code RandomStringUtils} instances should NOT be constructed in
046     * standard programming. Instead, the class should be used as
047     * {@code RandomStringUtils.random(5);}.</p>
048     *
049     * <p>This constructor is public to permit tools that require a JavaBean instance
050     * to operate.</p>
051     */
052    public RandomStringUtils() {
053      super();
054    }
055
056    // Random
057    //-----------------------------------------------------------------------
058    /**
059     * <p>Creates a random string whose length is the number of characters
060     * specified.</p>
061     *
062     * <p>Characters will be chosen from the set of all characters.</p>
063     *
064     * @param count  the length of random string to create
065     * @return the random string
066     */
067    public static String random(final int count) {
068        return random(count, false, false);
069    }
070
071    /**
072     * <p>Creates a random string whose length is the number of characters
073     * specified.</p>
074     *
075     * <p>Characters will be chosen from the set of characters whose
076     * ASCII value is between {@code 32} and {@code 126} (inclusive).</p>
077     *
078     * @param count  the length of random string to create
079     * @return the random string
080     */
081    public static String randomAscii(final int count) {
082        return random(count, 32, 127, false, false);
083    }
084    
085    /**
086     * <p>Creates a random string whose length is the number of characters
087     * specified.</p>
088     *
089     * <p>Characters will be chosen from the set of alphabetic
090     * characters.</p>
091     *
092     * @param count  the length of random string to create
093     * @return the random string
094     */
095    public static String randomAlphabetic(final int count) {
096        return random(count, true, false);
097    }
098    
099    /**
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}