Identifiers { private static String makeRandomId(int l, String validStartChars, String validNonStartChars) { if (l <= 0) return ""; char[] id = new char[l]; int s = validStartChars.length(); int n = validNonStartChars.length(); int d = random.nextInt(s * n * n * n); int i = 0; id[i] = validStartChars.charAt(d % s); d /= s; if (++i < l) do { id[i] = validNonStartChars.charAt(d % n); if (++i >= l) break; if (i % 4 == 0) { d = random.nextInt(n * n * n *n); } else { d /= n; } } while (true); return new String(id); }  static String makeRandomId(int l); static String makeRandomLowercaseId(int l); static String makeRandomPassword(final int length); static String makeRandomPassword(final int length, String... passwordValidCharsPool); static String makeIdFromHash(long d); static String makeRandomJavaId(int l); static double randomDouble(); static long randomLong(); static boolean randomBoolean(); static int randomInt(); static int randomInt(int upbound); static byte[] randomBytes(byte[] buf); static byte[] randomBytes(int length); static String makeRandomBase64Id(int length); static String getBase64IdFromValue(long value); static String getBase64IdFromValue(long value, int length); static void appendBase64IdFromValueOfLength(long value, int length, StringBuffer sb); static void appendBase64IdFromValueOfLength(long value, int length, StringBuilder sb); static boolean isValidToken(String token, String validStartChars, String validSubsequentChars); static final String UPPER_CASE_ALPHA; static final String LOWER_CASE_ALPHA; static final String NUMERIC; static final String NON_ALPHA_NUMERIC; static final String JAVA_GOOD_START_CHARS; static final String JAVA_GOOD_NONSTART_CHARS; static final String JAVA_GOOD_SEGMENT_REGEX; static final String JAVA_GOOD_PACKAGE_OR_CLASS_REGEX; static final String JAVA_GOOD_BINARY_REGEX; static final String JAVA_GENERATED_IDENTIFIER_START_CHARS; static final String JAVA_GENERATED_IDENTIFIERNONSTART_CHARS; static final String BASE64_VALID_CHARS; static final String ID_VALID_START_CHARS; static final String ID_VALID_NONSTART_CHARS; static final String PASSWORD_VALID_CHARS; }
@Test public void testRandomId() { String id1 = Identifiers.makeRandomId(4); Assert.assertEquals(id1.length(), 4); String id2 = Identifiers.makeRandomId(4); Assert.assertNotEquals(id1, id2); }
@Test(enabled = false) public void testRandomIdRandomness() { int collisionTestCnt = 100000; int sampleSize = 2000; int duplicateTests = 0; for(int testIdx = 0; testIdx < collisionTestCnt; testIdx++) { Set<String> randomIds = new HashSet<String>(); for (int sampleCnt = 0; sampleCnt < sampleSize; sampleCnt++) { if(!randomIds.add(Identifiers.makeRandomId(4))) { duplicateTests++; break; } } } double probability = ((double)duplicateTests)*100/collisionTestCnt; log.info("testRandomIdRandomness probability = " + probability); Assert.assertEquals(probability, 15, 0.5d, "Expected probability of collision with id of length 4 and 2000 samples is 15%."); }