Java Code Examples for org.apache.commons.text.RandomStringGenerator#generate()

The following examples show how to use org.apache.commons.text.RandomStringGenerator#generate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HtmlPage2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * This was producing java.io.IOException: File name too long as of HtmlUnit-2.9.
 * Many file systems have a limit 255 byte for file names.
 * @throws Exception if the test fails
 */
@Test
public void saveShouldStripLongFileNames() throws Exception {
    final RandomStringGenerator generator = new RandomStringGenerator.Builder().withinRange('a', 'z').build();
    final String longName = generator.generate(500) + ".html";
    final String html = "<html><body><iframe src='" + longName + "'></iframe></body></html>";

    final WebClient webClient = getWebClient();
    final MockWebConnection webConnection = new MockWebConnection();

    webConnection.setDefaultResponse("<html/>");
    webConnection.setResponse(URL_FIRST, html);
    webClient.setWebConnection(webConnection);

    final HtmlPage page = webClient.getPage(URL_FIRST);

    final File tmpFolder = tmpFolderProvider_.newFolder("hu");
    final File file = new File(tmpFolder, "hu_HtmlPageTest_save.html");
    page.save(file);
    assertTrue(file.exists());
    assertTrue(file.isFile());
}
 
Example 2
Source File: AsyncService.java    From Spring-Boot-2.0-Projects with MIT License 6 votes vote down vote up
@Transactional(rollbackFor = Exception.class)
public void sendResetPassword(String email) throws IOException {
    User user = userService.getByEmail(email);

    if (user != null) {
        ResetPasswordRequest resetPasswordRequest = new ResetPasswordRequest();
        resetPasswordRequest.setEmail(user.getEmail());

        RandomStringGenerator generator = new RandomStringGenerator.Builder()
                .withinRange('a', 'z').build();
        String newPassword = generator.generate(10);
        resetPasswordRequest.setNewPassword(newPassword);
        resetPasswordRequest.setUsername(user.getUsername());
        ProducerRecord<String, String> record = new ProducerRecord<>("resetPasswordRequests", objectMapper.writeValueAsString(resetPasswordRequest));
        kafkaTemplate.send(record);

        user.setPassword(passwordEncoder.encode(newPassword));
        userService.save(user);
    }
}
 
Example 3
Source File: LogRequestorTest.java    From docker-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testStdoutMessage() throws Exception {
    final Streams type = Streams.STDOUT;
    RandomStringGenerator randomGenerator = new RandomStringGenerator.Builder().build();
    final String message0 = randomGenerator.generate(257);
    final String message1 = "test test";
    final String message2 = randomGenerator.generate(666);

    final ByteBuffer body = responseContent(type, message0, message1, message2);
    final InputStream inputStream = new ByteArrayInputStream(body.array());

    setupMocks(inputStream);
    new LogRequestor(client, urlBuilder, containerId, callback).fetchLogs();

    new Verifications() {{
        callback.log(type.type, (Timestamp) any, message0);
        callback.log(type.type, (Timestamp) any, message1);
        callback.log(type.type, (Timestamp) any, message2);
    }};
}
 
Example 4
Source File: JadyerUtil.java    From seed with Apache License 2.0 5 votes vote down vote up
/**
 * 生成指定长度的,由纯数字组成的,随机字符串
 * <p>
 *     注意:返回的字符串的首字符,不会是零
 * </p>
 */
public static String randomNumeric(final int count) {
    //RandomStringUtils这个类不推荐使用了,用RandomStringGenerator来代替
    //return RandomStringUtils.randomNumeric(count);
    RandomStringGenerator generator = new RandomStringGenerator.Builder().withinRange('0', '9').build();
    String str = generator.generate(count);
    while(str.startsWith("0")){
        str = generator.generate(count);
    }
    return str;
}
 
Example 5
Source File: RandomTrackingNumberGenerationStrategy.java    From pizzeria with MIT License 5 votes vote down vote up
@Override
public String generatetrackingNumber(Order order) {
    UniformRandomProvider rng = RandomSource.create(RandomSource.SPLIT_MIX_64, order.getId());
    RandomStringGenerator randomStringGenerator = new RandomStringGenerator.Builder().usingRandom(rng::nextInt)
            .selectFrom(trackingNumberCharacters.toCharArray()).build();
    return randomStringGenerator.generate(trackingNumberLength);
}
 
Example 6
Source File: GenerateEncodedPassword.java    From spring-microservice-boilerplate with MIT License 5 votes vote down vote up
public static void main(String[] args) {
  RandomStringGenerator generator = new RandomStringGenerator.Builder()
      .withinRange('!', '}').build();
  String pwd = generator.generate(32);
  System.out.println(pwd);
  String encodedPassword = new CustomPasswordEncoder().encode(pwd);
  System.out.println(encodedPassword);
}
 
Example 7
Source File: LogRequestorTest.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testAllStreams() throws Exception {
    final Random rand = new Random();
    final int upperBound = 1024;

    RandomStringGenerator randomGenerator = new RandomStringGenerator.Builder().build();

    final Streams type0 = Streams.STDIN;
    final String msg0 = randomGenerator.generate(rand.nextInt(upperBound));
    final ByteBuffer buf0 = messageToBuffer(type0, msg0);

    final Streams type1 = Streams.STDOUT;
    final String msg1 = randomGenerator.generate(rand.nextInt(upperBound));
    final ByteBuffer buf1 = messageToBuffer(type1, msg1);

    final Streams type2 = Streams.STDERR;
    final String msg2 = randomGenerator.generate(rand.nextInt(upperBound));
    final ByteBuffer buf2 = messageToBuffer(type2, msg2);

    final ByteBuffer body = combineBuffers(buf0, buf1, buf2);
    final InputStream inputStream = new ByteArrayInputStream(body.array());

    setupMocks(inputStream);
    new LogRequestor(client, urlBuilder, containerId, callback).fetchLogs();

    new Verifications() {{
        callback.log(type0.type, (Timestamp) any, msg0);
        callback.log(type1.type, (Timestamp) any, msg1);
        callback.log(type2.type, (Timestamp) any, msg2);
    }};
}
 
Example 8
Source File: RandomPasswordGenerator.java    From tutorials with MIT License 5 votes vote down vote up
public String generateRandomAlphabet(int length, boolean lowerCase) {
    int low;
    int hi;
    if (lowerCase) {
        low = 97;
        hi = 122;
    } else {
        low = 65;
        hi = 90;
    }
    RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(low, hi)
        .build();
    return pwdGenerator.generate(length);
}
 
Example 9
Source File: CommonTests.java    From trellis with Apache License 2.0 4 votes vote down vote up
/**
 * Get a randomized Slug header with an appropriate suffix.
 * @param suffix the suffix
 * @return a randomized header name
 */
default String generateRandomValue(final String suffix) {
    final RandomStringGenerator generator = new RandomStringGenerator.Builder()
        .withinRange('a', 'z').build();
    return generator.generate(16) + "-" + suffix;
}
 
Example 10
Source File: RandomStringGeneratorTest.java    From spring-boot-cookbook with Apache License 2.0 4 votes vote down vote up
/**
 * <p>
 * Generates random Unicode strings containing the specified number of code points.
 * Instances are created using a builder class, which allows the
 * callers to define the properties of the generator. See the documentation for the
 * {@link RandomStringGenerator.Builder} class to see available properties.
 * </p>
 * <pre>
 * // Generates a 20 code point string, using only the letters a-z
 * RandomStringGenerator generator = new RandomStringGenerator.Builder()
 *     .withinRange('a', 'z').build();
 * String randomLetters = generator.generate(20);
 * </pre>
 * <pre>
 * // Using Apache Commons RNG for randomness
 * UniformRandomProvider rng = RandomSource.create(...);
 * // Generates a 20 code point string, using only the letters a-z
 * RandomStringGenerator generator = new RandomStringGenerator.Builder()
 *     .withinRange('a', 'z')
 *     .usingRandom(rng::nextInt) // uses Java 8 syntax
 *     .build();
 * String randomLetters = generator.generate(20);
 * </pre>
 * <p>
 * {@code RandomStringBuilder} instances are thread-safe when using the
 * default random number generator (RNG). If a custom RNG is set by calling the method
 * {@link RandomStringGenerator.Builder#usingRandom(TextRandomProvider) Builder.usingRandom(TextRandomProvider)}, thread-safety
 * must be ensured externally.
 * </p>
 *
 * @since 1.1
 */
@Test
public void generateRandomStringDemo() {
    //使用字母a-z,生成20个code point(维基百科称之为'码位')的随机字符串
    RandomStringGenerator generator1 = new RandomStringGenerator.Builder()
            .withinRange('a', 'z').build();
    String randomLetters = generator1.generate(20);
    System.out.println(StringUtils.center("随机字母字符串", 20, "="));
    System.out.println(randomLetters);

    //使用数字0-9,生成20个code point(维基百科称之为'码位')的随机字符串
    RandomStringGenerator generator2 = new RandomStringGenerator.Builder()
            .withinRange('0', '9').build();
    String randomNumbers = generator2.generate(20);
    System.out.println(StringUtils.center("随机数字字符串", 20, "="));
    System.out.println(randomNumbers);

    //使用码位为0到z的字符,生成20个code point(维基百科称之为'码位')的随机字符串
    RandomStringGenerator generator3 = new RandomStringGenerator.Builder()
            .withinRange('0', 'z').build();
    String random = generator3.generate(20);
    System.out.println(StringUtils.center("随机混合字符串", 20, "="));
    System.out.println(random);
}
 
Example 11
Source File: PsFacebookTest.java    From takes with MIT License 4 votes vote down vote up
/**
 * Tests if PsFacebook can call DefaultFacebookClient APIs.
 * @throws Exception if any error occurs
 */
@Test
public final void canLogin() throws Exception {
    final String identifier = RandomStringUtils.randomAlphanumeric(10);
    final RandomStringGenerator generator =
        new RandomStringGenerator.Builder()
            .filteredBy(
                Character::isLetterOrDigit, Character::isIdeographic
            ).build();
    final Pass pass = new PsFacebook(
        new FakeRequest(
            200,
            "HTTP OK",
            Collections.emptyList(),
            String.format(
                "access_token=%s",
                RandomStringUtils.randomAlphanumeric(10)
            ).getBytes(StandardCharsets.UTF_8)
        ),
        new DefaultWebRequestor() {
            @Override
            public Response executeGet(final String url) {
                return new Response(
                    HttpURLConnection.HTTP_OK,
                    String.format(
                        "{\"id\":\"%s\",\"name\":\"%s\"}",
                        identifier,
                        generator.generate(10)
                    )
                );
            }
        },
        generator.generate(10),
        generator.generate(10)
    );
    final Opt<Identity> identity = pass.enter(
        new RqFake(
            "GET",
            String.format(
                "?code=%s",
                RandomStringUtils.randomAlphanumeric(10)
            )
        )
    );
    MatcherAssert.assertThat(identity.has(), Matchers.is(true));
    MatcherAssert.assertThat(
        identity.get().urn(),
        CoreMatchers.equalTo(String.format("urn:facebook:%s", identifier))
    );
}
 
Example 12
Source File: Index.java    From sqlg with MIT License 4 votes vote down vote up
public static String generateName(SqlDialect sqlDialect) {
    RandomStringGenerator generator = new RandomStringGenerator.Builder()
            .withinRange('a', 'z').build();
    return generator.generate(sqlDialect.getMaximumIndexNameLength());
}
 
Example 13
Source File: RandomPasswordGenerator.java    From tutorials with MIT License 4 votes vote down vote up
public String generateRandomSpecialCharacters(int length) {
    RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(33, 45)
        .build();
    return pwdGenerator.generate(length);
}
 
Example 14
Source File: RandomPasswordGenerator.java    From tutorials with MIT License 4 votes vote down vote up
public String generateRandomNumbers(int length) {
    RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(48, 57)
        .build();
    return pwdGenerator.generate(length);
}
 
Example 15
Source File: RandomPasswordGenerator.java    From tutorials with MIT License 4 votes vote down vote up
public String generateRandomCharacters(int length) {
    RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(48, 57)
        .build();
    return pwdGenerator.generate(length);
}