Last active
November 7, 2021 04:39
-
-
Save fabiolimace/a679d03842b0b2cc9eacb9d83c8c8c19 to your computer and use it in GitHub Desktop.
A utility that generates time-based UUIDs for uploaded files
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
| package com.example; | |
| import java.nio.ByteBuffer; | |
| import java.nio.charset.StandardCharsets; | |
| import java.security.MessageDigest; | |
| import java.security.NoSuchAlgorithmException; | |
| import java.time.Instant; | |
| import java.util.UUID; | |
| import com.github.f4b6a3.uuid.UuidCreator; | |
| /** | |
| * A utility that generates time-based UUIDs for uploaded files. | |
| * | |
| * The upload date is transformed into the UUID's timestamp. | |
| * | |
| * The file name or URL is transformed into the UUID's node identifier. | |
| * | |
| * This example is inspired on a real use case found here in GitHub. | |
| */ | |
| public final class UploadVersion { | |
| private UploadVersion() { | |
| } | |
| public static UUID getVersion(Instant date, String name) { | |
| final long node = getNameHash(name); | |
| return UuidCreator.getTimeBased(date, null, node); | |
| } | |
| private static long getNameHash(String name) { | |
| try { | |
| MessageDigest hasher = MessageDigest.getInstance("MD5"); | |
| byte[] md5 = hasher.digest(name.getBytes(StandardCharsets.UTF_8)); | |
| return ByteBuffer.wrap(md5).getLong(); | |
| } catch (NoSuchAlgorithmException var3) { | |
| throw new InternalError("MD5 not supported", var3); | |
| } | |
| } | |
| public static void main(String[] args) { | |
| Instant date = Instant.now(); | |
| String name = "My uploaded file.jpg"; | |
| UUID uuid = UploadVersion.getVersion(date, name); | |
| System.out.println(uuid); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment