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
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}