In the era of APIs, each resource is identified by unique id. UUID can be used to generate unique id in distributed systems. This article explains how to create base64 unique id based on random UUID.
UUID
using java.util.UUID.randomUUID()
uuid.getMostSignificantBits()
(MSB) and uuid.getLeastSignificantBits()
(LSB).ByteBuffer
create byte[]
from MSB and LSB.UrlEncoder
of Base64
convert byte[]
to base64 String
.substring
remove the trailing padding ==
.Following Java code written as spring component. It should be straight forward to use it in other places as well. java.util.Base64
requires Java 8
.
package com.sakthipriyan.example;
import java.nio.ByteBuffer;
import java.util.Base64;
import java.util.Base64.Encoder;
import java.util.UUID;
import org.springframework.stereotype.Component;
@Component
public class Uuid {
private final Encoder encoder;
public Uuid() {
this.encoder = Base64.getUrlEncoder();
}
public String randomId() {
// Create random UUID
UUID uuid = UUID.randomUUID();
// Create byte[] for base64 from uuid
byte[] src = ByteBuffer.wrap(new byte[16])
.putLong(uuid.getMostSignificantBits())
.putLong(uuid.getLeastSignificantBits())
.array();
// Encode to Base64 and remove trailing ==
return encoder.encodeToString(src).substring(0, 22);
}
}
package com.sakthipriyan.example;
@Service
public class ExampleService {
@Autowired
private Uuid uuid;
public void doSomething(){
String uniqueId = uuid.randomId();
// Do whatever you want to do.
}
}
Base64 IDs generating using uuid.randomId()
Ah2_xI48RWSGwGDcNfbcGQ
eLQuFAB1QRyWY_DHYxUX4Q
oUSCSgEEQCqw1wlGT_kiSw
R_0tJRgqQDGGVT4kXFli_A
SqrVhuCsQlmoiiIn5Pgpiw
FMiXuPLFQwu7yINCqBt-yQ
UQk9E_8ZSaufMhe33Yh6CA
Uj8RweXQRh-Lj5J0CrI5Vw
d8bkw3SeStW-nS7SFMUV4A
-1b351PDTyqaVQ8OhsrAyQ
f487fbcf-3606-4f35-a23d-5ac3af6de754
generated using UUID.randomUUID().toString()
has 36 bytes including the -
.9If7zzYGTzWiPVrDr23nVA
generated using uuid.randomId()
has only 22 bytes.
Documenting Play Framework using Swagger
api
swagger
play framework
documentation
design
|
|
Creating REST API Specification
api
swagger
documentation
design
cricscore api
|
|
Set up G-WAN web server
web server
g wan
setup
|
|
Scala code to access documents in AWS S3 bucket
scala
aws
s3
http
code
dispatch
|
|
Auto refresh Chrome when files modified
chrome
python
webgen
code
|
|
Salesforce Bulk API usage with an example
salesforce
integration
code
|