Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for concise alternative for RandomStringUtils

This question is obsolete. org.apache.commons:commmons-lang3:3.7 removed the deprecated flag, and 3.8 confirmed that.

After updating to org.apache.commons:commons-lang3:3.6 from 3.5 I get many warnings about RandomStringUtils being deprecated. The suggested alternative is RandomStringGenerator from commons-text. However, that class is very clumsy to use if all you want is just a string (say, in a unit test). Compare:

String name1 = RandomStringUtils.randomAlphabetic(FIRST_NAME_LENGTH);
String name2 = new RandomStringGenerator.Builder().withinRange('a', 'z').build()
        .generate(FIRST_NAME_LENGTH);

(I know that that’s not even the same semantics, but wanted to keep it short.)

So I’m looking for a short and elegant way, ideally a drop-in replacement; Java 8, Spring, Guava and even test-only libraries are all welcome.

like image 286
Michael Piefel Avatar asked Jun 26 '17 15:06

Michael Piefel


2 Answers

I would consider using the Facade pattern to wrap the "clumsiness" of the RandomStringGenerator class.

Example:

public class RandomStringUtilsFacade
{
    public static String randomAlphabetic (final int firstNameLength)
    {
        return randomAlphabetic(firstNameLength, 'a', 'z');
    }

    // If you want to use the range
    public static String randomAlphabetic (final int firstNameLength, 
                                           final char low, final char high)
    {
        return new RandomStringGenerator.Builder().withinRange(low, high).build()
        .generate(firstNameLength);
    }
}
like image 124
Michael Markidis Avatar answered Oct 19 '22 10:10

Michael Markidis


return org.apache.commons.lang3.RandomStringUtils.random(24, "abcdefghijklmnopqrstuvwxyz0123456789");

how about this str @Michael Markidis

like image 1
Miller Qb Avatar answered Oct 19 '22 10:10

Miller Qb