Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

better random naming, fixes https://github.com/Azure/azure-sdk-for-ja… #868

Merged
merged 1 commit into from
Jun 21, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@
*/
public class ResourceNamer {
private final String randName;
private final long modulus = 100000L;
private final int moduloLen = 5;

/**
* Creates ResourceNamer.
Expand All @@ -27,39 +25,33 @@ public ResourceNamer(String name) {
* @return the random name
*/
public String randomName(String prefix, int maxLen) {
if (prefix.length() >= maxLen) {
throw new IllegalArgumentException("prefix length (" + prefix.length() + ") cannot be more than " + maxLen);
int minRandomnessLength = 5;
if (maxLen <= minRandomnessLength) {
return randomString(maxLen);
}

long milli = System.currentTimeMillis();
if (maxLen <= moduloLen) {
return String.valueOf(milli % maxLen);
if (maxLen <= prefix.length() + minRandomnessLength) {
return randomString(maxLen);
}

long modulo = (milli % this.modulus);
// Try prefix and randName together
if (prefix.length() + this.moduloLen + this.randName.length() <= maxLen) {
return prefix + modulo + this.randName;
String minRandomString = String.valueOf(System.currentTimeMillis() % 100000L);
if (maxLen <= prefix.length() + randName.length() + minRandomnessLength) {
String str = prefix + minRandomString;
return str + randomString((maxLen - str.length()) / 2);
}

// We cannot use prefix and randName try prefix
String name = prefix + modulo;
if (name.length() + 4 <= maxLen) {
return name + UUID.randomUUID()
.toString()
.replace("-", "").substring(0, 3);
} else if (name.length() <= maxLen) {
return name;
}
String str = prefix + randName + minRandomString;
return str + randomString((maxLen - str.length()) / 2);
}

// We cannot use prefix, use complete random string
name = UUID.randomUUID()
.toString()
.replace("-", "");
if (name.length() <= maxLen) {
return name;
private String randomString(int length) {
String str = "";
while (str.length() < length) {
str += UUID.randomUUID()
.toString()
.replace("-", "")
.substring(0, Math.min(32, length));
}

return name.substring(0, maxLen - moduloLen - 1) + (modulo);
return str;
}
}