CODEBANK-5 更新 maven-javadoc-plugin 的插件版本为 3.6.0

This commit is contained in:
YuCheng Hu 2023-10-28 22:02:35 -04:00
parent e31e6ba102
commit 29b5628dd7
15 changed files with 653 additions and 0 deletions

View File

@ -0,0 +1,8 @@
## Core Java UUID
### Relevant Articles:
- [Generating Alphanumeric UUID String in Java](https://www.baeldung.com/java-generate-alphanumeric-uuid)
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
- [Validate UUID String in Java](https://www.baeldung.com/java-validate-uuid-string)
- [Generate the Same UUID From a String in Java](https://www.baeldung.com/java-generate-same-uuid-from-string)
- [Generating Time Based UUIDs](https://www.baeldung.com/java-generating-time-based-uuids)

View File

@ -0,0 +1,149 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-uuid</artifactId>
<name>core-java-uuid</name>
<packaging>jar</packaging>
<parent>
<groupId>com.ossez.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.2-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.github.f4b6a3</groupId>
<artifactId>uuid-creator</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.uuid</groupId>
<artifactId>java-uuid-generator</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>com.github.f4b6a3</groupId>
<artifactId>tsid-creator</artifactId>
<version>5.2.3</version>
</dependency>
</dependencies>
<build>
<finalName>core-java-uuid</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/libs</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<executable>java</executable>
<mainClass>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</mainClass>
<arguments>
<argument>-Xmx300m</argument>
<argument>-XX:+UseParallelGC</argument>
<argument>-classpath</argument>
<classpath/>
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
</arguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>${maven-javadoc-plugin.version}</version>
<configuration>
<source>17</source>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*ManualTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
<include>**/*IntTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<id>run-benchmarks</id>
<!-- <phase>integration-test</phase> -->
<phase>none</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<classpathScope>test</classpathScope>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<classpath/>
<argument>org.openjdk.jmh.Main</argument>
<argument>.*</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<maven-javadoc-plugin.version>3.6.0</maven-javadoc-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,42 @@
package com.baeldung.timebaseduuid;
import com.fasterxml.uuid.Generators;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
public class JavaUUIDCreatorBenchmark {
public static void main(String[] args) throws InterruptedException {
int threadCount = 128;
int iterationCount = 100_000;
Map<UUID, Long> uuidMap = new ConcurrentHashMap<>();
AtomicLong collisionCount = new AtomicLong();
long startNanos = System.nanoTime();
CountDownLatch endLatch = new CountDownLatch(threadCount);
for (long i = 0; i < threadCount; i++) {
long threadId = i;
new Thread(() -> {
for (long j = 0; j < iterationCount; j++) {
UUID uuid = Generators.timeBasedGenerator().generate();
Long existingUUID = uuidMap.put(uuid, (threadId * iterationCount) + j);
if(existingUUID != null) {
collisionCount.incrementAndGet();
}
}
endLatch.countDown();
}).start();
}
endLatch.await();
System.out.println(threadCount * iterationCount + " UUIDs generated, " + collisionCount + " collisions in "
+ TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos) + "ms");
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.timebaseduuid;
import com.fasterxml.uuid.Generators;
public class JavaUUIDCreatorExample {
public static void main(String[] args) {
System.out.println("UUID Version 1: " + Generators.timeBasedGenerator().generate());
System.out.println("UUID Version 6: " + Generators.timeBasedReorderedGenerator().generate());
System.out.println("UUID Version 7: " + Generators.timeBasedEpochGenerator().generate());
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.timebaseduuid;
import com.github.f4b6a3.uuid.UuidCreator;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
public class UUIDCreatorBenchmark {
public static void main(String[] args) throws InterruptedException {
int threadCount = 128;
int iterationCount = 100_000;
Map<UUID, Long> uuidMap = new ConcurrentHashMap<>();
AtomicLong collisionCount = new AtomicLong();
long startNanos = System.nanoTime();
CountDownLatch endLatch = new CountDownLatch(threadCount);
for (long i = 0; i < threadCount; i++) {
long threadId = i;
new Thread(() -> {
for (long j = 0; j < iterationCount; j++) {
UUID uuid = UuidCreator.getTimeBased();
Long existingUUID = uuidMap.put(uuid, (threadId * iterationCount) + j);
if(existingUUID != null) {
collisionCount.incrementAndGet();
}
}
endLatch.countDown();
}).start();
}
endLatch.await();
System.out.println(threadCount * iterationCount + " UUIDs generated, " + collisionCount + " collisions in "
+ TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos) + "ms");
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.timebaseduuid;
import com.github.f4b6a3.uuid.UuidCreator;
public class UUIDCreatorExample {
public static void main(String[] args) {
System.out.println("UUID Version 1: " + UuidCreator.getTimeBased());
System.out.println("UUID Version 6: " + UuidCreator.getTimeOrdered());
System.out.println("UUID Version 7: " + UuidCreator.getTimeOrderedEpoch());
}
}

View File

@ -0,0 +1,164 @@
package com.baeldung.uuid;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Random;
import java.util.UUID;
public final class UUIDGenerator {
private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
private UUIDGenerator() {
}
/**
* Type 1 UUID Generation
*/
public static UUID generateType1UUID() {
final long most64SigBits = get64MostSignificantBitsForVersion1();
final long least64SigBits = get64LeastSignificantBitsForVersion1();
return new UUID(most64SigBits, least64SigBits);
}
private static long get64LeastSignificantBitsForVersion1() {
final long random63BitLong = new Random().nextLong() & 0x3FFFFFFFFFFFFFFFL;
long variant3BitFlag = 0x8000000000000000L;
return random63BitLong | variant3BitFlag;
}
private static long get64MostSignificantBitsForVersion1() {
final long currentTimeMillis = System.currentTimeMillis();
final long time_low = (currentTimeMillis & 0x0000_0000_FFFF_FFFFL) << 32;
final long time_mid = ((currentTimeMillis >> 32) & 0xFFFF) << 16;
final long version = 1 << 12;
final long time_high = ((currentTimeMillis >> 48) & 0x0FFF);
return time_low | time_mid | version | time_high;
}
/**
* Type 3 UUID Generation
*/
public static UUID generateType3UUID(String namespace, String name) {
final byte[] nameSpaceBytes = bytesFromUUID(namespace);
final byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8);
final byte[] result = joinBytes(nameSpaceBytes, nameBytes);
return UUID.nameUUIDFromBytes(result);
}
/**
* Type 4 UUID Generation
*/
public static UUID generateType4UUID() {
return UUID.randomUUID();
}
/**
* Type 5 UUID Generation
*/
public static UUID generateType5UUID(String namespace, String name) {
final byte[] nameSpaceBytes = bytesFromUUID(namespace);
final byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8);
final byte[] result = joinBytes(nameSpaceBytes, nameBytes);
return type5UUIDFromBytes(result);
}
public static UUID type5UUIDFromBytes(byte[] name) {
final MessageDigest md;
try {
md = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException exception) {
throw new InternalError("SHA-1 not supported", exception);
}
final byte[] bytes = Arrays.copyOfRange(md.digest(name), 0, 16);
bytes[6] &= 0x0f; /* clear version */
bytes[6] |= 0x50; /* set to version 5 */
bytes[8] &= 0x3f; /* clear variant */
bytes[8] |= 0x80; /* set to IETF variant */
return constructType5UUID(bytes);
}
private static UUID constructType5UUID(byte[] data) {
long msb = 0;
long lsb = 0;
assert data.length == 16 : "data must be 16 bytes in length";
for (int i = 0; i < 8; i++) {
msb = (msb << 8) | (data[i] & 0xff);
}
for (int i = 8; i < 16; i++) {
lsb = (lsb << 8) | (data[i] & 0xff);
}
return new UUID(msb, lsb);
}
private static byte[] bytesFromUUID(String uuidHexString) {
final String normalizedUUIDHexString = uuidHexString.replace("-", "");
assert normalizedUUIDHexString.length() == 32;
final byte[] bytes = new byte[16];
for (int i = 0; i < 16; i++) {
final byte b = hexToByte(normalizedUUIDHexString.substring(i * 2, i * 2 + 2));
bytes[i] = b;
}
return bytes;
}
public static byte hexToByte(String hexString) {
final int firstDigit = Character.digit(hexString.charAt(0), 16);
final int secondDigit = Character.digit(hexString.charAt(1), 16);
return (byte) ((firstDigit << 4) + secondDigit);
}
public static byte[] joinBytes(byte[] byteArray1, byte[] byteArray2) {
final int finalLength = byteArray1.length + byteArray2.length;
final byte[] result = new byte[finalLength];
System.arraycopy(byteArray1, 0, result, 0, byteArray1.length);
System.arraycopy(byteArray2, 0, result, byteArray1.length, byteArray2.length);
return result;
}
public static UUID generateType5UUID(String name) {
try {
final byte[] bytes = name.getBytes(StandardCharsets.UTF_8);
final MessageDigest md = MessageDigest.getInstance("SHA-1");
final byte[] hash = md.digest(bytes);
long msb = getLeastAndMostSignificantBitsVersion5(hash, 0);
long lsb = getLeastAndMostSignificantBitsVersion5(hash, 8);
// Set the version field
msb &= ~(0xfL << 12);
msb |= 5L << 12;
// Set the variant field to 2
lsb &= ~(0x3L << 62);
lsb |= 2L << 62;
return new UUID(msb, lsb);
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
private static long getLeastAndMostSignificantBitsVersion5(final byte[] src, final int offset) {
long ans = 0;
for (int i = offset + 7; i >= offset; i -= 1) {
ans <<= 8;
ans |= src[i] & 0xffL;
}
return ans;
}
}

View File

@ -0,0 +1,6 @@
log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>

View File

@ -0,0 +1,62 @@
package com.baeldung.uuid;
import org.junit.jupiter.api.Test;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
public class UUIDFromStringUnitTest {
@Test
void whenStringInUUIDFormat_thenFromStringWorks() {
String inputStr = "bbcc4621-d88f-4a94-ae2f-b38072bf5087";
UUID uuid = UUID.fromString(inputStr);
UUID uuid2 = UUID.fromString(inputStr);
UUID uuid3 = UUID.fromString(inputStr);
assertEquals(inputStr, uuid.toString());
assertEquals(uuid, uuid2);
assertEquals(uuid, uuid3);
}
@Test
void whenStringNotInUUIDFormat_thenFromStringRaisesException() {
String inputStr = "I am not a standard UUID representation.";
assertThrows(IllegalArgumentException.class, () -> UUID.fromString(inputStr));
}
@Test
void whenStringInFreeFormat_thenNameUUIDFromBytesWorks() {
String inputStr = "I am not a standard UUID representation.";
UUID uuid = UUID.nameUUIDFromBytes(inputStr.getBytes());
UUID uuid2 = UUID.nameUUIDFromBytes(inputStr.getBytes());
UUID uuid3 = UUID.nameUUIDFromBytes(inputStr.getBytes());
assertTrue(uuid != null);
assertEquals(uuid, uuid2);
assertEquals(uuid, uuid3);
assertEquals(3, uuid.version());
}
@Test
void whenStringInFreeFormat_thenGenerateVer5UUIDWorks() {
String inputStr = "I am not a standard UUID representation.";
UUID uuid = UUIDGenerator.generateType5UUID(inputStr);
UUID uuid2 = UUIDGenerator.generateType5UUID(inputStr);
UUID uuid3 = UUIDGenerator.generateType5UUID(inputStr);
assertEquals(5, uuid.version());
assertTrue(uuid != null);
assertEquals(uuid, uuid2);
assertEquals(uuid, uuid3);
}
}

View File

@ -0,0 +1,84 @@
package com.baeldung.uuid;
import org.junit.jupiter.api.Test;
import java.io.UnsupportedEncodingException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
class UUIDGeneratorUnitTest {
private static final String NAMESPACE_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
private static final String NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
@Test
void shouldGenerateType1UUIDWithCorrectVersionAndVariant() {
UUID uuid = UUIDGenerator.generateType1UUID();
assertEquals(36, uuid.toString().length());
assertEquals(1, uuid.version());
assertEquals(2, uuid.variant());
}
@Test
void shouldGenerateType1UUIDWithTheCurrentDate() {
UUID uuid = UUIDGenerator.generateType1UUID();
long time = uuid.timestamp();
LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault());
assertEquals(LocalDate.now(), dateTime.toLocalDate());
}
@Test
void version_3_UUID_is_correctly_generated_for_domain_baeldung_com() {
UUID uuid = UUIDGenerator.generateType3UUID(NAMESPACE_DNS, "baeldung.com");
assertEquals("23785b78-0132-3ac6-aff6-cfd5be162139", uuid.toString());
assertEquals(3, uuid.version());
assertEquals(2, uuid.variant());
}
@Test
void version_3_UUID_is_correctly_generated_for_domain_d() {
UUID uuid = UUIDGenerator.generateType3UUID(NAMESPACE_DNS, "d");
assertEquals("dbd41ecb-f466-33de-b309-1468addfc63b", uuid.toString());
assertEquals(3, uuid.version());
assertEquals(2, uuid.variant());
}
@Test
public void version_4_UUID_is_generated_with_correct_length_version_and_variant() {
UUID uuid = UUIDGenerator.generateType4UUID();
assertEquals(36, uuid.toString().length());
assertEquals(4, uuid.version());
assertEquals(2, uuid.variant());
}
@Test
public void version_5_UUID_is_correctly_generated_for_domain_baeldung_com() throws UnsupportedEncodingException {
UUID uuid = UUIDGenerator.generateType5UUID(NAMESPACE_URL, "baeldung.com");
assertEquals("aeff44a5-8a61-52b6-bcbe-c8e5bd7d0300", uuid.toString());
assertEquals(5, uuid.version());
assertEquals(2, uuid.variant());
}
@Test
public void version_5_UUID_is_correctly_generated_for_domain_baeldung_name() {
UUID uuid = UUIDGenerator.generateType5UUID("baeldung.com");
assertEquals("efd5462b-b07a-52a3-94ea-bf575c0e0e75", uuid.toString());
assertEquals(5, uuid.version());
assertEquals(2, uuid.variant());
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.uuid;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.UUID;
import java.util.regex.Pattern;
public class UUIDValidatorUnitTest {
@Test
public void whenValidUUIDStringIsValidated_thenValidationSucceeds() {
String validUUID = "26929514-237c-11ed-861d-0242ac120002";
Assertions.assertEquals(UUID.fromString(validUUID).toString(), validUUID);
String invalidUUID = "invalid-uuid";
Assertions.assertThrows(IllegalArgumentException.class, () -> UUID.fromString(invalidUUID));
}
@Test
public void whenUUIDIsValidatedUsingRegex_thenValidationSucceeds() {
Pattern UUID_REGEX =
Pattern.compile("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");
Assertions.assertTrue(UUID_REGEX.matcher("26929514-237c-11ed-861d-0242ac120002").matches());
Assertions.assertFalse(UUID_REGEX.matcher("invalid-uuid").matches());
}
}

View File

@ -0,0 +1,6 @@
log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>

View File

@ -0,0 +1,9 @@
# Root logger
log4j.rootLogger=INFO, file, stdout
# Write to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n