Created
November 8, 2013 03:55
-
-
Save liweinan/7366059 to your computer and use it in GitHub Desktop.
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.codec.binary.Base64; | |
import java.util.UUID; | |
public class UuidUtils { | |
public static String uuid() { | |
UUID uuid = UUID.randomUUID(); | |
return uuid.toString(); | |
} | |
public static String compressedUuid() { | |
UUID uuid = UUID.randomUUID(); | |
return compressedUUID(uuid); | |
} | |
protected static String compressedUUID(UUID uuid) { | |
byte[] byUuid = new byte[16]; | |
long least = uuid.getLeastSignificantBits(); | |
long most = uuid.getMostSignificantBits(); | |
long2bytes(most, byUuid, 0); | |
long2bytes(least, byUuid, 8); | |
String compressUUID = Base64.encodeBase64URLSafeString(byUuid); | |
return compressUUID; | |
} | |
protected static void long2bytes(long value, byte[] bytes, int offset) { | |
for (int i = 7; i > -1; i--) { | |
bytes[offset++] = (byte) ((value >> 8 * i) & 0xFF); | |
} | |
} | |
public static String compress(String uuidString) { | |
UUID uuid = UUID.fromString(uuidString); | |
return compressedUUID(uuid); | |
} | |
public static String uncompress(String compressedUuid) { | |
if (compressedUuid.length() != 22) { | |
throw new IllegalArgumentException("Invalid uuid!"); | |
} | |
byte[] byUuid = Base64.decodeBase64(compressedUuid + "=="); | |
long most = bytes2long(byUuid, 0); | |
long least = bytes2long(byUuid, 8); | |
UUID uuid = new UUID(most, least); | |
return uuid.toString(); | |
} | |
protected static long bytes2long(byte[] bytes, int offset) { | |
long value = 0; | |
for (int i = 7; i > -1; i--) { | |
value |= (((long) bytes[offset++]) & 0xFF) << 8 * i; | |
} | |
return value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment