Source code
Description: source: package: org.apache.commons.text, class: RandomStringGenerator, class: Builder

    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 = 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 = 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            if (chars != null) {
    188                for (final char c : chars) {
    189                    characterList.add(c);
    190                }
    191            }
    192            return this;
    193        }
    194
    195        /**
    196         * Overrides the default source of randomness.  It is highly
    197         * recommended that a random number generator library like
    198         * <a href="https://commons.apache.org/proper/commons-rng/">Apache Commons RNG</a>
    199         * be used to provide the random number generation.
    200         *
    201         * <p>
    202         * When using Java 8 or later, {@link TextRandomProvider} is a
    203         * functional interface and need not be explicitly implemented:
    204         * </p>
    205         * <pre>
    206         * {@code
    207         *     UniformRandomProvider rng = RandomSource.create(...);
    208         *     RandomStringGenerator gen = RandomStringGenerator.builder()
    209         *         .usingRandom(rng::nextInt)
    210         *         // additional builder calls as needed
    211         *         .build();
    212         * }
    213         * </pre>
    214         *
    215         * <p>
    216         * Passing {@code null} to this method will revert to the default source of
    217         * randomness.
    218         * </p>
    219         *
    220         * @param random
    221         *            the source of randomness, may be {@code null}
    222         * @return {@code this}, to allow method chaining
    223         */
    224        public Builder usingRandom(final TextRandomProvider random) {
    225            this.random = random;
    226            return this;
    227        }
    228
    229        /**
    230         * Sets the array of minimum and maximum char allowed in the
    231         * generated string.
    232         *
    233         * For example:
    234         * <pre>
    235         * {@code
    236         *     char [][] pairs = {{'0','9'}};
    237         *     char [][] pairs = {{'a','z'}};
    238         *     char [][] pairs = {{'a','z'},{'0','9'}};
    239         * }
    240         * </pre>
    241         *
    242         * @param pairs array of characters array, expected is to pass min, max pairs through this arg.
    243         * @return {@code this}, to allow method chaining.
    244         */
    245        public Builder withinRange(final char[]... pairs) {
    246            characterList = new ArrayList<>();
    247            if (pairs != null) {
    248                for (final char[] pair : pairs) {
    249                    Validate.isTrue(pair.length == 2, "Each pair must contain minimum and maximum code point");
    250                    final int minimumCodePoint = pair[0];
    251                    final int maximumCodePoint = pair[1];
    252                    Validate.isTrue(minimumCodePoint <= maximumCodePoint, "Minimum code point %d is larger than maximum code point %d", minimumCodePoint,
    253                            maximumCodePoint);
    254
    255                    for (int index = minimumCodePoint; index <= maximumCodePoint; index++) {
    256                        characterList.add((char) index);
    257                    }
    258                }
    259            }
    260            return this;
    261
    262        }
    263
    264        /**
    265         * Sets the minimum and maximum code points allowed in the
    266         * generated string.
    267         *
    268         * @param minimumCodePoint
    269         *            the smallest code point allowed (inclusive)
    270         * @param maximumCodePoint
    271         *            the largest code point allowed (inclusive)
    272         * @return {@code this}, to allow method chaining
    273         * @throws IllegalArgumentException
    274         *             if {@code maximumCodePoint >}
    275         *             {@link Character#MAX_CODE_POINT}
    276         * @throws IllegalArgumentException
    277         *             if {@code minimumCodePoint < 0}
    278         * @throws IllegalArgumentException
    279         *             if {@code minimumCodePoint > maximumCodePoint}
    280         */
    281        public Builder withinRange(final int minimumCodePoint, final int maximumCodePoint) {
    282            Validate.isTrue(minimumCodePoint <= maximumCodePoint,
    283                    "Minimum code point %d is larger than maximum code point %d", minimumCodePoint, maximumCodePoint);
    284            Validate.isTrue(minimumCodePoint >= 0, "Minimum code point %d is negative", minimumCodePoint);
    285            Validate.isTrue(maximumCodePoint <= Character.MAX_CODE_POINT,
    286                    "Value %d is larger than Character.MAX_CODE_POINT.", maximumCodePoint);
    287
    288            this.minimumCodePoint = minimumCodePoint;
    289            this.maximumCodePoint = maximumCodePoint;
    290            return this;
    291        }
    292    }
    293
    294    /**
    295     * Constructs a new builder.
    296     * @return a new builder.
    297     *
    298     * @since 1.11.0
    299     */
    300    public static Builder builder() {
    301        return new Builder();
    302    }
    303
    304    /**
    305     * The smallest allowed code point (inclusive).
    306     */
    307    private final int minimumCodePoint;
    308
    309    /**
    310     * The largest allowed code point (inclusive).
    311     */
    312    private final int maximumCodePoint;
    313
    314    /**
    315     * Filters for code points.
    316     */
    317    private final Set<CharacterPredicate> inclusivePredicates;
    318
    319    /**
    320     * The source of randomness for this generator.
    321     */
    322    private final TextRandomProvider random;
    323
    324    /**
    325     * The source of provided characters.
    326     */
    327    private final List<Character> characterList;
    328
    329    /**
    330     * Constructs the generator.
    331     *
    332     * @param minimumCodePoint
    333     *            smallest allowed code point (inclusive)
    334     * @param maximumCodePoint
    335     *            largest allowed code point (inclusive)
    336     * @param inclusivePredicates
    337     *            filters for code points
    338     * @param random
    339     *            source of randomness
    340     * @param characterList list of predefined set of characters.
    341     */
    342    private RandomStringGenerator(final int minimumCodePoint, final int maximumCodePoint,
    343                                  final Set<CharacterPredicate> inclusivePredicates, final TextRandomProvider random,
    344                                  final List<Character> characterList) {
    345        this.minimumCodePoint = minimumCodePoint;
    346        this.maximumCodePoint = maximumCodePoint;
    347        this.inclusivePredicates = inclusivePredicates;
    348        this.random = random;
    349        this.characterList = characterList;
    350    }
    351
    352    /**
    353     * Generates a random string, containing the specified number of code points.
    354     *
    355     * <p>
    356     * Code points are randomly selected between the minimum and maximum values defined
    357     * in the generator.
    358     * Surrogate and private use characters are not returned, although the
    359     * resulting string may contain pairs of surrogates that together encode a
    360     * supplementary character.
    361     * </p>
    362     * <p>
    363     * Note: the number of {@code char} code units generated will exceed
    364     * {@code length} if the string contains supplementary characters. See the
    365     * {@link Character} documentation to understand how Java stores Unicode
    366     * values.
    367     * </p>
    368     *
    369     * @param length
    370     *            the number of code points to generate
    371     * @return The generated string
    372     * @throws IllegalArgumentException
    373     *             if {@code length < 0}
    374     */
    375    public String generate(final int length) {
    376        if (length == 0) {
    377            return StringUtils.EMPTY;
    378        }
    379        Validate.isTrue(length > 0, "Length %d is smaller than zero.", length);
    380
    381        final StringBuilder builder = new StringBuilder(length);
    382        long remaining = length;
    383
    384        do {
    385            final int codePoint;
    386            if (characterList != null && !characterList.isEmpty()) {
    387                codePoint = generateRandomNumber(characterList);
    388            } else {
    389                codePoint = generateRandomNumber(minimumCodePoint, maximumCodePoint);
    390            }
    391            switch (Character.getType(codePoint)) {
    392            case Character.UNASSIGNED:
    393            case Character.PRIVATE_USE:
    394            case Character.SURROGATE:
    395                continue;
    396            default:
    397            }
    398
    399            if (inclusivePredicates != null) {
    400                boolean matchedFilter = false;
    401                for (final CharacterPredicate predicate : inclusivePredicates) {
    402                    if (predicate.test(codePoint)) {
    403                        matchedFilter = true;
    404                        break;
    405                    }
    406                }
    407                if (!matchedFilter) {
    408                    continue;
    409                }
    410            }
    411
    412            builder.appendCodePoint(codePoint);
    413            remaining--;
    414
    415        } while (remaining != 0);
    416
    417        return builder.toString();
    418    }
    419
    420    /**
    421     * Generates a random string, containing between the minimum (inclusive) and the maximum (inclusive)
    422     * number of code points.
    423     *
    424     * @param minLengthInclusive
    425     *            the minimum (inclusive) number of code points to generate
    426     * @param maxLengthInclusive
    427     *            the maximum (inclusive) number of code points to generate
    428     * @return The generated string
    429     * @throws IllegalArgumentException
    430     *             if {@code minLengthInclusive < 0}, or {@code maxLengthInclusive < minLengthInclusive}
    431     * @see RandomStringGenerator#generate(int)
    432     * @since 1.2
    433     */
    434    public String generate(final int minLengthInclusive, final int maxLengthInclusive) {
    435        Validate.isTrue(minLengthInclusive >= 0, "Minimum length %d is smaller than zero.", minLengthInclusive);
    436        Validate.isTrue(minLengthInclusive <= maxLengthInclusive,
    437                "Maximum length %d is smaller than minimum length %d.", maxLengthInclusive, minLengthInclusive);
    438        return generate(generateRandomNumber(minLengthInclusive, maxLengthInclusive));
    439    }
    440
    441    /**
    442     * Generates a random number within a range, using a {@link ThreadLocalRandom} instance
    443     * or the user-supplied source of randomness.
    444     *
    445     * @param minInclusive
    446     *            the minimum value allowed
    447     * @param maxInclusive
    448     *            the maximum value allowed
    449     * @return The random number.
    450     */
    451    private int generateRandomNumber(final int minInclusive, final int maxInclusive) {
    452        if (random != null) {
    453            return random.nextInt(maxInclusive - minInclusive + 1) + minInclusive;
    454        }
    455        return ThreadLocalRandom.current().nextInt(minInclusive, maxInclusive + 1);
    456    }
    457
    458    /**
    459     * Generates a random number within a range, using a {@link ThreadLocalRandom} instance
    460     * or the user-supplied source of randomness.
    461     *
    462     * @param characterList predefined char list.
    463     * @return The random number.
    464     */
    465    private int generateRandomNumber(final List<Character> characterList) {
    466        final int listSize = characterList.size();
    467        if (random != null) {
    468            return String.valueOf(characterList.get(random.nextInt(listSize))).codePointAt(0);
    469        }
    470        return String.valueOf(characterList.get(ThreadLocalRandom.current().nextInt(0, listSize))).codePointAt(0);
    471    }
    472}