Generating uuid in java

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A Java library for generating Universally Unique Identifiers (UUID).

License

f4b6a3/uuid-creator

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

This is a Java library for generating Universally Unique Identifiers.

  • UUID Version 1: the time-based version with gregorian epoch specified in RFC-4122;
  • UUID Version 2: the DCE Security version with embedded POSIX UIDs specified in DCE 1.1;
  • UUID Version 3: the name-based version that uses MD5 hashing specified in RFC-4122;
  • UUID Version 4: the randomly or pseudo-randomly generated version specified in RFC-4122;
  • UUID Version 5: the name-based version that uses SHA-1 hashing specified in RFC-4122;
  • UUID Version 6: the time-ordered version with gregorian epoch proposed as new UUID format;
  • UUID Version 7: the time-ordered version with Unix epoch proposed as new UUID format.
  • Prefix COMB GUID: a combination of random bytes with a prefix (millisecond);
  • Suffix COMB GUID: a combination of random bytes with a suffix (millisecond);
  • Short Prefix COMB GUID: a combination of random bytes with a small prefix (minute);
  • Short Suffix COMB GUID: a combination of random bytes with a small suffix (minute).

This project contains a micro benchmark and a good amount of unit tests.

The jar file can be downloaded directly from maven.org.

Add these lines to your pom.xml :

 https://search.maven.org/artifact/com.github.f4b6a3/uuid-creator --> dependency> groupId>com.github.f4b6a3groupId> artifactId>uuid-creatorartifactId> version>5.3.2version> dependency>

Module and bundle names are the same as the root package name.

All UUID types can be created from the facade UuidCreator .

UUID uuid = UuidCreator.getTimeBased();
UUID uuid = UuidCreator.getDceSecurity(UuidLocalDomain.LOCAL_DOMAIN_PERSON, 1234);
UUID uuid = UuidCreator.getNameBasedMd5(UuidNamespace.NAMESPACE_URL, "https://github.com/");
UUID uuid = UuidCreator.getRandomBased();
UUID uuid = UuidCreator.getNameBasedSha1(UuidNamespace.NAMESPACE_URL, "https://github.com/");
UUID uuid = UuidCreator.getTimeOrdered();
UUID uuid = UuidCreator.getTimeOrderedEpoch();
UUID uuid = UuidCreator.getPrefixComb();
UUID uuid = UuidCreator.getSuffixComb();
UUID uuid = UuidCreator.getShortPrefixComb();
UUID uuid = UuidCreator.getShortSuffixComb();

The GUID class is an alternative to the JDK’s built-in UUID .

GUID guid = GUID.v2(GUID.LOCAL_DOMAIN_PERSON, 1234);
GUID guid = GUID.v3(GUID.NAMESPACE_DNS, "www.example.com");
GUID guid = GUID.v5(GUID.NAMESPACE_DNS, "www.example.com");
GUID guid = GUID.v8(GUID.NAMESPACE_DNS, "www.example.com");

Other identifier generators

Check out the other ID generators from the same family:

  • ULID Creator: Universally Unique Lexicographically Sortable Identifiers
  • TSID Creator: Time Sortable Identifiers
  • KSUID Creator: K-Sortable Unique Identifiers

This library is Open Source software released under the MIT license.

About

A Java library for generating Universally Unique Identifiers (UUID).

Источник

Generate a UUID in Java

Java is one of the most popular programming languages in the world!

Since its humble beginnings at Sun Microsystems in 1991, Java has come to dominate enterprise backend software, run the majority of smart phones (Android), and be used extensively on desktop computers in apps such as LibreOffice and Minecraft.

How to Generate a UUID in Java

The Java language has built-in support for generating Version 4 UUIDs. Here’s an example of how you can create a UUID in Java code.

import java.util.UUID;
class MyUuidApp
public static void main(String[] args)
UUID uuid = UUID.randomUUID();
String uuidAsString = uuid.toString();
System.out.println("Your UUID is: " + uuidAsString);
>
>

Explanation

  • On line #1, we import the UUID class. This class is part of the standard Java JDK. No 3rd party libraries are required.
  • On line #5, the UUID class’ static method, randomUUID() , is used to generate a new, version 4 UUID. The generated UUID object is stored in the variable, uuid .
  • Line #6 converts the uuid object into a Java String by calling its toString() method. The String representation of a UUID looks like a standard UUID (i.e. f8c3de3d-1fea-4d7c-a8b0-29f63c4c3454 ). If you’re going to store the UUID in a file, database or model property, or send it via an API call to a different application, you’ll almost always need the String representation of the uuid object, rather than the uuid object itself.
  • The output from line #8 will be something like:
Your UUID is: f8c3de3d-1fea-4d7c-a8b0-29f63c4c3454

Convert from a String to a UUID in Java

Although it’s rare, in some circumstances you might need to convert from a String representation of a UUID (like the one from line #6 above) back into an instance of UUID .

Java’s UUID class provides for this scenario with the static method, fromString(String) . You can call this method like this:

import java.util.UUID;
class MyUuidApp
public static void main(String[] args)
UUID uuid = UUID.randomUUID();
String uuidAsString = uuid.toString();
UUID sameUuid = UUID.fromString(uuidAsString);
assert sameUuid.equals(uuid);
>
>

Explanation

  • Line #8 shows converting the string representation of a UUID into a Java UUID instance ( sameUuid ) using the fromString(String) method.
  • Line #9 is included to show that the 2 UUID instances are equal.

How can we improve this page? Let us know!

Источник

Java UUID Generator Example

Learn what is UUID and it’s versions and variants. Learn to generate UUID in Java using UUID.randomUUID() API. Also learn to generate version 5 UUID in Java.

UUID (Universally Unique IDentifier), also known as GUID (Globally Unique IDentifier) is 128 bits long identifier that is unique across both space and time, with respect to the space of all other UUIDs. It requires no central registration process. As a result, generation on demand can be completely automated, and used for a variety of purposes.

To understand how unique is a UUID, you should know that UUID generation algorithms support very high allocation rates of up to 10 million per second per machine if necessary, so that they could even be used as transaction IDs.

We can apply sorting, ordering and we can store them in databases. It makes it useful in programming in general.

Since UUIDs are unique and persistent, they make excellent Uniform Resource Names (URNs) with lowest mining cost in comparison to other alternatives.

The nil UUID is special form of UUID that is specified to have all 128 bits set to zero.

Do not assume that UUIDs are hard to guess; they should not be used as security capabilities. A predictable random number source will exacerbate the situation. Humans do not have the ability to easily check the integrity of a UUID by simply glancing at it.

A typical UID is displayed in 5 groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 alphanumeric characters and 4 hyphens).

Here ‘M’ indicate the UUID version and ‘N’ indicate the UUID variant.

  • The variant field contains a value which identifies the layout of the UUID.
  • The version field holds a value that describes the type of this UUID. There are five different basic types of UUIDs.
    1. Time-Based UUID (Version 1) – generated from a time and a node id
    2. DCE (Distributed Computing Environment) security (Version 2) – generated from an identifier (usually a group or user id), time, and a node id
    3. Name-based (Version 3) – generated by MD5 (128 bits) hashing of a namespace identifier and name
    4. Randomly generated UUIDs (Version 4) – generated using a random or pseudo-random number
    5. Name-based using SHA-1 hashing (Version 5) Recommended – generated by SHA-1 (160 bits) hashing of a namespace identifier and name. Java does not provide its implementation. We shall create our own.

3.1. UUID.randomUUID() – Version 4

Default API randomUUID() is a static factory to retrieve a type 4 (pseudo randomly generated) UUID. It is good enough for most of the usecases.

UUID uuid = UUID.randomUUID(); System.out.println(uuid); System.out.println(uuid.variant()); //2 System.out.println(uuid.version()); //4
17e3338d-344b-403c-8a87-f7d8006d6e33 2 4

3.2. Generate Version 5 UUID

Java does not provide inbuilt API to generate version 5 UUID, so we have to create our own implementation. Below is one such implementation. (Ref).

import java.nio.ByteOrder; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.UUID; public class UUID5 < public static UUID fromUTF8(String name) < return fromBytes(name.getBytes(Charset.forName("UTF-8"))); >private static UUID fromBytes(byte[] name) < if (name == null) < throw new NullPointerException("name == null"); >try < MessageDigest md = MessageDigest.getInstance("SHA-1"); return makeUUID(md.digest(name), 5); >catch (NoSuchAlgorithmException e) < throw new AssertionError(e); >> private static UUID makeUUID(byte[] hash, int version) < long msb = peekLong(hash, 0, ByteOrder.BIG_ENDIAN); long lsb = peekLong(hash, 8, ByteOrder.BIG_ENDIAN); // Set the version field msb &= ~(0xfL private static long peekLong(final byte[] src, final int offset, final ByteOrder order) < long ans = 0; if (order == ByteOrder.BIG_ENDIAN) < for (int i = offset; i < offset + 8; i += 1) < ans > else < for (int i = offset + 7; i >= offset; i -= 1) < ans > return ans; > >
UUID uuid = UUID5.fromUTF8("954aac7d-47b2-5975-9a80-37eeed186527"); System.out.println(uuid); System.out.println(uuid.variant()); System.out.println(uuid.version());
d1d16b54-9757-5743-86fa-9ffe3b937d78 2 5

Drop me your questions related to generating UUID in Java.

Источник

Читайте также:  Слив чат менеджера вк python
Оцените статью