From b5c422a3a9ccd5e54d5f0c9e4b98c07d6508f90e Mon Sep 17 00:00:00 2001 From: hoangtien2k3 Date: Fri, 23 Aug 2024 18:33:48 +0700 Subject: [PATCH] update fw --- README.md | 6 +- license.txt | 14 + pom.xml | 25 +- .../commons/config/DatabaseConfiguration.java | 3 +- .../commons/config/DatabaseConversion.java | 455 +++++++++--------- .../exception/ExceptionResponseConfig.java | 22 +- .../filter/webclient/ErrorHandlingFilter.java | 63 +-- .../webclient/TraceIdWebClientFilter.java | 19 +- .../repository/BaseTemplateRepository.java | 251 +++++----- .../hoangtien2k3/commons/utils/FileUtils.java | 134 +++--- 10 files changed, 502 insertions(+), 490 deletions(-) create mode 100644 license.txt diff --git a/README.md b/README.md index 4f473c6..314f50c 100644 --- a/README.md +++ b/README.md @@ -11,12 +11,12 @@ This README provides quickstart instructions on running [`fw-commons`]() on bare [![Maven Central](https://img.shields.io/badge/maven--central-1.1.0-orange.svg?style=plastic&logo=apachemaven)](https://central.sonatype.com/artifact/io.github.hoangtien2k3/fw-commons/1.1.0) [![Gradle](https://img.shields.io/badge/gradle-1.1.0-orange.svg?style=plastic&logo=apachemaven)](https://central.sonatype.com/artifact/io.github.hoangtien2k3/fw-commons/1.1.0) -#### ⬇️ [Download From Gradle and Maven Central](https://central.sonatype.com/artifact/io.github.hoangtien2k3/fw-commons/1.1.1) +#### ⬇️ [Download From Gradle and Maven Central](https://central.sonatype.com/artifact/io.github.hoangtien2k3/fw-commons/1.1.2) #### Gradle ```kotlin -implementation("io.github.hoangtien2k3:fw-commons:1.1.1") +implementation("io.github.hoangtien2k3:fw-commons:1.1.2") ``` #### Maven @@ -25,7 +25,7 @@ implementation("io.github.hoangtien2k3:fw-commons:1.1.1") io.github.hoangtien2k3 fw-commons - 1.1.1 + 1.1.2 ``` diff --git a/license.txt b/license.txt new file mode 100644 index 0000000..8f32215 --- /dev/null +++ b/license.txt @@ -0,0 +1,14 @@ +/* + * Copyright $YEAR author - Hoàng Anh Tiến + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + */ diff --git a/pom.xml b/pom.xml index 2cbf7b4..ed25c9a 100644 --- a/pom.xml +++ b/pom.xml @@ -11,7 +11,7 @@ io.github.hoangtien2k3 fw-commons - 1.1.1 + 1.1.2 jar fw-commons a commons java tool lib with spring boot framework @@ -507,26 +507,9 @@ - - - - - + + + diff --git a/src/main/java/io/hoangtien2k3/commons/config/DatabaseConfiguration.java b/src/main/java/io/hoangtien2k3/commons/config/DatabaseConfiguration.java index 11c4901..9a5cafa 100644 --- a/src/main/java/io/hoangtien2k3/commons/config/DatabaseConfiguration.java +++ b/src/main/java/io/hoangtien2k3/commons/config/DatabaseConfiguration.java @@ -12,7 +12,8 @@ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ -//package io.hoangtien2k3.commons.config; // package io.hoangtien2k3.commons.config; +// package io.hoangtien2k3.commons.config; // package +// io.hoangtien2k3.commons.config; // // import java.util.List; // diff --git a/src/main/java/io/hoangtien2k3/commons/config/DatabaseConversion.java b/src/main/java/io/hoangtien2k3/commons/config/DatabaseConversion.java index c913419..15e78b2 100644 --- a/src/main/java/io/hoangtien2k3/commons/config/DatabaseConversion.java +++ b/src/main/java/io/hoangtien2k3/commons/config/DatabaseConversion.java @@ -1,9 +1,12 @@ -///* +/// * // * Copyright 2024 author - Hoàng Anh Tiến // * -// * Permission is hereby granted, free of charge, to any person obtaining a copy -// * of this software and associated documentation files (the "Software"), to deal -// * in the Software without restriction, including without limitation the rights +// * Permission is hereby granted, free of charge, to any person obtaining a +/// copy +// * of this software and associated documentation files (the "Software"), to +/// deal +// * in the Software without restriction, including without limitation the +/// rights // * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // * copies of the Software, and to permit persons to whom the Software is // * furnished to do so, subject to the following conditions: @@ -12,33 +15,34 @@ // * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // */ -//package io.hoangtien2k3.commons.config; +// package io.hoangtien2k3.commons.config; // -//import io.r2dbc.spi.Blob; -//import java.nio.ByteBuffer; -//import java.nio.charset.StandardCharsets; -//import java.time.*; -//import java.util.*; -//import lombok.extern.slf4j.Slf4j; -//import org.jetbrains.annotations.NotNull; -//import org.springframework.core.convert.converter.Converter; -//import org.springframework.data.convert.ReadingConverter; -//import org.springframework.data.convert.WritingConverter; -//import org.springframework.data.r2dbc.convert.MappingR2dbcConverter; -//import org.springframework.data.r2dbc.convert.R2dbcCustomConversions; -//import org.springframework.data.r2dbc.dialect.MySqlDialect; -//import org.springframework.data.r2dbc.mapping.R2dbcMappingContext; -//import org.springframework.data.relational.core.mapping.NamingStrategy; -//import org.springframework.stereotype.Component; -//import reactor.core.publisher.Mono; +// import io.r2dbc.spi.Blob; +// import java.nio.ByteBuffer; +// import java.nio.charset.StandardCharsets; +// import java.time.*; +// import java.util.*; +// import lombok.extern.slf4j.Slf4j; +// import org.jetbrains.annotations.NotNull; +// import org.springframework.core.convert.converter.Converter; +// import org.springframework.data.convert.ReadingConverter; +// import org.springframework.data.convert.WritingConverter; +// import org.springframework.data.r2dbc.convert.MappingR2dbcConverter; +// import org.springframework.data.r2dbc.convert.R2dbcCustomConversions; +// import org.springframework.data.r2dbc.dialect.MySqlDialect; +// import org.springframework.data.r2dbc.mapping.R2dbcMappingContext; +// import org.springframework.data.relational.core.mapping.NamingStrategy; +// import org.springframework.stereotype.Component; +// import reactor.core.publisher.Mono; // -///** +/// ** // * The {@code DatabaseConversion} class provides utility methods to configure // * and create a {@link MappingR2dbcConverter} with custom conversions for // * handling various data types between Java objects and database records. // *

// * This class sets up custom converters for types such as {@link Instant}, -// * {@link UUID}, {@link BitSet}, and others, ensuring proper conversion between +// * {@link UUID}, {@link BitSet}, and others, ensuring proper conversion +/// between // * database and Java types. // *

// *

@@ -65,226 +69,235 @@ // * MappingR2dbcConverter converter = conversion.getR2dbcConverter(); // * // */ -//@Slf4j -//@Component -//public class DatabaseConversion { +// @Slf4j +// @Component +// public class DatabaseConversion { // -// /** -// * Creates and returns a MappingR2dbcConverter configured with custom -// * conversions and a mapping context. -// * -// * @return MappingR2dbcConverter instance for converting between Java objects -// * and database records. -// */ -// public MappingR2dbcConverter getR2dbcConverter() { -// R2dbcMappingContext mappingContext = getR2dbcMappingContext(); -// R2dbcCustomConversions r2dbcCustomConversions = getR2dbcCustomConversions(); -// return new MappingR2dbcConverter(mappingContext, r2dbcCustomConversions); -// } +// /** +// * Creates and returns a MappingR2dbcConverter configured with custom +// * conversions and a mapping context. +// * +// * @return MappingR2dbcConverter instance for converting between Java objects +// * and database records. +// */ +// public MappingR2dbcConverter getR2dbcConverter() { +// R2dbcMappingContext mappingContext = getR2dbcMappingContext(); +// R2dbcCustomConversions r2dbcCustomConversions = getR2dbcCustomConversions(); +// return new MappingR2dbcConverter(mappingContext, r2dbcCustomConversions); +// } // -// /** -// * Creates and configures a R2dbcMappingContext with a naming strategy and -// * custom conversions. -// * -// * @return R2dbcMappingContext instance used to map entities to database tables -// * and columns. -// */ -// private R2dbcMappingContext getR2dbcMappingContext() { -// NamingStrategy namingStrategy = NamingStrategy.INSTANCE; -// R2dbcCustomConversions r2dbcCustomConversions = getR2dbcCustomConversions(); -// R2dbcMappingContext context = new R2dbcMappingContext(namingStrategy); -// context.setSimpleTypeHolder(r2dbcCustomConversions.getSimpleTypeHolder()); -// return context; -// } +// /** +// * Creates and configures a R2dbcMappingContext with a naming strategy and +// * custom conversions. +// * +// * @return R2dbcMappingContext instance used to map entities to database +/// tables +// * and columns. +// */ +// private R2dbcMappingContext getR2dbcMappingContext() { +// NamingStrategy namingStrategy = NamingStrategy.INSTANCE; +// R2dbcCustomConversions r2dbcCustomConversions = getR2dbcCustomConversions(); +// R2dbcMappingContext context = new R2dbcMappingContext(namingStrategy); +// context.setSimpleTypeHolder(r2dbcCustomConversions.getSimpleTypeHolder()); +// return context; +// } // -// /** -// * Creates and returns an R2dbcCustomConversions instance configured with a list -// * of custom converters. -// * -// * @return R2dbcCustomConversions instance for custom conversion logic. -// */ -// private R2dbcCustomConversions getR2dbcCustomConversions() { -// return R2dbcCustomConversions.of(MySqlDialect.INSTANCE, getListConverters()); -// } +// /** +// * Creates and returns an R2dbcCustomConversions instance configured with a +/// list +// * of custom converters. +// * +// * @return R2dbcCustomConversions instance for custom conversion logic. +// */ +// private R2dbcCustomConversions getR2dbcCustomConversions() { +// return R2dbcCustomConversions.of(MySqlDialect.INSTANCE, getListConverters()); +// } // -// /** -// * Provides a list of custom converters used for data conversion between Java -// * types and database types. -// * -// * @return List of custom converters. -// */ -// public List getListConverters() { -// List converters = new ArrayList<>(); -// converters.add(InstantWriteConverter.INSTANCE); -// converters.add(InstantReadConverter.INSTANCE); -// converters.add(BitSetReadConverter.INSTANCE); -// converters.add(DurationWriteConverter.INSTANCE); -// converters.add(DurationReadConverter.INSTANCE); -// converters.add(ZonedDateTimeReadConverter.INSTANCE); -// converters.add(ZonedDateTimeWriteConverter.INSTANCE); -// converters.add(BinaryToUUIDConverter.INSTANCE); -// converters.add(BlobToStringConverter.INSTANCE); -// converters.add(UUIDToBinaryConverter.INSTANCE); -// converters.add(LocalDateTimeToDateReadConverter.INSTANCE); -// return converters; -// } +// /** +// * Provides a list of custom converters used for data conversion between Java +// * types and database types. +// * +// * @return List of custom converters. +// */ +// public List getListConverters() { +// List converters = new ArrayList<>(); +// converters.add(InstantWriteConverter.INSTANCE); +// converters.add(InstantReadConverter.INSTANCE); +// converters.add(BitSetReadConverter.INSTANCE); +// converters.add(DurationWriteConverter.INSTANCE); +// converters.add(DurationReadConverter.INSTANCE); +// converters.add(ZonedDateTimeReadConverter.INSTANCE); +// converters.add(ZonedDateTimeWriteConverter.INSTANCE); +// converters.add(BinaryToUUIDConverter.INSTANCE); +// converters.add(BlobToStringConverter.INSTANCE); +// converters.add(UUIDToBinaryConverter.INSTANCE); +// converters.add(LocalDateTimeToDateReadConverter.INSTANCE); +// return converters; +// } // -// /** -// * Converter to write Instant values to LocalDateTime in UTC. -// */ -// @WritingConverter -// public enum InstantWriteConverter implements Converter { -// INSTANCE; +// /** +// * Converter to write Instant values to LocalDateTime in UTC. +// */ +// @WritingConverter +// public enum InstantWriteConverter implements Converter { +// INSTANCE; // -// @Override -// public LocalDateTime convert(@NotNull Instant source) { -// return LocalDateTime.ofInstant(source, ZoneOffset.UTC); -// } -// } +// @Override +// public LocalDateTime convert(@NotNull Instant source) { +// return LocalDateTime.ofInstant(source, ZoneOffset.UTC); +// } +// } // -// /** -// * Converter to read Blob values as Strings. -// */ -// @ReadingConverter -// public enum BlobToStringConverter implements Converter { -// INSTANCE; +// /** +// * Converter to read Blob values as Strings. +// */ +// @ReadingConverter +// public enum BlobToStringConverter implements Converter { +// INSTANCE; // -// @Override -// public String convert(@NotNull Blob source) { -// try { -// return Mono.from(source.stream()) -// .map(bb -> StandardCharsets.UTF_8.decode(bb).toString()) -// .toFuture() -// .get(); -// } catch (Exception e) { -// log.error("Exception when read blob value", e); -// return null; -// } -// } -// } +// @Override +// public String convert(@NotNull Blob source) { +// try { +// return Mono.from(source.stream()) +// .map(bb -> StandardCharsets.UTF_8.decode(bb).toString()) +// .toFuture() +// .get(); +// } catch (Exception e) { +// log.error("Exception when read blob value", e); +// return null; +// } +// } +// } // -// /** -// * Converter to write UUID values to byte arrays. -// */ -// @WritingConverter -// public enum UUIDToBinaryConverter implements Converter { -// INSTANCE; +// /** +// * Converter to write UUID values to byte arrays. +// */ +// @WritingConverter +// public enum UUIDToBinaryConverter implements Converter { +// INSTANCE; // -// @Override -// public byte[] convert(UUID uuid) { -// ByteBuffer bb = ByteBuffer.wrap(new byte[16]); -// bb.putLong(uuid.getMostSignificantBits()); -// bb.putLong(uuid.getLeastSignificantBits()); -// return bb.array(); -// } -// } +// @Override +// public byte[] convert(UUID uuid) { +// ByteBuffer bb = ByteBuffer.wrap(new byte[16]); +// bb.putLong(uuid.getMostSignificantBits()); +// bb.putLong(uuid.getLeastSignificantBits()); +// return bb.array(); +// } +// } // -// /** -// * Converter to read byte arrays as UUID values. -// */ -// @ReadingConverter -// public enum BinaryToUUIDConverter implements Converter { -// INSTANCE; +// /** +// * Converter to read byte arrays as UUID values. +// */ +// @ReadingConverter +// public enum BinaryToUUIDConverter implements Converter { +// INSTANCE; // -// @Override -// public UUID convert(@NotNull byte[] source) { -// ByteBuffer byteBuffer = ByteBuffer.wrap(source); -// long high = byteBuffer.getLong(); -// long low = byteBuffer.getLong(); -// return new UUID(high, low); -// } -// } +// @Override +// public UUID convert(@NotNull byte[] source) { +// ByteBuffer byteBuffer = ByteBuffer.wrap(source); +// long high = byteBuffer.getLong(); +// long low = byteBuffer.getLong(); +// return new UUID(high, low); +// } +// } // -// /** -// * Converter to read LocalDateTime values as Instant values in UTC. -// */ -// @ReadingConverter -// public enum InstantReadConverter implements Converter { -// INSTANCE; +// /** +// * Converter to read LocalDateTime values as Instant values in UTC. +// */ +// @ReadingConverter +// public enum InstantReadConverter implements Converter +/// { +// INSTANCE; // -// @Override -// public Instant convert(LocalDateTime localDateTime) { -// return localDateTime.toInstant(ZoneOffset.UTC); -// } -// } +// @Override +// public Instant convert(LocalDateTime localDateTime) { +// return localDateTime.toInstant(ZoneOffset.UTC); +// } +// } // -// /** -// * Converter to read BitSet as Boolean values. -// */ -// @ReadingConverter -// public enum BitSetReadConverter implements Converter { -// INSTANCE; +// /** +// * Converter to read BitSet as Boolean values. +// */ +// @ReadingConverter +// public enum BitSetReadConverter implements Converter { +// INSTANCE; // -// @Override -// public Boolean convert(BitSet bitSet) { -// return bitSet.get(0); -// } -// } +// @Override +// public Boolean convert(BitSet bitSet) { +// return bitSet.get(0); +// } +// } // -// /** -// * Converter to read LocalDateTime values as ZonedDateTime in UTC. -// */ -// @ReadingConverter -// public enum ZonedDateTimeReadConverter implements Converter { -// INSTANCE; +// /** +// * Converter to read LocalDateTime values as ZonedDateTime in UTC. +// */ +// @ReadingConverter +// public enum ZonedDateTimeReadConverter implements Converter { +// INSTANCE; // -// @Override -// public ZonedDateTime convert(@NotNull LocalDateTime localDateTime) { -// return ZonedDateTime.of(localDateTime, ZoneOffset.UTC); -// } -// } +// @Override +// public ZonedDateTime convert(@NotNull LocalDateTime localDateTime) { +// return ZonedDateTime.of(localDateTime, ZoneOffset.UTC); +// } +// } // -// /** -// * Converter to write ZonedDateTime values as LocalDateTime. -// */ -// @WritingConverter -// public enum ZonedDateTimeWriteConverter implements Converter { -// INSTANCE; +// /** +// * Converter to write ZonedDateTime values as LocalDateTime. +// */ +// @WritingConverter +// public enum ZonedDateTimeWriteConverter implements Converter { +// INSTANCE; // -// @Override -// public LocalDateTime convert(ZonedDateTime zonedDateTime) { -// return zonedDateTime.toLocalDateTime(); -// } -// } +// @Override +// public LocalDateTime convert(ZonedDateTime zonedDateTime) { +// return zonedDateTime.toLocalDateTime(); +// } +// } // -// /** -// * Converter to write Duration values as Long values representing milliseconds. -// */ -// @WritingConverter -// public enum DurationWriteConverter implements Converter { -// INSTANCE; +// /** +// * Converter to write Duration values as Long values representing +/// milliseconds. +// */ +// @WritingConverter +// public enum DurationWriteConverter implements Converter { +// INSTANCE; // -// @Override -// public Long convert(Duration source) { -// return source.toMillis(); -// } -// } +// @Override +// public Long convert(Duration source) { +// return source.toMillis(); +// } +// } // -// /** -// * Converter to read LocalDateTime values as Date values in the system's default -// * timezone. -// */ -// @ReadingConverter -// public enum LocalDateTimeToDateReadConverter implements Converter { -// INSTANCE; +// /** +// * Converter to read LocalDateTime values as Date values in the system's +/// default +// * timezone. +// */ +// @ReadingConverter +// public enum LocalDateTimeToDateReadConverter implements +/// Converter { +// INSTANCE; // -// @Override -// public Date convert(LocalDateTime localDateTime) { -// Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant(); -// return Date.from(instant); -// } -// } +// @Override +// public Date convert(LocalDateTime localDateTime) { +// Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant(); +// return Date.from(instant); +// } +// } // -// /** -// * Converter to read Long values as Duration values representing milliseconds. -// */ -// @ReadingConverter -// public enum DurationReadConverter implements Converter { -// INSTANCE; +// /** +// * Converter to read Long values as Duration values representing milliseconds. +// */ +// @ReadingConverter +// public enum DurationReadConverter implements Converter { +// INSTANCE; // -// @Override -// public Duration convert(@NotNull Long source) { -// return Duration.ofMillis(source); -// } -// } -//} +// @Override +// public Duration convert(@NotNull Long source) { +// return Duration.ofMillis(source); +// } +// } +// } diff --git a/src/main/java/io/hoangtien2k3/commons/config/exception/ExceptionResponseConfig.java b/src/main/java/io/hoangtien2k3/commons/config/exception/ExceptionResponseConfig.java index 5fcc86c..72b45f6 100644 --- a/src/main/java/io/hoangtien2k3/commons/config/exception/ExceptionResponseConfig.java +++ b/src/main/java/io/hoangtien2k3/commons/config/exception/ExceptionResponseConfig.java @@ -20,7 +20,7 @@ import io.hoangtien2k3.commons.utils.DataUtil; import io.hoangtien2k3.commons.utils.Translator; import io.micrometer.tracing.Tracer; -//import io.r2dbc.spi.R2dbcException; +// import io.r2dbc.spi.R2dbcException; import java.nio.file.AccessDeniedException; import java.util.List; import java.util.Objects; @@ -112,15 +112,17 @@ public Mono>> runtimeException( * the current server web exchange * @return a Mono containing the ResponseEntity with TraceErrorResponse */ -// @ExceptionHandler(R2dbcException.class) -// public Mono>> r2dbcException( -// R2dbcException ex, ServerWebExchange serverWebExchange) { -// String traceId = Objects.requireNonNull(tracer.currentSpan()).context().traceId(); -// log.error("R2dbc trace-id {} , error ", traceId, ex); -// return Mono.just(new ResponseEntity<>( -// new TraceErrorResponse<>(CommonErrorCode.SQL_ERROR, "Server error", null, traceId), -// HttpStatus.INTERNAL_SERVER_ERROR)); -// } + // @ExceptionHandler(R2dbcException.class) + // public Mono>> r2dbcException( + // R2dbcException ex, ServerWebExchange serverWebExchange) { + // String traceId = + // Objects.requireNonNull(tracer.currentSpan()).context().traceId(); + // log.error("R2dbc trace-id {} , error ", traceId, ex); + // return Mono.just(new ResponseEntity<>( + // new TraceErrorResponse<>(CommonErrorCode.SQL_ERROR, "Server error", null, + // traceId), + // HttpStatus.INTERNAL_SERVER_ERROR)); + // } /** * Handles access denied exceptions. Logs the exception with a trace ID and diff --git a/src/main/java/io/hoangtien2k3/commons/filter/webclient/ErrorHandlingFilter.java b/src/main/java/io/hoangtien2k3/commons/filter/webclient/ErrorHandlingFilter.java index 11b8363..ee0e588 100644 --- a/src/main/java/io/hoangtien2k3/commons/filter/webclient/ErrorHandlingFilter.java +++ b/src/main/java/io/hoangtien2k3/commons/filter/webclient/ErrorHandlingFilter.java @@ -1,9 +1,12 @@ -///* +/// * // * Copyright 2024 author - Hoàng Anh Tiến // * -// * Permission is hereby granted, free of charge, to any person obtaining a copy -// * of this software and associated documentation files (the "Software"), to deal -// * in the Software without restriction, including without limitation the rights +// * Permission is hereby granted, free of charge, to any person obtaining a +/// copy +// * of this software and associated documentation files (the "Software"), to +/// deal +// * in the Software without restriction, including without limitation the +/// rights // * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // * copies of the Software, and to permit persons to whom the Software is // * furnished to do so, subject to the following conditions: @@ -12,30 +15,32 @@ // * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // */ -//package io.hoangtien2k3.commons.filter.webclient; // package io.hoangtien2k3.commons.filter.webclient; +// package io.hoangtien2k3.commons.filter.webclient; // package +/// io.hoangtien2k3.commons.filter.webclient; // -//import org.springframework.web.reactive.function.client.ClientRequest; -//import org.springframework.web.reactive.function.client.ClientResponse; -//import -// org.springframework.web.reactive.function.client.ExchangeFilterFunction; -//import org.springframework.web.reactive.function.client.ExchangeFunction; -//import reactor.core.publisher.Mono; +// import org.springframework.web.reactive.function.client.ClientRequest; +// import org.springframework.web.reactive.function.client.ClientResponse; +// import +// org.springframework.web.reactive.function.client.ExchangeFilterFunction; +// import org.springframework.web.reactive.function.client.ExchangeFunction; +// import reactor.core.publisher.Mono; // -//public class ErrorHandlingFilter implements ExchangeFilterFunction { -// @Override -// public Mono filter(ClientRequest request, ExchangeFunction -// next) { -// return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> { -// clientResponse.statusCode(); -// if (clientResponse.statusCode().is5xxServerError() || clientResponse.statusCode().is4xxClientError()) { -// return clientResponse.bodyToMono(String.class) -// .flatMap(errorBody -> { -// return Mono.error(new -// CustomWebClientResponseException(errorBody, clientResponse.statusCode())); -// }); -// } else { -// return Mono.just(clientResponse); -// } -// }); -// } -//} +// public class ErrorHandlingFilter implements ExchangeFilterFunction { +// @Override +// public Mono filter(ClientRequest request, ExchangeFunction +// next) { +// return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> { +// clientResponse.statusCode(); +// if (clientResponse.statusCode().is5xxServerError() || +/// clientResponse.statusCode().is4xxClientError()) { +// return clientResponse.bodyToMono(String.class) +// .flatMap(errorBody -> { +// return Mono.error(new +// CustomWebClientResponseException(errorBody, clientResponse.statusCode())); +// }); +// } else { +// return Mono.just(clientResponse); +// } +// }); +// } +// } diff --git a/src/main/java/io/hoangtien2k3/commons/filter/webclient/TraceIdWebClientFilter.java b/src/main/java/io/hoangtien2k3/commons/filter/webclient/TraceIdWebClientFilter.java index ef8e903..28fcd8a 100644 --- a/src/main/java/io/hoangtien2k3/commons/filter/webclient/TraceIdWebClientFilter.java +++ b/src/main/java/io/hoangtien2k3/commons/filter/webclient/TraceIdWebClientFilter.java @@ -1,18 +1,4 @@ -///* -// * Copyright 2024 author - Hoàng Anh Tiến -// * -// * Permission is hereby granted, free of charge, to any person obtaining a copy -// * of this software and associated documentation files (the "Software"), to deal -// * in the Software without restriction, including without limitation the rights -// * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// * copies of the Software, and to permit persons to whom the Software is -// * furnished to do so, subject to the following conditions: -// * -// * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -// */ -//package io.hoangtien2k3.commons.filter.webclient; // package io.hoangtien2k3.commons.filter.webclient; +//package io.hoangtien2k3.commons.filter.webclient; // //import brave.Tracer; //import brave.Tracing; @@ -22,8 +8,7 @@ //import org.springframework.stereotype.Component; //import org.springframework.web.reactive.function.client.ClientRequest; //import org.springframework.web.reactive.function.client.ClientResponse; -//import -// org.springframework.web.reactive.function.client.ExchangeFilterFunction; +//import org.springframework.web.reactive.function.client.ExchangeFilterFunction; //import org.springframework.web.reactive.function.client.ExchangeFunction; //import reactor.core.publisher.Mono; // diff --git a/src/main/java/io/hoangtien2k3/commons/repository/BaseTemplateRepository.java b/src/main/java/io/hoangtien2k3/commons/repository/BaseTemplateRepository.java index f8430f8..4dfa832 100644 --- a/src/main/java/io/hoangtien2k3/commons/repository/BaseTemplateRepository.java +++ b/src/main/java/io/hoangtien2k3/commons/repository/BaseTemplateRepository.java @@ -1,9 +1,12 @@ -///* +/// * // * Copyright 2024 author - Hoàng Anh Tiến // * -// * Permission is hereby granted, free of charge, to any person obtaining a copy -// * of this software and associated documentation files (the "Software"), to deal -// * in the Software without restriction, including without limitation the rights +// * Permission is hereby granted, free of charge, to any person obtaining a +/// copy +// * of this software and associated documentation files (the "Software"), to +/// deal +// * in the Software without restriction, including without limitation the +/// rights // * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // * copies of the Software, and to permit persons to whom the Software is // * furnished to do so, subject to the following conditions: @@ -12,23 +15,23 @@ // * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // */ -//package io.hoangtien2k3.commons.repository; +// package io.hoangtien2k3.commons.repository; // -//import com.fasterxml.jackson.databind.MapperFeature; -//import com.fasterxml.jackson.databind.ObjectMapper; -//import com.fasterxml.jackson.databind.PropertyNamingStrategies; -//import com.fasterxml.jackson.databind.json.JsonMapper; -//import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; -//import io.hoangtien2k3.commons.utils.DataUtil; -//import java.util.Map; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.data.r2dbc.core.R2dbcEntityTemplate; -//import org.springframework.r2dbc.core.DatabaseClient; -//import org.springframework.stereotype.Component; -//import reactor.core.publisher.Flux; -//import reactor.core.publisher.Mono; +// import com.fasterxml.jackson.databind.MapperFeature; +// import com.fasterxml.jackson.databind.ObjectMapper; +// import com.fasterxml.jackson.databind.PropertyNamingStrategies; +// import com.fasterxml.jackson.databind.json.JsonMapper; +// import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +// import io.hoangtien2k3.commons.utils.DataUtil; +// import java.util.Map; +// import org.springframework.beans.factory.annotation.Autowired; +// import org.springframework.data.r2dbc.core.R2dbcEntityTemplate; +// import org.springframework.r2dbc.core.DatabaseClient; +// import org.springframework.stereotype.Component; +// import reactor.core.publisher.Flux; +// import reactor.core.publisher.Mono; // -///** +/// ** // * Base class for repositories providing common query operations using R2DBC. // * // *

@@ -46,112 +49,114 @@ // * @see ObjectMapper // * @see DatabaseClient // */ -//@Component -//public class BaseTemplateRepository { +// @Component +// public class BaseTemplateRepository { // -// private final R2dbcEntityTemplate entityTemplate; -// private final ObjectMapper objectMapper; +// private final R2dbcEntityTemplate entityTemplate; +// private final ObjectMapper objectMapper; // -// /** -// * Constructs a {@link BaseTemplateRepository} with the specified -// * {@link R2dbcEntityTemplate}. -// * -// *

-// * The constructor initializes the {@link ObjectMapper} with custom -// * configuration for JSON processing, including a {@link JavaTimeModule} for -// * handling Java 8 time types, and a naming strategy for property names. -// *

-// * -// * @param entityTemplate -// * the {@link R2dbcEntityTemplate} used for database operations -// */ -// @Autowired -// public BaseTemplateRepository(R2dbcEntityTemplate entityTemplate) { -// this.entityTemplate = entityTemplate; -// this.objectMapper = JsonMapper.builder() -// .addModule(new JavaTimeModule()) -// .propertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE) -// .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true) -// .build(); -// } +// /** +// * Constructs a {@link BaseTemplateRepository} with the specified +// * {@link R2dbcEntityTemplate}. +// * +// *

+// * The constructor initializes the {@link ObjectMapper} with custom +// * configuration for JSON processing, including a {@link JavaTimeModule} for +// * handling Java 8 time types, and a naming strategy for property names. +// *

+// * +// * @param entityTemplate +// * the {@link R2dbcEntityTemplate} used for database operations +// */ +// @Autowired +// public BaseTemplateRepository(R2dbcEntityTemplate entityTemplate) { +// this.entityTemplate = entityTemplate; +// this.objectMapper = JsonMapper.builder() +// .addModule(new JavaTimeModule()) +// .propertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE) +// .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true) +// .build(); +// } // -// /** -// * Executes a SQL query and returns the results as a {@link Flux} of the -// * specified type. -// * -// *

-// * This method binds the provided parameters to the SQL query and converts the -// * raw result rows to the specified type using {@link #convert(Map, Class)}. -// *

-// * -// * @param sql -// * the SQL query to execute -// * @param params -// * a map of parameters to bind to the SQL query -// * @param type -// * the class of the result type -// * @param -// * the type of the result -// * @return a {@link Flux} of results of the specified type -// */ -// protected Flux listQuery(String sql, Map params, Class type) { -// DatabaseClient.GenericExecuteSpec spec = -// entityTemplate.getDatabaseClient().sql(sql); -// if (!DataUtil.isNullOrEmpty(params)) { -// for (String param : params.keySet()) { -// spec = spec.bind(param, params.get(param)); -// } -// } -// return spec.fetch().all().map(raw -> convert(raw, type)); -// } +// /** +// * Executes a SQL query and returns the results as a {@link Flux} of the +// * specified type. +// * +// *

+// * This method binds the provided parameters to the SQL query and converts the +// * raw result rows to the specified type using {@link #convert(Map, Class)}. +// *

+// * +// * @param sql +// * the SQL query to execute +// * @param params +// * a map of parameters to bind to the SQL query +// * @param type +// * the class of the result type +// * @param +// * the type of the result +// * @return a {@link Flux} of results of the specified type +// */ +// protected Flux listQuery(String sql, Map params, +/// Class type) { +// DatabaseClient.GenericExecuteSpec spec = +// entityTemplate.getDatabaseClient().sql(sql); +// if (!DataUtil.isNullOrEmpty(params)) { +// for (String param : params.keySet()) { +// spec = spec.bind(param, params.get(param)); +// } +// } +// return spec.fetch().all().map(raw -> convert(raw, type)); +// } // -// /** -// * Executes a SQL query to count the number of rows and returns the count as a -// * {@link Mono}. -// * -// *

-// * This method appends a count query to the provided SQL query and binds the -// * provided parameters. The result is cast to a {@link Long}. -// *

-// * -// * @param sql -// * the SQL query to count rows -// * @param params -// * a map of parameters to bind to the SQL query -// * @return a {@link Mono} containing the count of rows -// */ -// protected Mono countQuery(String sql, Map params) { -// String query = "select count(*) as common_count_col from (" + sql + ") as common_count_alias"; -// DatabaseClient.GenericExecuteSpec spec = -// entityTemplate.getDatabaseClient().sql(query); -// if (!DataUtil.isNullOrEmpty(params)) { -// for (String param : params.keySet()) { -// spec = spec.bind(param, params.get(param)); -// } -// } -// return spec.fetch() -// .first() -// .map(result -> result.get("common_count_col")) -// .cast(Long.class); -// } +// /** +// * Executes a SQL query to count the number of rows and returns the count as a +// * {@link Mono}. +// * +// *

+// * This method appends a count query to the provided SQL query and binds the +// * provided parameters. The result is cast to a {@link Long}. +// *

+// * +// * @param sql +// * the SQL query to count rows +// * @param params +// * a map of parameters to bind to the SQL query +// * @return a {@link Mono} containing the count of rows +// */ +// protected Mono countQuery(String sql, Map params) { +// String query = "select count(*) as common_count_col from (" + sql + ") as +/// common_count_alias"; +// DatabaseClient.GenericExecuteSpec spec = +// entityTemplate.getDatabaseClient().sql(query); +// if (!DataUtil.isNullOrEmpty(params)) { +// for (String param : params.keySet()) { +// spec = spec.bind(param, params.get(param)); +// } +// } +// return spec.fetch() +// .first() +// .map(result -> result.get("common_count_col")) +// .cast(Long.class); +// } // -// /** -// * Converts a map of raw data to an object of the specified type. -// * -// *

-// * This method uses {@link ObjectMapper} to convert the raw data to the -// * specified type. -// *

-// * -// * @param raw -// * a map of raw data -// * @param type -// * the class of the result type -// * @param -// * the type of the result -// * @return the converted object of the specified type -// */ -// protected T convert(Map raw, Class type) { -// return objectMapper.convertValue(raw, type); -// } -//} +// /** +// * Converts a map of raw data to an object of the specified type. +// * +// *

+// * This method uses {@link ObjectMapper} to convert the raw data to the +// * specified type. +// *

+// * +// * @param raw +// * a map of raw data +// * @param type +// * the class of the result type +// * @param +// * the type of the result +// * @return the converted object of the specified type +// */ +// protected T convert(Map raw, Class type) { +// return objectMapper.convertValue(raw, type); +// } +// } diff --git a/src/main/java/io/hoangtien2k3/commons/utils/FileUtils.java b/src/main/java/io/hoangtien2k3/commons/utils/FileUtils.java index 39f875e..2707461 100644 --- a/src/main/java/io/hoangtien2k3/commons/utils/FileUtils.java +++ b/src/main/java/io/hoangtien2k3/commons/utils/FileUtils.java @@ -1,9 +1,12 @@ -///* +/// * // * Copyright 2024 author - Hoàng Anh Tiến // * -// * Permission is hereby granted, free of charge, to any person obtaining a copy -// * of this software and associated documentation files (the "Software"), to deal -// * in the Software without restriction, including without limitation the rights +// * Permission is hereby granted, free of charge, to any person obtaining a +/// copy +// * of this software and associated documentation files (the "Software"), to +/// deal +// * in the Software without restriction, including without limitation the +/// rights // * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // * copies of the Software, and to permit persons to whom the Software is // * furnished to do so, subject to the following conditions: @@ -12,70 +15,71 @@ // * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // */ -//package io.hoangtien2k3.commons.utils; // package io.hoangtien2k3.commons.utils; +// package io.hoangtien2k3.commons.utils; // package +/// io.hoangtien2k3.commons.utils; // -//import java.security.cert.X509Certificate; +// import java.security.cert.X509Certificate; // -//public class FileUtils { +// public class FileUtils { // -// public static String createHash(String certificate, String file) { -// String folderRootCA = "./RootCA"; -// X509Certificate[] certChain = -// X509ExtensionUtil.getCertChainOfCert(certificate, folderRootCA); -// String fontPath = "./font/times.ttf"; -// SignPdfFile pdfSig = new SignPdfFile(); -// return HashFilePDF.getHashTypeRectangleText(pdfSig, file, certChain, -// fontPath); -// } +// public static String createHash(String certificate, String file) { +// String folderRootCA = "./RootCA"; +// X509Certificate[] certChain = +// X509ExtensionUtil.getCertChainOfCert(certificate, folderRootCA); +// String fontPath = "./font/times.ttf"; +// SignPdfFile pdfSig = new SignPdfFile(); +// return HashFilePDF.getHashTypeRectangleText(pdfSig, file, certChain, +// fontPath); +// } // -// public static void createHash(SignPdfFile pdfSig, String certificate, String -// file) { -// String folderRootCA = "./RootCA"; -// X509Certificate[] certChain = -// X509ExtensionUtil.getCertChainOfCert(certificate, folderRootCA); -// String fontPath = "./font/times.ttf"; -// getHashTypeRectangleText(pdfSig, file, certChain, fontPath); -// } +// public static void createHash(SignPdfFile pdfSig, String certificate, String +// file) { +// String folderRootCA = "./RootCA"; +// X509Certificate[] certChain = +// X509ExtensionUtil.getCertChainOfCert(certificate, folderRootCA); +// String fontPath = "./font/times.ttf"; +// getHashTypeRectangleText(pdfSig, file, certChain, fontPath); +// } // -// public static Boolean insertSignaturePdfFile(String signature, String -// destPath, String certificate, String file) { -// SignPdfFile pdfSig = new SignPdfFile(); -// createHash(pdfSig, certificate, file); -// TimestampConfig timestampConfig = new TimestampConfig(); -// timestampConfig.setUseTimestamp(false); -// return pdfSig.insertSignature(signature, destPath, timestampConfig); -// } +// public static Boolean insertSignaturePdfFile(String signature, String +// destPath, String certificate, String file) { +// SignPdfFile pdfSig = new SignPdfFile(); +// createHash(pdfSig, certificate, file); +// TimestampConfig timestampConfig = new TimestampConfig(); +// timestampConfig.setUseTimestamp(false); +// return pdfSig.insertSignature(signature, destPath, timestampConfig); +// } // -// public static void getHashTypeRectangleText(SignPdfFile pdfSig, String -// filePath, X509Certificate[] certChain, String fontPath) { -// float widthRectangle = DisplayConfig.WIDTH_RECTANGLE_DEFAULT; -// float heightRectangle = DisplayConfig.HEIGHT_RECTANGLE_DEFAULT; -// int locateSign = DisplayConfig.LOCATE_SIGN_DEFAULT; -// float marginTopOfRectangle = DisplayConfig.MARGIN_TOP_OF_RECTANGLE_DEFAULT; -// float marginBottomOfRectangle = 420; -// float marginRightOfRectangle = -// DisplayConfig.MARGIN_RIGHT_OF_RECTANGLE_DEFAULT; -// float marginLeftOfRectangle = 310; -// String displayText = DisplayConfig.DISPLAY_TEXT_DEFAULT_EMPTY; -// String formatRectangleText = DisplayConfig.FORMAT_RECTANGLE_TEXT_DEFAULT; -// String contact = CertUtils.getCN(certChain[0]); -// String reason = "Ký số"; -// String location = "Hà Nội"; -// String dateFormatString = DisplayConfig.DATE_FORMAT_STRING_DEFAULT; -// int sizeFont = DisplayConfig.SIZE_FONT_DEFAULT; -// String ou = DisplayConfig.ORGANIZATION_UNIT_DEFAULT_EMPTY; -// String o = DisplayConfig.ORGANIZATION_DEFAULT_EMPTY; -// DisplayConfig displayConfig = -// DisplayConfig.generateDisplayConfigRectangleText( -// 2, widthRectangle, heightRectangle, locateSign, -// marginTopOfRectangle, marginBottomOfRectangle, -// marginRightOfRectangle, marginLeftOfRectangle, -// displayText, formatRectangleText, -// contact, reason, location, -// dateFormatString, fontPath, sizeFont, -// ou, o); -// String digestAlg = SignPdfAsynchronous.HASH_ALGORITHM_SHA256; -// String cryptAlg = SignPdfAsynchronous.CRYPT_ALGORITHM_RSA; -// pdfSig.createHash(filePath, certChain, digestAlg, cryptAlg, displayConfig); -// } -//} +// public static void getHashTypeRectangleText(SignPdfFile pdfSig, String +// filePath, X509Certificate[] certChain, String fontPath) { +// float widthRectangle = DisplayConfig.WIDTH_RECTANGLE_DEFAULT; +// float heightRectangle = DisplayConfig.HEIGHT_RECTANGLE_DEFAULT; +// int locateSign = DisplayConfig.LOCATE_SIGN_DEFAULT; +// float marginTopOfRectangle = DisplayConfig.MARGIN_TOP_OF_RECTANGLE_DEFAULT; +// float marginBottomOfRectangle = 420; +// float marginRightOfRectangle = +// DisplayConfig.MARGIN_RIGHT_OF_RECTANGLE_DEFAULT; +// float marginLeftOfRectangle = 310; +// String displayText = DisplayConfig.DISPLAY_TEXT_DEFAULT_EMPTY; +// String formatRectangleText = DisplayConfig.FORMAT_RECTANGLE_TEXT_DEFAULT; +// String contact = CertUtils.getCN(certChain[0]); +// String reason = "Ký số"; +// String location = "Hà Nội"; +// String dateFormatString = DisplayConfig.DATE_FORMAT_STRING_DEFAULT; +// int sizeFont = DisplayConfig.SIZE_FONT_DEFAULT; +// String ou = DisplayConfig.ORGANIZATION_UNIT_DEFAULT_EMPTY; +// String o = DisplayConfig.ORGANIZATION_DEFAULT_EMPTY; +// DisplayConfig displayConfig = +// DisplayConfig.generateDisplayConfigRectangleText( +// 2, widthRectangle, heightRectangle, locateSign, +// marginTopOfRectangle, marginBottomOfRectangle, +// marginRightOfRectangle, marginLeftOfRectangle, +// displayText, formatRectangleText, +// contact, reason, location, +// dateFormatString, fontPath, sizeFont, +// ou, o); +// String digestAlg = SignPdfAsynchronous.HASH_ALGORITHM_SHA256; +// String cryptAlg = SignPdfAsynchronous.CRYPT_ALGORITHM_RSA; +// pdfSig.createHash(filePath, certChain, digestAlg, cryptAlg, displayConfig); +// } +// }