Skip to content

Commit

Permalink
AMP-30334 add base 36 generator
Browse files Browse the repository at this point in the history
  • Loading branch information
kelsonpw committed Oct 8, 2020
1 parent 825f34f commit db95a4b
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 13 deletions.
18 changes: 6 additions & 12 deletions src/main/java/com/amplitude/identitymanager/Identity.java
Original file line number Diff line number Diff line change
@@ -1,44 +1,38 @@
package com.amplitude.identitymanager;

import android.util.Log;

public class Identity {
private String _userId;
private String _deviceId;

private void logIdentityWarning(String message) {
Log.w(Identity.class.getName(), message);
}

public String initializeDeviceId(String deviceId) {
if (deviceId == null) {
if (_deviceId == null) {
String deviceIdToUse = "";
if (deviceId.length() > 0) {
deviceIdToUse = deviceId;
} else {
deviceIdToUse = "generateBase36Id";
deviceIdToUse = IdentityUtils.generateBase36Id();
}
_deviceId = deviceIdToUse;
} else {
logIdentityWarning("Cannot set device ID twice for same identity. Skipping operation.");
IdentityUtils.logIdentityWarning("Cannot set device ID twice for same identity. Skipping operation.");
}

return deviceId;
}

public String initializeDeviceId() {
if (_deviceId == null) {
_deviceId = "generateBase36Id";
_deviceId = IdentityUtils.generateBase36Id();
} else {
logIdentityWarning("Cannot set device ID twice for same identity. Skipping operation.");
IdentityUtils.logIdentityWarning("Cannot set device ID twice for same identity. Skipping operation.");
}

return _deviceId;
}

public String getDeviceId() {
if (_deviceId == null) {
logIdentityWarning("Did not detect device ID; generating one for this instance.");
IdentityUtils.logIdentityWarning("Did not detect device ID; generating one for this instance.");
return initializeDeviceId();
} else {
return _deviceId;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,4 @@ public Identity getInstance() {
return identityToSet;
}
}
}
}
24 changes: 24 additions & 0 deletions src/main/java/com/amplitude/identitymanager/IdentityUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.amplitude.identitymanager;

import android.util.Log;

public class IdentityUtils {
static private final int device_id_length = 25;
static private final String base_36_char_set = "abcdefghijklmnopqrstuvwxyz0123456789";
static private final int base_36_radix = 36;

static void logIdentityWarning(String message) {
Log.w(Identity.class.getName(), message);
}

static String generateBase36Id() {
String stringBuilder = "";
for (int idx = 0; idx < device_id_length; idx++) {
double randomIdx = Math.floor(Math.random() * base_36_radix);
char nextChar = base_36_char_set.charAt((int)randomIdx);
stringBuilder += nextChar;
}

return stringBuilder;
}
}

0 comments on commit db95a4b

Please sign in to comment.