Created
January 10, 2018 12:47
-
-
Save hanbei/cab696baa7d6b599ab9f8f2b6dfb4fff to your computer and use it in GitHub Desktop.
RandomUrlGenerator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.apache.commons.lang3.RandomStringUtils; | |
import java.security.SecureRandom; | |
import java.util.Random; | |
import java.util.stream.IntStream; | |
import static java.util.stream.Collectors.joining; | |
public final class RandomUrlGenerator { | |
private RandomUrlGenerator() { | |
// not allowed to construct | |
} | |
private static final Random random = new SecureRandom(); | |
private static final String[] schemes = new String[]{ | |
"http", "https" | |
}; | |
private static final String[] endings = new String[]{ | |
"io", "com", "de", "co.uk", "tv", "koeln", "price", "adult" | |
}; | |
public static String url() { | |
return host() + path() + queryParameter(); | |
} | |
public static String queryParameter() { | |
return queryParameter(random.nextInt(5)); | |
} | |
private static String queryParameter(int size) { | |
String queryParameter = IntStream.range(0, size) | |
.mapToObj( | |
i -> RandomStringUtils.randomAlphabetic(4, 10).toLowerCase() + "=" + RandomStringUtils.randomAlphabetic(4, 10).toLowerCase() | |
) | |
.collect(joining("&", "?", "")); | |
if (queryParameter.equals("?")) { | |
return ""; | |
} | |
return queryParameter; | |
} | |
public static String path() { | |
return path(random.nextInt(5)); | |
} | |
private static String path(int pathSegments) { | |
return IntStream.range(1, pathSegments).mapToObj(i -> RandomStringUtils.randomAlphabetic(4, 10).toLowerCase()).collect(joining("/", "/", "")); | |
} | |
public static String host() { | |
return choice(schemes) + "://www." + RandomStringUtils.randomAlphabetic(4, 10).toLowerCase() + "." + choice(endings); | |
} | |
public static <T> T choice(T[] array) { | |
return array[random.nextInt(array.length)]; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.Before; | |
import org.junit.Test; | |
import java.net.MalformedURLException; | |
import java.net.URI; | |
import java.net.URISyntaxException; | |
import java.net.URL; | |
public class RandomUrlGeneratorTest { | |
@Before | |
public void setup() { | |
} | |
@Test | |
public void urlIsValid() throws MalformedURLException, URISyntaxException { | |
for (int i = 0; i < 100000; i++) { | |
String randomUrl = RandomUrlGenerator.url(); | |
new URI(randomUrl); | |
new URL(randomUrl); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment