From eb65ed35b1c7f82c90908c9fb7ea646ecd52a433 Mon Sep 17 00:00:00 2001 From: Fabio Lima Date: Sun, 15 Mar 2020 05:17:00 -0300 Subject: [PATCH] Updated pom.xml to use commons Removed files that are also included in f4b6a3/commons. --- .gitignore | 16 +- pom.xml | 7 +- .../com/github/f4b6a3/ulid/UlidCreator.java | 61 +-- .../UlidBasedGuidCreator.java} | 132 +++-- .../ulid/random/Xorshift128PlusRandom.java | 80 --- .../f4b6a3/ulid/random/XorshiftRandom.java | 82 --- .../github/f4b6a3/ulid/util/Base32Util.java | 507 ------------------ .../com/github/f4b6a3/ulid/util/ByteUtil.java | 258 --------- .../f4b6a3/ulid/util/FingerprintUtil.java | 177 ------ .../github/f4b6a3/ulid/util/NetworkData.java | 198 ------- .../com/github/f4b6a3/ulid/util/UlidUtil.java | 3 + .../java/com/github/f4b6a3/TestSuite.java | 10 +- .../com/github/f4b6a3/UniquenessTest.java | 24 +- .../java/com/github/f4b6a3/demo/DemoTest.java | 4 +- .../github/f4b6a3/ulid/UlidCreatorTest.java | 2 +- .../UlidBasedGuidCreatorMock.java} | 10 +- .../UlidBasedGuidCreatorTest.java} | 54 +- .../f4b6a3/ulid/random/NaiveRandomTest.java | 45 -- .../f4b6a3/ulid/util/Base32UtilTest.java | 410 -------------- .../github/f4b6a3/ulid/util/ByteUtilTest.java | 145 ----- .../github/f4b6a3/ulid/util/UlidUtilTest.java | 10 +- 21 files changed, 173 insertions(+), 2062 deletions(-) rename src/main/java/com/github/f4b6a3/ulid/{guid/GuidCreator.java => creator/UlidBasedGuidCreator.java} (71%) delete mode 100644 src/main/java/com/github/f4b6a3/ulid/random/Xorshift128PlusRandom.java delete mode 100644 src/main/java/com/github/f4b6a3/ulid/random/XorshiftRandom.java delete mode 100644 src/main/java/com/github/f4b6a3/ulid/util/Base32Util.java delete mode 100644 src/main/java/com/github/f4b6a3/ulid/util/ByteUtil.java delete mode 100644 src/main/java/com/github/f4b6a3/ulid/util/FingerprintUtil.java delete mode 100644 src/main/java/com/github/f4b6a3/ulid/util/NetworkData.java rename src/test/java/com/github/f4b6a3/ulid/{guid/GuidCreatorMock.java => creator/UlidBasedGuidCreatorMock.java} (58%) rename src/test/java/com/github/f4b6a3/ulid/{guid/GuidCreatorTest.java => creator/UlidBasedGuidCreatorTest.java} (72%) delete mode 100644 src/test/java/com/github/f4b6a3/ulid/random/NaiveRandomTest.java delete mode 100644 src/test/java/com/github/f4b6a3/ulid/util/Base32UtilTest.java delete mode 100644 src/test/java/com/github/f4b6a3/ulid/util/ByteUtilTest.java diff --git a/.gitignore b/.gitignore index d7cc4bd..0b4a50f 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,17 @@ # Maven log/ target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +# https://github.com/takari/maven-wrapper#usage-without-binary-jar +.mvn/wrapper/maven-wrapper.jar +.factorypath # Compiled class file *.class @@ -31,6 +42,5 @@ target/ # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* -# Other -release.properties -.factorypath + + diff --git a/pom.xml b/pom.xml index a9f8daa..cd92d16 100644 --- a/pom.xml +++ b/pom.xml @@ -26,12 +26,17 @@ UTF-8 - 8 + 11 ${jdk.version} ${jdk.version} + + com.github.f4b6a3 + commons + 1.0.0 + junit junit diff --git a/src/main/java/com/github/f4b6a3/ulid/UlidCreator.java b/src/main/java/com/github/f4b6a3/ulid/UlidCreator.java index ef51584..2219c21 100644 --- a/src/main/java/com/github/f4b6a3/ulid/UlidCreator.java +++ b/src/main/java/com/github/f4b6a3/ulid/UlidCreator.java @@ -26,8 +26,8 @@ package com.github.f4b6a3.ulid; import java.util.UUID; +import com.github.f4b6a3.ulid.creator.UlidBasedGuidCreator; import com.github.f4b6a3.ulid.exception.UlidCreatorException; -import com.github.f4b6a3.ulid.guid.GuidCreator; /** * A factory for Universally Unique Lexicographically Sortable Identifiers. @@ -39,31 +39,13 @@ public class UlidCreator { private UlidCreator() { } - /** - * Returns a ULID. - * - * @return a ULID - */ - public static String getUlid() { - return GuidCreatorLazyHolder.INSTANCE.createUlid(); - } - - /** - * Returns a fast ULID. - * - * @return a ULID - */ - public static String getFastUlid() { - return FastGuidCreatorLazyHolder.INSTANCE.createUlid(); - } - /** * Returns ULID as GUID object. * * @return a GUID */ - public static UUID getGuid() { - return GuidCreatorLazyHolder.INSTANCE.create(); + public static UUID getUlid() { + return GuidCreatorLazyHolder.INSTANCE.createGuid(); } /** @@ -71,47 +53,48 @@ public class UlidCreator { * * @return a GUID */ - public static UUID getFastGuid() { - return FastGuidCreatorLazyHolder.INSTANCE.create(); + public static UUID getFastUlid() { + return FastGuidCreatorLazyHolder.INSTANCE.createGuid(); } /** - * Returns ULID as byte sequence. + * Returns a ULID. * - * @return a GUID + * @return a ULID */ - public static byte[] getBytes() { - return GuidCreatorLazyHolder.INSTANCE.createBytes(); + public static String getUlidString() { + return GuidCreatorLazyHolder.INSTANCE.createString(); } /** - * Returns fast ULID as byte sequence. + * Returns a fast ULID. * - * @return a GUID + * @return a ULID */ - public static byte[] getFastBytes() { - return FastGuidCreatorLazyHolder.INSTANCE.createBytes(); + public static String getFastUlidString() { + return FastGuidCreatorLazyHolder.INSTANCE.createString(); } /** * Return a GUID creator for direct use. * - * This library uses the {@link GuidCreator} internally to generate ULIDs. + * This library uses the {@link UlidBasedGuidCreator} internally to generate + * ULIDs. * - * The {@link GuidCreator} throws a {@link UlidCreatorException} when too - * many values are requested in the same millisecond. + * The {@link UlidBasedGuidCreator} throws a {@link UlidCreatorException} when + * too many values are requested in the same millisecond. * - * @return a {@link GuidCreator} + * @return a {@link UlidBasedGuidCreator} */ - public static GuidCreator getGuidCreator() { - return new GuidCreator(); + public static UlidBasedGuidCreator getGuidCreator() { + return new UlidBasedGuidCreator(); } private static class GuidCreatorLazyHolder { - static final GuidCreator INSTANCE = getGuidCreator(); + static final UlidBasedGuidCreator INSTANCE = getGuidCreator(); } private static class FastGuidCreatorLazyHolder { - static final GuidCreator INSTANCE = getGuidCreator().withFastRandomGenerator(); + static final UlidBasedGuidCreator INSTANCE = getGuidCreator().withFastRandomGenerator(); } } diff --git a/src/main/java/com/github/f4b6a3/ulid/guid/GuidCreator.java b/src/main/java/com/github/f4b6a3/ulid/creator/UlidBasedGuidCreator.java similarity index 71% rename from src/main/java/com/github/f4b6a3/ulid/guid/GuidCreator.java rename to src/main/java/com/github/f4b6a3/ulid/creator/UlidBasedGuidCreator.java index df3f714..a8e4b64 100644 --- a/src/main/java/com/github/f4b6a3/ulid/guid/GuidCreator.java +++ b/src/main/java/com/github/f4b6a3/ulid/creator/UlidBasedGuidCreator.java @@ -22,18 +22,18 @@ * SOFTWARE. */ -package com.github.f4b6a3.ulid.guid; +package com.github.f4b6a3.ulid.creator; -import java.security.SecureRandom; import java.util.Random; import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; import com.github.f4b6a3.ulid.timestamp.TimestampStrategy; -import com.github.f4b6a3.ulid.util.FingerprintUtil; import com.github.f4b6a3.ulid.util.UlidUtil; +import com.github.f4b6a3.commons.random.Xorshift128PlusRandom; +import com.github.f4b6a3.commons.util.FingerprintUtil; +import com.github.f4b6a3.commons.util.RandomUtil; import com.github.f4b6a3.ulid.exception.UlidCreatorException; -import com.github.f4b6a3.ulid.random.Xorshift128PlusRandom; -import com.github.f4b6a3.ulid.random.XorshiftRandom; import com.github.f4b6a3.ulid.timestamp.DefaultTimestampStrategy; /** @@ -42,7 +42,7 @@ import com.github.f4b6a3.ulid.timestamp.DefaultTimestampStrategy; * * ULID specification: https://github.com/ulid/spec */ -public class GuidCreator { +public class UlidBasedGuidCreator { protected long randomMsb = 0; protected long randomLsb = 0; @@ -57,11 +57,13 @@ public class GuidCreator { protected Random random; + protected boolean useThreadLocal = false; + protected static final String OVERRUN_MESSAGE = "The system overran the generator by requesting too many GUIDs."; protected TimestampStrategy timestampStrategy; - public GuidCreator() { + public UlidBasedGuidCreator() { this.reset(); this.timestampStrategy = new DefaultTimestampStrategy(); } @@ -81,8 +83,8 @@ public class GuidCreator { * The random part is reset to a new value every time the millisecond part * changes. * - * If more than one GUID is generated within the same millisecond, the - * random part is incremented by one. + * If more than one GUID is generated within the same millisecond, the random + * part is incremented by one. * * The maximum GUIDs that can be generated per millisecond is 2^80. * @@ -97,33 +99,32 @@ public class GuidCreator { * * ##### Randomness * - * It is a 80 bits integer. Cryptographically secure source of randomness, - * if possible. + * It is a 80 bits integer. Cryptographically secure source of randomness, if + * possible. * * #### Sorting * - * The left-most character must be sorted first, and the right-most - * character sorted last (lexical order). The default ASCII character set - * must be used. Within the same millisecond, sort order is not guaranteed. + * The left-most character must be sorted first, and the right-most character + * sorted last (lexical order). The default ASCII character set must be used. + * Within the same millisecond, sort order is not guaranteed. * * #### Monotonicity * * When generating a ULID within the same millisecond, we can provide some - * guarantees regarding sort order. Namely, if the same millisecond is - * detected, the random component is incremented by 1 bit in the least - * significant bit position (with carrying). + * guarantees regarding sort order. Namely, if the same millisecond is detected, + * the random component is incremented by 1 bit in the least significant bit + * position (with carrying). * - * If, in the extremely unlikely event that, you manage to generate more - * than 2^80 ULIDs within the same millisecond, or cause the random - * component to overflow with less, the generation will fail. + * If, in the extremely unlikely event that, you manage to generate more than + * 2^80 ULIDs within the same millisecond, or cause the random component to + * overflow with less, the generation will fail. * * @return {@link UUID} a UUID value * - * @throws UlidCreatorException - * an overrun exception if too many requests are made within the - * same millisecond. + * @throws UlidCreatorException an overrun exception if too many requests are + * made within the same millisecond. */ - public synchronized UUID create() { + public synchronized UUID createGuid() { final long timestamp = this.getTimestamp(); @@ -141,21 +142,11 @@ public class GuidCreator { * * @return a ULID string */ - public synchronized String createUlid() { - UUID guid = create(); + public synchronized String createString() { + UUID guid = createGuid(); return UlidUtil.fromUuidToUlid(guid); } - /** - * Return a ULID as byte sequence. - * - * @return a byte sequence - */ - public synchronized byte[] createBytes() { - UUID guid = create(); - return UlidUtil.fromUuidToBytes(guid); - } - /** * Return the current timestamp and resets or increments the random part. * @@ -181,9 +172,12 @@ public class GuidCreator { protected synchronized void reset() { // Get random values - if (random == null) { - this.randomMsb = truncate(SecureRandomLazyHolder.INSTANCE.nextLong()); - this.randomLsb = truncate(SecureRandomLazyHolder.INSTANCE.nextLong()); + if (useThreadLocal) { + this.randomMsb = truncate(ThreadLocalRandom.current().nextLong()); + this.randomLsb = truncate(ThreadLocalRandom.current().nextLong()); + } else if (random == null) { + this.randomMsb = truncate(RandomUtil.get().nextLong()); + this.randomLsb = truncate(RandomUtil.get().nextLong()); } else { this.randomMsb = truncate(random.nextLong()); this.randomLsb = truncate(random.nextLong()); @@ -199,8 +193,7 @@ public class GuidCreator { * * An exception is thrown when more than 2^80 increment operations are made. * - * @throws UlidCreatorException - * if an overrun happens. + * @throws UlidCreatorException if an overrun happens. */ protected synchronized void increment() { @@ -213,12 +206,11 @@ public class GuidCreator { /** * Used for changing the timestamp strategy. * - * @param timestampStrategy - * a timestamp strategy - * @return {@link GuidCreator} + * @param timestampStrategy a timestamp strategy + * @return {@link UlidBasedGuidCreator} */ @SuppressWarnings("unchecked") - public synchronized T withTimestampStrategy(TimestampStrategy timestampStrategy) { + public synchronized T withTimestampStrategy(TimestampStrategy timestampStrategy) { this.timestampStrategy = timestampStrategy; return (T) this; } @@ -229,18 +221,22 @@ public class GuidCreator { * * The default random generator is {@link java.security.SecureRandom}. * - * For other faster pseudo-random generators, see {@link XorshiftRandom} and - * its variations. + * For other faster pseudo-random generators, see {@link XorshiftRandom} and its + * variations. * * See {@link Random}. * - * @param random - * a random generator - * @return {@link GuidCreator} + * @param random a random generator + * @return {@link UlidBasedGuidCreator} */ @SuppressWarnings("unchecked") - public synchronized T withRandomGenerator(Random random) { + public synchronized T withRandomGenerator(Random random) { + this.random = random; + + // disable thread local + this.useThreadLocal = false; + return (T) this; } @@ -253,20 +249,42 @@ public class GuidCreator { * See {@link Xorshift128PlusRandom} and * {@link FingerprintUtil#getFingerprint()} * - * @return {@link GuidCreator} + * @return {@link UlidBasedGuidCreator} */ @SuppressWarnings("unchecked") - public synchronized T withFastRandomGenerator() { + public synchronized T withFastRandomGenerator() { + final int salt = (int) FingerprintUtil.getFingerprint(); this.random = new Xorshift128PlusRandom(salt); + + // disable thread local + this.useThreadLocal = false; + + return (T) this; + } + + /** + * Replaces the default random generator with ThreadLocalRandom. + * + * See {@link java.util.concurrent.ThreadLocalRandom} + * + * @return {@link RandomUuidCreator} + */ + @SuppressWarnings("unchecked") + public synchronized T withThreadLocalRandomGenerator() { + + this.useThreadLocal = true; + + // remove random instance + this.random = null; + return (T) this; } /** * Truncate long to half random component. * - * @param value - * a value to be truncated. + * @param value a value to be truncated. * @return truncated value */ protected synchronized long truncate(final long value) { @@ -286,8 +304,4 @@ public class GuidCreator { protected long extractRandomMsb(UUID uuid) { return ((uuid.getMostSignificantBits() & 0xffff) << 24) | (uuid.getLeastSignificantBits() >>> 40); } - - private static class SecureRandomLazyHolder { - static final Random INSTANCE = new SecureRandom(); - } } diff --git a/src/main/java/com/github/f4b6a3/ulid/random/Xorshift128PlusRandom.java b/src/main/java/com/github/f4b6a3/ulid/random/Xorshift128PlusRandom.java deleted file mode 100644 index de19962..0000000 --- a/src/main/java/com/github/f4b6a3/ulid/random/Xorshift128PlusRandom.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2020 Fabio Lima - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.github.f4b6a3.ulid.random; - -import java.util.Random; - -/** - * A subclass of {@link java.util.Random} that implements the Xorshift 128 Plus - * random number generator. - * - * https://en.wikipedia.org/wiki/Xorshift - * - */ -public class Xorshift128PlusRandom extends Random { - - private static final long serialVersionUID = -7271232011767476928L; - - long[] seed = new long[2]; - private static int count; - - public Xorshift128PlusRandom() { - this((int) System.nanoTime()); - } - - /** - * Constructor that receives an integer as 'salt'. This value is combined - * with the current milliseconds and the object hash code to generate two - * seeds. - * - * @param salt - * a number used to generate two seeds. - */ - public Xorshift128PlusRandom(int salt) { - long time = System.currentTimeMillis() + count++; - long hash = (long) this.hashCode(); - this.seed[0] = (((long) salt) << 32) | (time & 0x00000000ffffffffL); - this.seed[1] = (((long) salt) << 32) | (hash & 0x00000000ffffffffL); - } - - public Xorshift128PlusRandom(long[] seed) { - this.seed = seed; - } - - @Override - protected int next(int bits) { - return (int) (nextLong() >>> (64 - bits)); - } - - @Override - public long nextLong() { - long x = seed[0]; - final long y = seed[1]; - seed[0] = y; - x ^= x << 23; // a - seed[1] = x ^ y ^ (x >>> 17) ^ (y >>> 26); // b, c - return seed[1] + y; - } -} \ No newline at end of file diff --git a/src/main/java/com/github/f4b6a3/ulid/random/XorshiftRandom.java b/src/main/java/com/github/f4b6a3/ulid/random/XorshiftRandom.java deleted file mode 100644 index 7a89cb1..0000000 --- a/src/main/java/com/github/f4b6a3/ulid/random/XorshiftRandom.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018-2020 Fabio Lima - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.github.f4b6a3.ulid.random; - -import java.util.Random; - -/** - * A subclass of {@link java.util.Random} that implements the Xorshift random - * number generator. - * - * https://en.wikipedia.org/wiki/Xorshift - * - * Reference: - * - * George Marsaglia. 2003. Xorshift RNGs. Journal of Statistical Software 8, 14 - * (2003), 1–6. https://www.jstatsoft.org/article/view/v008i14 - * - */ -public class XorshiftRandom extends Random { - - private static final long serialVersionUID = 5084310156945573858L; - - private long seed; - private static int count; - - public XorshiftRandom() { - this((int) System.nanoTime()); - } - - /** - * Constructor that receives an integer as 'salt'. This value is combined - * with the current milliseconds to generate the seed. - * - * @param salt - * a number used to generate the seed. - */ - public XorshiftRandom(int salt) { - long time = System.currentTimeMillis() + count++; - this.seed = (((long) salt) << 32) | (time & 0x00000000ffffffffL); - } - - public XorshiftRandom(long seed) { - this.seed = seed; - } - - @Override - protected int next(int bits) { - return (int) (nextLong() >>> (64 - bits)); - } - - @Override - public long nextLong() { - long x = this.seed; - x ^= (x << 13); - x ^= (x >>> 7); - x ^= (x << 17); - this.seed = x; - return x; - } -} \ No newline at end of file diff --git a/src/main/java/com/github/f4b6a3/ulid/util/Base32Util.java b/src/main/java/com/github/f4b6a3/ulid/util/Base32Util.java deleted file mode 100644 index eeec394..0000000 --- a/src/main/java/com/github/f4b6a3/ulid/util/Base32Util.java +++ /dev/null @@ -1,507 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2020 Fabio Lima - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.github.f4b6a3.ulid.util; - -import java.math.BigInteger; -import java.nio.charset.StandardCharsets; - -/** - * - * This class contain static methods for encoding to and from Base 32. - * - * Supported alphabets: base32, base32hex, zbase32 and crockford base32. - * - * RFC-4648: https://tools.ietf.org/html/rfc4648 - * - * Wikipedia: https://en.wikipedia.org/wiki/Base32 - * - */ -public class Base32Util { - - public static final String ALPHABET_BASE_32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; - public static final String ALPHABET_BASE_32_HEX = "0123456789ABCDEFGHIJKLMNOPQRSTUV"; - public static final String ALPHABET_BASE_32_Z = "ybndrfg8ejkmcpqxot1uwisza345h769"; - public static final String ALPHABET_BASE_32_CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; - - private static final char[] _ALPHABET_BASE_32 = ALPHABET_BASE_32.toCharArray(); - private static final char[] _ALPHABET_BASE_32_HEX = ALPHABET_BASE_32_HEX.toCharArray(); - private static final char[] _ALPHABET_BASE_32_Z = ALPHABET_BASE_32_Z.toCharArray(); - private static final char[] _ALPHABET_BASE_32_CROCKFORD = ALPHABET_BASE_32_CROCKFORD.toCharArray(); - - private static final int[] PADDING_ENCODE = { 0, 6, 4, 3, 1 }; - private static final int[] PADDING_DECODE = { 0, 4, 4, 3, 3, 2, 2, 1 }; - - private static final int BASE = 32; - - private Base32Util() { - } - - // ---------------------- - // Base 32 - // ---------------------- - - public static String toBase32(long number) { - return encodeLong(number, _ALPHABET_BASE_32); - } - - public static String toBase32(BigInteger number) { - return encodeBigInteger(number, _ALPHABET_BASE_32); - } - - public static String toBase32(byte[] bytes) { - return encode(bytes, _ALPHABET_BASE_32, '='); - } - - public static String toBase32(String string) { - return toBase32(toBytes(string)); - } - - public static byte[] fromBase32(String string) { - return decode(normalize(string), _ALPHABET_BASE_32, '='); - } - - public static String fromBase32AsString(String string) { - return toString(fromBase32(string)); - } - - public static long fromBase32AsLong(String string) { - return decodeLong(normalize(string), _ALPHABET_BASE_32); - } - - public static BigInteger fromBase32AsBigInteger(String string) { - return decodeBigInteger(normalize(string), _ALPHABET_BASE_32); - } - - // ---------------------- - // Base 32 Hex - // ---------------------- - - public static String toBase32Hex(long number) { - return encodeLong(number, _ALPHABET_BASE_32_HEX); - } - - public static String toBase32Hex(BigInteger number) { - return encodeBigInteger(number, _ALPHABET_BASE_32_HEX); - } - - public static String toBase32Hex(byte[] bytes) { - return encode(bytes, _ALPHABET_BASE_32_HEX, '='); - } - - public static String toBase32Hex(String string) { - return toBase32Hex(toBytes(string)); - } - - public static byte[] fromBase32Hex(String string) { - return decode(normalize(string), _ALPHABET_BASE_32_HEX, '='); - } - - public static String fromBase32HexAsString(String string) { - return toString(fromBase32Hex(string)); - } - - public static long fromBase32HexAsLong(String string) { - return decodeLong(normalize(string), _ALPHABET_BASE_32_HEX); - } - - public static BigInteger fromBase32HexAsBigInteger(String string) { - return decodeBigInteger(normalize(string), _ALPHABET_BASE_32_HEX); - } - - // ---------------------- - // Base 32 Crockford - // ---------------------- - - public static String toBase32Crockford(long number) { - return encodeLong(number, _ALPHABET_BASE_32_CROCKFORD); - } - - public static String toBase32Crockford(BigInteger number) { - return encodeBigInteger(number, _ALPHABET_BASE_32_CROCKFORD); - } - - public static String toBase32Crockford(byte[] bytes) { - return encode(bytes, _ALPHABET_BASE_32_CROCKFORD, null); - } - - public static String toBase32Crockford(String string) { - return toBase32Crockford(toBytes(string)); - } - - public static byte[] fromBase32Crockford(String string) { - return decode(normalizeCrockford(string), _ALPHABET_BASE_32_CROCKFORD, null); - } - - public static String fromBase32CrockfordAsString(String string) { - return toString(fromBase32Crockford(string)); - } - - public static long fromBase32CrockfordAsLong(String string) { - return decodeLong(normalizeCrockford(string), _ALPHABET_BASE_32_CROCKFORD); - } - - public static BigInteger fromBase32CrockfordAsBigInteger(String string) { - return decodeBigInteger(normalizeCrockford(string), _ALPHABET_BASE_32_CROCKFORD); - } - - // ---------------------- - // Z Base 32 Z - // ---------------------- - - public static String toBase32Z(long number) { - return encodeLong(number, _ALPHABET_BASE_32_Z); - } - - public static String toBase32Z(BigInteger number) { - return encodeBigInteger(number, _ALPHABET_BASE_32_Z); - } - - public static String toBase32Z(byte[] bytes) { - return encode(bytes, _ALPHABET_BASE_32_Z, null); - } - - public static String toBase32Z(String string) { - return toBase32Z(toBytes(string)); - } - - public static byte[] fromBase32Z(String string) { - return decode(normalizeZ(string), _ALPHABET_BASE_32_Z, null); - } - - public static String fromBase32ZAsString(String string) { - return toString(fromBase32Z(string)); - } - - public static long fromBase32ZAsLong(String string) { - return decodeLong(normalizeZ(string), _ALPHABET_BASE_32_Z); - } - - public static BigInteger fromBase32ZAsBigInteger(String string) { - return decodeBigInteger(normalizeZ(string), _ALPHABET_BASE_32_Z); - } - - // ---------------------- - // Utils - // ---------------------- - - /** - * Convert a string to an array of bytes using UTF-8. - * - * @param string a string - * @return a string - */ - public static byte[] toBytes(String string) { - return string.getBytes(StandardCharsets.UTF_8); - } - - /** - * Convert an array of bytes to a string using UTF-8. - * - * @param bytes a byte sequence - * @return a string - */ - public static String toString(byte[] bytes) { - return new String(bytes, StandardCharsets.UTF_8); - } - - // ---------------------- - // Encoder and Decoder - // ---------------------- - - /** - * Encode a long number to base 32 string. - * - * @param number - * a long number - * @param alphabet - * an alphabet - * @return a base32 encoded string - */ - public static String encodeLong(long number, char[] alphabet) { - - long n = number; - StringBuilder builder = new StringBuilder(); - - while (n > 0) { - builder.append(alphabet[(int) (n % BASE)]); - n = n / BASE; - } - - return builder.reverse().toString(); - } - - /** - * Encode a BigInteger to base 32 string. - * - * @param number - * a BigInteger - * @param alphabet - * an alphabet - * @return a base32 encoded string - */ - public static String encodeBigInteger(BigInteger number, char[] alphabet) { - - BigInteger n = number; - BigInteger b = BigInteger.valueOf(BASE); - - StringBuilder builder = new StringBuilder(); - - while (n.compareTo(BigInteger.ZERO) > 0) { - builder.append(alphabet[n.remainder(b).intValue()]); - n = n.divide(b); - } - - return builder.reverse().toString(); - } - - /** - * Decode a base 32 string to a long number. - * - * @param string - * a base 32 encoded string - * @param alphabet - * an alphabet - * @return a long number - */ - public static long decodeLong(String string, char[] alphabet) { - - long n = 0; - - for (char c : string.toCharArray()) { - int d = map(c, alphabet); - n = BASE * n + d; - } - - return n; - } - - /** - * Decode a base 32 string to a BigInteger. - * - * @param string - * a base 32 encoded string - * @param alphabet - * an alphabet - * @return a BigInteger - */ - public static BigInteger decodeBigInteger(String string, char[] alphabet) { - - BigInteger n = BigInteger.ZERO; - BigInteger b = BigInteger.valueOf(BASE); - - for (char c : string.toCharArray()) { - int d = map(c, alphabet); - n = b.multiply(n).add(BigInteger.valueOf(d)); - } - - return n; - } - - /** - * Encode an array of bytes into a base 32 string. - * - * @param bytes - * an array of bytes - * @param alphabet - * an alphabet - * @param padding - * a padding char, if necessary - * @return a base 32 encoded string - */ - public static String encode(byte[] bytes, char[] alphabet, Character padding) { - - if (bytes == null || bytes.length == 0) { - return ""; - } - - int div = bytes.length / 5; - int mod = bytes.length % 5; - - int blocks = (div + (mod == 0 ? 0 : 1)); - - byte[] input = new byte[5 * blocks]; - char[] output = new char[8 * blocks]; - - System.arraycopy(bytes, 0, input, 0, bytes.length); - - for (int i = 0; i < blocks; i++) { - byte[] blk = new byte[5]; - System.arraycopy(input, i * 5, blk, 0, 5); - - int[] out = new int[8]; - - out[0] = ((blk[0] & 0b11111000) >>> 3); - out[1] = ((blk[0] & 0b00000111) << 2) | ((blk[1] & 0b11000000) >>> 6); - out[2] = ((blk[1] & 0b00111110) >>> 1); - out[3] = ((blk[1] & 0b00000001) << 4) | ((blk[2] & 0b11110000) >>> 4); - out[4] = ((blk[2] & 0b00001111) << 1) | ((blk[3] & 0b10000000) >>> 7); - out[5] = ((blk[3] & 0b01111100) >>> 2); - out[6] = ((blk[3] & 0b00000011) << 3) | ((blk[4] & 0b11100000) >>> 5); - out[7] = (blk[4] & 0b00011111); - - char[] chars = new char[8]; - for (int j = 0; j < 8; j++) { - chars[j] = alphabet[out[j]]; - } - - System.arraycopy(chars, 0, output, i * 8, 8); - } - - int outputSize = output.length - PADDING_ENCODE[mod]; - if (padding != null) { - // Add padding: '=' - for (int i = outputSize; i < output.length; i++) { - output[i] = padding; - } - } else { - // Remove padding - char[] temp = new char[outputSize]; - System.arraycopy(output, 0, temp, 0, outputSize); - output = temp; - } - - return new String(output); - } - - /** - * Decode a base 32 string into an byte array. - * - * @param string - * a base 32 encoded string - * @param alphabet - * an alphabet - * @param padding - * a padding char, if necessary - * @return a byte array - */ - public static byte[] decode(String string, char[] alphabet, Character padding) { - - if (string == null || string.length() == 0) { - return new byte[0]; - } - - char[] chars = null; - char[] alph = alphabet; - - if (padding != null) { - chars = string.replaceAll(padding.toString(), "").toCharArray(); - } else { - chars = string.toCharArray(); - } - - validate(chars, alph); - - int div = chars.length / 8; - int mod = chars.length % 8; - int size = (div + (mod == 0 ? 0 : 1)); - - char[] input = new char[8 * size]; - byte[] output = new byte[5 * size]; - - System.arraycopy(chars, 0, input, 0, chars.length); - - for (int i = 0; i < size; i++) { - char[] blk = new char[8]; - System.arraycopy(input, i * 8, blk, 0, 8); - - byte[] out = new byte[5]; - - out[0] = (byte) ((map(blk[0], alph) << 3) | (map(blk[1], alph) >>> 2)); - out[1] = (byte) ((map(blk[1], alph) << 6) | (map(blk[2], alph) << 1) | (map(blk[3], alph) >>> 4)); - out[2] = (byte) ((map(blk[3], alph) << 4) | (map(blk[4], alph) >>> 1)); - out[3] = (byte) ((map(blk[4], alph) << 7) | (map(blk[5], alph) << 2) | (map(blk[6], alph) >>> 3)); - out[4] = (byte) ((map(blk[6], alph) << 5) | (map(blk[7], alph))); - - System.arraycopy(out, 0, output, i * 5, 5); - - } - - // Remove padding - int outputSize = output.length - PADDING_DECODE[mod]; - byte[] temp = new byte[outputSize]; - System.arraycopy(output, 0, temp, 0, outputSize); - output = temp; - - return output; - } - - protected static void validate(char[] chars, char[] alphabet) { - for (int i = 0; i < chars.length; i++) { - boolean found = false; - for (int j = 0; j < alphabet.length; j++) { - if (chars[i] == alphabet[j]) { - found = true; - break; - } - } - if (!found) { - throw new Base32UtilException("Invalid character"); - } - } - } - - private static int map(char c, char[] alphabet) { - for (int i = 0; i < alphabet.length; i++) { - if (alphabet[i] == c) { - return (byte) i; - } - } - return (byte) '0'; - } - - protected static String normalize(String string) { - if (string == null) { - return ""; - } - return string.toUpperCase(); - } - - protected static String normalizeZ(String string) { - if (string == null) { - return ""; - } - return string.toLowerCase(); - } - - protected static String normalizeCrockford(String string) { - if (string == null) { - return ""; - } - String normalized = string.toUpperCase(); - normalized = normalized.replaceAll("-", ""); - normalized = normalized.replaceAll("I", "1"); - normalized = normalized.replaceAll("L", "1"); - normalized = normalized.replaceAll("O", "0"); - return normalized; - } - - public static class Base32UtilException extends RuntimeException { - private static final long serialVersionUID = 1L; - - public Base32UtilException(String message) { - super(message); - } - } -} \ No newline at end of file diff --git a/src/main/java/com/github/f4b6a3/ulid/util/ByteUtil.java b/src/main/java/com/github/f4b6a3/ulid/util/ByteUtil.java deleted file mode 100644 index 25b03ab..0000000 --- a/src/main/java/com/github/f4b6a3/ulid/util/ByteUtil.java +++ /dev/null @@ -1,258 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2020 Fabio Lima - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.github.f4b6a3.ulid.util; - -/** - * Class that contains many static methods for byte handling. - */ -public class ByteUtil { - - private ByteUtil() { - } - - /** - * Get a number from a given hexadecimal string. - * - * @param hexadecimal a string - * @return a long - */ - public static long toNumber(final String hexadecimal) { - return toNumber(toBytes(hexadecimal)); - } - - /** - * Get a number from a given array of bytes. - * - * @param bytes a byte array - * @return a long - */ - public static long toNumber(final byte[] bytes) { - return toNumber(bytes, 0, bytes.length); - } - - public static long toNumber(final byte[] bytes, final int start, final int end) { - long result = 0; - for (int i = start; i < end; i++) { - result = (result << 8) | (bytes[i] & 0xff); - } - return result; - } - - /** - * Get an array of bytes from a given number. - * - * @param number a long value - * @return a byte array - */ - public static byte[] toBytes(final long number) { - return new byte[] { - (byte) (number >>> 56), - (byte) (number >>> 48), - (byte) (number >>> 40), - (byte) (number >>> 32), - (byte) (number >>> 24), - (byte) (number >>> 16), - (byte) (number >>> 8), - (byte) (number) - }; - } - - /** - * Get an array of bytes from a given hexadecimal string. - * - * @param hexadecimal a string - * @return a byte array - */ - public static byte[] toBytes(final String hexadecimal) { - final int length = hexadecimal.length(); - byte[] bytes = new byte[length / 2]; - for (int i = 0; i < length; i += 2) { - bytes[i / 2] = (byte) ((fromHexChar(hexadecimal.charAt(i)) << 4) | fromHexChar(hexadecimal.charAt(i + 1))); - } - return bytes; - } - - /** - * Get a hexadecimal string from given array of bytes. - * - * @param bytes byte array - * @return a string - */ - public static String toHexadecimal(final byte[] bytes) { - final int length = bytes.length; - final char[] hexadecimal = new char[length * 2]; - for (int i = 0; i < length; i++) { - final int v = bytes[i] & 0xFF; - hexadecimal[i * 2] = toHexChar(v >>> 4); - hexadecimal[(i * 2) + 1] = toHexChar(v & 0x0F); - } - return new String(hexadecimal); - } - - /** - * Get a hexadecimal string from given number. - * - * @param number an integer - * @return a string - */ - public static String toHexadecimal(final long number) { - return toHexadecimal(toBytes(number)); - } - - /** - * Get a number value from a hexadecimal char. - * - * @param chr a character - * @return an integer - */ - public static int fromHexChar(final char chr) { - - if (chr >= 0x61 && chr <= 0x66) { - // ASCII codes from 'a' to 'f' - return (int) chr - 0x57; - } else if (chr >= 0x41 && chr <= 0x46) { - // ASCII codes from 'A' to 'F' - return (int) chr - 0x37; - } else if (chr >= 0x30 && chr <= 0x39) { - // ASCII codes from 0 to 9 - return (int) chr - 0x30; - } - - return 0; - } - - /** - * Get a hexadecimal from a number value. - * - * @param number an integer - * @return a char - */ - public static char toHexChar(final int number) { - if (number >= 0x0a && number <= 0x0f) { - // ASCII codes from 'a' to 'f' - return (char) (0x57 + number); - } else if (number >= 0x00 && number <= 0x09) { - // ASCII codes from 0 to 9 - return (char) (0x30 + number); - } - return 0; - } - - /** - * Get a new array with a specific length and filled with a byte value. - * - * @param length array size - * @param value byte value - * @return a byte array - */ - public static byte[] array(final int length, final byte value) { - final byte[] result = new byte[length]; - for (int i = 0; i < length; i++) { - result[i] = value; - } - return result; - } - - /** - * Copy an entire array. - * - * @param bytes byte array - * @return a byte array - */ - public static byte[] copy(final byte[] bytes) { - return copy(bytes, 0, bytes.length); - } - - /** - * Copy part of an array. - * - * @param bytes byte array - * @param start start position - * @param end end position - * @return a byte array - */ - public static byte[] copy(final byte[] bytes, final int start, final int end) { - final int length = end - start; - final byte[] result = new byte[length]; - System.arraycopy(bytes, start, result, 0, length); - return result; - } - - /** - * Concatenates two byte arrays. - * - * @param bytes1 byte array 1 - * @param bytes2 byte array 2 - * @return a byte array - */ - public static byte[] concat(final byte[] bytes1, final byte[] bytes2) { - final byte[] result = new byte[bytes1.length + bytes2.length]; - System.arraycopy(bytes1, 0, result, 0, bytes1.length); - System.arraycopy(bytes2, 0, result, bytes1.length, bytes2.length); - return result; - } - - /** - * Replace part of an array of bytes with another subarray of bytes and - * starting from a given index. - * - * @param bytes byte array - * @param replacement replacement byte array - * @param index start position - * @return a byte array - */ - public static byte[] replace(final byte[] bytes, final byte[] replacement, final int index) { - - byte[] result = new byte[bytes.length]; - - for (int i = 0; i < index; i++) { - result[i] = bytes[i]; - } - - for (int i = 0; i < replacement.length; i++) { - result[index + i] = replacement[i]; - } - return result; - } - - /** - * Check if two arrays of bytes are equal. - * - * @param bytes1 byte array 1 - * @param bytes2 byte array 2 - * @return a boolean - */ - public static boolean equalArrays(final byte[] bytes1, final byte[] bytes2) { - if (bytes1.length != bytes2.length) { - return false; - } - for (int i = 0; i < bytes1.length; i++) { - if (bytes1[i] != bytes2[i]) { - return false; - } - } - return true; - } -} diff --git a/src/main/java/com/github/f4b6a3/ulid/util/FingerprintUtil.java b/src/main/java/com/github/f4b6a3/ulid/util/FingerprintUtil.java deleted file mode 100644 index 6de9aaf..0000000 --- a/src/main/java/com/github/f4b6a3/ulid/util/FingerprintUtil.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2020 Fabio Lima - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.github.f4b6a3.ulid.util; - -import java.nio.charset.Charset; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.List; -import java.util.Locale; -import java.util.TimeZone; - -public class FingerprintUtil { - - private static MessageDigest messageDigest; - - private FingerprintUtil() { - } - - /** - * Returns long value representing a host fingerprint. - * - * The fingerprint is calculated from a list of system properties: OS + JVM - * + network details + system resources + locale + timezone. - * - * It uses these information to generate the fingerprint: operating system - * (name, version, arch), java virtual machine (vendor, version, runtime, - * VM), network settings (IP, MAC, host name, domain name), system resources - * (CPU cores, memory), locale (language, charset) and timezone. These - * information are concatenated and passed to a SHA-256 message digest. - * - * It returns the last 8 bytes of the resulting hash as long value. - * - * Read: https://en.wikipedia.org/wiki/Device_fingerprint - * - * @return a fingerprint as long value - */ - public static long getFingerprint() { - String hash = getSystemDataHash(); - return ByteUtil.toNumber(hash); - } - - /** - * Returns a SHA-256 hash string generated from all the system data: OS + - * JVM + network details + system resources. - * - * @return a string - */ - protected static String getSystemDataHash() { - - if (messageDigest == null) { - messageDigest = getMessageDigest(); - } - - String os = getOperatingSystem(); - String jvm = getJavaVirtualMachine(); - String net = getNetwork(); - String loc = getLocalization(); - String res = getResources(); - String string = String.join(" ", os, jvm, net, loc, res); - - byte[] bytes = string.getBytes(); - byte[] hash = messageDigest.digest(bytes); - - return ByteUtil.toHexadecimal(hash); - } - - /** - * Returns a string of the OS details. - * - * @return a string - */ - protected static String getOperatingSystem() { - String name = System.getProperty("os.name"); - String version = System.getProperty("os.version"); - String arch = System.getProperty("os.arch"); - return String.join(" ", name, version, arch); - } - - /** - * Returns a string of the JVM details. - * - * @return a string - */ - protected static String getJavaVirtualMachine() { - String vendor = System.getProperty("java.vendor"); - String version = System.getProperty("java.version"); - String rtName = System.getProperty("java.runtime.name"); - String rtVersion = System.getProperty("java.runtime.version"); - String vmName = System.getProperty("java.vm.name"); - String vmVersion = System.getProperty("java.vm.version"); - return String.join(" ", vendor, version, rtName, rtVersion, vmName, vmVersion); - } - - /** - * Return a string with locale, charset, encoding and timezone. - * - * @return a string - */ - protected static String getLocalization() { - String locale = Locale.getDefault().toString(); - String charset = Charset.defaultCharset().toString(); - String encoding = System.getProperty("file.encoding"); - String timezone = TimeZone.getDefault().getID(); - return String.join(" ", locale, charset, encoding, timezone); - } - - /** - * Returns a string of CPU cores and maximum memory available. - * - * @return a string - */ - protected static String getResources() { - int procs = Runtime.getRuntime().availableProcessors(); - long memory = Runtime.getRuntime().maxMemory(); - return String.join(" ", procs + " processors", memory + " bytes"); - } - - /** - * Returns a string of the network details. - * - * It's done in three two steps: - * - * 1. it tries to find the network data associated with the host name; - * - * 2. otherwise, it iterates through all interfaces to return the first one - * that is up and running. - * - * @return a string - */ - protected static String getNetwork() { - - NetworkData networkData = NetworkData.getNetworkData(); - - if (networkData == null) { - List networkDataList = NetworkData.getNetworkDataList(); - if (networkDataList != null && !networkDataList.isEmpty()) { - networkData = networkDataList.get(0); - } - } - - if (networkData == null) { - return null; - } - - return networkData.toString(); - } - - private static MessageDigest getMessageDigest() { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException e) { - throw new InternalError("Message digest algorithm not supported.", e); - } - } -} diff --git a/src/main/java/com/github/f4b6a3/ulid/util/NetworkData.java b/src/main/java/com/github/f4b6a3/ulid/util/NetworkData.java deleted file mode 100644 index 9b74fef..0000000 --- a/src/main/java/com/github/f4b6a3/ulid/util/NetworkData.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2018-2019 Fabio Lima - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.github.f4b6a3.ulid.util; - -import java.net.InetAddress; -import java.net.InterfaceAddress; -import java.net.NetworkInterface; -import java.net.SocketException; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; - -public class NetworkData { - - private String hostName; - private String hostCanonicalName; - private String interfaceName; - private String interfaceDisplayName; - private String interfaceHardwareAddress; - private List interfaceAddresses; - - public String getHostName() { - return hostName; - } - - public void setHostName(String hostName) { - this.hostName = hostName; - } - - public String getHostCanonicalName() { - return hostCanonicalName; - } - - public void setHostCanonicalName(String hostCanonicalName) { - this.hostCanonicalName = hostCanonicalName; - } - - public String getInterfaceName() { - return interfaceName; - } - - public void setInterfaceName(String interfaceName) { - this.interfaceName = interfaceName; - } - - public String getInterfaceDisplayName() { - return interfaceDisplayName; - } - - public void setInterfaceDisplayName(String interfaceDisplayName) { - this.interfaceDisplayName = interfaceDisplayName; - } - - public String getInterfaceHardwareAddress() { - return interfaceHardwareAddress; - } - - public void setInterfaceHardwareAddress(String interfaceHardwareAddress) { - this.interfaceHardwareAddress = interfaceHardwareAddress; - } - - public List getInterfaceAddresses() { - return interfaceAddresses; - } - - public void setInterfaceAddresses(List interfaceAddresses) { - this.interfaceAddresses = interfaceAddresses; - } - - @Override - public String toString() { - - String interfaceAddressesString = null; - if (this.interfaceAddresses != null) { - interfaceAddressesString = String.join(" ", this.interfaceAddresses); - } - - return String.join(" ", this.interfaceHardwareAddress, this.hostName, this.hostCanonicalName, - this.interfaceName, this.interfaceDisplayName, interfaceAddressesString); - } - - /** - * Returns a {@link NetworkData}. - * - * This method returns the network data associated to the host name. - * - * @return a {@link NetworkData} - */ - public static NetworkData getNetworkData() { - - try { - InetAddress inetAddress = InetAddress.getLocalHost(); - NetworkInterface networkInterface = NetworkInterface.getByInetAddress(inetAddress); - return buildNetworkData(networkInterface, inetAddress); - } catch (UnknownHostException | SocketException e) { - return null; - } - } - - /** - * Returns a list of {@link NetworkData}. - * - * This method iterates over all the network interfaces to return those that - * are up and running. - * - * NOTE: it may be VERY EXPENSIVE on Windows systems, because that OS - * creates a lot of virtual network interfaces. - * - * @return a list of {@link NetworkData} - */ - public static List getNetworkDataList() { - try { - InetAddress inetAddress = InetAddress.getLocalHost(); - List networkInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); - - HashSet networkDataHashSet = new HashSet<>(); - for (NetworkInterface networkInterface : networkInterfaces) { - NetworkData networkData = buildNetworkData(networkInterface, inetAddress); - if (networkData != null) { - networkDataHashSet.add(networkData); - } - } - return new ArrayList<>(networkDataHashSet); - } catch (SocketException | NullPointerException | UnknownHostException e) { - return Collections.emptyList(); - } - } - - private static NetworkData buildNetworkData(NetworkInterface networkInterface, InetAddress inetAddress) - throws SocketException { - if (isPhysicalNetworkInterface(networkInterface)) { - - String hostName = inetAddress != null ? inetAddress.getHostName() : null; - String hostCanonicalName = inetAddress != null ? inetAddress.getCanonicalHostName() : null; - String interfaceName = networkInterface.getName(); - String interfaceDisplayName = networkInterface.getDisplayName(); - String interfaceHardwareAddress = ByteUtil.toHexadecimal(networkInterface.getHardwareAddress()); - List interfaceAddresses = getInterfaceAddresses(networkInterface); - - NetworkData networkData = new NetworkData(); - networkData.setHostName(hostName); - networkData.setHostCanonicalName(hostCanonicalName); - networkData.setInterfaceName(interfaceName); - networkData.setInterfaceDisplayName(interfaceDisplayName); - networkData.setInterfaceHardwareAddress(interfaceHardwareAddress); - networkData.setInterfaceAddresses(interfaceAddresses); - - return networkData; - } - return null; - } - - private static boolean isPhysicalNetworkInterface(NetworkInterface networkInterface) { - try { - return networkInterface != null && networkInterface.isUp() - && !(networkInterface.isLoopback() || networkInterface.isVirtual()); - } catch (SocketException e) { - return false; - } - } - - private static List getInterfaceAddresses(NetworkInterface networkInterface) { - HashSet addresses = new HashSet<>(); - List interfaceAddresses = networkInterface.getInterfaceAddresses(); - if (interfaceAddresses != null && !interfaceAddresses.isEmpty()) { - for (InterfaceAddress addr : interfaceAddresses) { - if (addr.getAddress() != null) { - addresses.add(addr.getAddress().getHostAddress()); - } - } - } - return new ArrayList<>(addresses); - } -} diff --git a/src/main/java/com/github/f4b6a3/ulid/util/UlidUtil.java b/src/main/java/com/github/f4b6a3/ulid/util/UlidUtil.java index 208b4b8..c40091d 100644 --- a/src/main/java/com/github/f4b6a3/ulid/util/UlidUtil.java +++ b/src/main/java/com/github/f4b6a3/ulid/util/UlidUtil.java @@ -27,6 +27,9 @@ package com.github.f4b6a3.ulid.util; import java.time.Instant; import java.util.UUID; +import com.github.f4b6a3.commons.util.Base32Util; +import com.github.f4b6a3.commons.util.ByteUtil; + public class UlidUtil { // Date: 10889-08-02T05:31:50.655Z diff --git a/src/test/java/com/github/f4b6a3/TestSuite.java b/src/test/java/com/github/f4b6a3/TestSuite.java index 330ed02..1b8b62f 100644 --- a/src/test/java/com/github/f4b6a3/TestSuite.java +++ b/src/test/java/com/github/f4b6a3/TestSuite.java @@ -4,20 +4,14 @@ import org.junit.runner.RunWith; import org.junit.runners.Suite; import com.github.f4b6a3.ulid.UlidCreatorTest; -import com.github.f4b6a3.ulid.guid.GuidCreatorTest; -import com.github.f4b6a3.ulid.random.NaiveRandomTest; +import com.github.f4b6a3.ulid.creator.UlidBasedGuidCreatorTest; import com.github.f4b6a3.ulid.timestamp.DefaultTimestampStrategyTest; -import com.github.f4b6a3.ulid.util.Base32UtilTest; -import com.github.f4b6a3.ulid.util.ByteUtilTest; import com.github.f4b6a3.ulid.util.UlidUtilTest; @RunWith(Suite.class) @Suite.SuiteClasses({ DefaultTimestampStrategyTest.class, - ByteUtilTest.class, - NaiveRandomTest.class, - GuidCreatorTest.class, - Base32UtilTest.class, + UlidBasedGuidCreatorTest.class, UlidUtilTest.class, UlidCreatorTest.class, }) diff --git a/src/test/java/com/github/f4b6a3/UniquenessTest.java b/src/test/java/com/github/f4b6a3/UniquenessTest.java index 2ce9148..5613ba3 100644 --- a/src/test/java/com/github/f4b6a3/UniquenessTest.java +++ b/src/test/java/com/github/f4b6a3/UniquenessTest.java @@ -4,8 +4,8 @@ import java.util.HashSet; import java.util.UUID; import com.github.f4b6a3.ulid.UlidCreator; +import com.github.f4b6a3.ulid.creator.UlidBasedGuidCreator; import com.github.f4b6a3.ulid.exception.UlidCreatorException; -import com.github.f4b6a3.ulid.guid.GuidCreator; import com.github.f4b6a3.ulid.timestamp.FixedTimestampStretegy; /** @@ -27,7 +27,7 @@ public class UniquenessTest { private boolean verbose; // Show progress or not // GUID creator based on ULID spec - private GuidCreator creator; + private UlidBasedGuidCreator creator; /** * Initialize the test. @@ -36,7 +36,7 @@ public class UniquenessTest { * @param requestCount * @param creator */ - public UniquenessTest(int threadCount, int requestCount, GuidCreator creator, boolean progress) { + public UniquenessTest(int threadCount, int requestCount, UlidBasedGuidCreator creator, boolean progress) { this.threadCount = threadCount; this.requestCount = requestCount; this.creator = creator; @@ -87,7 +87,7 @@ public class UniquenessTest { @Override public void run() { - double progress = 0; + int progress = 0; int max = requestCount; for (int i = 0; i < max; i++) { @@ -95,37 +95,37 @@ public class UniquenessTest { // Request a UUID UUID uuid = null; try { - uuid = creator.create(); + uuid = creator.createGuid(); } catch (UlidCreatorException e) { // Ignore the overrun exception and try again - uuid = creator.create(); + uuid = creator.createGuid(); } if (verbose) { // Calculate and show progress - progress = (i * 1.0 / max) * 100; - if (progress % 1 == 0) { + progress = (int) ((i * 1.0 / max) * 100); + if (progress % 10 == 0) { System.out.println(String.format("[Thread %06d] %s %s %s%%", id, uuid, i, (int) progress)); } } synchronized (hashSet) { // Insert the value in cache, if it does not exist in it. if (!hashSet.add(uuid)) { - throw new UlidCreatorException( - String.format("[DUPLICATE][Thread %s] %s %s %s%%", id, uuid, i, (int) progress)); + System.err.println( + String.format("[Thread %06d] %s %s %s%% [DUPLICATE]", id, uuid, i, (int) progress)); } } } if (verbose) { // Finished - System.out.println(String.format("[Thread %s] Done.", id)); + System.out.println(String.format("[Thread %06d] Done.", id)); } } } public static void execute(boolean verbose, int threadCount, int requestCount) { - GuidCreator creator = UlidCreator.getGuidCreator() + UlidBasedGuidCreator creator = UlidCreator.getGuidCreator() .withTimestampStrategy(new FixedTimestampStretegy(System.currentTimeMillis())); UniquenessTest test = new UniquenessTest(threadCount, requestCount, creator, verbose); diff --git a/src/test/java/com/github/f4b6a3/demo/DemoTest.java b/src/test/java/com/github/f4b6a3/demo/DemoTest.java index 3cccdf1..c46baca 100644 --- a/src/test/java/com/github/f4b6a3/demo/DemoTest.java +++ b/src/test/java/com/github/f4b6a3/demo/DemoTest.java @@ -14,7 +14,7 @@ public class DemoTest { System.out.println(HORIZONTAL_LINE); for (int i = 0; i < max; i++) { - System.out.println(UlidCreator.getUlid()); + System.out.println(UlidCreator.getUlidString()); } System.out.println(HORIZONTAL_LINE); @@ -22,7 +22,7 @@ public class DemoTest { System.out.println(HORIZONTAL_LINE); for (int i = 0; i < max; i++) { - System.out.println(UlidCreator.getGuid()); + System.out.println(UlidCreator.getUlid()); } } diff --git a/src/test/java/com/github/f4b6a3/ulid/UlidCreatorTest.java b/src/test/java/com/github/f4b6a3/ulid/UlidCreatorTest.java index 3681817..2f45030 100644 --- a/src/test/java/com/github/f4b6a3/ulid/UlidCreatorTest.java +++ b/src/test/java/com/github/f4b6a3/ulid/UlidCreatorTest.java @@ -21,7 +21,7 @@ public class UlidCreatorTest { long startTime = System.currentTimeMillis(); for (int i = 0; i < DEFAULT_LOOP_MAX; i++) { - list[i] = UlidCreator.getUlid(); + list[i] = UlidCreator.getUlidString(); } long endTime = System.currentTimeMillis(); diff --git a/src/test/java/com/github/f4b6a3/ulid/guid/GuidCreatorMock.java b/src/test/java/com/github/f4b6a3/ulid/creator/UlidBasedGuidCreatorMock.java similarity index 58% rename from src/test/java/com/github/f4b6a3/ulid/guid/GuidCreatorMock.java rename to src/test/java/com/github/f4b6a3/ulid/creator/UlidBasedGuidCreatorMock.java index fdf7570..98587b5 100644 --- a/src/test/java/com/github/f4b6a3/ulid/guid/GuidCreatorMock.java +++ b/src/test/java/com/github/f4b6a3/ulid/creator/UlidBasedGuidCreatorMock.java @@ -1,13 +1,15 @@ -package com.github.f4b6a3.ulid.guid; +package com.github.f4b6a3.ulid.creator; -class GuidCreatorMock extends GuidCreator { +import com.github.f4b6a3.ulid.creator.UlidBasedGuidCreator; - public GuidCreatorMock(long previousTimestamp) { +class UlidBasedGuidCreatorMock extends UlidBasedGuidCreator { + + public UlidBasedGuidCreatorMock(long previousTimestamp) { super(); this.previousTimestamp = previousTimestamp; } - public GuidCreatorMock(long randomMsb, long randomLsb, long randomMsbMax, long randomLsbMax, long previousTimestamp) { + public UlidBasedGuidCreatorMock(long randomMsb, long randomLsb, long randomMsbMax, long randomLsbMax, long previousTimestamp) { this.randomMsb = randomMsb; this.randomLsb = randomLsb; diff --git a/src/test/java/com/github/f4b6a3/ulid/guid/GuidCreatorTest.java b/src/test/java/com/github/f4b6a3/ulid/creator/UlidBasedGuidCreatorTest.java similarity index 72% rename from src/test/java/com/github/f4b6a3/ulid/guid/GuidCreatorTest.java rename to src/test/java/com/github/f4b6a3/ulid/creator/UlidBasedGuidCreatorTest.java index a1ff0d7..3e50d25 100644 --- a/src/test/java/com/github/f4b6a3/ulid/guid/GuidCreatorTest.java +++ b/src/test/java/com/github/f4b6a3/ulid/creator/UlidBasedGuidCreatorTest.java @@ -1,17 +1,17 @@ -package com.github.f4b6a3.ulid.guid; +package com.github.f4b6a3.ulid.creator; import java.util.Random; import java.util.UUID; import org.junit.Test; +import com.github.f4b6a3.commons.random.Xorshift128PlusRandom; import com.github.f4b6a3.ulid.exception.UlidCreatorException; -import com.github.f4b6a3.ulid.random.Xorshift128PlusRandom; import com.github.f4b6a3.ulid.timestamp.FixedTimestampStretegy; import static org.junit.Assert.*; -public class GuidCreatorTest { +public class UlidBasedGuidCreatorTest { private static final long DEFAULT_LOOP_MAX = 1_000_000; @@ -22,13 +22,13 @@ public class GuidCreatorTest { @Test public void testRandomMostSignificantBits() { - GuidCreatorMock creator = new GuidCreatorMock(TIMESTAMP); + UlidBasedGuidCreatorMock creator = new UlidBasedGuidCreatorMock(TIMESTAMP); creator.withTimestampStrategy(new FixedTimestampStretegy(TIMESTAMP)); - UUID uuid = creator.create(); + UUID uuid = creator.createGuid(); long firstMsb = creator.extractRandomMsb(uuid); for (int i = 0; i < DEFAULT_LOOP_MAX; i++) { - uuid = creator.create(); + uuid = creator.createGuid(); } @@ -37,7 +37,7 @@ public class GuidCreatorTest { assertEquals(String.format("The last MSB should be iqual to the first %s.", expectedMsb), expectedMsb, lastMsb); creator.withTimestampStrategy(new FixedTimestampStretegy(TIMESTAMP + 1)); - uuid = creator.create(); + uuid = creator.createGuid(); lastMsb = uuid.getMostSignificantBits(); assertNotEquals("The last MSB should be random after timestamp changed.", firstMsb, lastMsb); } @@ -45,13 +45,13 @@ public class GuidCreatorTest { @Test public void testRandomLeastSignificantBits() { - GuidCreatorMock creator = new GuidCreatorMock(TIMESTAMP); + UlidBasedGuidCreatorMock creator = new UlidBasedGuidCreatorMock(TIMESTAMP); creator.withTimestampStrategy(new FixedTimestampStretegy(TIMESTAMP)); - UUID uuid = creator.create(); + UUID uuid = creator.createGuid(); long firstLsb = creator.extractRandomLsb(uuid); for (int i = 0; i < DEFAULT_LOOP_MAX; i++) { - uuid = creator.create(); + uuid = creator.createGuid(); } long lastLsb = creator.extractRandomLsb(uuid); @@ -60,7 +60,7 @@ public class GuidCreatorTest { long notExpected = firstLsb + DEFAULT_LOOP_MAX + 1; creator.withTimestampStrategy(new FixedTimestampStretegy(TIMESTAMP + 1)); - uuid = creator.create(); + uuid = creator.createGuid(); lastLsb = uuid.getLeastSignificantBits(); assertNotEquals("The last LSB should be random after timestamp changed.", notExpected, lastLsb); } @@ -68,14 +68,14 @@ public class GuidCreatorTest { @Test public void testIncrementOfRandomLeastSignificantBits() { - GuidCreatorMock creator = new GuidCreatorMock(TIMESTAMP); + UlidBasedGuidCreatorMock creator = new UlidBasedGuidCreatorMock(TIMESTAMP); creator.withTimestampStrategy(new FixedTimestampStretegy(TIMESTAMP)); long lsb = creator.getRandomLsb(); UUID uuid = new UUID(0, 0); for (int i = 0; i < DEFAULT_LOOP_MAX; i++) { - uuid = creator.create(); + uuid = creator.createGuid(); } long expectedLsb = lsb + DEFAULT_LOOP_MAX; @@ -89,14 +89,14 @@ public class GuidCreatorTest { @Test public void testIncrementOfRandomMostSignificantBits() { - GuidCreatorMock creator = new GuidCreatorMock(TIMESTAMP); + UlidBasedGuidCreatorMock creator = new UlidBasedGuidCreatorMock(TIMESTAMP); creator.withTimestampStrategy(new FixedTimestampStretegy(TIMESTAMP)); long msb = creator.getRandomMsb(); UUID uuid = new UUID(0, 0); for (int i = 0; i < DEFAULT_LOOP_MAX; i++) { - uuid = creator.create(); + uuid = creator.createGuid(); } long expectedMsb = msb; @@ -116,15 +116,15 @@ public class GuidCreatorTest { long msb = msbMax - 1; long lsb = lsbMax - DEFAULT_LOOP_MAX; - GuidCreatorMock creator = new GuidCreatorMock(msb, lsb, msbMax, lsbMax, TIMESTAMP); + UlidBasedGuidCreatorMock creator = new UlidBasedGuidCreatorMock(msb, lsb, msbMax, lsbMax, TIMESTAMP); creator.withTimestampStrategy(new FixedTimestampStretegy(TIMESTAMP)); for (int i = 0; i < DEFAULT_LOOP_MAX - 1; i++) { - creator.create(); + creator.createGuid(); } try { - creator.create(); + creator.createGuid(); fail("It should throw an overflow exception."); } catch (UlidCreatorException e) { // success @@ -134,32 +134,32 @@ public class GuidCreatorTest { @Test public void testShouldThrowOverflowException2() { - long msbMax = (RANDOM.nextLong() & GuidCreatorMock.HALF_RANDOM_COMPONENT) - | GuidCreatorMock.INCREMENT_MAX; - long lsbMax = (RANDOM.nextLong() & GuidCreatorMock.HALF_RANDOM_COMPONENT) - | GuidCreatorMock.INCREMENT_MAX; + long msbMax = (RANDOM.nextLong() & UlidBasedGuidCreatorMock.HALF_RANDOM_COMPONENT) + | UlidBasedGuidCreatorMock.INCREMENT_MAX; + long lsbMax = (RANDOM.nextLong() & UlidBasedGuidCreatorMock.HALF_RANDOM_COMPONENT) + | UlidBasedGuidCreatorMock.INCREMENT_MAX; long msb = msbMax - 1; long lsb = lsbMax - DEFAULT_LOOP_MAX; - GuidCreatorMock creator = new GuidCreatorMock(msb, lsb, msbMax, lsbMax, TIMESTAMP); + UlidBasedGuidCreatorMock creator = new UlidBasedGuidCreatorMock(msb, lsb, msbMax, lsbMax, TIMESTAMP); creator.withTimestampStrategy(new FixedTimestampStretegy(TIMESTAMP)); UUID uuid = new UUID(0, 0); for (int i = 0; i < DEFAULT_LOOP_MAX - 1; i++) { - uuid = creator.create(); + uuid = creator.createGuid(); } - long expectedLsb = (lsbMax - 1) & GuidCreatorMock.HALF_RANDOM_COMPONENT; + long expectedLsb = (lsbMax - 1) & UlidBasedGuidCreatorMock.HALF_RANDOM_COMPONENT; long randomLsb = creator.extractRandomLsb(uuid); assertEquals("Incorrect LSB after loop.", expectedLsb, randomLsb); - long expectedMsb = (msbMax - 1) & GuidCreatorMock.HALF_RANDOM_COMPONENT; + long expectedMsb = (msbMax - 1) & UlidBasedGuidCreatorMock.HALF_RANDOM_COMPONENT; long randomMsb = creator.extractRandomMsb(uuid); assertEquals("Incorrect MSB after loop.", expectedMsb, randomMsb); try { - creator.create(); + creator.createGuid(); fail("It should throw an overflow exception."); } catch (UlidCreatorException e) { // success diff --git a/src/test/java/com/github/f4b6a3/ulid/random/NaiveRandomTest.java b/src/test/java/com/github/f4b6a3/ulid/random/NaiveRandomTest.java deleted file mode 100644 index 0041649..0000000 --- a/src/test/java/com/github/f4b6a3/ulid/random/NaiveRandomTest.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.github.f4b6a3.ulid.random; - -import org.junit.Test; - -import static org.junit.Assert.*; - -public class NaiveRandomTest { - - private static final int DEFAULT_LOOP_LIMIT = 100_000; - private static final String EXPECTED_BIT_COUNT_RANDOM_LONG = "The average bit count expected for random long values is 32"; - - @Test - public void testXorshiftNextLongNaiveAverageBitCount() { - - double accumulator = 0; - - XorshiftRandom random = new XorshiftRandom(); - - for(int i = 0; i < DEFAULT_LOOP_LIMIT; i++) { - long value = random.nextLong(); - accumulator += Long.bitCount(value); - } - - double average = Math.round(accumulator / DEFAULT_LOOP_LIMIT); - - assertTrue(EXPECTED_BIT_COUNT_RANDOM_LONG, average == 32); - } - - @Test - public void testXorshift128PlusNextLongNaiveAverageBitCount() { - - double accumulator = 0; - - Xorshift128PlusRandom random = new Xorshift128PlusRandom(); - - for (int i = 0; i < DEFAULT_LOOP_LIMIT; i++) { - long value = random.nextLong(); - accumulator += Long.bitCount(value); - } - - double average = Math.round(accumulator / DEFAULT_LOOP_LIMIT); - - assertTrue(EXPECTED_BIT_COUNT_RANDOM_LONG, average == 32); - } -} diff --git a/src/test/java/com/github/f4b6a3/ulid/util/Base32UtilTest.java b/src/test/java/com/github/f4b6a3/ulid/util/Base32UtilTest.java deleted file mode 100644 index 2ff3d31..0000000 --- a/src/test/java/com/github/f4b6a3/ulid/util/Base32UtilTest.java +++ /dev/null @@ -1,410 +0,0 @@ -package com.github.f4b6a3.ulid.util; - -import static org.junit.Assert.*; - -import java.math.BigInteger; - -import org.junit.Test; - -import com.github.f4b6a3.ulid.util.Base32Util.Base32UtilException; - -public class Base32UtilTest { - - private static final String LONG_TEXT = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras finibus fringilla sem, ac dictum dui mollis vitae. Suspendisse id euismod nunc. Curabitur mollis felis nec scelerisque eleifend. Curabitur eleifend, eros sed pellentesque egestas, dolor risus sodales sapien, ut finibus urna nisi id massa. Maecenas facilisis accumsan vestibulum. Fusce et sapien sed justo lacinia efficitur. Aenean libero mi, auctor nec rutrum at, tincidunt eu nisi. Curabitur urna quam, lobortis vel sem ullamcorper, dignissim varius metus. Proin congue nunc ut nisl hendrerit, vel euismod nunc auctor. Nunc metus arcu, lacinia ac dolor quis, dignissim tempor ante. Nunc condimentum tortor nec urna mattis venenatis. Vestibulum elit magna, sollicitudin eu iaculis at, faucibus eu lacus. Curabitur ultrices, elit non dictum vulputate, ligula elit egestas elit, vitae tincidunt lacus massa eu justo. Nam a velit ullamcorper, tincidunt tortor in, sodales velit. Suspendisse non mi quis lacus lacinia ultrices at at massa. Nullam tempus turpis duis."; - - private static final String LONG_TEXT_BASE_32 = "JRXXEZLNEBUXA43VNUQGI33MN5ZCA43JOQQGC3LFOQWCAY3PNZZWKY3UMV2HK4RAMFSGS4DJONRWS3THEBSWY2LUFYQEG4TBOMQGM2LONFRHK4ZAMZZGS3THNFWGYYJAONSW2LBAMFRSAZDJMN2HK3JAMR2WSIDNN5WGY2LTEB3GS5DBMUXCAU3VONYGK3TENFZXGZJANFSCAZLVNFZW233EEBXHK3TDFYQEG5LSMFRGS5DVOIQG233MNRUXGIDGMVWGS4ZANZSWGIDTMNSWYZLSNFZXC5LFEBSWYZLJMZSW4ZBOEBBXK4TBMJUXI5LSEBSWYZLJMZSW4ZBMEBSXE33TEBZWKZBAOBSWY3DFNZ2GK43ROVSSAZLHMVZXIYLTFQQGI33MN5ZCA4TJON2XGIDTN5SGC3DFOMQHGYLQNFSW4LBAOV2CAZTJNZUWE5LTEB2XE3TBEBXGS43JEBUWIIDNMFZXGYJOEBGWCZLDMVXGC4ZAMZQWG2LMNFZWS4ZAMFRWG5LNONQW4IDWMVZXI2LCOVWHK3JOEBDHK43DMUQGK5BAONQXA2LFNYQHGZLEEBVHK43UN4QGYYLDNFXGSYJAMVTGM2LDNF2HK4ROEBAWK3TFMFXCA3DJMJSXE3ZANVUSYIDBOVRXI33SEBXGKYZAOJ2XI4TVNUQGC5BMEB2GS3TDNFSHK3TUEBSXKIDONFZWSLRAIN2XEYLCNF2HK4RAOVZG4YJAOF2WC3JMEBWG6YTPOJ2GS4ZAOZSWYIDTMVWSA5LMNRQW2Y3POJYGK4RMEBSGSZ3ONFZXG2LNEB3GC4TJOVZSA3LFOR2XGLRAKBZG62LOEBRW63THOVSSA3TVNZRSA5LUEBXGS43MEBUGK3TEOJSXE2LUFQQHMZLMEBSXK2LTNVXWIIDOOVXGGIDBOVRXI33SFYQE45LOMMQG2ZLUOVZSAYLSMN2SYIDMMFRWS3TJMEQGCYZAMRXWY33SEBYXK2LTFQQGI2LHNZUXG43JNUQHIZLNOBXXEIDBNZ2GKLRAJZ2W4YZAMNXW4ZDJNVSW45DVNUQHI33SORXXEIDOMVRSA5LSNZQSA3LBOR2GS4ZAOZSW4ZLOMF2GS4ZOEBLGK43UNFRHK3DVNUQGK3DJOQQG2YLHNZQSYIDTN5WGY2LDNF2HKZDJNYQGK5JANFQWG5LMNFZSAYLUFQQGMYLVMNUWE5LTEBSXKIDMMFRXK4ZOEBBXK4TBMJUXI5LSEB2WY5DSNFRWK4ZMEBSWY2LUEBXG63RAMRUWG5DVNUQHM5LMOB2XIYLUMUWCA3DJM52WYYJAMVWGS5BAMVTWK43UMFZSAZLMNF2CYIDWNF2GCZJAORUW4Y3JMR2W45BANRQWG5LTEBWWC43TMEQGK5JANJ2XG5DPFYQE4YLNEBQSA5TFNRUXIIDVNRWGC3LDN5ZHAZLSFQQHI2LOMNUWI5LOOQQHI33SORXXEIDJNYWCA43PMRQWYZLTEB3GK3DJOQXCAU3VONYGK3TENFZXGZJANZXW4IDNNEQHC5LJOMQGYYLDOVZSA3DBMNUW42LBEB2WY5DSNFRWK4ZAMF2CAYLUEBWWC43TMEXCATTVNRWGC3JAORSW24DVOMQHI5LSOBUXGIDEOVUXGLQ="; - private static final String LONG_TEXT_BASE_32_HEX = "9HNN4PBD41KN0SRLDKG68RRCDTP20SR9EGG62RB5EGM20ORFDPPMAORKCLQ7ASH0C5I6IS39EDHMIRJ741IMOQBK5OG46SJ1ECG6CQBED5H7ASP0CPP6IRJ7D5M6OO90EDIMQB10C5HI0P39CDQ7AR90CHQMI83DDTM6OQBJ41R6IT31CKN20KRLEDO6ARJ4D5PN6P90D5I20PBLD5PMQRR441N7ARJ35OG46TBIC5H6IT3LE8G6QRRCDHKN6836CLM6ISP0DPIM683JCDIMOPBID5PN2TB541IMOPB9CPIMSP1E411NASJ1C9KN8TBI41IMOPB9CPIMSP1C41IN4RRJ41PMAP10E1IMOR35DPQ6ASRHELII0PB7CLPN8OBJ5GG68RRCDTP20SJ9EDQN683JDTI62R35ECG76OBGD5IMSB10ELQ20PJ9DPKM4TBJ41QN4RJ141N6ISR941KM883DC5PN6O9E416M2PB3CLN62SP0CPGM6QBCD5PMISP0C5HM6TBDEDGMS83MCLPN8QB2ELM7AR9E4137ASR3CKG6AT10EDGN0QB5DOG76PB441L7ASRKDSG6OOB3D5N6IO90CLJ6CQB3D5Q7ASHE410MARJ5C5N20R39C9IN4RP0DLKIO831ELHN8RRI41N6AOP0E9QN8SJLDKG62T1C41Q6IRJ3D5I7ARJK41INA83ED5PMIBH08DQN4OB2D5Q7ASH0ELP6SO90E5QM2R9C41M6UOJFE9Q6ISP0EPIMO83JCLMI0TBCDHGMQORFE9O6ASHC41I6IPRED5PN6QBD41R62SJ9ELPI0RB5EHQN6BH0A1P6UQBE41HMURJ7ELII0RJLDPHI0TBK41N6ISRC41K6ARJ4E9IN4QBK5GG7CPBC41INAQBJDLNM883EELN66831ELHN8RRI5OG4STBECCG6QPBKELPI0OBICDQIO83CC5HMIRJ9C4G62OP0CHNMORRI41ONAQBJ5GG68QB7DPKN6SR9DKG78PBDE1NN4831DPQ6ABH09PQMSOP0CDNMSP39DLIMST3LDKG78RRIEHNN483ECLHI0TBIDPGI0RB1EHQ6ISP0EPIMSPBEC5Q6ISPE41B6ASRKD5H7AR3LDKG6AR39EGG6QOB7DPGIO83JDTM6OQB3D5Q7AP39DOG6AT90D5GM6TBCD5PI0OBK5GG6COBLCDKM4TBJ41INA83CC5HNASPE411NASJ1C9KN8TBI41QMOT3ID5HMASPC41IMOQBK41N6URH0CHKM6T3LDKG7CTBCE1QN8OBKCKM20R39CTQMOO90CLM6IT10CLJMASRKC5PI0PBCD5Q2O83MD5Q62P90EHKMSOR9CHQMST10DHGM6TBJ41MM2SRJC4G6AT90D9QN6T3F5OG4SOBD41GI0TJ5DHKN883LDHM62RB3DTP70PBI5GG78QBECDKM8TBEEGG78RRIEHNN4839DOM20SRFCHGMOPBJ41R6AR39EGN20KRLEDO6ARJ4D5PN6P90DPNMS83DD4G72TB9ECG6OOB3ELPI0R31CDKMSQB141QMOT3ID5HMASP0C5Q20OBK41MM2SRJC4N20JJLDHM62R90EHIMQS3LECG78TBIE1KN6834ELKN6BG="; - private static final String LONG_TEXT_BASE_32_Z = "jtzzr3mprbwzyh5ipwoge55cp73nyh5jqoogn5mfqosnya5xp33ska5wci48khtycf1g1hdjqpts15u8rb1sa4mwfaorghubqcogc4mqpft8kh3yc33g15u8pfsgaajyqp1s4mbycft1y3djcp48k5jyct4s1edpp7sga4murb5g17dbcwznyw5iqpagk5urpf3zg3jypf1ny3mipf3s455rrbz8k5udfaorg7m1cftg17diqeog455cptwzgedgcisg1h3yp31sgeducp1sa3m1pf3zn7mfrb1sa3mjc31sh3bqrbbzkhubcjwze7m1rb1sa3mjc31sh3bcrb1zr55urb3sk3byqb1sa5dfp34gkh5tqi11y3m8ci3zeamufooge55cp73nyhujqp4zgedup71gn5dfqco8gamopf1shmbyqi4ny3ujp3wsr7murb4zr5ubrbzg1h5jrbwseedpcf3zgajqrbgsn3mdcizgnh3yc3osg4mcpf3s1h3ycftsg7mpqposhedsci3ze4mnqis8k5jqrbd8kh5dcwogk7byqpozy4mfpao8g3mrrbi8kh5wphogaamdpfzg1ajyciugc4mdpf48khtqrbysk5ufcfzny5djcj1zr53ypiw1aedbqitze551rbzgka3yqj4zehuipwogn7bcrb4g15udpf18k5uwrb1zkedqpf3s1mtyep4zramnpf48khtyqi3ghajyqf4sn5jcrbsg6auxqj4g1h3yq31saeducis1y7mcptos4a5xqjagkhtcrb1g135qpf3zg4mprb5gnhujqi31y5mfqt4zgmtykb3g64mqrbts65u8qi11y5uip3t1y7mwrbzg1h5crbwgk5urqj1zr4mwfoo8c3mcrb1zk4mupizseedqqizggedbqitze551faorh7mqccog43mwqi31yam1cp41aedccfts15ujcrogna3yctzsa551rbazk4mufooge4m8p3wzgh5jpwo8e3mpqbzzredbp34gkmtyj34sha3ycpzsh3djpi1sh7dipwo8e551qtzzredqcit1y7m1p3o1y5mbqt4g1h3yq31sh3mqcf4g1h3qrbmgkh5wpft8k5dipwogk5djqoog4am8p3o1aedup7sga4mdpf48k3djpaogk7jypfosg7mcpf31yamwfoogcamicpwsr7murb1zkedccftzkh3qrbbzkhubcjwze7m1rb4sa7d1pftskh3crb1sa4mwrbzg65tyctwsg7dipwo8c7mcqb4zeamwcwsny5djc74saajycisg17byciuskh5wcf31y3mcpf4naedspf4gn3jyqtwsha5jct4sh7byptosg7murbssnh5ucrogk7jypj4zg7dxfaorhamprbo1y7ufptwzeediptsgn5mdp738y3m1foo8e4mqcpwse7mqqoo8e551qtzzredjpasnyh5xctosa3murb5gk5djqoznyw5iqpagk5urpf3zg3jyp3zshedppro8n7mjqcogaamdqi31y5dbcpwsh4mbrb4sa7d1pftskh3ycf4nyamwrbssnh5ucrznyuuiptsgn5jyqt1s4hdiqco8e7m1qbwzgedrqiwzgmo"; - private static final String LONG_TEXT_BASE_32_CROCKFORD = "9HQQ4SBD41MQ0WVNDMG68VVCDXS20WV9EGG62VB5EGP20RVFDSSPARVMCNT7AWH0C5J6JW39EDHPJVK741JPRTBM5RG46WK1ECG6CTBED5H7AWS0CSS6JVK7D5P6RR90EDJPTB10C5HJ0S39CDT7AV90CHTPJ83DDXP6RTBK41V6JX31CMQ20MVNEDR6AVK4D5SQ6S90D5J20SBND5SPTVV441Q7AVK35RG46XBJC5H6JX3NE8G6TVVCDHMQ6836CNP6JWS0DSJP683KCDJPRSBJD5SQ2XB541JPRSB9CSJPWS1E411QAWK1C9MQ8XBJ41JPRSB9CSJPWS1C41JQ4VVK41SPAS10E1JPRV35DST6AWVHENJJ0SB7CNSQ8RBK5GG68VVCDXS20WK9EDTQ683KDXJ62V35ECG76RBGD5JPWB10ENT20SK9DSMP4XBK41TQ4VK141Q6JWV941MP883DC5SQ6R9E416P2SB3CNQ62WS0CSGP6TBCD5SPJWS0C5HP6XBDEDGPW83PCNSQ8TB2ENP7AV9E4137AWV3CMG6AX10EDGQ0TB5DRG76SB441N7AWVMDWG6RRB3D5Q6JR90CNK6CTB3D5T7AWHE410PAVK5C5Q20V39C9JQ4VS0DNMJR831ENHQ8VVJ41Q6ARS0E9TQ8WKNDMG62X1C41T6JVK3D5J7AVKM41JQA83ED5SPJBH08DTQ4RB2D5T7AWH0ENS6WR90E5TP2V9C41P6YRKFE9T6JWS0ESJPR83KCNPJ0XBCDHGPTRVFE9R6AWHC41J6JSVED5SQ6TBD41V62WK9ENSJ0VB5EHTQ6BH0A1S6YTBE41HPYVK7ENJJ0VKNDSHJ0XBM41Q6JWVC41M6AVK4E9JQ4TBM5GG7CSBC41JQATBKDNQP883EENQ66831ENHQ8VVJ5RG4WXBECCG6TSBMENSJ0RBJCDTJR83CC5HPJVK9C4G62RS0CHQPRVVJ41RQATBK5GG68TB7DSMQ6WV9DMG78SBDE1QQ4831DST6ABH09STPWRS0CDQPWS39DNJPWX3NDMG78VVJEHQQ483ECNHJ0XBJDSGJ0VB1EHT6JWS0ESJPWSBEC5T6JWSE41B6AWVMD5H7AV3NDMG6AV39EGG6TRB7DSGJR83KDXP6RTB3D5T7AS39DRG6AX90D5GP6XBCD5SJ0RBM5GG6CRBNCDMP4XBK41JQA83CC5HQAWSE411QAWK1C9MQ8XBJ41TPRX3JD5HPAWSC41JPRTBM41Q6YVH0CHMP6X3NDMG7CXBCE1TQ8RBMCMP20V39CXTPRR90CNP6JX10CNKPAWVMC5SJ0SBCD5T2R83PD5T62S90EHMPWRV9CHTPWX10DHGP6XBK41PP2WVKC4G6AX90D9TQ6X3F5RG4WRBD41GJ0XK5DHMQ883NDHP62VB3DXS70SBJ5GG78TBECDMP8XBEEGG78VVJEHQQ4839DRP20WVFCHGPRSBK41V6AV39EGQ20MVNEDR6AVK4D5SQ6S90DSQPW83DD4G72XB9ECG6RRB3ENSJ0V31CDMPWTB141TPRX3JD5HPAWS0C5T20RBM41PP2WVKC4Q20KKNDHP62V90EHJPTW3NECG78XBJE1MQ6834ENMQ6BG"; - - private static final String SHORT_TEXT = "Lorem ipsum dolor sit volutpat."; - private static final String SHORT_TEXT_BASE_32 = "JRXXEZLNEBUXA43VNUQGI33MN5ZCA43JOQQHM33MOV2HAYLUFY======"; - private static final String SHORT_TEXT_BASE_32_HEX = "9HNN4PBD41KN0SRLDKG68RRCDTP20SR9EGG7CRRCELQ70OBK5O======"; - private static final String SHORT_TEXT_BASE_32_Z = "jtzzr3mprbwzyh5ipwoge55cp73nyh5jqoo8c55cqi48yamwfa"; - private static final String SHORT_TEXT_BASE_32_CROCKFORD = "9HQQ4SBD41MQ0WVNDMG68VVCDXS20WV9EGG7CVVCENT70RBM5R"; - - private static final String[] WORDS = { "", "f", "fo", "foo", "foob", "fooba", "foobar", "foobarc", "foobarcp", - "foobarcpt", "foobarcpto" }; - - private static final String[] WORDS_BASE_32 = { "", "MY======", "MZXQ====", "MZXW6===", "MZXW6YQ=", "MZXW6YTB", - "MZXW6YTBOI======", "MZXW6YTBOJRQ====", "MZXW6YTBOJRXA===", "MZXW6YTBOJRXA5A=", "MZXW6YTBOJRXA5DP" }; - - private static final String[] WORDS_BASE_32_HEX = { "", "CO======", "CPNG====", "CPNMU===", "CPNMUOG=", "CPNMUOJ1", - "CPNMUOJ1E8======", "CPNMUOJ1E9HG====", "CPNMUOJ1E9HN0===", "CPNMUOJ1E9HN0T0=", "CPNMUOJ1E9HN0T3F" }; - - private static final String[] WORDS_BASE_32_Z = { "", "ca", "c3zo", "c3zs6", "c3zs6ao", "c3zs6aub", "c3zs6aubqe", - "c3zs6aubqjto", "c3zs6aubqjtzy", "c3zs6aubqjtzy7y", "c3zs6aubqjtzy7dx" }; - - private static final String[] WORDS_BASE_32_CROCKFORD = { "", "CR", "CSQG", "CSQPY", "CSQPYRG", "CSQPYRK1", - "CSQPYRK1E8", "CSQPYRK1E9HG", "CSQPYRK1E9HQ0", "CSQPYRK1E9HQ0X0", "CSQPYRK1E9HQ0X3F" }; - - private static final int[] NUMBERS = { 102685630, 725393777, 573697669, 614668535, 790665079, 728958755, 966150230, - 410015018, 605266173, 946077566, 214051168, 775737014, 723003700, 391609366, 147844737, 514081413, - 488279622, 550860813, 611087782, 223492126, 706308515, 158990768, 549042286, 26926303, 775714134, 602886016, - 27282100, 675097356, 641101167, 515280699, 454184468, 371424784, 633917378, 887459583, 792903202, 168552040, - 824806922, 696445335, 653338746, 357696553, 353677217, 972662902, 400738139, 537701151, 202077579, - 110209145, 356152341, 168702810, 684185451, 419840003, 480132486, 308833881, 997154252, 918202260, - 103304091, 328467776, 648729690, 733655121, 645189051, 342500864, 560919543, 509761384, 626871960, - 429248550, 319025067, 507317265, 348303729, 256009160, 660250872, 85224414, 414490625, 355994979, 318005886, - 326093128, 492813589, 569014099, 503350412, 168303553, 801566586, 800368918, 742601973, 395588591, - 257341245, 722366808, 501878988, 200718306, 184948029, 149469829, 992401543, 240364551, 976817281, - 161998068, 515579566, 275182272, 376045488, 899163436, 941443452, 974372015, 934795357, 958806784 }; - - private static final String[] NUMBERS_BASE_32 = { "DB5W56", "VTZILR", "RDD3UF", "SKGGHX", "XSBF3X", "VXGBZD", - "4ZMSCW", "MHAVJK", "SBHIH5", "4GH736", "GMEKLA", "XDZTVW", "VRQKJU", "LVO7AW", "EM73UB", "PKIQUF", - "ORVDSG", "QNK6AN", "SGY5NG", "GVEOA6", "VBS2ND", "EXUANQ", "QLTODO", "ZVXG7", "XDY5KW", "R66T4A", "2ASVU", - "UD2KYM", "TDM3LP", "PLNDZ3", "NRETQU", "LCG7QQ", "S4RT6C", "2OLDX7", "XUFPRC", "FAXZTI", "YSTDQK", - "UYF2MX", "TPCKD2", "KVEBBJ", "KRJL5B", "47TKDW", "L6FR23", "QAZKY7", "GAW5ML", "DJDKDZ", "KTU5AV", - "FA4M22", "UMPV3L", "MQMQAD", "OJ4PMG", "JGQ3SZ", "5W6XOM", "3LVJ4U", "DCQS43", "JZIBKA", "TKVVC2", - "V3VMCR", "THJTN3", "KGUJQA", "QW547X", "PGEV3I", "SV2TUY", "MZLUBG", "JQH35L", "PD2DAR", "KMFMLR", - "HUEY6I", "TVVIHY", "CRI266", "MLJIAB", "KTQDLD", "JPIYT6", "JW7SKI", "OV7PIV", "Q6U52T", "PABBEM", - "FAQG6B", "X4N332", "X3JKIW", "WEGNHV", "LZIM7P", "HVNNZ5", "VQ44KY", "O6UEGM", "F7NN7C", "FQMFJ5", - "EOROUF", "5SNWEH", "HFHLAH", "5DSDEB", "E2PZHU", "PLWHVO", "IGN4WA", "LGT75Q", "2ZQJJM", "4B2SL4", - "5BHPFP", "33PWC5", "4SMOYA" }; - - private static final String[] NUMBERS_BASE_32_HEX = { "31TMTU", "LJP8BH", "H33RK5", "IA667N", "NI15RN", "LN61P3", - "SPCI2M", "C70L9A", "I1787T", "S67VRU", "6C4AB0", "N3PJLM", "LHGA9K", "BLEV0M", "4CVRK1", "FA8GK5", - "EHL3I6", "GDAU0D", "I6OTD6", "6L4E0U", "L1IQD3", "4NK0DG", "GBJE3E", "PLN6V", "N3OTAM", "HUUJS0", "Q0ILK", - "K3QAOC", "J3CRBF", "FBD3PR", "DH4JGK", "B26VGG", "ISHJU2", "QEB3NV", "NK5FH2", "50NPJ8", "OIJ3GA", - "KO5QCN", "JF2A3Q", "AL4119", "AH9BT1", "SVJA3M", "BU5HQR", "G0PAOV", "60MTCB", "393A3P", "AJKT0L", - "50SCQQ", "KCFLRB", "CGCG03", "E9SFC6", "96GRIP", "TMUNEC", "RBL9SK", "32GISR", "9P81A0", "JALL2Q", - "LRLC2H", "J79JDR", "A6K9G0", "GMTSVN", "F64LR8", "ILQJKO", "CPBK16", "9G7RTB", "F3Q30H", "AC5CBH", - "7K4OU8", "JLL87O", "2H8QUU", "CB9801", "AJG3B3", "9F8OJU", "9MVIA8", "ELVF8L", "GUKTQJ", "F0114C", - "50G6U1", "NSDRRQ", "NR9A8M", "M46D7L", "BP8CVF", "7LDDPT", "LGSSAO", "EUK46C", "5VDDV2", "5GC59T", - "4EHEK5", "TIDM47", "757B07", "T3I341", "4QFP7K", "FBM7LE", "86DSM0", "B6JVTG", "QPG99C", "S1QIBS", - "T17F5F", "RRFM2T", "SICEO0" }; - - private static final String[] NUMBERS_BASE_32_Z = { "db7s76", "iu3emt", "tdd5wf", "1kgg8z", "z1bf5z", "izgb3d", - "h3c1ns", "c8yijk", "1b8e87", "hg8956", "gcrkmy", "zd3uis", "itokjw", "miq9ys", "rc95wb", "xkeowf", - "qtid1g", "opk6yp", "1ga7pg", "girqy6", "ib14pd", "rzwypo", "omuqdq", "3izg9", "zda7ks", "t66uhy", "4y1iw", - "wd4kac", "udc5mx", "xmpd35", "ptruow", "mng9oo", "1htu6n", "4qmdz9", "zwfxtn", "fyz3ue", "a1udok", - "waf4cz", "uxnkd4", "kirbbj", "ktjm7b", "h9ukds", "m6ft45", "oy3ka9", "gys7cm", "djdkd3", "kuw7yi", - "fyhc44", "wcxi5m", "cocoyd", "qjhxcg", "jgo513", "7s6zqc", "5mijhw", "dno1h5", "j3ebky", "ukiin4", - "i5icnt", "u8jup5", "kgwjoy", "os7h9z", "xgri5e", "1i4uwa", "c3mwbg", "jo857m", "xd4dyt", "kcfcmt", - "8wra6e", "uiie8a", "nte466", "cmjeyb", "kuodmd", "jxeau6", "js91ke", "qi9xei", "o6w74u", "xybbrc", - "fyog6b", "zhp554", "z5jkes", "srgp8i", "m3ec9x", "8ipp37", "iohhka", "q6wrgc", "f9pp9n", "focfj7", - "rqtqwf", "71psr8", "8f8my8", "7d1drb", "r4x38w", "xms8iq", "egphsy", "mgu97o", "43ojjc", "hb41mh", - "7b8xfx", "55xsn7", "h1cqay" }; - - private static final String[] NUMBERS_BASE_32_CROCKFORD = { "31XPXY", "NKS8BH", "H33VM5", "JA667Q", "QJ15VQ", - "NQ61S3", "WSCJ2P", "C70N9A", "J1787X", "W67ZVY", "6C4AB0", "Q3SKNP", "NHGA9M", "BNEZ0P", "4CZVM1", - "FA8GM5", "EHN3J6", "GDAY0D", "J6RXD6", "6N4E0Y", "N1JTD3", "4QM0DG", "GBKE3E", "SNQ6Z", "Q3RXAP", "HYYKW0", - "T0JNM", "M3TARC", "K3CVBF", "FBD3SV", "DH4KGM", "B26ZGG", "JWHKY2", "TEB3QZ", "QM5FH2", "50QSK8", "RJK3GA", - "MR5TCQ", "KF2A3T", "AN4119", "AH9BX1", "WZKA3P", "BY5HTV", "G0SARZ", "60PXCB", "393A3S", "AKMX0N", - "50WCTT", "MCFNVB", "CGCG03", "E9WFC6", "96GVJS", "XPYQEC", "VBN9WM", "32GJWV", "9S81A0", "KANN2T", - "NVNC2H", "K79KDV", "A6M9G0", "GPXWZQ", "F64NV8", "JNTKMR", "CSBM16", "9G7VXB", "F3T30H", "AC5CBH", - "7M4RY8", "KNN87R", "2H8TYY", "CB9801", "AKG3B3", "9F8RKY", "9PZJA8", "ENZF8N", "GYMXTK", "F0114C", - "50G6Y1", "QWDVVT", "QV9A8P", "P46D7N", "BS8CZF", "7NDDSX", "NGWWAR", "EYM46C", "5ZDDZ2", "5GC59X", - "4EHEM5", "XJDP47", "757B07", "X3J341", "4TFS7M", "FBP7NE", "86DWP0", "B6KZXG", "TSG99C", "W1TJBW", - "X17F5F", "VVFP2X", "WJCER0" }; - - private static final String INVALID_CHARS_BASE_32 = "!@#$%*()-_+|,.;:[]0189"; - private static final String INVALID_CHARS_BASE_32_HEX = "!@#$%*()-_+|,.;:[]XYZ"; - private static final String INVALID_CHARS_BASE_32_Z = "!@#$%*()-_+|,.;:[]iv2"; - private static final String INVALID_CHARS_BASE_32_CROCKFORD = "!@#$%*()-_+|,.;:[]ILOU"; - - @Test - public void testToBase32() { - String result = Base32Util.toBase32(LONG_TEXT); - assertEquals(LONG_TEXT_BASE_32.length(), result.length()); - assertTrue(LONG_TEXT_BASE_32.equals(result)); - - result = Base32Util.toBase32(SHORT_TEXT); - assertEquals(SHORT_TEXT_BASE_32.length(), result.length()); - assertTrue(SHORT_TEXT_BASE_32.equals(result)); - - for (int i = 0; i < WORDS.length; i++) { - result = Base32Util.toBase32(WORDS[i]); - assertEquals(WORDS_BASE_32[i].length(), result.length()); - assertTrue(WORDS_BASE_32[i].equals(result)); - } - } - - @Test - public void testFromBase32() { - String result = Base32Util.fromBase32AsString(LONG_TEXT_BASE_32); - assertEquals(LONG_TEXT.length(), result.length()); - assertTrue(LONG_TEXT.equals(result)); - - result = Base32Util.fromBase32AsString(SHORT_TEXT_BASE_32); - assertEquals(SHORT_TEXT.length(), result.length()); - assertTrue(SHORT_TEXT.equals(result)); - - for (int i = 0; i < WORDS.length; i++) { - result = Base32Util.fromBase32AsString(WORDS_BASE_32[i]); - assertEquals(WORDS[i].length(), result.length()); - assertTrue(WORDS[i].equals(result)); - } - - int count = 0; - for (int i = 0; i < INVALID_CHARS_BASE_32.length(); i++) { - try { - Base32Util.fromBase32AsString(SHORT_TEXT_BASE_32 + INVALID_CHARS_BASE_32.charAt(i)); - } catch (Base32UtilException e) { - count++; - } - } - assertEquals(INVALID_CHARS_BASE_32.length(), count); - - } - - @Test - public void testToBase32Hex() { - String result = Base32Util.toBase32Hex(LONG_TEXT); - assertTrue(LONG_TEXT_BASE_32_HEX.equals(result)); - assertEquals(LONG_TEXT_BASE_32_HEX.length(), result.length()); - - result = Base32Util.toBase32Hex(SHORT_TEXT); - assertTrue(SHORT_TEXT_BASE_32_HEX.equals(result)); - assertEquals(SHORT_TEXT_BASE_32_HEX.length(), result.length()); - - for (int i = 0; i < WORDS.length; i++) { - result = Base32Util.toBase32Hex(WORDS[i]); - assertEquals(WORDS_BASE_32_HEX[i].length(), result.length()); - assertTrue(WORDS_BASE_32_HEX[i].equals(result)); - } - } - - @Test - public void testFromBase32Hex() { - String result = Base32Util.fromBase32HexAsString(LONG_TEXT_BASE_32_HEX); - assertTrue(LONG_TEXT.equals(result)); - assertEquals(LONG_TEXT.length(), result.length()); - - result = Base32Util.fromBase32HexAsString(SHORT_TEXT_BASE_32_HEX); - assertEquals(SHORT_TEXT.length(), result.length()); - assertTrue(SHORT_TEXT.equals(result)); - - for (int i = 0; i < WORDS.length; i++) { - result = Base32Util.fromBase32HexAsString(WORDS_BASE_32_HEX[i]); - assertEquals(WORDS[i].length(), result.length()); - assertTrue(WORDS[i].equals(result)); - } - - int count = 0; - for (int i = 0; i < INVALID_CHARS_BASE_32_HEX.length(); i++) { - try { - Base32Util.fromBase32AsString(SHORT_TEXT_BASE_32_HEX + INVALID_CHARS_BASE_32_HEX.charAt(i)); - } catch (Base32UtilException e) { - count++; - } - } - assertEquals(INVALID_CHARS_BASE_32_HEX.length(), count); - } - - @Test - public void testToBase32Z() { - String result = Base32Util.toBase32Z(LONG_TEXT); - assertTrue(LONG_TEXT_BASE_32_Z.equals(result)); - assertEquals(LONG_TEXT_BASE_32_Z.length(), result.length()); - - result = Base32Util.toBase32Z(SHORT_TEXT); - assertEquals(SHORT_TEXT_BASE_32_Z.length(), result.length()); - assertTrue(SHORT_TEXT_BASE_32_Z.equals(result)); - - for (int i = 0; i < WORDS.length; i++) { - result = Base32Util.toBase32Z(WORDS[i]); - assertEquals(WORDS_BASE_32_Z[i].length(), result.length()); - assertTrue(WORDS_BASE_32_Z[i].equals(result)); - } - } - - @Test - public void testFromBase32Z() { - String result = Base32Util.fromBase32ZAsString(LONG_TEXT_BASE_32_Z); - assertTrue(LONG_TEXT.equals(result)); - assertEquals(LONG_TEXT.length(), result.length()); - - result = Base32Util.fromBase32ZAsString(SHORT_TEXT_BASE_32_Z); - assertTrue(SHORT_TEXT.equals(result)); - assertEquals(SHORT_TEXT.length(), result.length()); - - for (int i = 0; i < WORDS.length; i++) { - result = Base32Util.fromBase32ZAsString(WORDS_BASE_32_Z[i]); - assertEquals(WORDS[i].length(), result.length()); - assertTrue(WORDS[i].equals(result)); - } - - int count = 0; - for (int i = 0; i < INVALID_CHARS_BASE_32_Z.length(); i++) { - try { - Base32Util.fromBase32AsString(SHORT_TEXT_BASE_32_Z + INVALID_CHARS_BASE_32_Z.charAt(i)); - } catch (Base32UtilException e) { - count++; - } - } - assertEquals(INVALID_CHARS_BASE_32_Z.length(), count); - } - - @Test - public void testToBase32Crockford() { - String result = Base32Util.toBase32Crockford(LONG_TEXT); - assertEquals(LONG_TEXT_BASE_32_CROCKFORD.length(), result.length()); - assertTrue(LONG_TEXT_BASE_32_CROCKFORD.equals(result)); - - result = Base32Util.toBase32Crockford(SHORT_TEXT); - assertEquals(SHORT_TEXT_BASE_32_CROCKFORD.length(), result.length()); - assertTrue(SHORT_TEXT_BASE_32_CROCKFORD.equals(result)); - - for (int i = 0; i < WORDS.length; i++) { - result = Base32Util.toBase32Crockford(WORDS[i]); - assertEquals(WORDS_BASE_32_CROCKFORD[i].length(), result.length()); - assertTrue(WORDS_BASE_32_CROCKFORD[i].equals(result)); - } - } - - @Test - public void testFromBase32Crockford() { - String result = Base32Util.fromBase32CrockfordAsString(LONG_TEXT_BASE_32_CROCKFORD); - assertEquals(LONG_TEXT.length(), result.length()); - assertTrue(LONG_TEXT.equals(result)); - - result = Base32Util.fromBase32CrockfordAsString(SHORT_TEXT_BASE_32_CROCKFORD); - assertEquals(SHORT_TEXT.length(), result.length()); - assertTrue(SHORT_TEXT.equals(result)); - - for (int i = 0; i < WORDS.length; i++) { - result = Base32Util.fromBase32CrockfordAsString(WORDS_BASE_32_CROCKFORD[i]); - assertEquals(WORDS[i].length(), result.length()); - assertTrue(WORDS[i].equals(result)); - } - - int count = 0; - for (int i = 0; i < INVALID_CHARS_BASE_32_CROCKFORD.length(); i++) { - try { - Base32Util.fromBase32AsString(SHORT_TEXT_BASE_32_CROCKFORD + INVALID_CHARS_BASE_32_CROCKFORD.charAt(i)); - } catch (Base32UtilException e) { - count++; - } - } - assertEquals(INVALID_CHARS_BASE_32_CROCKFORD.length(), count); - } - - @Test - public void testToBase32AsNumber() { - String result = null; - - // Encode from long to base 32 - for (int i = 0; i < NUMBERS.length; i++) { - result = Base32Util.toBase32(NUMBERS[i]); - assertEquals(NUMBERS_BASE_32[i].length(), result.length()); - assertEquals(NUMBERS_BASE_32[i], result); - } - - // Encode from BigInteger to base 32 - for (int i = 0; i < NUMBERS.length; i++) { - result = Base32Util.toBase32(BigInteger.valueOf((NUMBERS[i]))); - assertEquals(NUMBERS_BASE_32[i].length(), result.length()); - assertEquals(NUMBERS_BASE_32[i], result); - } - - // Decode from base 32 to long - long number = 0; - for (int i = 0; i < NUMBERS.length; i++) { - number = Base32Util.fromBase32AsLong((NUMBERS_BASE_32[i])); - assertEquals(NUMBERS[i], number); - } - - // Decode from base 32 to BigInteger - for (int i = 0; i < NUMBERS.length; i++) { - number = Base32Util.fromBase32AsBigInteger((NUMBERS_BASE_32[i])).longValue(); - assertEquals(NUMBERS[i], number); - } - } - - @Test - public void testToBase32HexAsNumber() { - String result = null; - - // Encode from long to base 32 - for (int i = 0; i < NUMBERS_BASE_32_HEX.length; i++) { - result = Base32Util.toBase32Hex(NUMBERS[i]); - assertEquals(NUMBERS_BASE_32_HEX[i].length(), result.length()); - assertEquals(NUMBERS_BASE_32_HEX[i], result); - } - - // Encode from BigInteger to base 32 - for (int i = 0; i < NUMBERS_BASE_32_HEX.length; i++) { - result = Base32Util.toBase32Hex(BigInteger.valueOf(NUMBERS[i])); - assertEquals(NUMBERS_BASE_32_HEX[i].length(), result.length()); - assertEquals(NUMBERS_BASE_32_HEX[i], result); - } - - // Decode from base 32 to long - long number = 0; - for (int i = 0; i < NUMBERS.length; i++) { - number = Base32Util.fromBase32HexAsLong((NUMBERS_BASE_32_HEX[i])); - assertEquals(NUMBERS[i], number); - } - - // Decode from base 32 to BigInteger - for (int i = 0; i < NUMBERS.length; i++) { - number = Base32Util.fromBase32HexAsBigInteger((NUMBERS_BASE_32_HEX[i])).longValue(); - assertEquals(NUMBERS[i], number); - } - } - - @Test - public void testToBase32ZAsNumber() { - String result = null; - - // Encode from long to base 32 - for (int i = 0; i < NUMBERS.length; i++) { - result = Base32Util.toBase32Z(NUMBERS[i]); - assertEquals(NUMBERS_BASE_32_Z[i].length(), result.length()); - assertEquals(NUMBERS_BASE_32_Z[i], result); - } - - // Encode from BigInteger to base 32 - for (int i = 0; i < NUMBERS.length; i++) { - result = Base32Util.toBase32Z(BigInteger.valueOf(NUMBERS[i])); - assertEquals(NUMBERS_BASE_32_Z[i].length(), result.length()); - assertEquals(NUMBERS_BASE_32_Z[i], result); - } - - // Decode from base 32 to long - long number = 0; - for (int i = 0; i < NUMBERS.length; i++) { - number = Base32Util.fromBase32ZAsLong((NUMBERS_BASE_32_Z[i])); - assertEquals(NUMBERS[i], number); - } - - // Decode from base 32 to BigInteger - for (int i = 0; i < NUMBERS.length; i++) { - number = Base32Util.fromBase32ZAsBigInteger((NUMBERS_BASE_32_Z[i])).longValue(); - assertEquals(NUMBERS[i], number); - } - } - - @Test - public void testToBase32CrockfordAsNumber() { - String result = null; - - // Encode from long to base 32 - for (int i = 0; i < NUMBERS.length; i++) { - result = Base32Util.toBase32Crockford(NUMBERS[i]); - assertEquals(NUMBERS_BASE_32_CROCKFORD[i].length(), result.length()); - assertEquals(NUMBERS_BASE_32_CROCKFORD[i], result); - } - - // Encode from BigInteger to base 32 - for (int i = 0; i < NUMBERS.length; i++) { - result = Base32Util.toBase32Crockford(BigInteger.valueOf(NUMBERS[i])); - assertEquals(NUMBERS_BASE_32_CROCKFORD[i].length(), result.length()); - assertEquals(NUMBERS_BASE_32_CROCKFORD[i], result); - } - - // Decode from base 32 to long - long number = 0; - for (int i = 0; i < NUMBERS.length; i++) { - number = Base32Util.fromBase32CrockfordAsLong((NUMBERS_BASE_32_CROCKFORD[i])); - assertEquals(NUMBERS[i], number); - } - - // Decode from base 32 to BigInteger - for (int i = 0; i < NUMBERS.length; i++) { - number = Base32Util.fromBase32CrockfordAsBigInteger((NUMBERS_BASE_32_CROCKFORD[i])).longValue(); - assertEquals(NUMBERS[i], number); - } - } -} diff --git a/src/test/java/com/github/f4b6a3/ulid/util/ByteUtilTest.java b/src/test/java/com/github/f4b6a3/ulid/util/ByteUtilTest.java deleted file mode 100644 index 9e869f6..0000000 --- a/src/test/java/com/github/f4b6a3/ulid/util/ByteUtilTest.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.github.f4b6a3.ulid.util; - -import org.junit.Test; - -import static com.github.f4b6a3.ulid.util.ByteUtil.*; - -import static org.junit.Assert.*; - -public class ByteUtilTest { - - - private long[] numbers = { 0x0000000000000000L, 0x0000000000000001L, 0x0000000000000012L, 0x0000000000000123L, - 0x0000000000001234L, 0x0000000000012345L, 0x0000000000123456L, 0x0000000001234567L, 0x0000000012345678L, - 0x0000000123456789L, 0x000000123456789aL, 0x00000123456789abL, 0x0000123456789abcL, 0x000123456789abcdL, - 0x00123456789abcdeL, 0x0123456789abcdefL }; - - private String[] hexadecimals = { "0000000000000000", "0000000000000001", "0000000000000012", "0000000000000123", - "0000000000001234", "0000000000012345", "0000000000123456", "0000000001234567", "0000000012345678", - "0000000123456789", "000000123456789a", "00000123456789ab", "0000123456789abc", "000123456789abcd", - "00123456789abcde", "0123456789abcdef" }; - - private byte[][] bytes = { - { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 }, - { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01 }, - { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x12 }, - { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x23 }, - { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x12, (byte) 0x34 }, - { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x23, (byte) 0x45 }, - { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x12, (byte) 0x34, (byte) 0x56 }, - { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x23, (byte) 0x45, (byte) 0x67 }, - { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78 }, - { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x23, (byte) 0x45, (byte) 0x67, (byte) 0x89 }, - { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a }, - { (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x23, (byte) 0x45, (byte) 0x67, (byte) 0x89, (byte) 0xab }, - { (byte) 0x00, (byte) 0x00, (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc }, - { (byte) 0x00, (byte) 0x01, (byte) 0x23, (byte) 0x45, (byte) 0x67, (byte) 0x89, (byte) 0xab, (byte) 0xcd }, - { (byte) 0x00, (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc, (byte) 0xde }, - { (byte) 0x01, (byte) 0x23, (byte) 0x45, (byte) 0x67, (byte) 0x89, (byte) 0xab, (byte) 0xcd, (byte) 0xef } - }; - - @Test - public void testConcat() { - - String string1 = "CONCA"; - String string2 = "TENATE"; - - byte[] bytes1 = (string1 + string2).getBytes(); - byte[] bytes2 = concat(string1.getBytes(), string2.getBytes()); - - assertEquals(bytes1.length, bytes2.length); - - for (int i = 0; i < bytes1.length; i++) { - if (bytes1[i] != bytes2[i]) { - fail(); - } - } - } - - @Test - public void testReplace() { - - byte[] bytes1 = bytes[0]; - byte[] bytes2 = {(byte) 0x01, (byte) 0x23 }; - - byte[] bytes3 = replace(bytes1, bytes2, 6); - - assertEquals(bytes[0].length, bytes3.length); - - for (int i = 0; i < bytes[0].length; i++) { - if (bytes3[i] != bytes[3][i]) { - fail(); - } - } - } - - @Test - public void testToBytes() { - - byte[] bytes1 = toBytes(numbers[15]); - - assertEquals(bytes[15].length, bytes1.length); - - for (int i = 0; i < bytes[15].length; i++) { - if (bytes1[i] != bytes[15][i]) { - fail(); - } - } - } - - @Test - public void testCopy() { - - byte[] bytes1 = copy(bytes[15]); - - assertEquals(bytes[15].length, bytes1.length); - - for (int i = 0; i < bytes[15].length; i++) { - if (bytes1[i] != bytes[15][i]) { - fail(); - } - } - } - - @Test - public void testArray() { - - byte[] bytes1 = array(bytes[0].length, bytes[0][0]); - - assertEquals(bytes[0].length, bytes1.length); - - for (int i = 0; i < bytes[0].length; i++) { - if (bytes1[i] != bytes[0][i]) { - fail(); - } - } - } - - @Test - public void testToNumberFromBytes() { - for (int i = 0; i < numbers.length; i++) { - assertEquals(numbers[i], toNumber(bytes[i])); - } - } - - @Test - public void testToBytesFromHexadecimals() { - for (int i = 0; i < bytes.length; i++) { - assertTrue(equalArrays(bytes[i], toBytes(hexadecimals[i]))); - } - } - - @Test - public void testToHexadecimalFromBytes() { - for (int i = 0; i < hexadecimals.length; i++) { - assertEquals(hexadecimals[i], toHexadecimal(bytes[i])); - } - } - - @Test - public void testToNumberFromHexadecimal() { - for (int i = 0; i < hexadecimals.length; i++) { - assertEquals(numbers[i], toNumber(hexadecimals[i])); - } - } -} diff --git a/src/test/java/com/github/f4b6a3/ulid/util/UlidUtilTest.java b/src/test/java/com/github/f4b6a3/ulid/util/UlidUtilTest.java index d94e21b..e41b7a1 100644 --- a/src/test/java/com/github/f4b6a3/ulid/util/UlidUtilTest.java +++ b/src/test/java/com/github/f4b6a3/ulid/util/UlidUtilTest.java @@ -7,6 +7,8 @@ import java.util.UUID; import org.junit.Test; import com.github.f4b6a3.ulid.util.UlidUtil.UlidUtilException; +import com.github.f4b6a3.commons.util.Base32Util; +import com.github.f4b6a3.commons.util.ByteUtil; import com.github.f4b6a3.ulid.UlidCreator; public class UlidUtilTest { @@ -182,7 +184,7 @@ public class UlidUtilTest { for (int i = 0; i < DEFAULT_LOOP_MAX; i++) { - UUID uuid1 = UlidCreator.getGuid(); + UUID uuid1 = UlidCreator.getUlid(); String ulid = UlidUtil.fromUuidToUlid(uuid1); assertTrue("ULID is null", ulid != null); @@ -200,7 +202,7 @@ public class UlidUtilTest { @Test public void testToAndFromBytes() { for (int i = 0; i < DEFAULT_LOOP_MAX; i++) { - String ulid1 = UlidCreator.getUlid(); + String ulid1 = UlidCreator.getUlidString(); byte[] bytes = UlidUtil.fromUlidToBytes(ulid1); String ulid2 = UlidUtil.fromBytesToUlid(bytes); @@ -223,7 +225,7 @@ public class UlidUtilTest { @Test public void testFromUuidToBytes() { for (int i = 0; i < DEFAULT_LOOP_MAX; i++) { - UUID uuid1 = UlidCreator.getGuid(); + UUID uuid1 = UlidCreator.getUlid(); byte[] bytes = UlidUtil.fromUuidToBytes(uuid1); long msb = ByteUtil.toNumber(ByteUtil.copy(bytes, 0, 8)); long lsb = ByteUtil.toNumber(ByteUtil.copy(bytes, 8, 16)); @@ -235,7 +237,7 @@ public class UlidUtilTest { @Test public void testFromBytesToUuid() { for (int i = 0; i < DEFAULT_LOOP_MAX; i++) { - UUID uuid1 = UlidCreator.getGuid(); + UUID uuid1 = UlidCreator.getUlid(); byte[] bytes = UlidUtil.fromUuidToBytes(uuid1); UUID uuid2 = UlidUtil.fromBytesToUuid(bytes); assertEquals(uuid1, uuid2);