docs(global): Improve documentation comments

Enriched the content of the documentation to ensure every package and
class has proper documentation comments; Modified the formatting for
consistent and neat presentation.
This commit is contained in:
Zihlu Wang
2023-07-30 02:27:05 +08:00
parent 89837f78f3
commit 65daccf478
19 changed files with 616 additions and 186 deletions
+4 -1
View File
@@ -2,6 +2,9 @@
JDevKit is a Java Development Kit that offers a set of convenient tools for writing code efficiently. JDevKit is a Java Development Kit that offers a set of convenient tools for writing code efficiently.
## Modules ## Modules
### `devkit-core`
The core module for `JDevKit`, by now, this module contains the commonly used classes of the whole `dev-kit`.
### `guid` ### `guid`
A module for generating globally unique IDs. It includes a facade interface and an implementation of GUID generation using the Snowflake algorithm. More globally unique ID generation modes will be added in the future. A module for generating globally unique IDs. It includes a facade interface and an implementation of GUID generation using the Snowflake algorithm. More globally unique ID generation modes will be added in the future.
@@ -52,7 +55,7 @@ implementation 'cn.org.codecrafters:$artifactId:$version'
If you want to check the available versions, please check out at our [official site](). If you want to check the available versions, please check out at our [official site]().
## Contribution ## Contribution
Contributions are welcome! If you encounter any issues or want to contribute to the project, please feel free to **[raise an issue]()** or **[submit a pull request]()**. Contributions are welcome! If you encounter any issues or want to contribute to the project, please feel free to **[raise an issue](https://github.com/CodeCraftersCN/jdevkit/issues/new)** or **[submit a pull request]()**.
## License ## License
This project is licensed under the [Apache License 2.0](LICENSE). This project is licensed under the [Apache License 2.0](LICENSE).
@@ -24,15 +24,18 @@ import java.util.Base64;
/** /**
* Utility class for Base64 encoding and decoding of strings. * Utility class for Base64 encoding and decoding of strings.
* <p> * <p>
* The {@code Base64Util} class provides static methods to encode and decode strings using Base64 encoding. * The {@code Base64Util} class provides static methods to encode and decode
* It utilizes the {@link Base64} class from the Java standard library for performing the encoding and decoding operations. * strings using Base64 encoding. It utilizes the {@link Base64} class from the
* This utility class offers convenient methods to encode and decode strings with different character sets. * Java standard library for performing the encoding and decoding operations.
* This utility class offers convenient methods to encode and decode strings
* with different character sets.
* <p> * <p>
* This class is designed as a final class with a private constructor to prevent instantiation. * This class is designed as a final class with a private constructor to
* All methods in this class are static, allowing easy access to the Base64 encoding and decoding functionality. * prevent instantiation. All methods in this class are static, allowing easy
* access to the Base64 encoding and decoding functionality.
* <p> * <p>
* Example usage: * Example usage:
* <pre>{@code * <pre>
* String original = "Hello, World!"; * String original = "Hello, World!";
* *
* // Encode the string using UTF-8 charset * // Encode the string using UTF-8 charset
@@ -42,17 +45,15 @@ import java.util.Base64;
* // Decode the encoded string using UTF-8 charset * // Decode the encoded string using UTF-8 charset
* String decoded = Base64Util.decode(encoded); * String decoded = Base64Util.decode(encoded);
* System.out.println("Decoded string: " + decoded); * System.out.println("Decoded string: " + decoded);
* }</pre> * </pre>
* <p> * <p>
* <b>Note:</b> This utility class uses the default charset (UTF-8) if no specific charset is provided. * <b>Note:</b> This utility class uses the default charset (UTF-8) if no
* It is recommended to specify the charset explicitly to ensure consistent encoding and decoding. * specific charset is provided. It is recommended to specify the charset
* <p> * explicitly to ensure consistent encoding and decoding.
* <b>Thread Safety:</b> The methods in this class are thread-safe.
* Multiple threads can safely use the methods for encoding and decoding strings simultaneously.
* *
* @since 10 Jul 2023
* @author Zihlu Wang * @author Zihlu Wang
* @version 1.0.0 * @version 1.0.0
* @since 1.0.0
*/ */
public final class Base64Util { public final class Base64Util {
@@ -25,15 +25,14 @@ import java.util.function.Supplier;
/** /**
* Utility class to simplify if...else logic using lambda expressions. * Utility class to simplify if...else logic using lambda expressions.
* <p> * <p>
* The BranchUtil class provides static methods to simplify conditional * The BranchUtil class provides static methods to simplify conditional logic
* logic in Java development by leveraging lambda expressions. It offers * in Java development by leveraging lambda expressions. It offers convenient
* convenient methods to replace verbose if...else statements with more * methods to replace verbose if...else statements with more concise and
* concise and expressive functional constructs. * expressive functional constructs.
* <p> * <p>
* Developers can use the methods in this utility class to streamline * Developers can use the methods in this utility class to streamline their
* their code, enhance readability, and promote a more functional style * code, enhance readability, and promote a more functional style of
* of programming when dealing with branching logic and conditional * programming when dealing with branching logic and conditional statements.
* statements.
* <p> * <p>
* <b>Example:</b> * <b>Example:</b>
* <pre> * <pre>
@@ -54,7 +53,8 @@ import java.util.function.Supplier;
* }, () -> { * }, () -> {
* // do something * // do something
* }); * });
* // If you only need an if branch, you can remove the second Supplier instance. * // If you only need an if branch, you can remove the second Supplier
* // instance.
* *
* // To check if all boolean expressions are true, use the 'and' method: * // To check if all boolean expressions are true, use the 'and' method:
* BranchUtil.and(1 == 1, 2 == 1) * BranchUtil.and(1 == 1, 2 == 1)
@@ -66,17 +66,17 @@ import java.util.function.Supplier;
* </pre> * </pre>
* *
* <b>Note:</b> * <b>Note:</b>
* The {@link #and(Boolean...)} and {@link #or(Boolean...)} methods accept any number of boolean expressions. * The {@link #and(Boolean...)} and {@link #or(Boolean...)} methods accept any
* number of boolean expressions.
* <p> * <p>
* Created on 9 Jul 2023.
* *
* @param <T> the type of the result to be handled by the methods * @param <T> the type of the result to be handled by the methods
* @author Zihlu Wang
* @version 1.0.0
* @see java.util.function.Supplier * @see java.util.function.Supplier
* @see java.util.function.BooleanSupplier * @see java.util.function.BooleanSupplier
* @see java.lang.Runnable * @see java.lang.Runnable
* @since 9 Jul 2023 * @since 1.0.0
* @version 1.0.0
* @author Zihlu Wang
*/ */
public final class BranchUtil<T> { public final class BranchUtil<T> {
@@ -95,11 +95,13 @@ public final class BranchUtil<T> {
} }
/** /**
* Creates a {@code BranchUtil} instance to evaluate a logical OR operation on the provided boolean expressions. * Creates a {@code BranchUtil} instance to evaluate a logical OR operation
* on the provided boolean expressions.
* *
* @param booleans the boolean expressions to be evaluated * @param booleans the boolean expressions to be evaluated
* @param <T> the type of the result to be handled by the methods * @param <T> the type of the result to be handled by the methods
* @return a {@code BranchUtil} instance representing the result of the logical OR operation * @return a {@code BranchUtil} instance representing the result of the
* logical OR operation
*/ */
public static <T> BranchUtil<T> or(Boolean... booleans) { public static <T> BranchUtil<T> or(Boolean... booleans) {
var result = Arrays.stream(booleans) var result = Arrays.stream(booleans)
@@ -109,11 +111,13 @@ public final class BranchUtil<T> {
} }
/** /**
* Creates a {@code BranchUtil} instance to evaluate a logical AND operation on the provided boolean expressions. * Creates a {@code BranchUtil} instance to evaluate a logical AND
* operation on the provided boolean expressions.
* *
* @param booleans the boolean expressions to be evaluated * @param booleans the boolean expressions to be evaluated
* @param <T> the type of the result to be handled by the methods * @param <T> the type of the result to be handled by the methods
* @return a {@code BranchUtil} instance representing the result of the logical AND operation * @return a {@code BranchUtil} instance representing the result of the
* logical AND operation
*/ */
public static <T> BranchUtil<T> and(Boolean... booleans) { public static <T> BranchUtil<T> and(Boolean... booleans) {
var result = Arrays.stream(booleans) var result = Arrays.stream(booleans)
@@ -123,11 +127,14 @@ public final class BranchUtil<T> {
} }
/** /**
* Creates a {@code BranchUtil} instance to evaluate a logical OR operation on the provided boolean suppliers. * Creates a {@code BranchUtil} instance to evaluate a logical OR operation
* on the provided boolean suppliers.
* *
* @param booleanSuppliers the boolean suppliers to be evaluated * @param booleanSuppliers the boolean suppliers to be evaluated
* @param <T> the type of the result to be handled by the methods * @param <T> the type of the result to be handled by the
* @return a {@code BranchUtil} instance representing the result of the logical OR operation * methods
* @return a {@code BranchUtil} instance representing the result of the
* logical OR operation
*/ */
public static <T> BranchUtil<T> or(BooleanSupplier... booleanSuppliers) { public static <T> BranchUtil<T> or(BooleanSupplier... booleanSuppliers) {
var result = Arrays.stream(booleanSuppliers) var result = Arrays.stream(booleanSuppliers)
@@ -137,11 +144,14 @@ public final class BranchUtil<T> {
} }
/** /**
* Creates a {@code BranchUtil} instance to evaluate a logical AND operation on the provided boolean suppliers. * Creates a {@code BranchUtil} instance to evaluate a logical AND
* operation on the provided boolean suppliers.
* *
* @param booleanSuppliers the boolean suppliers to be evaluated * @param booleanSuppliers the boolean suppliers to be evaluated
* @param <T> the type of the result to be handled by the methods * @param <T> the type of the result to be handled by the
* @return a {@code BranchUtil} instance representing the result of the logical AND operation * methods
* @return a {@code BranchUtil} instance representing the result of the
* logical AND operation
*/ */
public static <T> BranchUtil<T> and(BooleanSupplier... booleanSuppliers) { public static <T> BranchUtil<T> and(BooleanSupplier... booleanSuppliers) {
var result = Arrays.stream(booleanSuppliers) var result = Arrays.stream(booleanSuppliers)
@@ -151,13 +161,21 @@ public final class BranchUtil<T> {
} }
/** /**
* Handles the result of the boolean expressions by executing the appropriate handler based on the result. * Handles the result of the boolean expressions by executing the
* If the result is {@code true}, the {@code ifHandler} is executed. If the result is {@code false} and an * appropriate handler based on the result.
* {@code elseHandler} is provided, it is executed. Returns the result of the executed handler. * <p>
* If the result is {@code true}, the {@code ifHandler} is executed. If the
* result is {@code false} and an {@code elseHandler} is provided, it is
* executed.
* <p>
* Returns the result of the executed handler.
* *
* @param ifHandler the handler to be executed if the result is {@code true} * @param ifHandler the handler to be executed if the result is
* @param elseHandler the handler to be executed if the result is {@code false} (optional) * {@code true}
* @return the result of the executed handler, or {@code null} if no elseHandler is provided * @param elseHandler the handler to be executed if the result is
* {@code false} (optional)
* @return the result of the executed handler, or {@code null} if no
* {@code elseHandler} is provided
*/ */
public T handle(Supplier<T> ifHandler, Supplier<T> elseHandler) { public T handle(Supplier<T> ifHandler, Supplier<T> elseHandler) {
if (this.result && Objects.nonNull(ifHandler)) { if (this.result && Objects.nonNull(ifHandler)) {
@@ -172,10 +190,13 @@ public final class BranchUtil<T> {
} }
/** /**
* Handles the result of the boolean expressions by executing the provided handler if the result is {@code true}. * Handles the result of the boolean expressions by executing the provided
* handler if the result is {@code true}.
* <p>
* Returns the result of the executed handler. * Returns the result of the executed handler.
* *
* @param ifHandler the handler to be executed if the result is {@code true} * @param ifHandler the handler to be executed if the result is
* {@code true}
* @return the result of the executed handler * @return the result of the executed handler
*/ */
public T handle(Supplier<T> ifHandler) { public T handle(Supplier<T> ifHandler) {
@@ -183,12 +204,17 @@ public final class BranchUtil<T> {
} }
/** /**
* Handles the result of the boolean expressions by executing the appropriate handler based on the result. * Handles the result of the boolean expressions by executing the
* If the result is {@code true}, the {@code ifHandler} is executed. If the result is {@code false} and an * appropriate handler based on the result.
* {@code elseHandler} is provided, it is executed. * <p>
* If the result is {@code true}, the {@code ifHandler} is executed. If the
* result is {@code false} and an {@code elseHandler} is provided, it is
* executed.
* *
* @param ifHandler the handler to be executed if the result is {@code true} * @param ifHandler the handler to be executed if the result is
* @param elseHandler the handler to be executed if the result is {@code false} (optional) * {@code true}
* @param elseHandler the handler to be executed if the result is
* {@code false} (optional)
*/ */
public void handle(Runnable ifHandler, Runnable elseHandler) { public void handle(Runnable ifHandler, Runnable elseHandler) {
if (this.result && Objects.nonNull(ifHandler)) { if (this.result && Objects.nonNull(ifHandler)) {
@@ -204,9 +230,11 @@ public final class BranchUtil<T> {
} }
/** /**
* Handles the result of the boolean expressions by executing the provided handler if the result is {@code true}. * Handles the result of the boolean expressions by executing the provided
* handler if the result is {@code true}.
* *
* @param ifHandler the handler to be executed if the result is {@code true} * @param ifHandler the handler to be executed if the result is
* {@code true}
*/ */
public void handle(Runnable ifHandler) { public void handle(Runnable ifHandler) {
handle(ifHandler, null); handle(ifHandler, null);
@@ -78,12 +78,14 @@ import java.util.function.Function;
* .divide(7) * .divide(7)
* .getValue(2); * .getValue(2);
* </pre> * </pre>
* The above expressions perform various mathematical calculations using the ChainedCalcUtil class. * The above expressions perform various mathematical calculations using the
* ChainedCalcUtil class.
* <p> * <p>
* <b>Note:</b> * <b>Note:</b>
* The ChainedCalcUtil class internally uses BigDecimal to handle high-precision calculations. It is important to note * The ChainedCalcUtil class internally uses BigDecimal to handle
* that BigDecimal operations can be memory-intensive and may have performance implications for extremely large numbers * high-precision calculations. It is important to note that BigDecimal
* or complex calculations. * operations can be memory-intensive and may have performance implications
* for extremely large numbers or complex calculations.
* *
* @author sunzsh * @author sunzsh
* @version 1.0.0 * @version 1.0.0
@@ -124,7 +126,8 @@ public final class ChainedCalcUtil {
} }
/** /**
* Adds the specified value to the current value with a specified scale before the operation. * Adds the specified value to the current value with a specified scale
* before the operation.
* *
* @param other the value to be added * @param other the value to be added
* @param beforeOperateScale the scale to be applied before the operation * @param beforeOperateScale the scale to be applied before the operation
@@ -145,7 +148,8 @@ public final class ChainedCalcUtil {
} }
/** /**
* Subtracts the specified value from the current value with a specified scale before the operation. * Subtracts the specified value from the current value with a specified
* scale before the operation.
* *
* @param other the value to be subtracted * @param other the value to be subtracted
* @param beforeOperateScale the scale to be applied before the operation * @param beforeOperateScale the scale to be applied before the operation
@@ -166,7 +170,8 @@ public final class ChainedCalcUtil {
} }
/** /**
* Multiplies the current value by the specified value with a specified scale before the operation. * Multiplies the current value by the specified value with a specified
* scale before the operation.
* *
* @param other the value to be multiplied by * @param other the value to be multiplied by
* @param beforeOperateScale the scale to be applied before the operation * @param beforeOperateScale the scale to be applied before the operation
@@ -187,7 +192,8 @@ public final class ChainedCalcUtil {
} }
/** /**
* Divides the current value by the specified value with a specified scale before the operation. * Divides the current value by the specified value with a specified scale
* before the operation.
* *
* @param other the value to divide by * @param other the value to divide by
* @param beforeOperateScale the scale to be applied before the operation * @param beforeOperateScale the scale to be applied before the operation
@@ -210,7 +216,8 @@ public final class ChainedCalcUtil {
} }
/** /**
* Divides the current value by the specified value with a specified scale and a scale applied before the operation. * Divides the current value by the specified value with a specified scale
* and a scale applied before the operation.
* *
* @param other the value to divide by * @param other the value to divide by
* @param scale the scale for the result * @param scale the scale for the result
@@ -278,7 +285,8 @@ public final class ChainedCalcUtil {
} }
/** /**
* Applies the specified operator function to the current value and another value. * Applies the specified operator function to the current value and another
* value.
* *
* @param operator the operator function to apply * @param operator the operator function to apply
* @param otherValue the value to apply the operator with * @param otherValue the value to apply the operator with
@@ -289,11 +297,13 @@ public final class ChainedCalcUtil {
} }
/** /**
* Applies the specified operator function to the current value and another value with a specified scale before the operation. * Applies the specified operator function to the current value and another
* value with a specified scale before the operation.
* *
* @param operator the operator function to apply * @param operator the operator function to apply
* @param other the value to apply the operator with * @param other the value to apply the operator with
* @param beforeOperateScale the scale to be applied before the operation, or null if not applicable * @param beforeOperateScale the scale to be applied before the operation,
* or null if not applicable
* @return a ChainedCalcUtil instance with the updated value * @return a ChainedCalcUtil instance with the updated value
*/ */
private ChainedCalcUtil operator(BiFunction<BigDecimal, BigDecimal, BigDecimal> operator, Object other, Integer beforeOperateScale) { private ChainedCalcUtil operator(BiFunction<BigDecimal, BigDecimal, BigDecimal> operator, Object other, Integer beforeOperateScale) {
@@ -301,11 +311,13 @@ public final class ChainedCalcUtil {
} }
/** /**
* Applies the specified operator function to the current value and another value. * Applies the specified operator function to the current value and another
* value.
* *
* @param operatorFunction the operator function to apply * @param operatorFunction the operator function to apply
* @param anotherValue the value to apply the operator with * @param anotherValue the value to apply the operator with
* @param beforeOperateScale the scale to be applied before the operation, or null if not applicable * @param beforeOperateScale the scale to be applied before the operation,
* or null if not applicable
* @return a ChainedCalcUtil instance with the updated value * @return a ChainedCalcUtil instance with the updated value
*/ */
private synchronized ChainedCalcUtil baseOperator(Function<BigDecimal, BigDecimal> operatorFunction, private synchronized ChainedCalcUtil baseOperator(Function<BigDecimal, BigDecimal> operatorFunction,
@@ -325,7 +337,8 @@ public final class ChainedCalcUtil {
* Converts the specified value to a BigDecimal. * Converts the specified value to a BigDecimal.
* *
* @param value the value to convert * @param value the value to convert
* @param scale the scale to apply to the resulting BigDecimal, or null if not applicable * @param scale the scale to apply to the resulting BigDecimal, or null if
* not applicable
* @return the converted BigDecimal value * @return the converted BigDecimal value
*/ */
private BigDecimal convertBigDecimal(Object value, Integer scale) { private BigDecimal convertBigDecimal(Object value, Integer scale) {
@@ -27,8 +27,9 @@ import java.util.Optional;
/** /**
* Utility class for performing hash operations on strings. * Utility class for performing hash operations on strings.
* <p> * <p>
* The HashUtil class provides convenient methods for calculating various hash functions on strings, including MD2, MD5, * The HashUtil class provides convenient methods for calculating various hash
* SHA-1, SHA-224, SHA-256, SHA-384, and SHA-512. It allows developers to easily obtain the hash value of a given * functions on strings, including MD2, MD5, SHA-1, SHA-224, SHA-256, SHA-384,
* and SHA-512. It allows developers to easily obtain the hash value of a given
* string using different algorithms. * string using different algorithms.
* <p> * <p>
* Example usage: * Example usage:
@@ -54,18 +55,19 @@ import java.util.Optional;
* // Perform SHA-512 hash operation * // Perform SHA-512 hash operation
* String sha512Hash = HashUtil.sha512("someString"); * String sha512Hash = HashUtil.sha512("someString");
* </pre> * </pre>
* The above examples demonstrate how to use the HashUtil class to calculate hash values for a given string using different * The above examples demonstrate how to use the HashUtil class to calculate
* algorithms. * hash values for a given string using different algorithms.
* <p> * <p>
* <b>Note:</b> * <b>Note:</b>
* The hash functions provided by the HashUtil class are one-way hash functions, meaning the original data cannot be * The hash functions provided by the HashUtil class are one-way hash
* retrieved from the hash value. These hash functions are commonly used for data integrity checks and password * functions, meaning the original data cannot be retrieved from the hash
* storage, but they should not be used for encryption purposes. * value. These hash functions are commonly used for data integrity checks and
* password storage, but they should not be used for encryption purposes.
* *
* @see java.security.MessageDigest
* @since 9 Jul 2023
* @version 1.0.0
* @author Zihlu Wang * @author Zihlu Wang
* @version 1.0.0
* @see java.security.MessageDigest
* @since 1.0.0
*/ */
public final class HashUtil { public final class HashUtil {
@@ -76,13 +78,17 @@ public final class HashUtil {
} }
/** /**
* Calculates the hash value of the specified string using the specified algorithm and charset. * Calculates the hash value of the specified string using the specified
* algorithm and charset.
* *
* @param method the hash algorithm to use * @param method the hash algorithm to use
* @param value the string to calculate the hash value for * @param value the string to calculate the hash value for
* @param charset the charset to use for encoding the string (default is UTF-8 if null) * @param charset the charset to use for encoding the string (default is
* @return the hash value as a hexadecimal string, or an empty string if the algorithm is not available * UTF-8 if null)
* @throws RuntimeException if an unknown algorithm name is provided (should not occur under controlled usage) * @return the hash value as a hexadecimal string, or an empty string if
* the algorithm is not available
* @throws RuntimeException if an unknown algorithm name is provided
* (should not occur under controlled usage)
*/ */
private static String hash(String method, String value, Charset charset) { private static String hash(String method, String value, Charset charset) {
try { try {
@@ -108,10 +114,12 @@ public final class HashUtil {
} }
/** /**
* Calculates the MD2 hash value of the specified string using the given charset. * Calculates the MD2 hash value of the specified string using the given
* charset.
* *
* @param value the string to calculate the MD2 hash value for * @param value the string to calculate the MD2 hash value for
* @param charset the charset to use for encoding the string (default is UTF-8 if null) * @param charset the charset to use for encoding the string (default is
* UTF-8 if null)
* @return the MD2 hash value as a hexadecimal string * @return the MD2 hash value as a hexadecimal string
*/ */
public static String md2(String value, Charset charset) { public static String md2(String value, Charset charset) {
@@ -120,7 +128,8 @@ public final class HashUtil {
} }
/** /**
* Calculates the MD2 hash value of the specified string using the UTF-8 charset. * Calculates the MD2 hash value of the specified string using the UTF-8
* charset.
* *
* @param value the string to calculate the MD2 hash value for * @param value the string to calculate the MD2 hash value for
* @return the MD2 hash value as a hexadecimal string * @return the MD2 hash value as a hexadecimal string
@@ -130,10 +139,12 @@ public final class HashUtil {
} }
/** /**
* Calculates the MD5 hash value of the specified string using the given charset. * Calculates the MD5 hash value of the specified string using the given
* charset.
* *
* @param value the string to calculate the MD5 hash value for * @param value the string to calculate the MD5 hash value for
* @param charset the charset to use for encoding the string (default is UTF-8 if null) * @param charset the charset to use for encoding the string (default is
* UTF-8 if null)
* @return the MD5 hash value as a hexadecimal string * @return the MD5 hash value as a hexadecimal string
*/ */
public static String md5(String value, Charset charset) { public static String md5(String value, Charset charset) {
@@ -142,7 +153,8 @@ public final class HashUtil {
} }
/** /**
* Calculates the MD5 hash value of the specified string using the UTF-8 charset. * Calculates the MD5 hash value of the specified string using the UTF-8
* charset.
* *
* @param value the string to calculate the MD5 hash value for * @param value the string to calculate the MD5 hash value for
* @return the MD5 hash value as a hexadecimal string * @return the MD5 hash value as a hexadecimal string
@@ -152,10 +164,12 @@ public final class HashUtil {
} }
/** /**
* Calculates the SHA-1 hash value of the specified string using the given charset. * Calculates the SHA-1 hash value of the specified string using the given
* charset.
* *
* @param value the string to calculate the SHA-1 hash value for * @param value the string to calculate the SHA-1 hash value for
* @param charset the charset to use for encoding the string (default is UTF-8 if null) * @param charset the charset to use for encoding the string (default is
* UTF-8 if null)
* @return the SHA-1 hash value as a hexadecimal string * @return the SHA-1 hash value as a hexadecimal string
*/ */
public static String sha1(String value, Charset charset) { public static String sha1(String value, Charset charset) {
@@ -164,7 +178,8 @@ public final class HashUtil {
} }
/** /**
* Calculates the SHA-1 hash value of the specified string using the UTF-8 charset. * Calculates the SHA-1 hash value of the specified string using the UTF-8
* charset.
* *
* @param value the string to calculate the SHA-1 hash value for * @param value the string to calculate the SHA-1 hash value for
* @return the SHA-1 hash value as a hexadecimal string * @return the SHA-1 hash value as a hexadecimal string
@@ -174,10 +189,12 @@ public final class HashUtil {
} }
/** /**
* Calculates the SHA-224 hash value of the specified string using the given charset. * Calculates the SHA-224 hash value of the specified string using the
* given charset.
* *
* @param value the string to calculate the SHA-224 hash value for * @param value the string to calculate the SHA-224 hash value for
* @param charset the charset to use for encoding the string (default is UTF-8 if null) * @param charset the charset to use for encoding the string (default is
* UTF-8 if null)
* @return the SHA-224 hash value as a hexadecimal string * @return the SHA-224 hash value as a hexadecimal string
*/ */
public static String sha224(String value, Charset charset) { public static String sha224(String value, Charset charset) {
@@ -186,7 +203,8 @@ public final class HashUtil {
} }
/** /**
* Calculates the SHA-224 hash value of the specified string using the UTF-8 charset. * Calculates the SHA-224 hash value of the specified string using the
* UTF-8 charset.
* *
* @param value the string to calculate the SHA-224 hash value for * @param value the string to calculate the SHA-224 hash value for
* @return the SHA-224 hash value as a hexadecimal string * @return the SHA-224 hash value as a hexadecimal string
@@ -196,10 +214,12 @@ public final class HashUtil {
} }
/** /**
* Calculates the SHA-256 hash value of the specified string using the given charset. * Calculates the SHA-256 hash value of the specified string using the
* given charset.
* *
* @param value the string to calculate the SHA-256 hash value for * @param value the string to calculate the SHA-256 hash value for
* @param charset the charset to use for encoding the string (default is UTF-8 if null) * @param charset the charset to use for encoding the string (default is
* UTF-8 if null)
* @return the SHA-256 hash value as a hexadecimal string * @return the SHA-256 hash value as a hexadecimal string
*/ */
public static String sha256(String value, Charset charset) { public static String sha256(String value, Charset charset) {
@@ -208,7 +228,8 @@ public final class HashUtil {
} }
/** /**
* Calculates the SHA-256 hash value of the specified string using the UTF-8 charset. * Calculates the SHA-256 hash value of the specified string using the
* UTF-8 charset.
* *
* @param value the string to calculate the SHA-256 hash value for * @param value the string to calculate the SHA-256 hash value for
* @return the SHA-256 hash value as a hexadecimal string * @return the SHA-256 hash value as a hexadecimal string
@@ -218,10 +239,12 @@ public final class HashUtil {
} }
/** /**
* Calculates the SHA-384 hash value of the specified string using the given charset. * Calculates the SHA-384 hash value of the specified string using the
* given charset.
* *
* @param value the string to calculate the SHA-384 hash value for * @param value the string to calculate the SHA-384 hash value for
* @param charset the charset to use for encoding the string (default is UTF-8 if null) * @param charset the charset to use for encoding the string (default is
* UTF-8 if null)
* @return the SHA-384 hash value as a hexadecimal string * @return the SHA-384 hash value as a hexadecimal string
*/ */
public static String sha384(String value, Charset charset) { public static String sha384(String value, Charset charset) {
@@ -230,7 +253,8 @@ public final class HashUtil {
} }
/** /**
* Calculates the SHA-384 hash value of the specified string using the UTF-8 charset. * Calculates the SHA-384 hash value of the specified string using the
* UTF-8 charset.
* *
* @param value the string to calculate the SHA-384 hash value for * @param value the string to calculate the SHA-384 hash value for
* @return the SHA-384 hash value as a hexadecimal string * @return the SHA-384 hash value as a hexadecimal string
@@ -240,10 +264,12 @@ public final class HashUtil {
} }
/** /**
* Calculates the SHA-512 hash value of the specified string using the given charset. * Calculates the SHA-512 hash value of the specified string using the
* given charset.
* *
* @param value the string to calculate the SHA-384 hash value for * @param value the string to calculate the SHA-384 hash value for
* @param charset the charset to use for encoding the string (default is UTF-8 if null) * @param charset the charset to use for encoding the string (default is
* UTF-8 if null)
* @return the SHA-512 hash value as a hexadecimal string * @return the SHA-512 hash value as a hexadecimal string
*/ */
public static String sha512(String value, Charset charset) { public static String sha512(String value, Charset charset) {
@@ -252,7 +278,8 @@ public final class HashUtil {
} }
/** /**
* Calculates the SHA-512 hash value of the specified string using the UTF-8 charset. * Calculates the SHA-512 hash value of the specified string using the
* UTF-8 charset.
* *
* @param value the string to calculate the SHA-384 hash value for * @param value the string to calculate the SHA-384 hash value for
* @return the SHA-512 hash value as a hexadecimal string * @return the SHA-512 hash value as a hexadecimal string
@@ -24,8 +24,11 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
/** /**
* MapUtil is a utility class that provides methods for converting objects to maps and maps to objects. * MapUtil is a utility class that provides methods for converting objects to
* It also provides methods for getting and setting field values using reflection. * maps and maps to objects.
* <p>
* It also provides methods for getting and setting field values using
* reflection.
* *
* @author Zihlu Wang * @author Zihlu Wang
* @version 1.0.0 * @version 1.0.0
@@ -41,11 +44,13 @@ public final class MapUtil {
} }
/** /**
* Converts an object to a map by mapping the field names to their corresponding values. * Converts an object to a map by mapping the field names to their
* corresponding values.
* *
* @param obj the object to be converted to a map * @param obj the object to be converted to a map
* @return a map representing the fields and their values of the object * @return a map representing the fields and their values of the object
* @throws IllegalAccessException if an error occurs while accessing the fields of the object * @throws IllegalAccessException if an error occurs while accessing the
* fields of the object
*/ */
public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException { public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
if (obj == null) { if (obj == null) {
@@ -67,16 +72,22 @@ public final class MapUtil {
} }
/** /**
* Converts a map to an object of the specified type by setting the field values using the map entries. * Converts a map to an object of the specified type by setting the field
* values using the map entries.
* *
* @param map the map representing the fields and their values * @param map the map representing the fields and their values
* @param requiredType the class of the object to be created * @param requiredType the class of the object to be created
* @param <T> the type of the object to be created * @param <T> the type of the object to be created
* @return an object of the specified type with the field values set from the map * @return an object of the specified type with the field values set from
* @throws NoSuchMethodException if the constructor of the required type is not found * the map
* @throws InvocationTargetException if an error occurs while invoking the constructor * @throws NoSuchMethodException if the constructor of the required
* @throws InstantiationException if the required type is abstract or an interface * type is not found
* @throws IllegalAccessException if an error occurs while accessing the fields of the object * @throws InvocationTargetException if an error occurs while invoking the
* constructor
* @throws InstantiationException if the required type is abstract or an
* interface
* @throws IllegalAccessException if an error occurs while accessing the
* fields of the object
*/ */
public static <T> T mapToObject(Map<String, Object> map, Class<T> requiredType) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { public static <T> T mapToObject(Map<String, Object> map, Class<T> requiredType) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
var bean = requiredType.getConstructor().newInstance(); var bean = requiredType.getConstructor().newInstance();
@@ -130,9 +141,12 @@ public final class MapUtil {
* @param fieldName the name of the field * @param fieldName the name of the field
* @param fieldType the class representing the type of the field value * @param fieldType the class representing the type of the field value
* @param <T> the type of the field value * @param <T> the type of the field value
* @return the value of the field in the object, or null if the field does not exist or cannot be accessed * @return the value of the field in the object, or null if the field does
* @throws IllegalAccessException if an error occurs while accessing the field * not exist or cannot be accessed
* @throws InvocationTargetException if an error occurs while invoking the field getter method * @throws IllegalAccessException if an error occurs while accessing the
* field
* @throws InvocationTargetException if an error occurs while invoking the
* field getter method
*/ */
public static <T> T getFieldValue(Object obj, String fieldName, Class<T> fieldType) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { public static <T> T getFieldValue(Object obj, String fieldName, Class<T> fieldType) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
var methodName = getMethodName("get", fieldName); var methodName = getMethodName("get", fieldName);
@@ -149,8 +163,10 @@ public final class MapUtil {
* @param obj the object in which to set the field value * @param obj the object in which to set the field value
* @param fieldName the name of the field * @param fieldName the name of the field
* @param fieldValue the value to be set * @param fieldValue the value to be set
* @throws InvocationTargetException if an error occurs while invoking the field setter method * @throws InvocationTargetException if an error occurs while invoking the
* @throws IllegalAccessException if an error occurs while accessing the field * field setter method
* @throws IllegalAccessException if an error occurs while accessing the
* field
*/ */
public static void setFieldValue(Object obj, String fieldName, Object fieldValue) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { public static void setFieldValue(Object obj, String fieldName, Object fieldValue) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
var objectClass = obj.getClass(); var objectClass = obj.getClass();
@@ -174,7 +190,8 @@ public final class MapUtil {
/** /**
* Returns the default string representation of the specified object. * Returns the default string representation of the specified object.
* *
* @param obj the object for which to return the default string representation * @param obj the object for which to return the default string
* representation
* @return the default string representation of the object * @return the default string representation of the object
*/ */
private static String defaultObject(Object obj) { private static String defaultObject(Object obj) {
@@ -191,7 +208,8 @@ public final class MapUtil {
* @param value the value to be casted * @param value the value to be casted
* @param requiredType the type to which the value should be casted * @param requiredType the type to which the value should be casted
* @param <T> the type to which the value should be casted * @param <T> the type to which the value should be casted
* @return the casted value, or null if the value cannot be casted to the required type * @return the casted value, or null if the value cannot be casted to the
* required type
*/ */
public static <T> T cast(Object value, Class<T> requiredType) { public static <T> T cast(Object value, Class<T> requiredType) {
if (requiredType.isInstance(value)) { if (requiredType.isInstance(value)) {
@@ -16,7 +16,13 @@
*/ */
/** /**
* Commonly used utils that helps to improve dev efficiency. * <h3>JDevKit Dev-Utils - Common Utility Classes</h3>
* <p>
* This package is part of JDevKit, an open-source Java Development Kit that
* provides a set of convenient tools to streamline code development and
* enhance productivity. This package serves as the root package for the module
* dev-utils, which contains a collection of common utility classes commonly
* used in all Java Application development.
* *
* @author Zihlu Wang * @author Zihlu Wang
* @since 1.0.0 * @since 1.0.0
@@ -18,28 +18,96 @@
package cn.org.codecrafters.devkit.core.exceptions; package cn.org.codecrafters.devkit.core.exceptions;
/** /**
* NotImplementedException * NotImplementedException - Custom Runtime Exception
* <p>
* The {@code NotImplementedException} class is a custom runtime exception
* that represents a situation where a particular method or functionality is
* not implemented or is currently unavailable in the codebase. It extends the
* standard {@code RuntimeException} class, making it an unchecked exception.
* <p>
* This exception is typically thrown when developers need to indicate that a
* specific part of the code is incomplete or requires further implementation.
* It serves as a placeholder to highlight unfinished sections of the
* application during development and testing phases.
* <p>
* Usage Example:
* <pre>
* public void someMethod() {
* // Some code...
* throw new NotImplementedException("""
* This feature will be implemented in a future release.
* """);
* }
* </pre>
* <p>
* For more information and the latest version of JDevKit, please visit our
* website <a href="https://codecrafters.org.cn">codecrafters.org.cn</a>.
* <p>
* <h4>Contact</h4>
* <ul>
* <li>
* <a href="https://github.com/CodeCraftersCN/jdevkit/issues/new"
* >GitHub Issues</a>
* </li>
* <li>
* <a href="https://discord.gg/">Discord Community</a>
* </li>
* </ul>
* *
* @author Zihlu Wang * @author Zihlu Wang
* @since 29 Jul 2023 * @version 1.0.0
* @see RuntimeException
* @since 1.0.0
*/ */
public class NotImplementedException extends RuntimeException { public class NotImplementedException extends RuntimeException {
/**
* Creates a new {@code NotImplementedException} with no specific error
* message.
*/
public NotImplementedException() { public NotImplementedException() {
} }
/**
* Creates a new {@code NotImplementedException} with the provided error
* message.
*
* @param message the error message associated with this exception
*/
public NotImplementedException(String message) { public NotImplementedException(String message) {
super(message); super(message);
} }
/**
* Creates a new {@code NotImplementedException} with the specified error
* message and a cause for this exception.
*
* @param message the error message associated with this exception
* @param cause the cause of this exception
*/
public NotImplementedException(String message, Throwable cause) { public NotImplementedException(String message, Throwable cause) {
super(message, cause); super(message, cause);
} }
/**
* Creates a new {@code NotImplementedException} with the specified cause.
*
* @param cause the cause of this exception
*/
public NotImplementedException(Throwable cause) { public NotImplementedException(Throwable cause) {
super(cause); super(cause);
} }
/**
* Creates a new {@code NotImplementedException} with the specified error
* message, cause, suppression flag, and stack trace writable flag.
*
* @param message the error message associated with this
* exception
* @param cause the cause of this exception
* @param enableSuppression whether suppression is enabled or disabled
* @param writableStackTrace whether the stack trace should be writable
*/
public NotImplementedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { public NotImplementedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace); super(message, cause, enableSuppression, writableStackTrace);
} }
@@ -16,9 +16,28 @@
*/ */
/** /**
* The core package for JDevKit, containing the core classes of JDevKit. * This package is a part of JDevKit, an open-source Java Development Kit that
* provides a set of convenient tools to streamline code development and
* enhance productivity. This package serves as the core package containing
* common exceptions that are used throughout the entireJDevKit project.
* <p>
* JDevKit is designed to be modular, and other specific feature modules within
* the library may rely on these exceptions from the core package.
* <p>
* For more information and the latest version of JDevKit, please visit our
* website <a href="https://codecrafters.org.cn">codecrafters.org.cn</a>.
* <p>
* <h4>Contact</h4>
* <ul>
* <li>
* <a href="https://github.com/CodeCraftersCN/jdevkit/issues/new"
* >GitHub Issues</a>
* </li>
* <li>
* <a href="https://discord.gg/">Discord Community</a>
* </li>
* </ul>
* *
* @author Zihlu Wang * @since 1.0.0
* @since 29 Jul 2023
*/ */
package cn.org.codecrafters.devkit.core; package cn.org.codecrafters.devkit.core;
@@ -16,12 +16,25 @@
*/ */
/** /**
* JDevKit package, please see documents for more details. * <h3>JDevKit - Java Development Kit</h3>
* <p> * <p>
* You may check the details of JDevKit at <a * This package is the main part of JDevKit, an open-source Java class library
* href="https://codecrafters.org.cn/JDevKit"> codecrafters.org.cn </a> * that provides a set of convenient tools to streamline code development and
* * enhance productivity. This package serves as the root package for several
* @author Zihlu Wang * modules, containing devkit-core, guid and dev-utils module.
* @since 1.0.0 * <p>
* For more information and the latest version of JDevKit, please visit our
* website <a href="https://codecrafters.org.cn">codecrafters.org.cn</a>.
* <p>
* <h4>Contact</h4>
* <ul>
* <li>
* <a href="https://github.com/CodeCraftersCN/jdevkit/issues/new"
* >GitHub Issues</a>
* </li>
* <li>
* <a href="https://discord.gg/">Discord Community</a>
* </li>
* </ul>
*/ */
package cn.org.codecrafters.devkit; package cn.org.codecrafters.devkit;
@@ -18,7 +18,7 @@
package cn.org.codecrafters.devkit.guid; package cn.org.codecrafters.devkit.guid;
/** /**
* The `GuidCreator` is a generic interface for generating globally unique * The {@code GuidCreator} is a generic interface for generating globally unique
* identifiers (GUIDs) of a specific type. * identifiers (GUIDs) of a specific type.
* <p> * <p>
* The type of ID is determined by the class implementing this interface. * The type of ID is determined by the class implementing this interface.
@@ -32,6 +32,7 @@ public interface GuidCreator<IdType> {
/** /**
* Generates and returns the next globally unique ID. * Generates and returns the next globally unique ID.
* <p>
* The exact implementation of how the globally unique ID is generated and * The exact implementation of how the globally unique ID is generated and
* returned will depend on the class implementing this method. * returned will depend on the class implementing this method.
* *
@@ -23,23 +23,28 @@ import java.time.LocalDateTime;
import java.time.ZoneOffset; import java.time.ZoneOffset;
/** /**
* SnowflakeGuidCreator is a GUID generator based on the Snowflake algorithm. * SnowflakeGuidCreator - GUID generator based on the Snowflake algorithm.
* It generates unique identifiers using a combination of timestamp, worker ID,
* and data center ID.
* *
* <p>The Snowflake algorithm allows for the generation of 64-bit long integers, * <p>
* with the following bit distribution: * The SnowflakeGuidCreator generates unique identifiers using the Snowflake
* - 1 bit for sign * algorithm, which combines a timestamp, worker ID, and data center ID to
* - 41 bits for timestamp (in milliseconds) * create 64-bit long integers. The bit distribution for the generated IDs is
* - 5 bits for data center ID * as follows:
* - 5 bits for worker ID * <ul>
* - 12 bits for sequence number (per millisecond) * <li>1 bit for sign</li>
* <li>41 bits for timestamp (in milliseconds)</li>
* <li>5 bits for data center ID</li>
* <li>5 bits for worker ID</li>
* <li>12 bits for sequence number (per millisecond)</li>
* </ul>
* *
* <p>The worker ID and data center ID must be specified during initialization, * <p>
* and they must be within the valid range defined by the bit size. * When initializing the SnowflakeGuidCreator, you must provide the worker ID
* The generator maintains an internal sequence number that increments for IDs * and data center ID, ensuring they are within the valid range defined by the
* generated within the same millisecond. If the system clock moves backwards, * bit size. The generator maintains an internal sequence number that
* an exception is thrown to avoid generating IDs with repeated timestamps. * increments for IDs generated within the same millisecond. If the system
* clock moves backward, an exception is thrown to prevent generating IDs with
* repeated timestamps.
* *
* @author Zihlu Wang * @author Zihlu Wang
* @version 1.0.0 * @version 1.0.0
@@ -48,7 +53,9 @@ import java.time.ZoneOffset;
public final class SnowflakeGuidCreator implements GuidCreator<Long> { public final class SnowflakeGuidCreator implements GuidCreator<Long> {
/** /**
* Default Custom Epoch (January 1, 2015, Midnight UTC = 2015-01-01T00:00:00Z) * Default custom epoch.
*
* @value 2015-01-01T00:00:00Z
*/ */
private static final long DEFAULT_CUSTOM_EPOCH = 1_420_070_400_000L; private static final long DEFAULT_CUSTOM_EPOCH = 1_420_070_400_000L;
@@ -88,7 +95,8 @@ public final class SnowflakeGuidCreator implements GuidCreator<Long> {
private long lastTimestamp = -1L; private long lastTimestamp = -1L;
/** /**
* Constructs a SnowflakeGuidGenerator with the default start epoch and custom worker ID, data center ID. * Constructs a SnowflakeGuidGenerator with the default start epoch and
* custom worker ID, data center ID.
* *
* @param workerId the worker ID (between 0 and 31). * @param workerId the worker ID (between 0 and 31).
* @param dataCentreId the data center ID (between 0 and 31). * @param dataCentreId the data center ID (between 0 and 31).
@@ -98,13 +106,16 @@ public final class SnowflakeGuidCreator implements GuidCreator<Long> {
} }
/** /**
* Constructs a SnowflakeGuidGenerator with a custom epoch, worker ID, and data center ID. * Constructs a SnowflakeGuidGenerator with a custom epoch, worker ID, and
* data center ID.
* *
* @param startEpoch the custom epoch timestamp (in milliseconds) to start generating IDs from * @param startEpoch the custom epoch timestamp (in milliseconds) to
* start generating IDs from
* @param workerId the worker ID (between 0 and 31) * @param workerId the worker ID (between 0 and 31)
* @param dataCentreId the data center ID (between 0 and 31) * @param dataCentreId the data center ID (between 0 and 31)
* @throws IllegalArgumentException if the start epoch is greater than the current timestamp, * @throws IllegalArgumentException if the start epoch is greater than the
* or if the worker ID or data center ID is out of range * current timestamp, or if the worker ID
* or data center ID is out of range
*/ */
public SnowflakeGuidCreator(long startEpoch, long workerId, long dataCentreId) { public SnowflakeGuidCreator(long startEpoch, long workerId, long dataCentreId) {
if (startEpoch > currentTimestamp()) { if (startEpoch > currentTimestamp()) {
@@ -18,20 +18,22 @@
package cn.org.codecrafters.devkit.guid.exceptions; package cn.org.codecrafters.devkit.guid.exceptions;
/** /**
* The TimingException class represents an exception that is thrown when there is an error related * The TimingException class represents an exception that is thrown when there
* to time sequence. * is an error related to time sequence.
* <p> * <p>
* This class extends the RuntimeException class, which means that instances of TimingException * This class extends the RuntimeException class, which means that instances of
* do not need to be declared in a method or constructor's throws clause. * TimingException do not need to be declared in a method or constructor's
* throws clause.
* <p> * <p>
* Instances of TimingException can be created with or without a message and a cause. The message * Instances of TimingException can be created with or without a message and a
* provides a description of the exception, while the cause represents the underlying cause of the * cause. The message provides a description of the exception, while the cause
* exception and provides additional information about the error. * represents the underlying cause of the exception and provides additional
* <p> * information about the error.
* TimingException is typically used to handle exceptions related to timing, such as timeouts or
* synchronization issues. It is a subclass of RuntimeException, which means it is an unchecked
* exception and does not need to be caught or declared.
* <p> * <p>
* TimingException is typically used to handle exceptions related to timing,
* such as timeouts or synchronization issues. It is a subclass of
* RuntimeException, which means it is an unchecked exception and does not need
* to be caught or declared.
* *
* @author Zihlu Wang * @author Zihlu Wang
* @since 1.0.0 * @since 1.0.0
@@ -39,14 +41,15 @@ package cn.org.codecrafters.devkit.guid.exceptions;
public class TimingException extends RuntimeException { public class TimingException extends RuntimeException {
/** /**
* A custom exception that is thrown when there is an issue with timing or scheduling. * A custom exception that is thrown when there is an issue with timing or
* scheduling.
*/ */
public TimingException() { public TimingException() {
} }
/** /**
* A custom exception that is thrown when there is an issue with timing or scheduling with * A custom exception that is thrown when there is an issue with timing or
* customized error message. * scheduling with customized error message.
* *
* @param message customized message * @param message customized message
*/ */
@@ -55,8 +58,8 @@ public class TimingException extends RuntimeException {
} }
/** /**
* A custom exception that is thrown when there is an issue with timing or scheduling with * A custom exception that is thrown when there is an issue with timing or
* customized error message. * scheduling with customized error message.
* *
* @param message customized message * @param message customized message
* @param cause the cause of this exception * @param cause the cause of this exception
@@ -66,8 +69,8 @@ public class TimingException extends RuntimeException {
} }
/** /**
* A custom exception that is thrown when there is an issue with timing or scheduling with * A custom exception that is thrown when there is an issue with timing or
* customized error message. * scheduling with customized error message.
* *
* @param cause the cause of this exception * @param cause the cause of this exception
*/ */
@@ -0,0 +1,23 @@
/*
* Copyright (C) 2023 CodeCraftersCN.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* The package provides all exceptions be used by module guid.
*
* @since 1.0.0
*/
package cn.org.codecrafters.devkit.guid.exceptions;
@@ -25,9 +25,9 @@
* <p> * <p>
* Key features include: * Key features include:
* <ul> * <ul>
* <li>Efficient generation of globally unique identifiers</li> * <li>Efficient generation of globally unique identifiers</li>
* <li>High performance and quick response</li> * <li>High performance and quick response</li>
* <li>Easy to integrate</li> * <li>Easy to integrate</li>
* </ul> * </ul>
* *
* @since 1.0.0 * @since 1.0.0
@@ -18,16 +18,36 @@
package cn.org.codecrafters.simplejwt; package cn.org.codecrafters.simplejwt;
/** /**
* ResolvedToken * ResolvedToken - Generic Record for Holding Resolved Tokens.
* <p>
* This class represents a generic record that holds a resolved token of type {@code T}. It is used as a simple
* container to store the resolved token value for further processing.
* <p>
* <b>Usage:</b>
* To create a new instance of {@code ResolvedToken}, use the static factory method {@code init}.
* *
* @param <T> the type of the resolved token
* @author Zihlu Wang * @author Zihlu Wang
* @since 29 Jul 2023 * @since 1.0.0
*/ */
public record ResolvedToken<T>(T resolvedToken) { public record ResolvedToken<T>(T resolvedToken) {
public ResolvedToken { /**
* Creates a new {@code ResolvedToken} instance with the provided {@code resolvedToken} value.
*
* @param resolvedToken the resolved token value to be stored in the {@code ResolvedToken}
*/
public ResolvedToken(T resolvedToken) {
this.resolvedToken = resolvedToken;
} }
/**
* Factory method to create a new {@code ResolvedToken} instance with the provided {@code resolvedToken} value.
*
* @param <T> the type of the resolved token
* @param resolvedToken the resolved token value to be stored in the {@code ResolvedToken}
* @return a new {@code ResolvedToken} instance containing the provided {@code resolvedToken}
*/
public static <T> ResolvedToken<T> init(T resolvedToken) { public static <T> ResolvedToken<T> init(T resolvedToken) {
return new ResolvedToken<>(resolvedToken); return new ResolvedToken<>(resolvedToken);
} }
@@ -17,11 +17,35 @@
package cn.org.codecrafters.simplejwt; package cn.org.codecrafters.simplejwt;
import java.util.Map;
/** /**
* PayloadObject * TokenPayload - Interface for JWT Payload Data Classes.
* <p>
* The {@code TokenPayload} interface is used to mark a data class as suitable
* for being used as the payload in a JSON Web Token (JWT). Any class
* implementing this interface can be used to represent the payload data that
* will be included in a JWT.
* <p>
* Implementing this interface indicates that the data class contains
* information that needs to be securely transmitted and verified as part of a
* JWT. The payload typically contains claims or attributes that provide
* additional information about the JWT subject or context.
* <p>
* <b>Usage:</b>
* To use a class as a JWT payload, simply implement the {@code TokenPayload}
* interface in the data class:
* <pre>
* public class UserData implements TokenPayload {
* // Class implementation with payload data...
* }
* </pre>
* *
* @author Zihlu Wang * @since 1.0.0
* @since 29 Jul 2023 * @version 1.0.0
*/ */
public interface TokenPayload { public interface TokenPayload {
// Marker interface for JWT payload data classes
} }
@@ -21,35 +21,164 @@ import java.time.Duration;
import java.util.Map; import java.util.Map;
/** /**
* TokenResolver * TokenResolver - Interface for Creating, Extracting, and Renewing Tokens.
* <p>
* The {@code TokenResolver} interface defines methods for creating,
* extracting, and renewing tokens, particularly JSON Web Tokens (JWTs). It
* provides a set of methods to generate tokens with various payload
* configurations, extract payloads from tokens, and renew expired tokens.
* <p>
* <b>Token Creation:</b>
* The interface provides overloaded methods for creating tokens with different
* payload configurations, including expiration time, audience, subject, and
* custom payload data. Clients can choose the appropriate method based on
* their specific token requirements.
* <p>
* <b>Token Extraction:</b>
* The interface includes methods to extract payload information from a given
* token. Clients can use these methods to obtain the payload data encoded in
* the token.
* <p>
* <b>Token Renewal:</b>
* The interface also offers methods for token renewal. Clients can renew an
* expired token by providing a new expiration time, audience, subject, and
* optional custom payload data.
* *
* @author Zihlu Wang * @version 1.0.0
* @since 29 Jul 2023 * @since 1.0.0
*/ */
public interface TokenResolver { public interface TokenResolver {
/**
* Creates a new token with the specified expiration time and audience.
*
* @param expireAfter the duration after which the token will expire
* @param audience the audience for which the token is intended
* @return the generated token as a {@code String}
*/
String createToken(Duration expireAfter, String audience); String createToken(Duration expireAfter, String audience);
/**
* Creates a new token with the specified expiration time, audience, and
* custom payload data.
*
* @param expireAfter the duration after which the token will expire
* @param audience the audience for which the token is intended
* @param payloads the custom payload data to be included in the token
* @return the generated token as a {@code String}
*/
String createToken(Duration expireAfter, String audience, Map<String, Object> payloads); String createToken(Duration expireAfter, String audience, Map<String, Object> payloads);
/**
* Creates a new token with the specified expiration time, audience, and
* strongly-typed payload data.
*
* @param <T> the type of the payload data, must implement
* {@link TokenPayload}
* @param expireAfter the duration after which the token will expire
* @param audience the audience for which the token is intended
* @param payloads the strongly-typed payload data to be included in the
* token
* @return the generated token as a {@code String}
*/
<T extends TokenPayload> String createToken(Duration expireAfter, String audience, T payloads); <T extends TokenPayload> String createToken(Duration expireAfter, String audience, T payloads);
/**
* Creates a new token with the specified expiration time, subject, and audience.
*
* @param expireAfter the duration after which the token will expire
* @param subject the subject of the token
* @param audience the audience for which the token is intended
* @return the generated token as a {@code String}
*/
String createToken(Duration expireAfter, String subject, String audience); String createToken(Duration expireAfter, String subject, String audience);
/**
* Creates a new token with the specified expiration time, subject,
* audience, and custom payload data.
*
* @param expireAfter the duration after which the token will expire
* @param subject the subject of the token
* @param audience the audience for which the token is intended
* @param payloads the custom payload data to be included in the token
* @return the generated token as a {@code String}
*/
String createToken(Duration expireAfter, String subject, String audience, Map<String, Object> payloads); String createToken(Duration expireAfter, String subject, String audience, Map<String, Object> payloads);
/**
* Creates a new token with the specified expiration time, subject,
* audience, and strongly-typed payload data.
*
* @param <T> the type of the payload data, must implement
* {@link TokenPayload}
* @param expireAfter the duration after which the token will expire
* @param subject the subject of the token
* @param audience the audience for which the token is intended
* @param payloads the strongly-typed payload data to be included in the
* token
* @return the generated token as a {@code String}
*/
<T extends TokenPayload> String createToken(Duration expireAfter, String subject, String audience, T payloads); <T extends TokenPayload> String createToken(Duration expireAfter, String subject, String audience, T payloads);
/**
* Extracts the payload information from the given token.
*
* @param token the token from which to extract the payload
* @return a map containing the extracted payload data
*/
Map<String, Object> extract(String token); Map<String, Object> extract(String token);
/**
* Extracts the payload information from the given token and maps it to the
* specified target type.
*
* @param <T> the target type to which the payload data will be
* mapped
* @param token the token from which to extract the payload
* @param targetType the target class representing the payload data type
* @return an instance of the specified target type with the extracted
* payload data
*/
<T extends TokenPayload> T extract(String token, Class<T> targetType); <T extends TokenPayload> T extract(String token, Class<T> targetType);
/**
* Renews the given expired token.
*
* @param oldToken the expired token to be renewed
* @return the renewed token as a {@code String}
*/
String renew(String oldToken); String renew(String oldToken);
/**
* Renews the given expired token with the specified custom payload data.
*
* @param oldToken the expired token to be renewed
* @param payloads the custom payload data to be included in the renewed
* token
* @return the renewed token as a {@code String}
*/
String renew(String oldToken, Map<String, Object> payloads); String renew(String oldToken, Map<String, Object> payloads);
/**
* Renews the given expired token with the specified strongly-typed
* payload data.
*
* @param <T> the type of the payload data, must implement
* {@link TokenPayload}
* @param oldToken the expired token to be renewed
* @param payloads the strongly-typed payload data to be included in the
* renewed token
* @return the renewed token as a {@code String}
*/
<T extends TokenPayload> String renew(String oldToken, T payloads); <T extends TokenPayload> String renew(String oldToken, T payloads);
/**
* Resolves the given token into a {@link ResolvedToken} object.
*
* @param <T> the type of the resolved token
* @param token the token to be resolved
* @return a {@link ResolvedToken} object containing the resolved token
*/
<T> ResolvedToken<T> resolve(String token); <T> ResolvedToken<T> resolve(String token);
} }
@@ -0,0 +1,23 @@
/*
* Copyright (C) 2023 CodeCraftersCN.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* package-info
*
* @author Zihlu Wang
*/
package cn.org.codecrafters.simplejwt;