Generate uuids in java

How do I generate UUID / GUID in Java?

UUID / GUID (Universally / Globally Unique Identifier) is frequently use in programming. Some of its usage are for creating random file names, session id in web application, transaction id and for record’s primary keys in database replacing the sequence or auto generated number.

To generate UUID in Java we can use the java.util.UUID class. This class was introduced in JDK 1.5. The UUID.randomUUID() method return a UUID object. To obtain the value of the random string generated we need to call the UUID.toString() method.

We can also get the version and the variant of the UUID using the version() method and variant() method respectively. Let’s see the code snippet below:

package org.kodejava.util; import java.util.UUID; public class RandomStringUUID < public static void main(String[] args) < // Creating a random UUID (Universally unique identifier). UUID uuid = UUID.randomUUID(); String randomUUIDString = uuid.toString(); System.out.println("Random UUID String = " + randomUUIDString); System.out.println("UUID version = " + uuid.version()); System.out.println("UUID variant language-text">Random UUID String = 87a20cdd-25da-4dc2-b787-68054ec2c5ca UUID version = 4 UUID variant = 2 

A programmer, recreational runner and diver, live in the island of Bali, Indonesia. Programming in Java, Spring, Hibernate / JPA. You can support me working on this project, buy me a cup of coffee ☕ every little bit helps, thank you 🙏

Читайте также:  Forum crvclub ru index php

Источник

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.

Источник

Generate uuids in java

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Java UUID Generator Example

Hello readers, in this tutorial, we are generating the UUID using the Java and Java UUID Generator API.

1. Introduction

Fig. 1: UUID Syntax

UUID / GUID ( Universally / Globally Unique Identifier ) is frequently used in programming. Some of its usages are for creating random file names, session id in the web application, transaction id and for record’s primary keys in the database (i.e. replacing the sequence or auto-generated number). UUID (i.e. Universally Unique Identifier) class is a part of the java.util package and represents an immutable universally unique identifier with a 128 bit number string value. It is represented in 32 Hexadecimal characters and is mixed with 4 dashes (i.e. — ) characters. UUID also was known as GUID which stands for Globally Unique Identifier. Following are the important methods available on the UUID class.

  • String toString() : This method will return a string object representing the UUID
  • int variant() : This method will return the variant number associated with the UUID
  • int version() : This method will return the version number associated with the UUID

Now, open up the Eclipse Ide and let’s see a few examples of how to generate the UUID object in Java!

2. Java UUID Generator Example

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig.2 : UUID Application Project Structure

2.3 Project Creation

Fig. 3: Create Maven Project

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project .

Fig. 4: Project Details

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on next button to proceed.

Fig. 5: Archetype Parameters

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT .

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

 4.0.0 JavaUuidEx JavaUuidEx 0.0.1-SNAPSHOT jar  

Developers can start adding the dependencies that they want to such as UUID Generator etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Maven Dependencies

Here, we specify the dependencies for the UUID Generator. The rest dependencies will be automatically resolved by the Maven framework and the updated file will have the following code:

 4.0.0 JavaUuidEx JavaUuidEx 0.0.1-SNAPSHOT  com.fasterxml.uuid java-uuid-generator 3.1.4   $  

3.2 Java Class Creation

Fig. 6: Java Package Creation

Let’s create the required Java files. Right-click on the src/main/java folder, New -> Package .

Fig. 7: Java Package Name (com.jcg.java)

A new pop window will open where we will enter the package name as: com.jcg.java .

Fig. 8: Java Class Creation

Once the package is created in the application, we will need to create the 2 different implementation classes in order to generate the UUID object. Right-click on the newly created package: New -> Class .

Fig. 9: Java Class (UuidExample.java)

A new pop window will open and enter the file name as: UuidExample . The utility class will be created inside the package: com.jcg.java .

Fig. 10: Java Class (JugUUIDExample.java)

Repeat the step (i.e. Fig. 7) and enter the filename as: JugUUIDExample . The main class will be created inside the package: com.jcg.java .

3.2.1 Implementation of Java UUID Class

To generate the UUID object in Java, developers can use the java.util.UUID class which was introduced in JDK 1.5. Let’s see the simple code snippet that follows this implementation.

package com.jcg.java; import java.util.UUID; public class UuidExample < public static void generateRandomUuid(int num) < /***** Generate Version 4 UUID - Randomly Generated UUID *****/ UUID uid = null; for(int i=1; i> public static void main(String[] args) < int num = 4; generateRandomUuid(num); >>

3.2.2 Implementation of Java UUID Generator Class

Developers can use the Java UUID Generator (JUG) utility to generate the UUID object. Let’s see the simple code snippet that follows this implementation.

package com.jcg.java; import java.util.UUID; import com.fasterxml.uuid.Generators; public class JugUUIDExample < public static void generateRandomUuid() < /***** Generate Version 1 UUID - Time-Based UUID *****/ UUID uuid1 = Generators.timeBasedGenerator().generate(); System.out.println("Generated Version 1 UUID?= " + uuid1.toString() + ", UUID Version?= " + uuid1.version() + ", UUID Variant?= " + uuid1.version() + "\n"); /***** Generate Version 4 UUID - Randomly Generated UUID *****/ UUID uuid2 = Generators.randomBasedGenerator().generate(); System.out.println("Generated Version 4 UUID?= " + uuid2.toString() + ", UUID Version?= " + uuid2.version() + ", UUID Variant? attachment_53890" aria-describedby="caption-attachment-53890" style="width: 832px" >Fig. 11: Run Application
Fig. 11: Run Application

5. Project Demo

The application shows the following logs as output for the UuidExample.java. This class will randomly generate a Version 4 UUID object.

Generated UUID?= 771cdd2e-e524-4218-b0da-21d0fd9a5307, UUID Version?= 4, UUID Variant?= 2 Generated UUID?= 16caf416-2434-42f5-ac5c-031bc3787247, UUID Version?= 4, UUID Variant?= 2 Generated UUID?= a42ac726-f54a-4094-a4d2-b7d1c70f9237, UUID Version?= 4, UUID Variant?= 2

The JugUUIDExample.java will generate a Version 1 and Version 4 UUID object and shows the following logs as output.

Generated Version 1 UUID?= c1336282-f08b-11e7-b344-c74db8d97c98, UUID Version?= 1, UUID Variant?= 1 Generated Version 4 UUID?= f803c0bc-ae39-4d1b-83c0-bcae392d1bd5, UUID Version?= 4, UUID Variant?= 4

That’s all for this post. Happy Learning!!

6. Conclusion

That’s all for Java UUID class and developers can use it to create the unique identifiers for their application. I hope this article served you whatever you were looking for.

7. Download the Eclipse Project

This was an example of Java UUID Generator for the beginners.

Источник

Оцените статью