docs: added JavaDoc

This commit is contained in:
zihluwang
2024-06-30 13:10:38 +08:00
parent da23cf1a83
commit 23e9cc8109
15 changed files with 216 additions and 238 deletions
@@ -23,15 +23,14 @@ import java.util.Base64;
import java.util.Objects; import java.util.Objects;
/** /**
* The {@link Base64Util} class provides static methods to encode and decode * The {@link Base64Util} class provides static methods to encode and decode strings with Base64
* strings with Base64 encoding. It utilizes the {@link Base64} class from the * encoding. It utilizes the {@link Base64} class from the Java standard library for performing the
* Java standard library for performing the encoding and decoding operations. * encoding and decoding operations. This utility class offers convenient methods to encode and
* This utility class offers convenient methods to encode and decode strings * decode strings with different character sets.
* with different character sets.
* <p> * <p>
* This class is designed as a final class with a private constructor to * This class is designed as a final class with a private constructor to prevent instantiation.
* prevent instantiation. All methods in this class are static, allowing easy * All methods in this class are static, allowing easy access to the Base64 encoding and
* access to the Base64 encoding and decoding functionality. * decoding functionality.
* <p> * <p>
* Example usage: * Example usage:
* <pre> * <pre>
@@ -46,9 +45,9 @@ import java.util.Objects;
* 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 * <b>Note:</b> This utility class uses the default charset (UTF-8) if no specific charset is
* specific charset is provided. It is recommended to specify the charset * provided. It is recommended to specify the charset explicitly to ensure consistent
* explicitly to ensure consistent encoding and decoding. * encoding and decoding.
* *
* @author Zihlu Wang * @author Zihlu Wang
* @version 1.1.0 * @version 1.1.0
@@ -23,14 +23,13 @@ import java.util.function.BooleanSupplier;
import java.util.function.Supplier; import java.util.function.Supplier;
/** /**
* The {@link BranchUtil} class provides static methods to simplify conditional * The {@link BranchUtil} class provides static methods to simplify conditional logic in Java
* logic in Java development by leveraging lambda expressions. It offers * development by leveraging lambda expressions. It offers convenient methods to replace verbose
* convenient methods to replace verbose {@code if...else} statements with more * {@code if...else} statements with more concise and expressive functional constructs.
* concise and expressive functional constructs.
* <p> * <p>
* Developers can use methods in this utility class to streamline their code, * Developers can use methods in this utility class to streamline their code, enhance readability,
* enhance readability, and promote a more functional style of programming when * and promote a more functional style of programming when dealing with branching logic and
* dealing with branching logic and conditional statements. * conditional statements.
* <p> * <p>
* <b>Example:</b> * <b>Example:</b>
* <pre> * <pre>
@@ -64,11 +63,11 @@ import java.util.function.Supplier;
* </pre> * </pre>
* <p> * <p>
* <b>Note:</b> * <b>Note:</b>
* The {@link #and(Boolean...)} and {@link #or(Boolean...)} methods accept any * The {@link #and(Boolean...)} and {@link #or(Boolean...)} methods accept any number of boolean
* number of boolean expressions. * expressions.
* *
* @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 * @author zihluwang
* @version 1.1.0 * @version 1.1.0
* @see java.util.function.Supplier * @see java.util.function.Supplier
* @see java.util.function.BooleanSupplier * @see java.util.function.BooleanSupplier
@@ -87,13 +86,12 @@ public final class BranchUtil<T> {
} }
/** /**
* Creates a {@code BranchUtil} instance to evaluate a logical OR operation * Creates a {@code BranchUtil} instance to evaluate a logical OR operation on the provided
* on the provided boolean expressions. * 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 * @return a {@code BranchUtil} instance representing the result of the logical OR operation
* 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)
@@ -103,13 +101,12 @@ public final class BranchUtil<T> {
} }
/** /**
* Creates a {@code BranchUtil} instance to evaluate a logical AND * Creates a {@code BranchUtil} instance to evaluate a logical AND operation on the provided
* operation on the provided boolean expressions. * 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 * @return a {@code BranchUtil} instance representing the result of the logical AND operation
* 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)
@@ -119,12 +116,11 @@ public final class BranchUtil<T> {
} }
/** /**
* Creates a {@code BranchUtil} instance to evaluate a logical OR operation * Creates a {@code BranchUtil} instance to evaluate a logical OR operation on the provided
* on the provided boolean suppliers. * 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 * @param <T> the type of the result to be handled by the methods
* methods
* @return a {@code BranchUtil} instance representing the result of the * @return a {@code BranchUtil} instance representing the result of the
* logical OR operation * logical OR operation
*/ */
@@ -136,12 +132,11 @@ public final class BranchUtil<T> {
} }
/** /**
* Creates a {@code BranchUtil} instance to evaluate a logical AND * Creates a {@code BranchUtil} instance to evaluate a logical AND operation on the provided
* operation on the provided boolean suppliers. * 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 * @param <T> the type of the result to be handled by the methods
* methods
* @return a {@code BranchUtil} instance representing the result of the * @return a {@code BranchUtil} instance representing the result of the
* logical AND operation * logical AND operation
*/ */
@@ -153,22 +148,18 @@ public final class BranchUtil<T> {
} }
/** /**
* Handles the result of the boolean expressions by executing the * Handles the result of the boolean expressions by executing the appropriate handler based
* appropriate handler based on the result. * on the result.
* <p> * <p>
* If the result is {@code true}, the {@code ifHandler} is executed. If the * If the result is {@code true}, the {@code ifHandler} is executed. If the result is
* result is {@code false} and an {@code elseHandler} is provided, it is * {@code false} and an {@code elseHandler} is provided, it is executed.
* executed.
* <p> * <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 * @param ifHandler the handler to be executed if the result is {@code true}
* {@code true} * @param elseHandler the handler to be executed if the result is {@code false} (optional)
* @param elseHandler the handler to be executed if the result is * @return the result of the executed handler, or {@code null} if no {@code elseHandler} is
* {@code false} (optional) * provided and the result of the evaluation is {@code false}
* @return the result of the executed handler, or {@code null} if no
* {@code elseHandler} is provided and the result of the evaluation is
* {@code false}
*/ */
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)) {
@@ -183,32 +174,28 @@ public final class BranchUtil<T> {
} }
/** /**
* Handles the result of the boolean expressions by executing the provided * Handles the result of the boolean expressions by executing the provided handler if the
* handler if the result is {@code true}. * result is {@code true}.
* <p> * <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 * @param ifHandler the handler to be executed if the result is {@code true}
* {@code true} * @return the result of the executed handler, or {@code null} if result of evaluation is
* @return the result of the executed handler, or {@code null} if result of * {@code false}
* evaluation is {@code false}
*/ */
public T handle(Supplier<T> ifHandler) { public T handle(Supplier<T> ifHandler) {
return handle(ifHandler, null); return handle(ifHandler, null);
} }
/** /**
* Handles the result of the boolean expressions by executing the * Handles the result of the boolean expressions by executing the appropriate handler based
* appropriate handler based on the result. * on the result.
* <p> * <p>
* If the result is {@code true}, the {@code ifHandler} is executed. If the * If the result is {@code true}, the {@code ifHandler} is executed. If the result is
* result is {@code false} and an {@code elseHandler} is provided, it is * {@code false} and an {@code elseHandler} is provided, it is executed.
* executed.
* *
* @param ifHandler the handler to be executed if the result is * @param ifHandler the handler to be executed if the result is {@code true}
* {@code true} * @param elseHandler the handler to be executed if the result is {@code false} (optional)
* @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)) {
@@ -224,11 +211,10 @@ public final class BranchUtil<T> {
} }
/** /**
* Handles the result of the boolean expressions by executing the provided * Handles the result of the boolean expressions by executing the provided handler if the
* handler if the result is {@code true}. * result is {@code true}.
* *
* @param ifHandler the handler to be executed if the result is * @param ifHandler the handler to be executed if the result is {@code true}
* {@code true}
*/ */
public void handle(Runnable ifHandler) { public void handle(Runnable ifHandler) {
handle(ifHandler, null); handle(ifHandler, null);
@@ -26,12 +26,11 @@ import java.util.function.BiFunction;
import java.util.function.Function; import java.util.function.Function;
/** /**
* The {@code ChainedCalcUtil} class provides a convenient way to perform * The {@code ChainedCalcUtil} class provides a convenient way to perform chained high-precision
* chained high-precision calculations using {@link BigDecimal}. It allows * calculations using {@link BigDecimal}. It allows users to perform mathematical operations such
* users to perform mathematical operations such as addition, subtraction, * as addition, subtraction, multiplication, and division with customisable precision and scale.
* multiplication, and division with customisable precision and scale. By using * By using this utility class, developers can achieve accurate results and avoid precision loss
* this utility class, developers can achieve accurate results and avoid * in their calculations.
* precision loss in their calculations.
* <p> * <p>
* <b>Usage:</b> * <b>Usage:</b>
* <pre> * <pre>
@@ -82,10 +81,9 @@ import java.util.function.Function;
* {@code ChainedCalcUtil} class. * {@code ChainedCalcUtil} class.
* <p> * <p>
* <b>Note:</b> * <b>Note:</b>
* The {@code ChainedCalcUtil} class internally uses {@link BigDecimal} to * The {@code ChainedCalcUtil} class internally uses {@link BigDecimal} to handle high-precision
* handle high-precision calculations. It is important to note that {@link * calculations. It is important to note that {@link BigDecimal} operations can be memory-intensive
* BigDecimal} operations can be memory-intensive and may have performance * and may have performance implications for extremely large numbers or complex calculations.
* implications for extremely large numbers or complex calculations.
* *
* @author sunzsh * @author sunzsh
* @version 1.1.0 * @version 1.1.0
@@ -96,8 +94,7 @@ import java.util.function.Function;
public final class ChainedCalcUtil { public final class ChainedCalcUtil {
/** /**
* Creates a {@code ChainedCalcUtil} instance with the specified initial * Creates a {@code ChainedCalcUtil} instance with the specified initial value.
* value.
* *
* @param value the initial value for the calculation * @param value the initial value for the calculation
*/ */
@@ -126,8 +123,7 @@ public final class ChainedCalcUtil {
} }
/** /**
* Adds the specified value to the current value with a specified scale * Adds the specified value to the current value with a specified scale before the operation.
* 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
@@ -148,8 +144,8 @@ public final class ChainedCalcUtil {
} }
/** /**
* Subtracts the specified value from the current value with a specified * Subtracts the specified value from the current value with a specified scale before
* scale before the operation. * 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
@@ -170,8 +166,8 @@ public final class ChainedCalcUtil {
} }
/** /**
* Multiplies the current value by the specified value with a specified * Multiplies the current value by the specified value with a specified scale before
* scale before the operation. * 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
@@ -192,8 +188,7 @@ public final class ChainedCalcUtil {
} }
/** /**
* Divides the current value by the specified value with a specified scale * Divides the current value by the specified value with a specified scale before the operation.
* 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
@@ -216,8 +211,8 @@ public final class ChainedCalcUtil {
} }
/** /**
* Divides the current value by the specified value with a specified scale * Divides the current value by the specified value with a specified scale and a scale applied
* and a scale applied before the operation. * 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
@@ -225,7 +220,9 @@ public final class ChainedCalcUtil {
* @return a {@code ChainedCalcUtil} instance with the updated value * @return a {@code ChainedCalcUtil} instance with the updated value
*/ */
public ChainedCalcUtil divideWithScale(Number other, Integer scale, Integer beforeOperateScale) { public ChainedCalcUtil divideWithScale(Number other, Integer scale, Integer beforeOperateScale) {
return baseOperator(otherValue -> this.value.divide(otherValue, scale, RoundingMode.HALF_UP), other, beforeOperateScale); return baseOperator((otherValue) ->
this.value.divide(otherValue, scale, RoundingMode.HALF_UP),
other, beforeOperateScale);
} }
/** /**
@@ -276,8 +273,7 @@ public final class ChainedCalcUtil {
} }
/** /**
* Applies the specified operator function to the current value and another * Applies the specified operator function to the current value and another value.
* 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
@@ -288,8 +284,8 @@ public final class ChainedCalcUtil {
} }
/** /**
* Applies the specified operator function to the current value and another * Applies the specified operator function to the current value and another value with a
* value with a specified scale before the operation. * 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
@@ -298,7 +294,10 @@ public final class ChainedCalcUtil {
* @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) {
return baseOperator((otherValue) -> operator.apply(this.value, otherValue), other, beforeOperateScale); return baseOperator((otherValue) ->
operator.apply(this.value, otherValue),
other,
beforeOperateScale);
} }
/** /**
@@ -328,8 +327,7 @@ public final class ChainedCalcUtil {
* Converts the specified value to a {@link BigDecimal}. * Converts the specified value to a {@link 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 * @param scale the scale to apply to the resulting BigDecimal, or null if not applicable
* 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) {
@@ -25,10 +25,9 @@ import java.util.Objects;
import java.util.Optional; import java.util.Optional;
/** /**
* The {@code HashUtil} class provides convenient methods for calculating * The {@code HashUtil} class provides convenient methods for calculating various hash functions on
* various hash functions on strings, including MD2, MD5, SHA-1, SHA-224, * strings, including MD2, MD5, SHA-1, SHA-224, SHA-256, SHA-384, and SHA-512. It allows developers
* SHA-256, SHA-384, and SHA-512. It allows developers to easily obtain the * to easily obtain the hash value of a given string using different algorithms.
* hash value of a given string using different algorithms.
* <p> * <p>
* Example usage: * Example usage:
* <pre> * <pre>
@@ -53,14 +52,14 @@ 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 {@code HashUtil} class to * The above examples demonstrate how to use the {@code HashUtil} class to calculate hash values
* calculate hash values for a given string using different algorithms. * 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 * The hash functions provided by the HashUtil class are one-way hash functions, meaning the
* functions, meaning the original data cannot be retrieved from the hash * original data cannot be retrieved from the hash value. These hash functions are commonly used
* value. These hash functions are commonly used for data integrity checks and * for data integrity checks and password storage, but they should not be used for
* password storage, but they should not be used for encryption purposes. * encryption purposes.
* *
* @author Zihlu Wang * @author Zihlu Wang
* @version 1.1.0 * @version 1.1.0
@@ -70,12 +69,10 @@ import java.util.Optional;
public final class HashUtil { public final class HashUtil {
/** /**
* Calculates the MD2 hash value of the specified string using the given * Calculates the MD2 hash value of the specified string using the given charset.
* charset.
* *
* @param value the string to calculate with the MD2 algorithm * @param value the string to calculate with the MD2 algorithm
* @param charset the charset to use for encoding the string (default is * @param charset the charset to use for encoding the string (default is UTF-8 if null)
* 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) {
@@ -84,8 +81,7 @@ public final class HashUtil {
} }
/** /**
* Calculates the MD2 hash value of the specified string using the UTF-8 * Calculates the MD2 hash value of the specified string using the UTF-8 charset.
* charset.
* *
* @param value the string to calculate with the MD2 algorithm * @param value the string to calculate with the MD2 algorithm
* @return the MD2 hash value as a hexadecimal string * @return the MD2 hash value as a hexadecimal string
@@ -95,12 +91,10 @@ public final class HashUtil {
} }
/** /**
* Calculates the MD5 hash value of the specified string using the given * Calculates the MD5 hash value of the specified string using the given charset.
* charset.
* *
* @param value the string to calculate with the MD5 algorithm * @param value the string to calculate with the MD5 algorithm
* @param charset the charset to use for encoding the string (default is * @param charset the charset to use for encoding the string (default is UTF-8 if null)
* 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) {
@@ -109,8 +103,7 @@ public final class HashUtil {
} }
/** /**
* Calculates the MD5 hash value of the specified string using the UTF-8 * Calculates the MD5 hash value of the specified string using the UTF-8 charset.
* charset.
* *
* @param value the string to calculate with the MD5 algorithm * @param value the string to calculate with the MD5 algorithm
* @return the MD5 hash value as a hexadecimal string * @return the MD5 hash value as a hexadecimal string
@@ -120,12 +113,10 @@ public final class HashUtil {
} }
/** /**
* Calculates the SHA-1 hash value of the specified string using the given * Calculates the SHA-1 hash value of the specified string using the given charset.
* charset.
* *
* @param value the string to calculate with the SHA-1 algorithm * @param value the string to calculate with the SHA-1 algorithm
* @param charset the charset to use for encoding the string (default is * @param charset the charset to use for encoding the string (default is UTF-8 if null)
* 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) {
@@ -134,8 +125,7 @@ public final class HashUtil {
} }
/** /**
* Calculates the SHA-1 hash value of the specified string using the UTF-8 * Calculates the SHA-1 hash value of the specified string using the UTF-8 charset.
* charset.
* *
* @param value the string to calculate with the SHA-1 algorithm * @param value the string to calculate with the SHA-1 algorithm
* @return the SHA-1 hash value as a hexadecimal string * @return the SHA-1 hash value as a hexadecimal string
@@ -145,12 +135,10 @@ public final class HashUtil {
} }
/** /**
* Calculates the SHA-224 hash value of the specified string using the * Calculates the SHA-224 hash value of the specified string using the given charset.
* given charset.
* *
* @param value the string to calculate with the SHA-225 algorithm * @param value the string to calculate with the SHA-225 algorithm
* @param charset the charset to use for encoding the string (default is * @param charset the charset to use for encoding the string (default is UTF-8 if null)
* 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) {
@@ -174,8 +162,7 @@ public final class HashUtil {
* given charset. * given charset.
* *
* @param value the string to calculate with the SHA-256 algorithm * @param value the string to calculate with the SHA-256 algorithm
* @param charset the charset to use for encoding the string (default is * @param charset the charset to use for encoding the string (default is UTF-8 if null)
* 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) {
@@ -184,8 +171,7 @@ public final class HashUtil {
} }
/** /**
* Calculates the SHA-256 hash value of the specified string using the * Calculates the SHA-256 hash value of the specified string using the UTF-8 charset.
* UTF-8 charset.
* *
* @param value the string to calculate with the SHA-256 algorithm * @param value the string to calculate with the SHA-256 algorithm
* @return the SHA-256 hash value as a hexadecimal string * @return the SHA-256 hash value as a hexadecimal string
@@ -195,12 +181,10 @@ public final class HashUtil {
} }
/** /**
* Calculates the SHA-384 hash value of the specified string using the * Calculates the SHA-384 hash value of the specified string using the given charset.
* given charset.
* *
* @param value the string to calculate with the SHA-384 algorithm * @param value the string to calculate with the SHA-384 algorithm
* @param charset the charset to use for encoding the string (default is * @param charset the charset to use for encoding the string (default is UTF-8 if null)
* 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) {
@@ -209,8 +193,7 @@ public final class HashUtil {
} }
/** /**
* Calculates the SHA-384 hash value of the specified string using the * Calculates the SHA-384 hash value of the specified string using the UTF-8 charset.
* UTF-8 charset.
* *
* @param value the string to calculate with the SHA-384 algorithm * @param value the string to calculate with the SHA-384 algorithm
* @return the SHA-384 hash value as a hexadecimal string * @return the SHA-384 hash value as a hexadecimal string
@@ -220,12 +203,10 @@ public final class HashUtil {
} }
/** /**
* Calculates the SHA-512 hash value of the specified string using the * Calculates the SHA-512 hash value of the specified string using the given charset.
* given charset.
* *
* @param value the string to calculate with the SHA-512 algorithm * @param value the string to calculate with the SHA-512 algorithm
* @param charset the charset to use for encoding the string (default is * @param charset the charset to use for encoding the string (default is UTF-8 if null)
* 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) {
@@ -234,8 +215,7 @@ public final class HashUtil {
} }
/** /**
* Calculates the SHA-512 hash value of the specified string using the * Calculates the SHA-512 hash value of the specified string using the UTF-8 charset.
* UTF-8 charset.
* *
* @param value the string to calculate with the SHA-512 algorithm * @param value the string to calculate with the SHA-512 algorithm
* @return the SHA-512 hash value as a hexadecimal string * @return the SHA-512 hash value as a hexadecimal string
@@ -256,12 +236,11 @@ public final class HashUtil {
* *
* @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 * @param charset the charset to use for encoding the string (default is UTF-8 if null)
* UTF-8 if null) * @return the hash value as a hexadecimal string, or an empty string if the algorithm is
* @return the hash value as a hexadecimal string, or an empty string if * not available
* the algorithm is not available * @throws RuntimeException if an unknown algorithm name is provided (should not occur under
* @throws RuntimeException if an unknown algorithm name is provided * controlled usage)
* (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 {
@@ -28,7 +28,7 @@ import java.util.Optional;
* to objects. * to objects.
* <p> * <p>
* Note: Since version 1.4.2, this util class removed reflection API and transferred to a safer API. * Note: Since version 1.4.2, this util class removed reflection API and transferred to a safer API.
* Please see <a href="">documentation</a> for more information. * Please see documentation for more information.
* *
* @author Zihlu Wang * @author Zihlu Wang
* @version 1.4.2 * @version 1.4.2
@@ -41,7 +41,9 @@ 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 <T> the type of the object
* @param entity the object to be converted to a map * @param entity the object to be converted to a map
* @param adapters adapts the entity for mapping 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
*/ */
public static <T> Map<String, Object> objectToMap(T entity, public static <T> Map<String, Object> objectToMap(T entity,
@@ -73,6 +75,7 @@ public final class MapUtil {
/** /**
* Retrieves the value of a field from an object using reflection. * Retrieves the value of a field from an object using reflection.
* *
* @param <E> the type of the entity
* @param <T> the type of the field value * @param <T> the type of the field value
* @param entity the object from which to retrieve the field value * @param entity the object from which to retrieve the field value
* @param adapter the adapter to execute the getter * @param adapter the adapter to execute the getter
@@ -86,6 +89,8 @@ public final class MapUtil {
/** /**
* Sets the value of a field in an object using reflection. * Sets the value of a field in an object using reflection.
* *
* @param <E> the type of the entity
* @param <T> the type of the field value
* @param entity the object in which to set the field value * @param entity the object in which to set the field value
* @param adapter the adapter to execute the setter * @param adapter the adapter to execute the setter
* @param fieldValue the value to be set * @param fieldValue the value to be set
@@ -24,11 +24,10 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
/** /**
* {@code MapUtil} is a utility class that provides methods for converting * {@code MapUtil} is a utility class that provides methods for converting objects to maps and
* objects to maps and maps to objects. * maps to objects.
* <p> * <p>
* It also provides methods for getting and setting field values using * It also provides methods for getting and setting field values using reflection.
* reflection.
* *
* @author zihluwang * @author zihluwang
* @version 1.4.2 * @version 1.4.2
@@ -38,13 +37,11 @@ import java.util.Map;
public final class ReflectMapUtil { public final class ReflectMapUtil {
/** /**
* Converts an object to a map by mapping the field names to their * Converts an object to a map by mapping the field names to their corresponding values.
* 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 * @throws IllegalAccessException if an error occurs while accessing the fields of the object
* 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) {
@@ -66,24 +63,21 @@ public final class ReflectMapUtil {
} }
/** /**
* Converts a map to an object of the specified type by setting the field * Converts a map to an object of the specified type by setting the field values using the
* values using the map entries. * 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 * @return an object of the specified type with the field values set from the map
* the map * @throws NoSuchMethodException if the constructor of the required type is not found
* @throws NoSuchMethodException if the constructor of the required * @throws InvocationTargetException if an error occurs while invoking the constructor
* type is not found * @throws InstantiationException if the required type is abstract or an interface
* @throws InvocationTargetException if an error occurs while invoking the * @throws IllegalAccessException if an error occurs while accessing the fields of the object
* 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();
if (map != null) { if (map != null) {
for (var entry : map.entrySet()) { for (var entry : map.entrySet()) {
@@ -143,7 +137,8 @@ public final class ReflectMapUtil {
* field getter method * field getter method
* @throws NoSuchMethodException if the specified getter is not present * @throws NoSuchMethodException if the specified getter is not present
*/ */
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);
var objectClass = obj.getClass(); var objectClass = obj.getClass();
var method = objectClass.getDeclaredMethod(methodName); var method = objectClass.getDeclaredMethod(methodName);
@@ -158,10 +153,8 @@ public final class ReflectMapUtil {
* @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 * @throws InvocationTargetException if an error occurs while invoking the field setter method
* field setter method * @throws IllegalAccessException if an error occurs while accessing the field
* @throws IllegalAccessException if an error occurs while accessing the
* field
* @throws NoSuchMethodException if the specific setter is not present * @throws NoSuchMethodException if the specific setter is not present
*/ */
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 {
@@ -178,8 +171,7 @@ public final class ReflectMapUtil {
* @param value the value to be cast * @param value the value to be cast
* @param requiredType the type to which the value should be cast * @param requiredType the type to which the value should be cast
* @param <T> the type to which the value should be cast * @param <T> the type to which the value should be cast
* @return the cast value, or null if the value cannot be cast to the * @return the cast value, or null if the value cannot be cast to the required type
* 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)) {
@@ -202,8 +194,7 @@ public final class ReflectMapUtil {
/** /**
* 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 * @param obj the object for which to return the default string representation
* 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) {
@@ -70,6 +70,12 @@ import java.util.Optional;
*/ */
public class PropertyGuard implements EnvironmentPostProcessor { public class PropertyGuard implements EnvironmentPostProcessor {
/**
* Create a {@link PropertyGuard} instance.
*/
public PropertyGuard() {
}
/** /**
* Process the encryption environment variables. * Process the encryption environment variables.
* *
@@ -25,8 +25,8 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import java.lang.annotation.Target;
/** /**
* This annotation marks the enum field declared in payload class will be * This annotation marks the enum field declared in payload class will be handled as basic data
* handled as basic data types in {@link TokenDataType}. * types in {@link TokenDataType}.
* *
* @author Zihlu Wang * @author Zihlu Wang
*/ */
@@ -35,14 +35,16 @@ import java.lang.annotation.Target;
public @interface TokenEnum { public @interface TokenEnum {
/** /**
* The name of the field of the base data corresponding to the * The name of the field of the base data corresponding to the enumeration data.
* enumeration data. *
* @return the name of the property
*/ */
String propertyName(); String propertyName();
/** /**
* The attribute {@code dataType} specifies what base data type to treat * The attribute {@code dataType} specifies what base data type to treat this enum as.
* this enum as. *
* @return the data type of the token
*/ */
TokenDataType dataType(); TokenDataType dataType();
@@ -233,7 +233,7 @@ public class JjwtTokenResolver implements TokenResolver<Jws<Claims>> {
* token * token
* @return the generated token as a {@code String} or {@code null} if * @return the generated token as a {@code String} or {@code null} if
* creation fails * creation fails
* @see MapUtil#objectToMap(Object) * @see MapUtil#objectToMap(Object, Map)
*/ */
@Override @Override
public <T extends TokenPayload> String createToken(Duration expireAfter, String audience, String subject, T payload) { public <T extends TokenPayload> String createToken(Duration expireAfter, String audience, String subject, T payload) {
@@ -291,7 +291,7 @@ public class JjwtTokenResolver implements TokenResolver<Jws<Claims>> {
* @param targetType the target class representing the payload data type * @param targetType the target class representing the payload data type
* @return an instance of the specified target type with the extracted * @return an instance of the specified target type with the extracted
* payload data, or {@code null} if extraction fails. * payload data, or {@code null} if extraction fails.
* @see MapUtil#mapToObject(Map, Class) * @see MapUtil#mapToObject(Map, Object, Map)
*/ */
@Override @Override
public <T extends TokenPayload> T extract(String token, Class<T> targetType) { public <T extends TokenPayload> T extract(String token, Class<T> targetType) {
@@ -61,6 +61,10 @@ import java.util.Map;
*/ */
public final class JjwtTokenResolverConfig implements TokenResolverConfig<SecureDigestAlgorithm<SecretKey, SecretKey>> { public final class JjwtTokenResolverConfig implements TokenResolverConfig<SecureDigestAlgorithm<SecretKey, SecretKey>> {
/**
* Get the instance for io.jsonwebtoken:jjwt config.
* @return the instance for io.jsonwebtoken:jjwt config
*/
public static JjwtTokenResolverConfig getInstance() { public static JjwtTokenResolverConfig getInstance() {
if (instance == null) { if (instance == null) {
instance = new JjwtTokenResolverConfig(); instance = new JjwtTokenResolverConfig();
@@ -69,8 +69,9 @@ public class AuthzeroTokenResolverAutoConfiguration {
* Constructs a new {@code SimpleJwtAutoConfiguration} instance with the * Constructs a new {@code SimpleJwtAutoConfiguration} instance with the
* provided SimpleJwtProperties. * provided SimpleJwtProperties.
* *
* @param simpleJwtProperties the SimpleJwtProperties instance * @param simpleJwtProperties a {@link SimpleJwtProperties} instance
* @param objectMapper Jackson JSON Handler * @param jtiCreator a creator to create ids for JSON Web Token
* @param objectMapper jackson JSON Handler
*/ */
@Autowired @Autowired
public AuthzeroTokenResolverAutoConfiguration(SimpleJwtProperties simpleJwtProperties, @Qualifier("jtiCreator") GuidCreator<?> jtiCreator, ObjectMapper objectMapper) { public AuthzeroTokenResolverAutoConfiguration(SimpleJwtProperties simpleJwtProperties, @Qualifier("jtiCreator") GuidCreator<?> jtiCreator, ObjectMapper objectMapper) {
@@ -80,11 +81,10 @@ public class AuthzeroTokenResolverAutoConfiguration {
} }
/** /**
* Creates a new {@link TokenResolver} bean using {@link * Creates a new {@link TokenResolver} bean using {@link AuthzeroTokenResolver} if no existing
* AuthzeroTokenResolver} if no existing {@link TokenResolver} bean is * {@link TokenResolver} bean is found. The {@link AuthzeroTokenResolver} is configured with the
* found. The {@link AuthzeroTokenResolver} is configured with the * provided {@link GuidCreator}, {@code algorithm}, {@code issuer}, and {@code secret}
* provided {@link GuidCreator}, {@code algorithm}, {@code issuer}, and * properties from {@link SimpleJwtProperties}.
* {@code secret} properties from {@link SimpleJwtProperties}.
* *
* @return the {@link TokenResolver} instance * @return the {@link TokenResolver} instance
*/ */
@@ -99,15 +99,8 @@ public class AuthzeroTokenResolverAutoConfiguration {
); );
} }
/**
* The GuidCreator instance to be used for generating JWT IDs (JTI).
*/
private final GuidCreator<?> jtiCreator; private final GuidCreator<?> jtiCreator;
/**
* The {@code SimpleJwtProperties} instance containing the configuration
* properties for Simple JWT.
*/
private final SimpleJwtProperties simpleJwtProperties; private final SimpleJwtProperties simpleJwtProperties;
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
@@ -37,6 +37,12 @@ import java.util.UUID;
@AutoConfiguration @AutoConfiguration
public class GuidAutoConfiguration { public class GuidAutoConfiguration {
/**
* Default constructor.
*/
public GuidAutoConfiguration() {
}
/** /**
* Create a default {@code jtiCreator} with UUID. * Create a default {@code jtiCreator} with UUID.
* *
@@ -66,9 +66,10 @@ import org.springframework.context.annotation.Bean;
public class JjwtTokenResolverAutoConfiguration { public class JjwtTokenResolverAutoConfiguration {
/** /**
* Constructs a new {@code SimpleJwtAutoConfiguration} instance with the * Constructs a new {@code SimpleJwtAutoConfiguration} instance with the provided
* provided SimpleJwtProperties. * {@link SimpleJwtProperties}.
* *
* @param jtiCreator a creator to create JSON Web Token ids
* @param simpleJwtProperties the SimpleJwtProperties instance * @param simpleJwtProperties the SimpleJwtProperties instance
*/ */
@Autowired @Autowired
@@ -78,11 +79,10 @@ public class JjwtTokenResolverAutoConfiguration {
} }
/** /**
* Creates a new {@link TokenResolver} bean using {@link * Creates a new {@link TokenResolver} bean using {@link JjwtTokenResolver} if no existing
* JjwtTokenResolver} if no existing {@link TokenResolver} bean is * {@link TokenResolver} bean is found. The {@link JjwtTokenResolver} is configured with the
* found. The {@link JjwtTokenResolver} is configured with the * provided {@link GuidCreator}, {@code algorithm}, {@code issuer}, and {@code secret}
* provided {@link GuidCreator}, {@code algorithm}, {@code issuer}, and * properties from {@link SimpleJwtProperties}.
* {@code secret} properties from {@link SimpleJwtProperties}.
* *
* @return the {@link TokenResolver} instance * @return the {@link TokenResolver} instance
*/ */
@@ -102,8 +102,8 @@ public class JjwtTokenResolverAutoConfiguration {
private final GuidCreator<?> jtiCreator; private final GuidCreator<?> jtiCreator;
/** /**
* The {@code SimpleJwtProperties} instance containing the configuration * The {@code SimpleJwtProperties} instance containing the configuration properties
* properties for Simple JWT. * for Simple JWT.
*/ */
private final SimpleJwtProperties simpleJwtProperties; private final SimpleJwtProperties simpleJwtProperties;
@@ -35,16 +35,22 @@ import java.util.Objects;
@Slf4j @Slf4j
public class GuidCreatorCondition implements Condition { public class GuidCreatorCondition implements Condition {
/**
* Default constructor.
*/
public GuidCreatorCondition() {
}
/** /**
* The condition to create bean {@code jtiCreator}. * The condition to create bean {@code jtiCreator}.
* <p> * <p>
* If Spring does not have a bean of type * If Spring does not have a bean of type {@link GuidCreator} named {@code jtiCreator} in the
* {@link GuidCreator} named {@code jtiCreator} * application context, then create {@code jtiCreator}.
* in the application context, then create {@code jtiCreator}.
* *
* @param context the spring application context * @param context the spring application context
* @param metadata the metadata of the {@link org.springframework.core.type.AnnotationMetadata class} * @param metadata the metadata of the {@link org.springframework.core.type.AnnotationMetadata
* or {@link org.springframework.core.type.MethodMetadata method} being checked * class} or {@link org.springframework.core.type.MethodMetadata method}
* being checked
*/ */
@Override @Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
@@ -25,21 +25,20 @@ import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
/** /**
* {@code SimpleJwtProperties} is a configuration properties class used to * {@code SimpleJwtProperties} is a configuration properties class used to store the properties
* store the properties related to Simple JWT library configurations. These * related to Simple JWT library configurations. These properties can be configured in the
* properties can be configured in the application's properties file (e.g., * application's properties file (e.g., application.properties) with the prefix
* application.properties) with the prefix "code-crafters.simple-jwt". * "onixbyte.simple-jwt".
* <p> * <p>
* {@code SimpleJwtProperties} provides configuration options for the JWT * {@code SimpleJwtProperties} provides configuration options for the JWT algorithm, issuer,
* algorithm, issuer, and secret. The properties are used by the {@link * and secret. The properties are used by the {@link AuthzeroTokenResolverAutoConfiguration} and
* AuthzeroTokenResolverAutoConfiguration} and {@link * {@link JjwtTokenResolver} to set up the necessary configurations for JWT generation
* JjwtTokenResolver} to set up the * and validation.
* necessary configurations for JWT generation and validation.
* <p> * <p>
* Developers can customise the JWT algorithm, issuer, and secret by setting * Developers can customise the JWT algorithm, issuer, and secret by setting the corresponding
* the corresponding properties in the application's properties file. The * properties in the application's properties file. The {@code SimpleJwtAutoConfiguration} class
* {@code SimpleJwtAutoConfiguration} class reads these properties and uses * reads these properties and uses them to create the TokenResolver bean with the
* them to create the TokenResolver bean with the desired configuration. * desired configuration.
* *
* @author Zihlu Wang * @author Zihlu Wang
* @version 1.1.0 * @version 1.1.0
@@ -49,6 +48,12 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "onixbyte.simple-jwt") @ConfigurationProperties(prefix = "onixbyte.simple-jwt")
public class SimpleJwtProperties { public class SimpleJwtProperties {
/**
* Default constructor.
*/
public SimpleJwtProperties() {
}
/** /**
* The algorithm used for JWT generation and validation. Default value is * The algorithm used for JWT generation and validation. Default value is
* {@link TokenAlgorithm#HS256} * {@link TokenAlgorithm#HS256}
@@ -56,15 +61,13 @@ public class SimpleJwtProperties {
private TokenAlgorithm algorithm = TokenAlgorithm.HS256; private TokenAlgorithm algorithm = TokenAlgorithm.HS256;
/** /**
* The issuer value to be included in the generated JWT. Default value is * The issuer value to be included in the generated JWT. Default value is an empty String.
* an empty String.
*/ */
private String issuer = ""; private String issuer = "";
/** /**
* The secret key used for JWT generation and validation. Default value is * The secret key used for JWT generation and validation. Default value is the result of call to
* the result of call to {@link * {@link SecretCreator#createSecret(int, boolean, boolean, boolean)}.
* SecretCreator#createSecret(int, boolean, boolean, boolean)}.
*/ */
private String secret = SecretCreator.createSecret(32, true, true, true); private String secret = SecretCreator.createSecret(32, true, true, true);