View Javadoc
1   /*
2    * Copyright (c) 2002-2025 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.util;
16  
17  import java.util.Random;
18  
19  /**
20   * Unit tests helper.
21   *
22   * @author René Schwietzke
23   */
24  public final class RandomUtils {
25      private static final String LOWERCHARS = "abcdefghijklmnopqrstuvwxyz";
26      private static final String UPPERCHARS = LOWERCHARS.toUpperCase();
27      private static final String CHARS = LOWERCHARS + UPPERCHARS;
28  
29      /**
30       * Private ctor to keep Checkstyle happy
31       */
32      private RandomUtils() {
33      }
34  
35      /**
36       * Fixed length random string of lower case and uppercase chars.
37       *
38       * @param random the random number generator
39       * @param length the length of the resulting string
40       * @return a random string of the desired length
41       */
42      public static String randomString(final Random random, final int length) {
43          return randomString(random, length, length);
44      }
45  
46      /**
47       * Variable length random string of lower case and upper case chars.
48       *
49       * @param random the random generator
50       * @param from min length
51       * @param to max length (inclusive)
52       * @return a random string
53       */
54      public static String randomString(final Random random, final int from, final int to) {
55          final int length = random.nextInt(to - from + 1) + from;
56  
57          final StringBuilder sb = new StringBuilder(to);
58  
59          for (int i = 0; i < length; i++) {
60              final int pos = random.nextInt(CHARS.length());
61              sb.append(CHARS.charAt(pos));
62          }
63  
64          return sb.toString();
65      }
66  }