Created
April 22, 2012 02:32
-
-
Save froop/2441957 to your computer and use it in GitHub Desktop.
[Java] UUIDをBase64に変換 (URLSafe)
This file contains hidden or 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
public class UUIDBase64URLSafeTest { | |
String toBase64Url(UUID uuid) { | |
return toBase64Url(uuid.getMostSignificantBits()) | |
+ toBase64Url(uuid.getLeastSignificantBits()); | |
} | |
String toBase64Url(long src) { | |
byte[] binaryData = toBinaryData(src); | |
return Base64.encodeBase64URLSafeString(binaryData); | |
} | |
private byte[] toBinaryData(long src) { | |
final int longBits = 64, byteBits = 8; | |
final int dataBytes = longBits / byteBits; | |
byte[] res = new byte[dataBytes]; | |
for (int i = 0; i < dataBytes; i++) { | |
res[i] = (byte) (src >>> byteBits * (dataBytes - i - 1)); | |
} | |
return res; | |
} | |
@Test | |
public void testToBase64UrlLong() { | |
assertEquals(StringUtils.repeat('A', 11), toBase64Url(0L)); | |
assertEquals("AAAAAAAAAAE", toBase64Url(1L)); | |
assertEquals("AAAAAAAAAD8", toBase64Url(63L)); | |
assertEquals("AAAAAAAAAEA", toBase64Url(64L)); | |
assertEquals("f_________8", toBase64Url(Long.MAX_VALUE)); | |
assertEquals("__________8", toBase64Url(-1L)); | |
assertEquals("gAAAAAAAAAA", toBase64Url(Long.MIN_VALUE)); | |
} | |
@Test | |
public void testToBase64Url() { | |
String res = toBase64Url(new UUID(1L, 2L)); | |
assertEquals("AAAAAAAAAAEAAAAAAAAAAI", res); | |
} | |
@Test | |
public void testToBase64UrlRandom() { | |
String res = toBase64Url(UUID.randomUUID()); | |
assertTrue(res, res.matches("[a-zA-Z0-9_-]{22}")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment