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.text;
018
019import java.util.ArrayList;
020import java.util.Collections;
021import java.util.HashSet;
022import java.util.List;
023import java.util.Set;
024import java.util.concurrent.ThreadLocalRandom;
025
026import org.apache.commons.lang3.ArrayUtils;
027import org.apache.commons.lang3.StringUtils;
028import org.apache.commons.lang3.Validate;
029
030/**
031 * Generates random Unicode strings containing the specified number of code points.
032 * Instances are created using a builder class, which allows the
033 * callers to define the properties of the generator. See the documentation for the
034 * {@link Builder} class to see available properties.
035 *
036 * <pre>
037 * // Generates a 20 code point string, using only the letters a-z
038 * RandomStringGenerator generator = new RandomStringGenerator.Builder()
039 *     .withinRange('a', 'z').build();
040 * String randomLetters = generator.generate(20);
041 * </pre>
042 * <pre>
043 * // Using Apache Commons RNG for randomness
044 * UniformRandomProvider rng = RandomSource.create(...);
045 * // Generates a 20 code point string, using only the letters a-z
046 * RandomStringGenerator generator = new RandomStringGenerator.Builder()
047 *     .withinRange('a', 'z')
048 *     .usingRandom(rng::nextInt) // uses Java 8 syntax
049 *     .build();
050 * String randomLetters = generator.generate(20);
051 * </pre>
052 * <p>
053 * {@code RandomStringGenerator} instances are thread-safe when using the
054 * default random number generator (RNG). If a custom RNG is set by calling the method
055 * {@link Builder#usingRandom(TextRandomProvider) Builder.usingRandom(TextRandomProvider)}, thread-safety
056 * must be ensured externally.
057 * </p>
058 * @since 1.1
059 */
060public final class RandomStringGenerator {
061
062    /**
063     * A builder for generating {@code RandomStringGenerator} instances.
064     *
065     * <p>The behavior of a generator is controlled by properties set by this
066     * builder. Each property has a default value, which can be overridden by
067     * calling the methods defined in this class, prior to calling {@link #build()}.</p>
068     *
069     * <p>All the property setting methods return the {@code Builder} instance to allow for method chaining.</p>
070     *
071     * <p>The minimum and maximum code point values are defined using {@link #withinRange(int, int)}. The
072     * default values are {@code 0} and {@link Character#MAX_CODE_POINT} respectively.</p>
073     *
074     * <p>The source of randomness can be set using {@link #usingRandom(TextRandomProvider)},
075     * otherwise {@link ThreadLocalRandom} is used.</p>
076     *
077     * <p>The type of code points returned can be filtered using {@link #filteredBy(CharacterPredicate...)},
078     * which defines a collection of tests that are applied to the randomly generated code points.
079     * The code points will only be included in the result if they pass at least one of the tests.
080     * Some commonly used predicates are provided by the {@link CharacterPredicates} enum.</p>
081     *
082     * <p>This class is not thread safe.</p>
083     * @since 1.1
084     */
085    public static class Builder implements org.apache.commons.text.Builder<RandomStringGenerator> {
086
087        /**
088         * The default maximum code point allowed: {@link Character#MAX_CODE_POINT}
089         * ({@value}).
090         */
091        public static final int DEFAULT_MAXIMUM_CODE_POINT = Character.MAX_CODE_POINT;
092
093        /**
094         * The default string length produced by this builder: {@value}.
095         */
096        public static final int DEFAULT_LENGTH = 0;
097
098        /**
099         * The default minimum code point allowed: {@value}.
100         */
101        public static final int DEFAULT_MINIMUM_CODE_POINT = 0;
102
103        /**
104         * The minimum code point allowed.
105         */
106        private int minimumCodePoint = DEFAULT_MINIMUM_CODE_POINT;
107
108        /**
109         * The maximum code point allowed.
110         */
111        private int maximumCodePoint = DEFAULT_MAXIMUM_CODE_POINT;
112
113        /**
114         * Filters for code points.
115         */
116        private Set<CharacterPredicate> inclusivePredicates;
117
118        /**
119         * The source of randomness.
120         */
121        private TextRandomProvider random;
122
123        /**
124         * The source of provided characters.
125         */
126        private List<Character> characterList;
127
128        /**
129         * Builds the {@code RandomStringGenerator} using the properties specified.
130         *
131         * @return The configured {@code RandomStringGenerator}
132         */
133        @Override
134        public RandomStringGenerator build() {
135            return new RandomStringGenerator(minimumCodePoint, maximumCodePoint, inclusivePredicates,
136                    random, characterList);
137        }
138
139        /**
140         * Limits the characters in the generated string to those that match at
141         * least one of the predicates supplied.
142         *
143         * <p>
144         * Passing {@code null} or an empty array to this method will revert to the
145         * default behavior of allowing any character. Multiple calls to this
146         * method will replace the previously stored predicates.
147         * </p>
148         *
149         * @param predicates
150         *            the predicates, may be {@code null} or empty
151         * @return {@code this}, to allow method chaining
152         */
153        public Builder filteredBy(final CharacterPredicate... predicates) {
154            if (ArrayUtils.isEmpty(predicates)) {
155                inclusivePredicates = null;
156                return this;
157            }
158
159            if (inclusivePredicates == null) {
160                inclusivePredicates = new HashSet<>();
161            } else {
162                inclusivePredicates.clear();
163            }
164
165            Collections.addAll(inclusivePredicates, predicates);
166
167            return this;
168        }
169
170        /**
171         * Limits the characters in the generated string to those who match at
172         * supplied list of Character.
173         *
174         * <p>
175         * Passing {@code null} or an empty array to this method will revert to the
176         * default behavior of allowing any character. Multiple calls to this
177         * method will replace the previously stored Character.
178         * </p>
179         *
180         * @param chars set of predefined Characters for random string generation
181         *            the Character can be, may be {@code null} or empty
182         * @return {@code this}, to allow method chaining
183         * @since 1.2
184         */
185        public Builder selectFrom(final char... chars) {
186            characterList = new ArrayList<>();
187            for (final char c : chars) {
188                characterList.add(c);
189            }
190            return this;
191        }
192
193        /**
194         * Overrides the default source of randomness.  It is highly
195         * recommended that a random number generator library like
196         * <a href="https://commons.apache.org/proper/commons-rng/">Apache Commons RNG</a>
197         * be used to provide the random number generation.
198         *
199         * <p>
200         * When using Java 8 or later, {@link TextRandomProvider} is a
201         * functional interface and need not be explicitly implemented:
202         * </p>
203         * <pre>
204         * {@code
205         *     UniformRandomProvider rng = RandomSource.create(...);
206         *     RandomStringGenerator gen = new RandomStringGenerator.Builder()
207         *         .usingRandom(rng::nextInt)
208         *         // additional builder calls as needed
209         *         .build();
210         * }
211         * </pre>
212         *
213         * <p>
214         * Passing {@code null} to this method will revert to the default source of
215         * randomness.
216         * </p>
217         *
218         * @param random
219         *            the source of randomness, may be {@code null}
220         * @return {@code this}, to allow method chaining
221         */
222        public Builder usingRandom(final TextRandomProvider random) {
223            this.random = random;
224            return this;
225        }
226
227        /**
228         * Sets the array of minimum and maximum char allowed in the
229         * generated string.
230         *
231         * For example:
232         * <pre>
233         * {@code
234         *     char [][] pairs = {{'0','9'}};
235         *     char [][] pairs = {{'a','z'}};
236         *     char [][] pairs = {{'a','z'},{'0','9'}};
237         * }
238         * </pre>
239         *
240         * @param pairs array of characters array, expected is to pass min, max pairs through this arg.
241         * @return {@code this}, to allow method chaining.
242         */
243        public Builder withinRange(final char[]... pairs) {
244            characterList = new ArrayList<>();
245            for (final char[] pair :  pairs) {
246                Validate.isTrue(pair.length == 2,
247                      "Each pair must contain minimum and maximum code point");
248                final int minimumCodePoint = pair[0];
249                final int maximumCodePoint = pair[1];
250                Validate.isTrue(minimumCodePoint <= maximumCodePoint,
251                    "Minimum code point %d is larger than maximum code point %d", minimumCodePoint, maximumCodePoint);
252
253                for (int index = minimumCodePoint; index <= maximumCodePoint; index++) {
254                    characterList.add((char) index);
255                }
256            }
257            return this;
258
259        }
260
261        /**
262         * Sets the minimum and maximum code points allowed in the
263         * generated string.
264         *
265         * @param minimumCodePoint
266         *            the smallest code point allowed (inclusive)
267         * @param maximumCodePoint
268         *            the largest code point allowed (inclusive)
269         * @return {@code this}, to allow method chaining
270         * @throws IllegalArgumentException
271         *             if {@code maximumCodePoint >}
272         *             {@link Character#MAX_CODE_POINT}
273         * @throws IllegalArgumentException
274         *             if {@code minimumCodePoint < 0}
275         * @throws IllegalArgumentException
276         *             if {@code minimumCodePoint > maximumCodePoint}
277         */
278        public Builder withinRange(final int minimumCodePoint, final int maximumCodePoint) {
279            Validate.isTrue(minimumCodePoint <= maximumCodePoint,
280                    "Minimum code point %d is larger than maximum code point %d", minimumCodePoint, maximumCodePoint);
281            Validate.isTrue(minimumCodePoint >= 0, "Minimum code point %d is negative", minimumCodePoint);
282            Validate.isTrue(maximumCodePoint <= Character.MAX_CODE_POINT,
283                    "Value %d is larger than Character.MAX_CODE_POINT.", maximumCodePoint);
284
285            this.minimumCodePoint = minimumCodePoint;
286            this.maximumCodePoint = maximumCodePoint;
287            return this;
288        }
289    }
290
291    /**
292     * The smallest allowed code point (inclusive).
293     */
294    private final int minimumCodePoint;
295
296    /**
297     * The largest allowed code point (inclusive).
298     */
299    private final int maximumCodePoint;
300
301    /**
302     * Filters for code points.
303     */
304    private final Set<CharacterPredicate> inclusivePredicates;
305
306    /**
307     * The source of randomness for this generator.
308     */
309    private final TextRandomProvider random;
310
311    /**
312     * The source of provided characters.
313     */
314    private final List<Character> characterList;
315
316    /**
317     * Constructs the generator.
318     *
319     * @param minimumCodePoint
320     *            smallest allowed code point (inclusive)
321     * @param maximumCodePoint
322     *            largest allowed code point (inclusive)
323     * @param inclusivePredicates
324     *            filters for code points
325     * @param random
326     *            source of randomness
327     * @param characterList list of predefined set of characters.
328     */
329    private RandomStringGenerator(final int minimumCodePoint, final int maximumCodePoint,
330                                  final Set<CharacterPredicate> inclusivePredicates, final TextRandomProvider random,
331                                  final List<Character> characterList) {
332        this.minimumCodePoint = minimumCodePoint;
333        this.maximumCodePoint = maximumCodePoint;
334        this.inclusivePredicates = inclusivePredicates;
335        this.random = random;
336        this.characterList = characterList;
337    }
338
339    /**
340     * Generates a random string, containing the specified number of code points.
341     *
342     * <p>
343     * Code points are randomly selected between the minimum and maximum values defined
344     * in the generator.
345     * Surrogate and private use characters are not returned, although the
346     * resulting string may contain pairs of surrogates that together encode a
347     * supplementary character.
348     * </p>
349     * <p>
350     * Note: the number of {@code char} code units generated will exceed
351     * {@code length} if the string contains supplementary characters. See the
352     * {@link Character} documentation to understand how Java stores Unicode
353     * values.
354     * </p>
355     *
356     * @param length
357     *            the number of code points to generate
358     * @return The generated string
359     * @throws IllegalArgumentException
360     *             if {@code length < 0}
361     */
362    public String generate(final int length) {
363        if (length == 0) {
364            return StringUtils.EMPTY;
365        }
366        Validate.isTrue(length > 0, "Length %d is smaller than zero.", length);
367
368        final StringBuilder builder = new StringBuilder(length);
369        long remaining = length;
370
371        do {
372            final int codePoint;
373            if (characterList != null && !characterList.isEmpty()) {
374                codePoint = generateRandomNumber(characterList);
375            } else {
376                codePoint = generateRandomNumber(minimumCodePoint, maximumCodePoint);
377            }
378            switch (Character.getType(codePoint)) {
379            case Character.UNASSIGNED:
380            case Character.PRIVATE_USE:
381            case Character.SURROGATE:
382                continue;
383            default:
384            }
385
386            if (inclusivePredicates != null) {
387                boolean matchedFilter = false;
388                for (final CharacterPredicate predicate : inclusivePredicates) {
389                    if (predicate.test(codePoint)) {
390                        matchedFilter = true;
391                        break;
392                    }
393                }
394                if (!matchedFilter) {
395                    continue;
396                }
397            }
398
399            builder.appendCodePoint(codePoint);
400            remaining--;
401
402        } while (remaining != 0);
403
404        return builder.toString();
405    }
406
407    /**
408     * Generates a random string, containing between the minimum (inclusive) and the maximum (inclusive)
409     * number of code points.
410     *
411     * @param minLengthInclusive
412     *            the minimum (inclusive) number of code points to generate
413     * @param maxLengthInclusive
414     *            the maximum (inclusive) number of code points to generate
415     * @return The generated string
416     * @throws IllegalArgumentException
417     *             if {@code minLengthInclusive < 0}, or {@code maxLengthInclusive < minLengthInclusive}
418     * @see RandomStringGenerator#generate(int)
419     * @since 1.2
420     */
421    public String generate(final int minLengthInclusive, final int maxLengthInclusive) {
422        Validate.isTrue(minLengthInclusive >= 0, "Minimum length %d is smaller than zero.", minLengthInclusive);
423        Validate.isTrue(minLengthInclusive <= maxLengthInclusive,
424                "Maximum length %d is smaller than minimum length %d.", maxLengthInclusive, minLengthInclusive);
425        return generate(generateRandomNumber(minLengthInclusive, maxLengthInclusive));
426    }
427
428    /**
429     * Generates a random number within a range, using a {@link ThreadLocalRandom} instance
430     * or the user-supplied source of randomness.
431     *
432     * @param minInclusive
433     *            the minimum value allowed
434     * @param maxInclusive
435     *            the maximum value allowed
436     * @return The random number.
437     */
438    private int generateRandomNumber(final int minInclusive, final int maxInclusive) {
439        if (random != null) {
440            return random.nextInt(maxInclusive - minInclusive + 1) + minInclusive;
441        }
442        return ThreadLocalRandom.current().nextInt(minInclusive, maxInclusive + 1);
443    }
444
445    /**
446     * Generates a random number within a range, using a {@link ThreadLocalRandom} instance
447     * or the user-supplied source of randomness.
448     *
449     * @param characterList predefined char list.
450     * @return The random number.
451     */
452    private int generateRandomNumber(final List<Character> characterList) {
453        final int listSize = characterList.size();
454        if (random != null) {
455            return String.valueOf(characterList.get(random.nextInt(listSize))).codePointAt(0);
456        }
457        return String.valueOf(characterList.get(ThreadLocalRandom.current().nextInt(0, listSize))).codePointAt(0);
458    }
459}