From 7729d4564a9d853cc69ef961e75e97e9f5e5be09 Mon Sep 17 00:00:00 2001 From: agrancaric Date: Mon, 22 Jan 2024 13:22:19 +0100 Subject: [PATCH] Migrate code to Java 17 standard and cleanup code --- .editorconfig | 14 +- .../api/model/EncryptionConfiguration.java | 26 +--- .../NrichEncryptAutoConfiguration.java | 10 +- .../properties/NrichEncryptProperties.java | 65 ++------- .../NrichEncryptAutoConfigurationTest.java | 2 + .../encrypt/aspect/BaseEncryptDataAdvice.java | 18 +-- .../encrypt/aspect/EncryptDataAspect.java | 9 +- .../aspect/EncryptMethodInterceptor.java | 17 +-- .../service/DefaultDataEncryptService.java | 9 +- .../encrypt/util/PointcutResolvingUtil.java | 2 +- .../encrypt/EncryptTestConfiguration.java | 27 ++-- .../DefaultDataEncryptServiceTest.java | 39 +++--- .../util/PointcutResolvingUtilTest.java | 5 +- .../excel/api/model/ColumnDataFormat.java | 20 +-- .../excel/api/model/TemplateVariable.java | 20 +-- .../nrich/excel/api/model/TypeDataFormat.java | 20 +-- .../NrichExcelAutoConfiguration.java | 4 +- .../properties/NrichExcelProperties.java | 63 ++------- .../NrichExcelAutoConfigurationTest.java | 2 + .../converter/DefaultCellValueConverter.java | 14 +- .../generator/PoiExcelReportGenerator.java | 10 +- .../croz/nrich/excel/model/PoiCellHolder.java | 34 +++-- .../nrich/excel/util/TypeDataFormatUtil.java | 16 +-- .../PoiExcelReportGeneratorTest.java | 20 ++- .../DefaultExcelReportServiceTest.java | 2 +- .../excel/testutil/PoiDataResolverUtil.java | 16 +-- .../excel/util/TypeDataFormatUtilTest.java | 7 +- .../api/model/ConstrainedProperty.java | 3 +- ...dPropertyClientValidatorConfiguration.java | 26 +--- .../ConstrainedPropertyConfiguration.java | 32 +---- .../api/model/FormConfiguration.java | 20 +-- ...onfigurationMappingCustomizerUtilTest.java | 3 +- ...ichFormConfigurationAutoConfiguration.java | 8 +- .../NrichFormConfigurationProperties.java | 42 ++---- ...ormConfigurationAutoConfigurationTest.java | 9 +- ...inedPropertyValidatorConverterService.java | 3 +- .../DefaultFormConfigurationService.java | 7 +- ...ourceFieldErrorMessageResolverService.java | 2 +- .../FormConfigurationTestConfiguration.java | 7 +- .../FormConfigurationControllerTest.java | 8 +- ...PropertyValidatorConverterServiceTest.java | 6 +- ...urationAnnotationResolvingServiceTest.java | 3 +- .../DefaultFormConfigurationServiceTest.java | 57 ++++---- ...eFieldErrorMessageResolverServiceTest.java | 4 +- ...nfigurationServiceTestSubclassRequest.java | 32 +++++ .../FormConfigurationGeneratingUtil.java | 4 +- .../NrichJacksonAutoConfiguration.java | 2 +- .../properties/NrichJacksonProperties.java | 38 ++---- .../NrichJacksonAutoConfigurationTest.java | 8 +- ...vertEmptyStringToNullDeserializerTest.java | 8 +- .../EntityClassSerializerModifierTest.java | 7 +- ...tityClassSerializerModifierTestEntity.java | 4 + .../jackson/util/JacksonModuleUtilTest.java | 4 +- .../DefaultJavaToJavascriptTypeConverter.java | 25 ++-- ...ToJavascriptTypeConversionServiceTest.java | 4 +- .../Slf4jLoggingServiceGeneratingUtil.java | 7 +- .../api/model/ValidationError.java | 20 +-- .../NrichNotificationAutoConfiguration.java | 6 +- .../DefaultNotificationResolverService.java | 16 +-- ...rceNotificationMessageResolverService.java | 7 +- ...efaultNotificationResolverServiceTest.java | 15 +-- ...otificationMessageResolverServiceTest.java | 13 +- ...MessageSourceResolvableGeneratingUtil.java | 6 +- .../testutil/NotificationGeneratingUtil.java | 21 +-- .../model/RegistryGroupConfiguration.java | 26 +--- .../data/request/ListBulkRegistryRequest.java | 16 +-- .../api/data/request/ListRegistryRequest.java | 37 +---- .../api/data/request/SearchParameter.java | 19 +-- .../api/enumdata/model/EnumResult.java | 15 +-- .../request/ListBulkRegistryEnumRequest.java | 16 +-- .../request/ListRegistryEnumRequest.java | 21 +-- .../api/history/model/EntityWithRevision.java | 21 +-- .../api/history/model/RevisionInfo.java | 32 +---- .../request/ListRegistryHistoryRequest.java | 43 ++---- .../NrichRegistryAutoConfiguration.java | 26 ++-- .../properties/NrichRegistryProperties.java | 86 +++--------- .../NrichRegistryAutoConfigurationTest.java | 28 ++-- .../comparator/DisplayOrderComparator.java | 2 + .../RegistryGroupConfigurationComparator.java | 4 +- .../DefaultRegistryConfigurationService.java | 33 +++-- .../RegistryClassResolvingConstants.java | 4 +- .../registry/core/model/PropertyWithType.java | 13 +- .../core/model/RegistryDataConfiguration.java | 10 +- .../RegistryDataConfigurationHolder.java | 12 +- .../core/model/RegistryGroupDefinition.java | 10 +- .../model/RegistryGroupDefinitionHolder.java | 11 +- .../RegistryHistoryConfigurationHolder.java | 18 +-- .../DefaultRegistryClassResolvingService.java | 5 +- ...tRegistryConfigurationResolverService.java | 16 +-- ...ityManagerRegistryEntityFinderService.java | 9 +- .../core/support/ManagedTypeWrapper.java | 7 +- .../core/support/SingularAssociation.java | 11 +- .../controller/RegistryDataController.java | 6 +- .../data/request/CreateRegistryRequest.java | 13 +- .../data/request/DeleteRegistryRequest.java | 22 +-- .../data/request/UpdateRegistryRequest.java | 16 +-- ...tRegistryDataRequestConversionService.java | 8 +- .../service/DefaultRegistryDataService.java | 32 ++--- .../service/DefaultRegistryEnumService.java | 8 +- .../DefaultRegistryHistoryService.java | 40 +++--- .../registry/RegistryTestConfiguration.java | 35 +++-- .../DisplayOrderComparatorTest.java | 4 +- ...istryGroupConfigurationComparatorTest.java | 4 +- .../RegistryPropertyComparatorTest.java | 4 +- ...faultRegistryConfigurationServiceTest.java | 6 +- ...istryConfigurationResolverServiceTest.java | 26 ++-- .../RegistryConfigurationGeneratingUtil.java | 10 +- ...ormConfigurationMappingCustomizerTest.java | 4 +- ...istryDataRequestConversionServiceTest.java | 4 +- .../stub/RegistryTestEmbeddedUserGroupId.java | 6 +- .../RegistryTestEntityWithEmbeddedId.java | 9 +- .../testutil/RegistryDataGeneratingUtil.java | 126 ++++-------------- .../RegistryDataMapGeneratingUtil.java | 6 +- .../RegistryRequestGeneratingUtil.java | 14 +- .../data/util/ClassLoadingUtilTest.java | 5 +- .../DefaultRegistryEnumServiceTest.java | 16 +-- .../testutil/RegistryEnumGeneratingUtil.java | 15 +-- ...RegistryHistoryControllerEndpointTest.java | 4 +- .../RegistryHistoryControllerTest.java | 4 +- .../DefaultRegistryHistoryServiceTest.java | 34 ++--- ...gistryHistoryTestEntityWithEmbeddedId.java | 8 +- ...ryHistoryTestEntityWithEmbeddedObject.java | 8 +- .../RegistryHistoryGeneratingUtil.java | 25 ++-- .../search/api/annotation/Projection.java | 2 +- .../model/operator/DefaultSearchOperator.java | 2 +- .../property/SearchPropertyConfiguration.java | 3 +- .../model/property/SearchPropertyJoin.java | 20 +-- .../model/property/SearchPropertyMapping.java | 20 +-- .../nrich/search/api/util/PageableUtil.java | 8 +- .../search/api/util/PageableUtilTest.java | 11 +- .../NrichSearchAutoConfiguration.java | 9 +- .../properties/NrichSearchProperties.java | 60 ++------- .../NrichSearchAutoConfigurationTest.java | 8 +- ...gDirectFieldAccessFallbackBeanWrapper.java | 2 +- ...ultStringToEntityPropertyMapConverter.java | 2 +- .../DefaultStringToTypeConverter.java | 17 +-- .../nrich/search/model/AttributeHolder.java | 12 +- .../search/model/AttributeHolderWithPath.java | 11 +- .../croz/nrich/search/model/Restriction.java | 18 +-- .../nrich/search/parser/SearchDataParser.java | 29 ++-- .../support/JpaEntityAttributeResolver.java | 16 +-- .../nrich/search/support/JpaQueryBuilder.java | 20 +-- .../util/ProjectionListResolverUtil.java | 9 +- .../nrich/search/util/PropertyNameUtil.java | 2 +- .../nrich/search/util/GroovyUtilTest.groovy | 18 ++- ...stResolverUtilWithGroovyClosureTest.groovy | 19 ++- ...lverUtilWithGroovyClosureTestEntity.groovy | 13 +- ...roovyClosureWithExceptionTestEntity.groovy | 13 +- .../nrich/search/SearchTestConfiguration.java | 5 +- ...tringToEntityPropertyMapConverterTest.java | 9 +- .../DefaultStringToTypeConverterTest.java | 6 +- .../repository/JpaSearchExecutorTest.java | 7 +- .../JpaStringSearchExecutorTest.java | 26 ++-- ...stEntityAdditionalRestrictionResolver.java | 3 +- .../search/repository/stub/TestEntityDto.java | 11 +- .../stub/TestEntityProjectionDto.java | 14 +- .../stub/TestEntitySearchRequest.java | 19 +-- .../support/JpaQueryBuilderTest.java | 65 ++++----- ...NaturalIdSearchExecutorGeneratingUtil.java | 8 +- ...earchRepositoryExecutorGeneratingUtil.java | 17 +-- ...ectFieldAccessFallbackBeanWrapperTest.java | 3 +- ...cessFallbackBeanWrapperGeneratingUtil.java | 11 -- .../search/util/PathResolvingUtilTest.java | 3 +- .../NrichCsrfAutoConfiguration.java | 6 +- .../csrf/properties/NrichCsrfProperties.java | 68 ++-------- .../NrichCsrfAutoConfigurationTest.java | 2 + .../core/controller/CsrfPingController.java | 7 +- .../csrf/core/util/CsrfUriUtilTest.java | 10 +- .../webflux/filter/CsrfWebFilterTest.java | 3 +- .../interceptor/CsrfInterceptorTest.java | 3 +- .../NrichValidationAutoConfiguration.java | 4 +- .../constraint/util/DateConverterUtil.java | 35 +++-- .../constraint/util/GroovyUtil.java | 19 ++- .../util/ValidationReflectionUtil.java | 12 +- .../validator/BaseValidFileValidator.java | 15 ++- .../constraint/validator/InListValidator.java | 4 +- .../ValidSearchPropertiesValidator.java | 2 +- .../constraint/stub/InListTestRequest.java | 9 +- .../stub/LastTimestampInDayTestRequest.java | 8 +- .../stub/MaxSizeInBytesTestRequest.java | 9 +- .../constraint/stub/MinDateTestRequest.java | 8 +- .../stub/NotNullWhenInvalidTestRequest.java | 10 +- .../stub/NotNullWhenTestRequest.java | 12 +- .../constraint/stub/NullWhenTestRequest.java | 12 +- ...llWhenTestRequestWithAutowiredService.java | 9 +- .../SpelExpressionEnvirnomentTestRequest.java | 9 +- ...ExpressionSystemPropertiesTestRequest.java | 9 +- .../stub/SpelExpressionTestRequest.java | 9 +- ...ableValidatorEmptyPropertyTestRequest.java | 10 +- ...esolvableValidatorFilePartTestRequest.java | 9 +- ...leValidatorInvalidTypeFileTestRequest.java | 9 +- ...lidatorMultipartFileCustomTestRequest.java | 17 +-- ...ableValidatorMultipartFileTestRequest.java | 9 +- ...ValidFileValidatorFilePartTestRequest.java | 9 +- ...leValidatorInvalidTypeFileTestRequest.java | 9 +- ...FileValidatorMultipartFileTestRequest.java | 9 +- ...angeValidatorDifferentTypeTestRequest.java | 10 +- ...lidRangeValidatorInclusiveTestRequest.java | 10 +- ...angeValidatorNotComparableTestRequest.java | 11 +- .../stub/ValidRangeValidatorTestRequest.java | 10 +- ...ValidSearchFieldsValidatorTestRequest.java | 12 +- .../validator/ValidFileValidatorTest.java | 38 ++---- .../NrichWebMvcAutoConfiguration.java | 6 +- .../properties/NrichWebMvcProperties.java | 70 ++-------- .../NrichWebMvcAutoConfigurationTest.java | 2 + ...tionErrorHandlingRestControllerAdvice.java | 12 +- ...faultTransientPropertyResolverService.java | 3 +- .../nrich/webmvc/WebmvcTestConfiguration.java | 4 +- .../advice/testutil/MapGeneratingUtil.java | 8 +- .../ConstrainedSessionLocaleResolverTest.java | 6 +- ...ropertyResolverServiceImplTestRequest.java | 2 +- .../nrich/webmvc/test/BaseControllerTest.java | 3 +- 212 files changed, 1036 insertions(+), 2148 deletions(-) create mode 100644 nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/stub/FormConfigurationServiceTestSubclassRequest.java diff --git a/.editorconfig b/.editorconfig index 4ec77a38c..e7445680d 100644 --- a/.editorconfig +++ b/.editorconfig @@ -263,14 +263,14 @@ ij_groovy_tab_width = 2 ij_groovy_continuation_indent_size = 4 ij_groovy_label_indent_size = 4 ij_groovy_align_multiline_array_initializer_expression = true -ij_groovy_align_multiline_assignment = true +ij_groovy_align_multiline_assignment = false ij_groovy_align_multiline_binary_operation = true -ij_groovy_align_multiline_chained_methods = true -ij_groovy_align_multiline_parameters = false -ij_groovy_align_multiline_parameters_in_calls = true -ij_groovy_align_multiline_ternary_operation = true -ij_groovy_array_initializer_new_line_after_left_brace = true -ij_groovy_array_initializer_right_brace_on_new_line = true +ij_groovy_align_multiline_chained_methods = false +ij_groovy_align_multiline_parameters = true +ij_groovy_align_multiline_parameters_in_calls = false +ij_groovy_align_multiline_ternary_operation = false +ij_groovy_array_initializer_new_line_after_left_brace = false +ij_groovy_array_initializer_right_brace_on_new_line = false ij_groovy_array_initializer_wrap = normal ij_groovy_assert_statement_wrap = on_every_item ij_groovy_assignment_wrap = normal diff --git a/nrich-encrypt-api/src/main/java/net/croz/nrich/encrypt/api/model/EncryptionConfiguration.java b/nrich-encrypt-api/src/main/java/net/croz/nrich/encrypt/api/model/EncryptionConfiguration.java index 058887c5b..2932071f0 100644 --- a/nrich-encrypt-api/src/main/java/net/croz/nrich/encrypt/api/model/EncryptionConfiguration.java +++ b/nrich-encrypt-api/src/main/java/net/croz/nrich/encrypt/api/model/EncryptionConfiguration.java @@ -17,31 +17,15 @@ package net.croz.nrich.encrypt.api.model; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - import java.util.List; /** * Method encrypt/decrypt configuration. + * + * @param methodToEncryptDecrypt Name of the method to encrypt/decrypt (fullyQualifiedClassName.methodName). + * @param propertyToEncryptDecryptList List of property paths to encrypt/decrypt. + * @param encryptionOperation Whether to encrypt method result or decrypt method parameters. */ -@RequiredArgsConstructor -@Getter -public class EncryptionConfiguration { - - /** - * Name of the method to encrypt/decrypt (fullyQualifiedClassName.methodName). - */ - private final String methodToEncryptDecrypt; - - /** - * List of property paths to encrypt/decrypt. - */ - private final List propertyToEncryptDecryptList; - - /** - * Whether to encrypt method result or decrypt method parameters. - */ - private final EncryptionOperation encryptionOperation; +public record EncryptionConfiguration(String methodToEncryptDecrypt, List propertyToEncryptDecryptList, EncryptionOperation encryptionOperation) { } diff --git a/nrich-encrypt-spring-boot-starter/src/main/java/net/croz/nrich/encrypt/starter/configuration/NrichEncryptAutoConfiguration.java b/nrich-encrypt-spring-boot-starter/src/main/java/net/croz/nrich/encrypt/starter/configuration/NrichEncryptAutoConfiguration.java index 3ac4accec..8b52076be 100644 --- a/nrich-encrypt-spring-boot-starter/src/main/java/net/croz/nrich/encrypt/starter/configuration/NrichEncryptAutoConfiguration.java +++ b/nrich-encrypt-spring-boot-starter/src/main/java/net/croz/nrich/encrypt/starter/configuration/NrichEncryptAutoConfiguration.java @@ -46,11 +46,11 @@ public class NrichEncryptAutoConfiguration { @ConditionalOnMissingBean @Bean public TextEncryptionService textEncryptionService(NrichEncryptProperties encryptProperties) { - String password = ObjectUtils.isEmpty(encryptProperties.getEncryptPassword()) ? KeyGenerators.string().generateKey() : encryptProperties.getEncryptPassword(); - String salt = ObjectUtils.isEmpty(encryptProperties.getEncryptSalt()) ? KeyGenerators.string().generateKey() : encryptProperties.getEncryptSalt(); + String password = ObjectUtils.isEmpty(encryptProperties.encryptPassword()) ? KeyGenerators.string().generateKey() : encryptProperties.encryptPassword(); + String salt = ObjectUtils.isEmpty(encryptProperties.encryptSalt()) ? KeyGenerators.string().generateKey() : encryptProperties.encryptSalt(); BytesEncryptor encryptor = Encryptors.standard(password, salt); - return new BytesEncryptorTextEncryptService(encryptor, encryptProperties.getTextEncryptCharset()); + return new BytesEncryptorTextEncryptService(encryptor, encryptProperties.textEncryptCharset()); } @ConditionalOnMissingBean @@ -71,8 +71,8 @@ public EncryptDataAspect encryptDataAspect(DataEncryptionService dataEncryptionS public Advisor encryptAdvisor(DataEncryptionService dataEncryptionService, NrichEncryptProperties encryptProperties) { AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); - pointcut.setExpression(PointcutResolvingUtil.resolvePointcutFromEncryptionConfigurationList(encryptProperties.getEncryptionConfigurationList())); + pointcut.setExpression(PointcutResolvingUtil.resolvePointcutFromEncryptionConfigurationList(encryptProperties.encryptionConfigurationList())); - return new DefaultPointcutAdvisor(pointcut, new EncryptMethodInterceptor(dataEncryptionService, encryptProperties.getEncryptionConfigurationList(), encryptProperties.getIgnoredMethodList())); + return new DefaultPointcutAdvisor(pointcut, new EncryptMethodInterceptor(dataEncryptionService, encryptProperties.encryptionConfigurationList(), encryptProperties.ignoredMethodList())); } } diff --git a/nrich-encrypt-spring-boot-starter/src/main/java/net/croz/nrich/encrypt/starter/properties/NrichEncryptProperties.java b/nrich-encrypt-spring-boot-starter/src/main/java/net/croz/nrich/encrypt/starter/properties/NrichEncryptProperties.java index db235612c..75c4d7f5e 100644 --- a/nrich-encrypt-spring-boot-starter/src/main/java/net/croz/nrich/encrypt/starter/properties/NrichEncryptProperties.java +++ b/nrich-encrypt-spring-boot-starter/src/main/java/net/croz/nrich/encrypt/starter/properties/NrichEncryptProperties.java @@ -17,63 +17,26 @@ package net.croz.nrich.encrypt.starter.properties; -import lombok.Getter; import net.croz.nrich.encrypt.api.model.EncryptionConfiguration; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.bind.DefaultValue; import java.util.List; -@Getter +/** + * @param encryptionConfigurationList Configuration list containing methods for encryption and decryption. + * @param ignoredMethodList Used in conjunction with encryptionConfigurationList. It allows defining methods that will not be encrypted. Methods should be in format: fullyQualifiedClasName.methodName. + * @param textEncryptCharset Charset to use for encryption. + * @param encryptAspectEnabled Whether an aspect bean {@link net.croz.nrich.encrypt.aspect.EncryptDataAspect} that handles encryption for {@link net.croz.nrich.encrypt.api.annotation.EncryptResult} + * and {@link net.croz.nrich.encrypt.api.annotation.DecryptArgument} is active. + * @param encryptAdvisorEnabled Whether an advisor bean {@link org.springframework.aop.Advisor} that handles encryption from is encryptionConfigurationList os active. + * @param encryptPassword Optional parameter. If it is null data is encrypted with randomly generated password on each application restart. If encrypted data + * will be persisted this parameter should be specified. + * @param encryptSalt Optional parameter. If it is null data is encrypted with randomly generated salt on each application restart. If encrypted data + * will be persisted this parameter should be specified. + */ @ConfigurationProperties("nrich.encrypt") -public class NrichEncryptProperties { - - /** - * Configuration list containing methods for encryption and decryption. - */ - private final List encryptionConfigurationList; - - /** - * Used in conjunction with encryptionConfigurationList. It allows defining methods that will not be encrypted. Methods should be in format: fullyQualifiedClasName.methodName. - */ - private final List ignoredMethodList; - - /** - * Charset to use for encryption. - */ - private final String textEncryptCharset; - - /** - * Whether an aspect bean {@link net.croz.nrich.encrypt.aspect.EncryptDataAspect} that handles encryption for {@link net.croz.nrich.encrypt.api.annotation.EncryptResult} - * and {@link net.croz.nrich.encrypt.api.annotation.DecryptArgument} is active. - */ - private final boolean encryptAspectEnabled; - - /** - * Whether an advisor bean {@link org.springframework.aop.Advisor} that handles encryption from is encryptionConfigurationList os active. - */ - private final boolean encryptAdvisorEnabled; - - /** - * Optional parameter. If it is null data is encrypted with randomly generated password on each application restart. If encrypted data - * will be persisted this parameter should be specified. - */ - private final String encryptPassword; - - /** - * Optional parameter. If it is null data is encrypted with randomly generated salt on each application restart. If encrypted data - * will be persisted this parameter should be specified. - */ - private final String encryptSalt; +public record NrichEncryptProperties(List encryptionConfigurationList, List ignoredMethodList, @DefaultValue("UTF-8") String textEncryptCharset, + @DefaultValue("true") boolean encryptAspectEnabled, @DefaultValue("true") boolean encryptAdvisorEnabled, String encryptPassword, String encryptSalt) { - public NrichEncryptProperties(List encryptionConfigurationList, List ignoredMethodList, @DefaultValue("UTF-8") String textEncryptCharset, - @DefaultValue("true") boolean encryptAspectEnabled, @DefaultValue("true") boolean encryptAdvisorEnabled, String encryptPassword, String encryptSalt) { - this.encryptionConfigurationList = encryptionConfigurationList; - this.ignoredMethodList = ignoredMethodList; - this.textEncryptCharset = textEncryptCharset; - this.encryptAspectEnabled = encryptAspectEnabled; - this.encryptAdvisorEnabled = encryptAdvisorEnabled; - this.encryptPassword = encryptPassword; - this.encryptSalt = encryptSalt; - } } diff --git a/nrich-encrypt-spring-boot-starter/src/test/java/net/croz/nrich/encrypt/starter/configuration/NrichEncryptAutoConfigurationTest.java b/nrich-encrypt-spring-boot-starter/src/test/java/net/croz/nrich/encrypt/starter/configuration/NrichEncryptAutoConfigurationTest.java index 9e59f76d9..4cfed8e44 100644 --- a/nrich-encrypt-spring-boot-starter/src/test/java/net/croz/nrich/encrypt/starter/configuration/NrichEncryptAutoConfigurationTest.java +++ b/nrich-encrypt-spring-boot-starter/src/test/java/net/croz/nrich/encrypt/starter/configuration/NrichEncryptAutoConfigurationTest.java @@ -20,6 +20,7 @@ import net.croz.nrich.encrypt.api.service.DataEncryptionService; import net.croz.nrich.encrypt.api.service.TextEncryptionService; import net.croz.nrich.encrypt.aspect.EncryptDataAspect; +import net.croz.nrich.encrypt.starter.properties.NrichEncryptProperties; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; @@ -39,6 +40,7 @@ void shouldConfigureDefaultConfiguration() { assertThat(context).hasSingleBean(TextEncryptionService.class); assertThat(context).hasSingleBean(DataEncryptionService.class); assertThat(context).hasSingleBean(EncryptDataAspect.class); + assertThat(context).hasSingleBean(NrichEncryptProperties.class); }); } diff --git a/nrich-encrypt/src/main/java/net/croz/nrich/encrypt/aspect/BaseEncryptDataAdvice.java b/nrich-encrypt/src/main/java/net/croz/nrich/encrypt/aspect/BaseEncryptDataAdvice.java index c3dc298f7..7bf3fb6bb 100644 --- a/nrich-encrypt/src/main/java/net/croz/nrich/encrypt/aspect/BaseEncryptDataAdvice.java +++ b/nrich-encrypt/src/main/java/net/croz/nrich/encrypt/aspect/BaseEncryptDataAdvice.java @@ -17,7 +17,6 @@ package net.croz.nrich.encrypt.aspect; -import lombok.RequiredArgsConstructor; import net.croz.nrich.encrypt.api.model.EncryptionContext; import net.croz.nrich.encrypt.api.service.DataEncryptionService; import org.springframework.security.core.Authentication; @@ -84,21 +83,16 @@ private T encryptCompletableFuture(EncryptionContext encryptionContext, List return encryptedFuture; } - @RequiredArgsConstructor - private static class ReactorEncryptor { + private record ReactorEncryptor(DataEncryptionService dataEncryptionService) { - private final DataEncryptionService dataEncryptionService; - - public T encryptReactorResult(EncryptionContext encryptionContext, List pathToEncryptList, T forEncryption) { - if (forEncryption instanceof Mono) { - @SuppressWarnings("unchecked") - T encryptedMono = (T) ((Mono) forEncryption).map(completedResult -> dataEncryptionService.encryptData(completedResult, pathToEncryptList, encryptionContext)); + T encryptReactorResult(EncryptionContext encryptionContext, List pathToEncryptList, T forEncryption) { + if (forEncryption instanceof Mono mono) { + @SuppressWarnings("unchecked") T encryptedMono = (T) mono.map(completedResult -> dataEncryptionService.encryptData(completedResult, pathToEncryptList, encryptionContext)); return encryptedMono; } - else if (forEncryption instanceof Flux) { - @SuppressWarnings("unchecked") - T encryptedFlux = (T) ((Flux) forEncryption).map(completedResult -> dataEncryptionService.encryptData(completedResult, pathToEncryptList, encryptionContext)); + else if (forEncryption instanceof Flux flux) { + @SuppressWarnings("unchecked") T encryptedFlux = (T) flux.map(completedResult -> dataEncryptionService.encryptData(completedResult, pathToEncryptList, encryptionContext)); return encryptedFlux; } diff --git a/nrich-encrypt/src/main/java/net/croz/nrich/encrypt/aspect/EncryptDataAspect.java b/nrich-encrypt/src/main/java/net/croz/nrich/encrypt/aspect/EncryptDataAspect.java index 0d1dc5226..6a8a65f3c 100644 --- a/nrich-encrypt/src/main/java/net/croz/nrich/encrypt/aspect/EncryptDataAspect.java +++ b/nrich-encrypt/src/main/java/net/croz/nrich/encrypt/aspect/EncryptDataAspect.java @@ -45,8 +45,7 @@ public Object aroundDecryptAnnotatedMethods(ProceedingJoinPoint proceedingJoinPo Signature signature = proceedingJoinPoint.getSignature(); Object[] arguments = proceedingJoinPoint.getArgs(); - if (signature instanceof MethodSignature && arguments.length > 0) { - MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature(); + if (signature instanceof MethodSignature methodSignature && arguments.length > 0) { String methodName = methodSignature.getMethod().getName(); Class[] parameterTypes = methodSignature.getMethod().getParameterTypes(); Annotation[][] parameterAnnotationList = proceedingJoinPoint.getTarget().getClass().getMethod(methodName, parameterTypes).getParameterAnnotations(); @@ -60,7 +59,7 @@ public Object aroundDecryptAnnotatedMethods(ProceedingJoinPoint proceedingJoinPo return arguments[index]; } - return decryptArgument(context, arguments[index], Arrays.asList(argumentAnnotation.argumentPathList())); + return decryptArgument(context, arguments[index], List.of(argumentAnnotation.argumentPathList())); }).toArray(); @@ -78,7 +77,7 @@ public Object aroundEncryptAnnotatedMethods(ProceedingJoinPoint proceedingJoinPo Object result = proceedingJoinPoint.proceed(arguments); - result = encryptResult(context, result, Arrays.asList(annotation.resultPathList())); + result = encryptResult(context, result, List.of(annotation.resultPathList())); return result; } @@ -96,7 +95,7 @@ private DecryptArgument decryptArgumentAnnotation(Annotation[] annotationList) { } private EncryptionContext createEncryptionContext(Signature signature, Object[] arguments) { - List argumentList = Arrays.asList(arguments); + List argumentList = List.of(arguments); String methodName = String.format(EncryptConstants.METHOD_NAME_FORMAT, signature.getDeclaringType().getName(), signature.getName()); String currentUsername = currentUsername(); diff --git a/nrich-encrypt/src/main/java/net/croz/nrich/encrypt/aspect/EncryptMethodInterceptor.java b/nrich-encrypt/src/main/java/net/croz/nrich/encrypt/aspect/EncryptMethodInterceptor.java index ac72b255a..dfdbb3a93 100644 --- a/nrich-encrypt/src/main/java/net/croz/nrich/encrypt/aspect/EncryptMethodInterceptor.java +++ b/nrich-encrypt/src/main/java/net/croz/nrich/encrypt/aspect/EncryptMethodInterceptor.java @@ -28,11 +28,9 @@ import org.aopalliance.intercept.MethodInvocation; import org.springframework.aop.ProxyMethodInvocation; -import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; @Slf4j @RequiredArgsConstructor @@ -46,13 +44,12 @@ public class EncryptMethodInterceptor extends BaseEncryptDataAdvice implements M @Override public Object invoke(MethodInvocation invocation) throws Throwable { - if (!(invocation instanceof ProxyMethodInvocation)) { + if (!(invocation instanceof ProxyMethodInvocation proxyMethodInvocation)) { log.debug("Found method: {} was not instance of ProxyMethodInvocation it will not be encrypted!!", methodName(invocation)); return invocation.proceed(); } - ProxyMethodInvocation proxyMethodInvocation = (ProxyMethodInvocation) invocation; String methodName = methodName(invocation); String anyMethodName = anyClassMethod(invocation); @@ -61,8 +58,8 @@ public Object invoke(MethodInvocation invocation) throws Throwable { } List foundConfigurationList = encryptionConfigurationList.stream() - .filter(configuration -> methodName.equals(configuration.getMethodToEncryptDecrypt()) || anyMethodName.equals(configuration.getMethodToEncryptDecrypt())) - .collect(Collectors.toList()); + .filter(configuration -> methodName.equals(configuration.methodToEncryptDecrypt()) || anyMethodName.equals(configuration.methodToEncryptDecrypt())) + .toList(); if (!foundConfigurationList.isEmpty()) { EncryptionConfiguration decryptArgumentsConfiguration = findEncryptionConfigurationForOperation(foundConfigurationList, EncryptionOperation.DECRYPT); @@ -75,7 +72,7 @@ public Object invoke(MethodInvocation invocation) throws Throwable { EncryptionContext context = createEncryptionContext(methodName, arguments); - decryptedArguments = decryptArguments(context, arguments, decryptArgumentsConfiguration.getPropertyToEncryptDecryptList()); + decryptedArguments = decryptArguments(context, arguments, decryptArgumentsConfiguration.propertyToEncryptDecryptList()); proxyMethodInvocation.setArguments(decryptedArguments); } @@ -85,7 +82,7 @@ public Object invoke(MethodInvocation invocation) throws Throwable { EncryptionContext context = createEncryptionContext(methodName, decryptedArguments == null ? arguments : decryptedArguments); - return encryptResult(context, proxyMethodInvocation.proceed(), encryptResultConfiguration.getPropertyToEncryptDecryptList()); + return encryptResult(context, proxyMethodInvocation.proceed(), encryptResultConfiguration.propertyToEncryptDecryptList()); } } @@ -107,13 +104,13 @@ private String anyClassMethod(MethodInvocation invocation) { private EncryptionConfiguration findEncryptionConfigurationForOperation(List encryptionConfigurationList, EncryptionOperation encryptionOperation) { return encryptionConfigurationList.stream() - .filter(configuration -> configuration.getEncryptionOperation() == encryptionOperation) + .filter(configuration -> configuration.encryptionOperation() == encryptionOperation) .findFirst() .orElse(null); } private EncryptionContext createEncryptionContext(String methodName, Object[] arguments) { - List argumentList = Arrays.asList(arguments); + List argumentList = List.of(arguments); String currentUsername = currentUsername(); return EncryptionContext.builder() diff --git a/nrich-encrypt/src/main/java/net/croz/nrich/encrypt/service/DefaultDataEncryptService.java b/nrich-encrypt/src/main/java/net/croz/nrich/encrypt/service/DefaultDataEncryptService.java index 29cbfe223..3307ef893 100644 --- a/nrich-encrypt/src/main/java/net/croz/nrich/encrypt/service/DefaultDataEncryptService.java +++ b/nrich-encrypt/src/main/java/net/croz/nrich/encrypt/service/DefaultDataEncryptService.java @@ -83,8 +83,8 @@ protected void executeEncryptionOperation(EncryptionContext encryptionContext, O protected void encryptDecryptNestedValue(EncryptionContext encryptionContext, Object objectContainingFieldsToEncryptOrDecrypt, String propertyName, EncryptionOperation operation) { if (objectContainingFieldsToEncryptOrDecrypt != null && propertyName != null) { - if (objectContainingFieldsToEncryptOrDecrypt instanceof Collection) { - ((Collection) objectContainingFieldsToEncryptOrDecrypt).forEach(value -> encryptDecryptValue(encryptionContext, value, propertyName, operation)); + if (objectContainingFieldsToEncryptOrDecrypt instanceof Collection collection) { + collection.forEach(value -> encryptDecryptValue(encryptionContext, value, propertyName, operation)); } else if (objectContainingFieldsToEncryptOrDecrypt instanceof Object[] objectArray) { Arrays.stream(objectArray).forEach(value -> encryptDecryptValue(encryptionContext, value, propertyName, operation)); @@ -134,10 +134,9 @@ else if (value instanceof String[] textToEncryptOrDecryptList) { return null; } - @SuppressWarnings("unchecked") protected Object getPropertyValueByPath(Object holder, String path) { - if (holder instanceof Map) { - return ((Map) holder).get(path); + if (holder instanceof Map map) { + return map.get(path); } try { diff --git a/nrich-encrypt/src/main/java/net/croz/nrich/encrypt/util/PointcutResolvingUtil.java b/nrich-encrypt/src/main/java/net/croz/nrich/encrypt/util/PointcutResolvingUtil.java index e0c6d5614..ec709c443 100644 --- a/nrich-encrypt/src/main/java/net/croz/nrich/encrypt/util/PointcutResolvingUtil.java +++ b/nrich-encrypt/src/main/java/net/croz/nrich/encrypt/util/PointcutResolvingUtil.java @@ -33,7 +33,7 @@ private PointcutResolvingUtil() { public static String resolvePointcutFromEncryptionConfigurationList(List encryptionConfigurationList) { return encryptionConfigurationList.stream() - .map(EncryptionConfiguration::getMethodToEncryptDecrypt) + .map(EncryptionConfiguration::methodToEncryptDecrypt) .map(method -> String.format(EXECUTION_METHOD_POINTCUT, method)) .collect(Collectors.joining(EXECUTION_METHOD_OR_SEPARATOR)); } diff --git a/nrich-encrypt/src/test/java/net/croz/nrich/encrypt/EncryptTestConfiguration.java b/nrich-encrypt/src/test/java/net/croz/nrich/encrypt/EncryptTestConfiguration.java index 2fb9d0e8d..902207802 100644 --- a/nrich-encrypt/src/test/java/net/croz/nrich/encrypt/EncryptTestConfiguration.java +++ b/nrich-encrypt/src/test/java/net/croz/nrich/encrypt/EncryptTestConfiguration.java @@ -40,8 +40,6 @@ import org.springframework.security.crypto.encrypt.Encryptors; import org.springframework.security.crypto.keygen.KeyGenerators; -import java.util.Arrays; -import java.util.Collections; import java.util.List; @EnableAspectJAutoProxy @@ -67,17 +65,10 @@ public EncryptDataAspect encryptDataAspect(DataEncryptionService dataEncryptionS @Bean public Advisor encryptorAdvisor(DataEncryptionService dataEncryptionService) { - List propertyList = Collections.singletonList("value"); + List propertyList = List.of("value"); String encryptMethodName = "net.croz.nrich.encrypt.aspect.stub.DefaultEncryptDataAspectTestService.dataToEncryptFromConfiguration"; - String decryptMethodName = "net.croz.nrich.encrypt.aspect.stub.DefaultEncryptDataAspectTestService.dataToDecryptFromConfiguration"; - String allInterceptorServiceMethods = "net.croz.nrich.encrypt.aspect.stub.DefaultEncryptionMethodInterceptorTestService.*"; - List encryptionConfigurationList = Arrays.asList( - new EncryptionConfiguration(encryptMethodName, propertyList, EncryptionOperation.ENCRYPT), - new EncryptionConfiguration(decryptMethodName, propertyList, EncryptionOperation.DECRYPT), - new EncryptionConfiguration(allInterceptorServiceMethods, propertyList, EncryptionOperation.ENCRYPT), - new EncryptionConfiguration(allInterceptorServiceMethods, propertyList, EncryptionOperation.DECRYPT) - ); - List ignoredMethodList = Collections.singletonList("net.croz.nrich.encrypt.aspect.stub.DefaultEncryptionMethodInterceptorTestService.ignoredMethod"); + List encryptionConfigurationList = createEncryptionConfiguration(encryptMethodName, propertyList); + List ignoredMethodList = List.of("net.croz.nrich.encrypt.aspect.stub.DefaultEncryptionMethodInterceptorTestService.ignoredMethod"); AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); @@ -95,4 +86,16 @@ public EncryptDataAspectTestService encryptDataAspectTestService() { public EncryptionMethodInterceptorTestService encryptionMethodInterceptorTestService() { return new DefaultEncryptionMethodInterceptorTestService(); } + + private List createEncryptionConfiguration(String encryptMethodName, List propertyList) { + String decryptMethodName = "net.croz.nrich.encrypt.aspect.stub.DefaultEncryptDataAspectTestService.dataToDecryptFromConfiguration"; + String allInterceptorServiceMethods = "net.croz.nrich.encrypt.aspect.stub.DefaultEncryptionMethodInterceptorTestService.*"; + + return List.of( + new EncryptionConfiguration(encryptMethodName, propertyList, EncryptionOperation.ENCRYPT), + new EncryptionConfiguration(decryptMethodName, propertyList, EncryptionOperation.DECRYPT), + new EncryptionConfiguration(allInterceptorServiceMethods, propertyList, EncryptionOperation.ENCRYPT), + new EncryptionConfiguration(allInterceptorServiceMethods, propertyList, EncryptionOperation.DECRYPT) + ); + } } diff --git a/nrich-encrypt/src/test/java/net/croz/nrich/encrypt/service/DefaultDataEncryptServiceTest.java b/nrich-encrypt/src/test/java/net/croz/nrich/encrypt/service/DefaultDataEncryptServiceTest.java index 5821060a4..52cbee3b4 100644 --- a/nrich-encrypt/src/test/java/net/croz/nrich/encrypt/service/DefaultDataEncryptServiceTest.java +++ b/nrich-encrypt/src/test/java/net/croz/nrich/encrypt/service/DefaultDataEncryptServiceTest.java @@ -28,7 +28,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; @@ -51,7 +50,7 @@ class DefaultDataEncryptServiceTest { @Test void shouldEncryptSimpleData() { // given - List propertyList = Collections.singletonList("propertyToEncryptDecrypt"); + List propertyList = List.of("propertyToEncryptDecrypt"); DataEncryptionServiceTestObject data = new DataEncryptionServiceTestObject(); data.setPropertyToEncryptDecrypt(TEXT_TO_ENCRYPT_DECRYPT); @@ -67,7 +66,7 @@ void shouldEncryptSimpleData() { @Test void shouldDecryptSimpleData() { // given - List propertyList = Collections.singletonList("propertyToEncryptDecrypt"); + List propertyList = List.of("propertyToEncryptDecrypt"); DataEncryptionServiceTestObject data = new DataEncryptionServiceTestObject(); data.setPropertyToEncryptDecrypt(TEXT_TO_ENCRYPT_DECRYPT); @@ -90,8 +89,8 @@ void shouldDecryptSimpleData() { @Test void shouldEncryptDecryptCollectionTextData() { // given - List propertyList = Collections.singletonList("listToEncrypt"); - List textList = Collections.singletonList("some text"); + List propertyList = List.of("listToEncrypt"); + List textList = List.of("some text"); DataEncryptionServiceTestObject data = new DataEncryptionServiceTestObject(); data.setListToEncrypt(textList); @@ -114,7 +113,7 @@ void shouldEncryptDecryptCollectionTextData() { @Test void shouldEncryptDecryptNestedTextData() { // given - List propertyList = Collections.singletonList("nestedTestObject.nestedFieldToEncrypt"); + List propertyList = List.of("nestedTestObject.nestedFieldToEncrypt"); String text = "some text"; DataEncryptionServiceTestObject data = new DataEncryptionServiceTestObject(); @@ -138,11 +137,11 @@ void shouldEncryptDecryptNestedTextData() { @Test void shouldEncryptDecryptNestedCollectionTextData() { // given - List propertyList = Collections.singletonList("nestedTestObjectList.nestedFieldToEncrypt"); + List propertyList = List.of("nestedTestObjectList.nestedFieldToEncrypt"); String text = "some text"; DataEncryptionServiceTestObject data = new DataEncryptionServiceTestObject(); - data.setNestedTestObjectList(Collections.singletonList(new DataEncryptionServiceNestedTestObject(text, null))); + data.setNestedTestObjectList(List.of(new DataEncryptionServiceNestedTestObject(text, null))); // when DataEncryptionServiceTestObject result = dataEncryptionService.encryptData(data, propertyList, EncryptionContext.builder().build()); @@ -162,7 +161,7 @@ void shouldEncryptDecryptNestedCollectionTextData() { @Test void shouldNotFailOnNullValues() { // given - List propertyList = Arrays.asList("propertyToEncryptDecrypt", "listToEncrypt", "nestedTestObject.nestedFieldToEncrypt", "nestedTestObjectList.nestedFieldToEncrypt"); + List propertyList = List.of("propertyToEncryptDecrypt", "listToEncrypt", "nestedTestObject.nestedFieldToEncrypt", "nestedTestObjectList.nestedFieldToEncrypt"); DataEncryptionServiceTestObject data = new DataEncryptionServiceTestObject(); // then @@ -176,7 +175,7 @@ void shouldNotFailOnNullValues() { @ParameterizedTest void shouldNotFailOnNestedNullOrInvalidValues() { // given - List propertyList = Collections.singletonList("nestedTestObject.parent.nestedFieldToEncrypt"); + List propertyList = List.of("nestedTestObject.parent.nestedFieldToEncrypt"); DataEncryptionServiceTestObject data = new DataEncryptionServiceTestObject(); // then @@ -189,7 +188,7 @@ void shouldNotFailOnNestedNullOrInvalidValues() { @Test void shouldNotFailOnNullValueWhenEncryptingData() { // given - List propertyList = Collections.singletonList("propertyToEncryptDecrypt"); + List propertyList = List.of("propertyToEncryptDecrypt"); DataEncryptionServiceTestObject data = null; // when @@ -202,7 +201,7 @@ void shouldNotFailOnNullValueWhenEncryptingData() { @Test void shouldNotFailOnNullValueWhenDecryptingData() { // given - List propertyList = Collections.singletonList("propertyToEncryptDecrypt"); + List propertyList = List.of("propertyToEncryptDecrypt"); DataEncryptionServiceTestObject data = null; // when @@ -216,7 +215,7 @@ void shouldNotFailOnNullValueWhenDecryptingData() { void shouldEncryptDecryptMapData() { // given String key = "mapKey"; - List propertyList = Collections.singletonList(key); + List propertyList = List.of(key); Map data = new HashMap<>(); data.put(key, TEXT_TO_ENCRYPT_DECRYPT); @@ -238,7 +237,7 @@ void shouldEncryptDecryptMapData() { void shouldEncryptDecryptNestedMapData() { // given String key = "mapKey"; - List propertyList = Collections.singletonList("mapKey.mapKey"); + List propertyList = List.of("mapKey.mapKey"); Map> data = new HashMap<>(); Map nestedData = new HashMap<>(); @@ -283,8 +282,8 @@ void shouldNotFailWhenEncryptingNestedNullData() { void shouldEncryptDecryptArrayData() { // given DataEncryptionServiceArrayTestObject testObject = new DataEncryptionServiceArrayTestObject(); - List propertyList = Arrays.asList("propertyEncryptDecrypt", "arrayEncrypt"); - DataEncryptionServiceArrayTestObject[] data = new DataEncryptionServiceArrayTestObject[] { testObject }; + List propertyList = List.of("propertyEncryptDecrypt", "arrayEncrypt"); + DataEncryptionServiceArrayTestObject[] data = { testObject }; testObject.setArrayEncrypt(new String[] { TEXT_TO_ENCRYPT_DECRYPT }); testObject.setPropertyEncryptDecrypt(TEXT_TO_ENCRYPT_DECRYPT); @@ -309,7 +308,7 @@ void shouldEncryptDecryptArrayData() { void shouldNotFailWithUnsupportedTypes() { // given int[] data = new int[] { 1 }; - List propertyList = Collections.singletonList("property"); + List propertyList = List.of("property"); // when Throwable thrown = catchThrowable(() -> dataEncryptionService.encryptData(data, propertyList, EncryptionContext.builder().build())); @@ -322,7 +321,7 @@ void shouldNotFailWithUnsupportedTypes() { void shouldEncryptDecryptStringCollection() { // given List propertyList = Collections.emptyList(); - List data = Collections.singletonList(TEXT_TO_ENCRYPT_DECRYPT); + List data = List.of(TEXT_TO_ENCRYPT_DECRYPT); // when List result = dataEncryptionService.encryptData(data, propertyList, EncryptionContext.builder().build()); @@ -341,7 +340,7 @@ void shouldEncryptDecryptStringCollection() { void shouldEncryptDecryptStringArray() { // given List propertyList = Collections.emptyList(); - String[] data = new String[] { TEXT_TO_ENCRYPT_DECRYPT }; + String[] data = { TEXT_TO_ENCRYPT_DECRYPT }; // when String[] result = dataEncryptionService.encryptData(data, propertyList, EncryptionContext.builder().build()); @@ -378,7 +377,7 @@ void shouldEncryptDecryptStringSet() { @Test void shouldNotFailForNonStringCollectionArray() { // given - Object[] data = new Object[] { "value", Integer.MAX_VALUE }; + Object[] data = { "value", Integer.MAX_VALUE }; // when Throwable thrown = catchThrowable(() -> dataEncryptionService.encryptData(data, Collections.emptyList(), EncryptionContext.builder().build())); diff --git a/nrich-encrypt/src/test/java/net/croz/nrich/encrypt/util/PointcutResolvingUtilTest.java b/nrich-encrypt/src/test/java/net/croz/nrich/encrypt/util/PointcutResolvingUtilTest.java index 735977c23..99600ad11 100644 --- a/nrich-encrypt/src/test/java/net/croz/nrich/encrypt/util/PointcutResolvingUtilTest.java +++ b/nrich-encrypt/src/test/java/net/croz/nrich/encrypt/util/PointcutResolvingUtilTest.java @@ -21,7 +21,6 @@ import net.croz.nrich.encrypt.api.model.EncryptionOperation; import org.junit.jupiter.api.Test; -import java.util.Collections; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @@ -32,8 +31,8 @@ class PointcutResolvingUtilTest { void shouldResolvePointcutFromEncryptionConfigurationList() { // given String method = "net.croz.nrich.encrypt.stub.ExampleService.exampleMethod"; - EncryptionConfiguration configuration = new EncryptionConfiguration(method, Collections.singletonList("id"), EncryptionOperation.ENCRYPT); - List encryptionConfigurationList = Collections.singletonList(configuration); + EncryptionConfiguration configuration = new EncryptionConfiguration(method, List.of("id"), EncryptionOperation.ENCRYPT); + List encryptionConfigurationList = List.of(configuration); // when String result = PointcutResolvingUtil.resolvePointcutFromEncryptionConfigurationList(encryptionConfigurationList); diff --git a/nrich-excel-api/src/main/java/net/croz/nrich/excel/api/model/ColumnDataFormat.java b/nrich-excel-api/src/main/java/net/croz/nrich/excel/api/model/ColumnDataFormat.java index 17bf979f1..684560295 100644 --- a/nrich-excel-api/src/main/java/net/croz/nrich/excel/api/model/ColumnDataFormat.java +++ b/nrich-excel-api/src/main/java/net/croz/nrich/excel/api/model/ColumnDataFormat.java @@ -17,24 +17,12 @@ package net.croz.nrich.excel.api.model; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - /** * Holds data format for excel column. Used when overriding default data format for specific column. + * + * @param columnIndex Column index. + * @param dataFormat Column data format (i.e dd.MM.yyyy, #,##0.00 etc.). */ -@RequiredArgsConstructor -@Getter -public class ColumnDataFormat { - - /** - * Column index. - */ - private final int columnIndex; - - /** - * Column data format (i.e dd.MM.yyyy, #,##0.00 etc.). - */ - private final String dataFormat; +public record ColumnDataFormat(int columnIndex, String dataFormat) { } diff --git a/nrich-excel-api/src/main/java/net/croz/nrich/excel/api/model/TemplateVariable.java b/nrich-excel-api/src/main/java/net/croz/nrich/excel/api/model/TemplateVariable.java index cfa9f3c58..72d789a12 100644 --- a/nrich-excel-api/src/main/java/net/croz/nrich/excel/api/model/TemplateVariable.java +++ b/nrich-excel-api/src/main/java/net/croz/nrich/excel/api/model/TemplateVariable.java @@ -17,25 +17,13 @@ package net.croz.nrich.excel.api.model; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - /** * Holder for variable that will be replaced in excel report template. * Variables are defined in template in following form
${variableName}
+ * + * @param name Name of template variable to replace. + * @param value Value of template variable that will replace name. */ -@RequiredArgsConstructor -@Getter -public class TemplateVariable { - - /** - * Name of template variable to replace. - */ - private final String name; - - /** - * Value of template variable that will replace name. - */ - private final String value; +public record TemplateVariable(String name, String value) { } diff --git a/nrich-excel-api/src/main/java/net/croz/nrich/excel/api/model/TypeDataFormat.java b/nrich-excel-api/src/main/java/net/croz/nrich/excel/api/model/TypeDataFormat.java index b2a8b7415..965a2ab35 100644 --- a/nrich-excel-api/src/main/java/net/croz/nrich/excel/api/model/TypeDataFormat.java +++ b/nrich-excel-api/src/main/java/net/croz/nrich/excel/api/model/TypeDataFormat.java @@ -17,24 +17,12 @@ package net.croz.nrich.excel.api.model; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - /** * Holds data format for specific type. + * + * @param type Type for which formatting is required (i.e. {@link java.util.Date}, {@link Float} etc.). + * @param dataFormat Type data format data format (i.e dd.MM.yyyy, #,##0.00 etc). */ -@RequiredArgsConstructor -@Getter -public class TypeDataFormat { - - /** - * Type for which formatting is required (i.e. {@link java.util.Date}, {@link Float} etc.). - */ - private final Class type; - - /** - * Type data format data format (i.e dd.MM.yyyy, #,##0.00 etc). - */ - private final String dataFormat; +public record TypeDataFormat(Class type, String dataFormat) { } diff --git a/nrich-excel-spring-boot-starter/src/main/java/net/croz/nrich/excel/starter/configuration/NrichExcelAutoConfiguration.java b/nrich-excel-spring-boot-starter/src/main/java/net/croz/nrich/excel/starter/configuration/NrichExcelAutoConfiguration.java index 699a8df72..2cc7709b5 100644 --- a/nrich-excel-spring-boot-starter/src/main/java/net/croz/nrich/excel/starter/configuration/NrichExcelAutoConfiguration.java +++ b/nrich-excel-spring-boot-starter/src/main/java/net/croz/nrich/excel/starter/configuration/NrichExcelAutoConfiguration.java @@ -50,8 +50,8 @@ public CellValueConverter defaultCellValueConverter(MessageSource messageSource) @Bean public ExcelReportGeneratorFactory excelReportGeneratorFactory(ResourceLoader resourceLoader, List cellValueConverterList, NrichExcelProperties excelProperties) { List typeDataFormatList = TypeDataFormatUtil.resolveTypeDataFormatList( - excelProperties.getDateFormat(), excelProperties.getDateTimeFormat(), excelProperties.getIntegerNumberFormat(), - excelProperties.getDecimalNumberFormat(), excelProperties.isWriteDateWithTime(), excelProperties.getTypeDataFormatList() + excelProperties.dateFormat(), excelProperties.dateTimeFormat(), excelProperties.integerNumberFormat(), + excelProperties.decimalNumberFormat(), excelProperties.writeDateWithTime(), excelProperties.typeDataFormatList() ); return new PoiExcelReportGeneratorFactory(resourceLoader, cellValueConverterList, typeDataFormatList); diff --git a/nrich-excel-spring-boot-starter/src/main/java/net/croz/nrich/excel/starter/properties/NrichExcelProperties.java b/nrich-excel-spring-boot-starter/src/main/java/net/croz/nrich/excel/starter/properties/NrichExcelProperties.java index 9ed0fc850..dfe57d6d4 100644 --- a/nrich-excel-spring-boot-starter/src/main/java/net/croz/nrich/excel/starter/properties/NrichExcelProperties.java +++ b/nrich-excel-spring-boot-starter/src/main/java/net/croz/nrich/excel/starter/properties/NrichExcelProperties.java @@ -17,62 +17,25 @@ package net.croz.nrich.excel.starter.properties; -import lombok.Getter; import net.croz.nrich.excel.api.model.TypeDataFormat; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.bind.DefaultValue; import java.util.List; -@Getter +/** + * @param dateFormat Date format used to set excel cell style for date values (i.e. {@link java.time.LocalDate}). + * @param dateTimeFormat Date time format used to set excel cell style for date time values (i.e. {@link java.time.LocalDateTime}). + * @param writeDateWithTime Whether dateFormat or dateTimeFormat should be used for date time values. + * @param integerNumberFormat Integer number format used to set excel cell style for integer numbers (short, integer, long, BigInteger). + * @param decimalNumberFormat Decimal number format used to set excel cell style for decimal numbers (float, double, BigDecimal). + * @param typeDataFormatList A list of formats that overrides default formats for classes. + * @param defaultConverterEnabled Whether default converter {@link net.croz.nrich.excel.converter.DefaultCellValueConverter} should be enabled. It handles conversion of objects to value + * accepted by excel generator implementation. + */ @ConfigurationProperties("nrich.excel") -public class NrichExcelProperties { - - /** - * Date format used to set excel cell style for date values (i.e. {@link java.time.LocalDate}). - */ - private final String dateFormat; - - /** - * Date time format used to set excel cell style for date time values (i.e. {@link java.time.LocalDateTime}). - */ - private final String dateTimeFormat; - - /** - * Whether dateFormat or dateTimeFormat should be used for date time values. - */ - private final boolean writeDateWithTime; - - /** - * Integer number format used to set excel cell style for integer numbers (short, integer, long, BigInteger). - */ - private final String integerNumberFormat; - - /** - * Decimal number format used to set excel cell style for decimal numbers (float, double, BigDecimal). - */ - private final String decimalNumberFormat; - - /** - * A list of formats that overrides default formats for classes. - */ - private final List typeDataFormatList; - - /** - * Whether default converter {@link net.croz.nrich.excel.converter.DefaultCellValueConverter} should be enabled. It handles conversion of objects to value - * accepted by excel generator implementation. - */ - private final boolean defaultConverterEnabled; +public record NrichExcelProperties(@DefaultValue("dd.MM.yyyy.") String dateFormat, @DefaultValue("dd.MM.yyyy. HH:mm") String dateTimeFormat, @DefaultValue("false") boolean writeDateWithTime, + @DefaultValue("#,##0") String integerNumberFormat, @DefaultValue("#,##0.00") String decimalNumberFormat, List typeDataFormatList, + @DefaultValue("true") boolean defaultConverterEnabled) { - public NrichExcelProperties(@DefaultValue("dd.MM.yyyy.") String dateFormat, @DefaultValue("dd.MM.yyyy. HH:mm") String dateTimeFormat, @DefaultValue("false") boolean writeDateWithTime, - @DefaultValue("#,##0") String integerNumberFormat, @DefaultValue("#,##0.00") String decimalNumberFormat, List typeDataFormatList, - @DefaultValue("true") boolean defaultConverterEnabled) { - this.dateFormat = dateFormat; - this.dateTimeFormat = dateTimeFormat; - this.writeDateWithTime = writeDateWithTime; - this.integerNumberFormat = integerNumberFormat; - this.decimalNumberFormat = decimalNumberFormat; - this.typeDataFormatList = typeDataFormatList; - this.defaultConverterEnabled = defaultConverterEnabled; - } } diff --git a/nrich-excel-spring-boot-starter/src/test/java/net/croz/nrich/excel/starter/configuration/NrichExcelAutoConfigurationTest.java b/nrich-excel-spring-boot-starter/src/test/java/net/croz/nrich/excel/starter/configuration/NrichExcelAutoConfigurationTest.java index 761d48af7..7e92e1af0 100644 --- a/nrich-excel-spring-boot-starter/src/test/java/net/croz/nrich/excel/starter/configuration/NrichExcelAutoConfigurationTest.java +++ b/nrich-excel-spring-boot-starter/src/test/java/net/croz/nrich/excel/starter/configuration/NrichExcelAutoConfigurationTest.java @@ -20,6 +20,7 @@ import net.croz.nrich.excel.api.converter.CellValueConverter; import net.croz.nrich.excel.api.generator.ExcelReportGeneratorFactory; import net.croz.nrich.excel.api.service.ExcelReportService; +import net.croz.nrich.excel.starter.properties.NrichExcelProperties; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; @@ -37,6 +38,7 @@ void shouldConfigureDefaultConfiguration() { assertThat(context).hasSingleBean(CellValueConverter.class); assertThat(context).hasSingleBean(ExcelReportGeneratorFactory.class); assertThat(context).hasSingleBean(ExcelReportService.class); + assertThat(context).hasSingleBean(NrichExcelProperties.class); }); } diff --git a/nrich-excel/src/main/java/net/croz/nrich/excel/converter/DefaultCellValueConverter.java b/nrich-excel/src/main/java/net/croz/nrich/excel/converter/DefaultCellValueConverter.java index 61a814d96..934228806 100644 --- a/nrich-excel/src/main/java/net/croz/nrich/excel/converter/DefaultCellValueConverter.java +++ b/nrich-excel/src/main/java/net/croz/nrich/excel/converter/DefaultCellValueConverter.java @@ -17,7 +17,6 @@ package net.croz.nrich.excel.converter; -import lombok.Getter; import lombok.RequiredArgsConstructor; import net.croz.nrich.excel.api.converter.CellValueConverter; import net.croz.nrich.excel.api.model.CellHolder; @@ -31,7 +30,6 @@ import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZonedDateTime; -import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.List; @@ -59,7 +57,7 @@ public boolean supports(CellHolder cell, Object value) { } private List initializeConverterList() { - return Arrays.asList( + return List.of( new ConverterHolder(Date.class, CellHolder::setCellValue), new ConverterHolder(Calendar.class, CellHolder::setCellValue), new ConverterHolder(Instant.class, (cell, value) -> cell.setCellValue(new Date(((Instant) value).toEpochMilli()))), @@ -83,7 +81,7 @@ private ConverterHolder findConverter(Object value) { } return converterHolderList.stream() - .filter(converterHolder -> converterHolder.getType().isAssignableFrom(value.getClass())) + .filter(converterHolder -> converterHolder.type().isAssignableFrom(value.getClass())) .findFirst() .orElse(null); } @@ -94,13 +92,7 @@ private String resolveEnumValue(Object value) { return messageSource.getMessage(messageCode, null, value.toString(), LocaleContextHolder.getLocale()); } - @RequiredArgsConstructor - @Getter - public static class ConverterHolder { - - private final Class type; - - private final BiConsumer setCellValueFunction; + public record ConverterHolder(Class type, BiConsumer setCellValueFunction) { } } diff --git a/nrich-excel/src/main/java/net/croz/nrich/excel/generator/PoiExcelReportGenerator.java b/nrich-excel/src/main/java/net/croz/nrich/excel/generator/PoiExcelReportGenerator.java index e4c0b68ce..d0bd84c66 100644 --- a/nrich-excel/src/main/java/net/croz/nrich/excel/generator/PoiExcelReportGenerator.java +++ b/nrich-excel/src/main/java/net/croz/nrich/excel/generator/PoiExcelReportGenerator.java @@ -122,8 +122,8 @@ private void processTemplateVariableMap(Sheet sheet, List temp if (matcher.find()) { String matchedExpression = matcher.group(1); String variableValue = templateVariableList.stream() - .filter(variable -> matchedExpression.equals(variable.getName())) - .map(TemplateVariable::getValue) + .filter(variable -> matchedExpression.equals(variable.name())) + .map(TemplateVariable::value) .findFirst() .orElse(""); @@ -168,7 +168,7 @@ private Map createStyleMap(List columnData } return columnDataFormatList.stream() - .collect(Collectors.toMap(ColumnDataFormat::getColumnIndex, entry -> createCellStyle(entry.getDataFormat()))); + .collect(Collectors.toMap(ColumnDataFormat::columnIndex, entry -> createCellStyle(entry.dataFormat()))); } private CellStyle createCellStyle(String dataFormat) { @@ -192,8 +192,8 @@ private SXSSFWorkbook initializeWorkBookWithTemplate(InputStream template, List< private Map, CellStyle> createDefaultStyleMap(List typeDataFormatList) { return typeDataFormatList.stream() - .filter(typeDataFormat -> typeDataFormat.getDataFormat() != null) - .collect(Collectors.toMap(TypeDataFormat::getType, value -> createCellStyle(value.getDataFormat()))); + .filter(typeDataFormat -> typeDataFormat.dataFormat() != null) + .collect(Collectors.toMap(TypeDataFormat::type, value -> createCellStyle(value.dataFormat()))); } private void autoSizeColumnsIfRequired() { diff --git a/nrich-excel/src/main/java/net/croz/nrich/excel/model/PoiCellHolder.java b/nrich-excel/src/main/java/net/croz/nrich/excel/model/PoiCellHolder.java index 5771010a9..34fedc179 100644 --- a/nrich-excel/src/main/java/net/croz/nrich/excel/model/PoiCellHolder.java +++ b/nrich-excel/src/main/java/net/croz/nrich/excel/model/PoiCellHolder.java @@ -17,7 +17,6 @@ package net.croz.nrich.excel.model; -import lombok.RequiredArgsConstructor; import net.croz.nrich.excel.api.model.CellHolder; import org.apache.poi.ss.usermodel.Cell; @@ -26,10 +25,7 @@ import java.util.Calendar; import java.util.Date; -@RequiredArgsConstructor -public class PoiCellHolder implements CellHolder { - - private final Cell cell; +public record PoiCellHolder(Cell cell) implements CellHolder { @Override public int getColumnIndex() { @@ -43,26 +39,26 @@ public int getRowIndex() { @Override public void setCellValue(Object value) { - if (value instanceof Boolean) { - cell.setCellValue((Boolean) value); + if (value instanceof Boolean booleanValue) { + cell.setCellValue(booleanValue); } - else if (value instanceof Number) { - cell.setCellValue(((Number) value).doubleValue()); + else if (value instanceof Number numberValue) { + cell.setCellValue(numberValue.doubleValue()); } - else if (value instanceof Date) { - cell.setCellValue((Date) value); + else if (value instanceof Date dateValue) { + cell.setCellValue(dateValue); } - else if (value instanceof Calendar) { - cell.setCellValue((Calendar) value); + else if (value instanceof Calendar calendarValue) { + cell.setCellValue(calendarValue); } - else if (value instanceof LocalDateTime) { - cell.setCellValue((LocalDateTime) value); + else if (value instanceof LocalDateTime localDateTimeValue) { + cell.setCellValue(localDateTimeValue); } - else if (value instanceof LocalDate) { - cell.setCellValue((LocalDate) value); + else if (value instanceof LocalDate localDateValue) { + cell.setCellValue(localDateValue); } - else if (value instanceof String) { - cell.setCellValue(value.toString()); + else if (value instanceof String stringValue) { + cell.setCellValue(stringValue); } else { throw new IllegalArgumentException("Set cell value called with unrecognized type!"); diff --git a/nrich-excel/src/main/java/net/croz/nrich/excel/util/TypeDataFormatUtil.java b/nrich-excel/src/main/java/net/croz/nrich/excel/util/TypeDataFormatUtil.java index add33bd72..4fd82a888 100644 --- a/nrich-excel/src/main/java/net/croz/nrich/excel/util/TypeDataFormatUtil.java +++ b/nrich-excel/src/main/java/net/croz/nrich/excel/util/TypeDataFormatUtil.java @@ -27,12 +27,10 @@ import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZonedDateTime; -import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; import java.util.stream.Stream; public final class TypeDataFormatUtil { @@ -47,7 +45,7 @@ public static List resolveTypeDataFormatList( List nonNullAdditionalDataFormatList = Optional.ofNullable(additionalTypeDataFormatList).orElse(Collections.emptyList()); - List typeDataFormatList = Arrays.asList( + List typeDataFormatList = List.of( new TypeDataFormat(Date.class, dateFormat), new TypeDataFormat(Instant.class, dateFormat), new TypeDataFormat(LocalDate.class, dateFormat), @@ -66,19 +64,19 @@ public static List resolveTypeDataFormatList( ); List allTypeDataFormatList = typeDataFormatList.stream() - .map(typeDataFormat -> Optional.ofNullable(findTypeDataFormat(nonNullAdditionalDataFormatList, typeDataFormat.getType())).orElse(typeDataFormat)) - .collect(Collectors.toList()); + .map(typeDataFormat -> Optional.ofNullable(findTypeDataFormat(nonNullAdditionalDataFormatList, typeDataFormat.type())).orElse(typeDataFormat)) + .toList(); List notAddedAdditionalTypeDataFormatList = nonNullAdditionalDataFormatList.stream() - .filter(typeDataFormat -> findTypeDataFormat(allTypeDataFormatList, typeDataFormat.getType()) == null) - .collect(Collectors.toList()); + .filter(typeDataFormat -> findTypeDataFormat(allTypeDataFormatList, typeDataFormat.type()) == null) + .toList(); - return Stream.concat(allTypeDataFormatList.stream(), notAddedAdditionalTypeDataFormatList.stream()).collect(Collectors.toList()); + return Stream.concat(allTypeDataFormatList.stream(), notAddedAdditionalTypeDataFormatList.stream()).toList(); } private static TypeDataFormat findTypeDataFormat(List typeDataFormatList, Class type) { return typeDataFormatList.stream() - .filter(typeDataFormat -> type.equals(typeDataFormat.getType())) + .filter(typeDataFormat -> type.equals(typeDataFormat.type())) .findFirst() .orElse(null); } diff --git a/nrich-excel/src/test/java/net/croz/nrich/excel/generator/PoiExcelReportGeneratorTest.java b/nrich-excel/src/test/java/net/croz/nrich/excel/generator/PoiExcelReportGeneratorTest.java index 4002c4911..ce5f780a2 100644 --- a/nrich-excel/src/test/java/net/croz/nrich/excel/generator/PoiExcelReportGeneratorTest.java +++ b/nrich-excel/src/test/java/net/croz/nrich/excel/generator/PoiExcelReportGeneratorTest.java @@ -38,8 +38,6 @@ import java.time.OffsetDateTime; import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; -import java.util.Arrays; -import java.util.Collections; import java.util.Date; import java.util.List; import java.util.TimeZone; @@ -68,11 +66,11 @@ void setup() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("messages"); - List cellValueConverterList = Collections.singletonList(new DefaultCellValueConverter(messageSource)); - InputStream template = this.getClass().getResourceAsStream("/excel/template.xlsx"); - List templateVariableList = Collections.singletonList(new TemplateVariable("templateVariable", "resolvedValue")); - List columnDataFormatList = Arrays.asList(new ColumnDataFormat(2, "dd-MM-yyyy"), new ColumnDataFormat(3, "dd-MM-yyyy HH:mm")); - List additionalFormatList = Collections.singletonList(new TypeDataFormat(Date.class, "dd-MM-yyyy")); + List cellValueConverterList = List.of(new DefaultCellValueConverter(messageSource)); + InputStream template = getClass().getResourceAsStream("/excel/template.xlsx"); + List templateVariableList = List.of(new TemplateVariable("templateVariable", "resolvedValue")); + List columnDataFormatList = List.of(new ColumnDataFormat(2, "dd-MM-yyyy"), new ColumnDataFormat(3, "dd-MM-yyyy HH:mm")); + List additionalFormatList = List.of(new TypeDataFormat(Date.class, "dd-MM-yyyy")); List typeDataFormatList = TypeDataFormatUtil.resolveTypeDataFormatList( "dd.MM.yyyy.", "dd.MM.yyyy. HH:mm", "#,##0", "#,##0.00", true, additionalFormatList ); @@ -88,12 +86,12 @@ void setup() { void shouldExportDataToExcel() { // given Instant now = Instant.now().truncatedTo(ChronoUnit.DAYS); - Object[] rowData = new Object[] { + Object[] rowData = { 1.1, "value", new Date(now.toEpochMilli()), ZonedDateTime.now().truncatedTo(ChronoUnit.DAYS), OffsetDateTime.now().truncatedTo(ChronoUnit.DAYS), now, now, 1, 1.5F, (short) 1, LocalDate.now(), LocalDateTime.now().truncatedTo(ChronoUnit.DAYS), BigDecimal.valueOf(1.5), 10L, TestEnum.FIRST, TestEnum.SECOND, null, "=123" }; // when resolving data from cells all dates are converted to instant, all decimal numbers are converted to double and all whole numbers are converted to integer - Object[] expectedRowData = new Object[] { 1.1, "value", now, now, now, now, now, 1, 1.5, 1, now, now, 1.5, 10, "First", "SECOND", null, "=123" }; + Object[] expectedRowData = { 1.1, "value", now, now, now, now, now, 1, 1.5, 1, now, now, 1.5, 10, "First", "SECOND", null, "=123" }; // when excelReportGenerator.writeRowData(rowData); @@ -113,7 +111,7 @@ void shouldExportDataToExcel() { @Test void shouldThrowExceptionWhenTryingToWriteToClosedGenerator() { // given - Object[] rowData = new Object[] { 1.0, "value", Instant.now().truncatedTo(ChronoUnit.DAYS), Instant.now().truncatedTo(ChronoUnit.DAYS) }; + Object[] rowData = { 1.0, "value", Instant.now().truncatedTo(ChronoUnit.DAYS), Instant.now().truncatedTo(ChronoUnit.DAYS) }; excelReportGenerator.writeRowData(rowData); excelReportGenerator.flush(); @@ -129,7 +127,7 @@ void shouldThrowExceptionWhenTryingToWriteToClosedGenerator() { void shouldSetDefaultFormatToColumnsWithoutDefinedFormat() { // given Instant now = Instant.now().truncatedTo(ChronoUnit.DAYS); - Object[] rowData = new Object[] { 1.1, 1, now, now, (short) 1, LocalDate.now(), LocalDateTime.now().truncatedTo(ChronoUnit.DAYS), BigDecimal.valueOf(1.5), 10L, new Date() }; + Object[] rowData = { 1.1, 1, now, now, (short) 1, LocalDate.now(), LocalDateTime.now().truncatedTo(ChronoUnit.DAYS), BigDecimal.valueOf(1.5), 10L, new Date() }; // when excelReportGenerator.writeRowData(rowData); diff --git a/nrich-excel/src/test/java/net/croz/nrich/excel/service/DefaultExcelReportServiceTest.java b/nrich-excel/src/test/java/net/croz/nrich/excel/service/DefaultExcelReportServiceTest.java index d9d7b1b19..f551f39d0 100644 --- a/nrich-excel/src/test/java/net/croz/nrich/excel/service/DefaultExcelReportServiceTest.java +++ b/nrich-excel/src/test/java/net/croz/nrich/excel/service/DefaultExcelReportServiceTest.java @@ -38,7 +38,7 @@ class DefaultExcelReportServiceTest { private static final int TEMPLATE_DATA_FIRST_ROW_INDEX = 3; - private static final Object[][] DEFAULT_ROW_DATA = new Object[][] { { 1.1, "value" } }; + private static final Object[][] DEFAULT_ROW_DATA = { { 1.1, "value" } }; @Autowired private DefaultExcelReportService excelReportService; diff --git a/nrich-excel/src/test/java/net/croz/nrich/excel/testutil/PoiDataResolverUtil.java b/nrich-excel/src/test/java/net/croz/nrich/excel/testutil/PoiDataResolverUtil.java index 1add3edf9..77c87fd03 100644 --- a/nrich-excel/src/test/java/net/croz/nrich/excel/testutil/PoiDataResolverUtil.java +++ b/nrich-excel/src/test/java/net/croz/nrich/excel/testutil/PoiDataResolverUtil.java @@ -39,16 +39,12 @@ public static Object getCellValue(Cell cell) { return null; } - switch (cell.getCellType()) { - case STRING: - return cell.getStringCellValue(); - case NUMERIC: - return DateUtil.isCellDateFormatted(cell) ? cell.getDateCellValue().toInstant() : asIntegerIfApplicable(cell.getNumericCellValue()); - case BOOLEAN: - return cell.getBooleanCellValue(); - default: - return null; - } + return switch (cell.getCellType()) { + case STRING -> cell.getStringCellValue(); + case NUMERIC -> DateUtil.isCellDateFormatted(cell) ? cell.getDateCellValue().toInstant() : asIntegerIfApplicable(cell.getNumericCellValue()); + case BOOLEAN -> cell.getBooleanCellValue(); + default -> null; + }; } public static List getRowCellValueList(Row row) { diff --git a/nrich-excel/src/test/java/net/croz/nrich/excel/util/TypeDataFormatUtilTest.java b/nrich-excel/src/test/java/net/croz/nrich/excel/util/TypeDataFormatUtilTest.java index 8a2cb66ae..58d57159c 100644 --- a/nrich-excel/src/test/java/net/croz/nrich/excel/util/TypeDataFormatUtilTest.java +++ b/nrich-excel/src/test/java/net/croz/nrich/excel/util/TypeDataFormatUtilTest.java @@ -28,7 +28,6 @@ import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZonedDateTime; -import java.util.Collections; import java.util.Date; import java.util.List; @@ -81,14 +80,14 @@ void shouldAllowForAdditionalFormatsToBeSpecified() { // given Class additionalClass = Object.class; String dataFormat = "dd/MM/yyyy"; - List overriddenFormatList = Collections.singletonList(new TypeDataFormat(additionalClass, dataFormat)); + List overriddenFormatList = List.of(new TypeDataFormat(additionalClass, dataFormat)); // when List formatList = TypeDataFormatUtil.resolveTypeDataFormatList("dd.MM.yyyy.", "dd.MM.yyyy. HH:mm", "#,##0", "#,##0.00", true, overriddenFormatList); - TypeDataFormat dateTypeDataFormat = formatList.stream().filter(typeDataFormat -> additionalClass.equals(typeDataFormat.getType())).findFirst().orElse(null); + TypeDataFormat dateTypeDataFormat = formatList.stream().filter(typeDataFormat -> additionalClass.equals(typeDataFormat.type())).findFirst().orElse(null); // then assertThat(dateTypeDataFormat).isNotNull(); - assertThat(dateTypeDataFormat.getDataFormat()).isEqualTo(dataFormat); + assertThat(dateTypeDataFormat.dataFormat()).isEqualTo(dataFormat); } } diff --git a/nrich-form-configuration-api/src/main/java/net/croz/nrich/formconfiguration/api/model/ConstrainedProperty.java b/nrich-form-configuration-api/src/main/java/net/croz/nrich/formconfiguration/api/model/ConstrainedProperty.java index 78a03cee2..99a266e57 100644 --- a/nrich-form-configuration-api/src/main/java/net/croz/nrich/formconfiguration/api/model/ConstrainedProperty.java +++ b/nrich-form-configuration-api/src/main/java/net/croz/nrich/formconfiguration/api/model/ConstrainedProperty.java @@ -21,7 +21,6 @@ import lombok.Getter; import jakarta.validation.metadata.ConstraintDescriptor; -import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @@ -73,7 +72,7 @@ public String getConstraintName() { * @return containing argument map */ public Map getConstraintArgumentMap() { - List ignoredKeyList = Arrays.asList("groups", "message", "payload"); + List ignoredKeyList = List.of("groups", "message", "payload"); return constraintDescriptor.getAttributes().entrySet().stream() .filter(entry -> !ignoredKeyList.contains(entry.getKey())) diff --git a/nrich-form-configuration-api/src/main/java/net/croz/nrich/formconfiguration/api/model/ConstrainedPropertyClientValidatorConfiguration.java b/nrich-form-configuration-api/src/main/java/net/croz/nrich/formconfiguration/api/model/ConstrainedPropertyClientValidatorConfiguration.java index 609442573..d84d73e2f 100644 --- a/nrich-form-configuration-api/src/main/java/net/croz/nrich/formconfiguration/api/model/ConstrainedPropertyClientValidatorConfiguration.java +++ b/nrich-form-configuration-api/src/main/java/net/croz/nrich/formconfiguration/api/model/ConstrainedPropertyClientValidatorConfiguration.java @@ -17,31 +17,15 @@ package net.croz.nrich.formconfiguration.api.model; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - import java.util.Map; /** * Client validation configuration for single constrained property. A class property with multiple constraints will be resolved to a list of ConstrainedPropertyClientValidatorConfiguration instances. + * + * @param name Constraint name (i.e. NotNull). + * @param argumentMap Constraint arguments as a map. + * @param errorMessage Error message that should be shown if validation fails. */ -@RequiredArgsConstructor -@Getter -public class ConstrainedPropertyClientValidatorConfiguration { - - /** - * Constraint name (i.e. NotNull). - */ - private final String name; - - /** - * Constraint arguments as a map. - */ - private final Map argumentMap; - - /** - * Error message that should be shown if validation fails. - */ - private final String errorMessage; +public record ConstrainedPropertyClientValidatorConfiguration(String name, Map argumentMap, String errorMessage) { } diff --git a/nrich-form-configuration-api/src/main/java/net/croz/nrich/formconfiguration/api/model/ConstrainedPropertyConfiguration.java b/nrich-form-configuration-api/src/main/java/net/croz/nrich/formconfiguration/api/model/ConstrainedPropertyConfiguration.java index 124049fc5..aca6c699c 100644 --- a/nrich-form-configuration-api/src/main/java/net/croz/nrich/formconfiguration/api/model/ConstrainedPropertyConfiguration.java +++ b/nrich-form-configuration-api/src/main/java/net/croz/nrich/formconfiguration/api/model/ConstrainedPropertyConfiguration.java @@ -17,36 +17,16 @@ package net.croz.nrich.formconfiguration.api.model; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - import java.util.List; /** * Contains all {@link ConstrainedPropertyClientValidatorConfiguration} instances for a single property with path. + * + * @param path Path to the property relative to a parent class that is mapped to form id. + * @param propertyType Type of constrained property. + * @param javascriptType Javascript type of constrained property. + * @param validatorList List of {@link ConstrainedPropertyClientValidatorConfiguration} instances that hold client side validation configuration. */ -@RequiredArgsConstructor -@Getter -public class ConstrainedPropertyConfiguration { - - /** - * Path to the property relative to a parent class that is mapped to form id. - */ - private final String path; - - /** - * Type of constrained property. - */ - private final Class propertyType; - - /** - * Javascript type of constrained property. - */ - private final String javascriptType; - - /** - * List of {@link ConstrainedPropertyClientValidatorConfiguration} instances that hold client side validation configuration. - */ - private final List validatorList; +public record ConstrainedPropertyConfiguration(String path, Class propertyType, String javascriptType, List validatorList) { } diff --git a/nrich-form-configuration-api/src/main/java/net/croz/nrich/formconfiguration/api/model/FormConfiguration.java b/nrich-form-configuration-api/src/main/java/net/croz/nrich/formconfiguration/api/model/FormConfiguration.java index 9dc51299d..12b36347d 100644 --- a/nrich-form-configuration-api/src/main/java/net/croz/nrich/formconfiguration/api/model/FormConfiguration.java +++ b/nrich-form-configuration-api/src/main/java/net/croz/nrich/formconfiguration/api/model/FormConfiguration.java @@ -17,27 +17,15 @@ package net.croz.nrich.formconfiguration.api.model; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - import java.util.List; /** * Hold configuration for specific form id. Form id is registered through
{@code Map> formIdConstraintHolderMap}
map and maps received * form id from client to a class that holds constrained properties. + * + * @param formId Registered form id for this form configuration. + * @param constrainedPropertyConfigurationList List of {@link ConstrainedPropertyConfiguration} instances holding property configuration for each property defined in the class that form id was mapped to. */ -@RequiredArgsConstructor -@Getter -public class FormConfiguration { - - /** - * Registered form id for this form configuration. - */ - private final String formId; - - /** - * List of {@link ConstrainedPropertyConfiguration} instances holding property configuration for each property defined in the class that form id was mapped to. - */ - private final List constrainedPropertyConfigurationList; +public record FormConfiguration(String formId, List constrainedPropertyConfigurationList) { } diff --git a/nrich-form-configuration-api/src/test/java/net/croz/nrich/formconfiguration/api/util/FormConfigurationMappingCustomizerUtilTest.java b/nrich-form-configuration-api/src/test/java/net/croz/nrich/formconfiguration/api/util/FormConfigurationMappingCustomizerUtilTest.java index 18349858c..1befb709f 100644 --- a/nrich-form-configuration-api/src/test/java/net/croz/nrich/formconfiguration/api/util/FormConfigurationMappingCustomizerUtilTest.java +++ b/nrich-form-configuration-api/src/test/java/net/croz/nrich/formconfiguration/api/util/FormConfigurationMappingCustomizerUtilTest.java @@ -22,6 +22,7 @@ import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; @@ -56,7 +57,7 @@ void shouldApplyFormConfigurationCustomizer() { FormConfigurationMappingCustomizer customizer = mapping -> mapping.put(key, value); // when - Map> result = FormConfigurationMappingCustomizerUtil.applyCustomizerList(formConfigurationMapping, Collections.singletonList(customizer)); + Map> result = FormConfigurationMappingCustomizerUtil.applyCustomizerList(formConfigurationMapping, List.of(customizer)); // then assertThat(result).containsEntry(key, value); diff --git a/nrich-form-configuration-spring-boot-starter/src/main/java/net/croz/nrich/formconfiguration/starter/configuration/NrichFormConfigurationAutoConfiguration.java b/nrich-form-configuration-spring-boot-starter/src/main/java/net/croz/nrich/formconfiguration/starter/configuration/NrichFormConfigurationAutoConfiguration.java index 54a27d846..ce43a94bc 100644 --- a/nrich-form-configuration-spring-boot-starter/src/main/java/net/croz/nrich/formconfiguration/starter/configuration/NrichFormConfigurationAutoConfiguration.java +++ b/nrich-form-configuration-spring-boot-starter/src/main/java/net/croz/nrich/formconfiguration/starter/configuration/NrichFormConfigurationAutoConfiguration.java @@ -29,10 +29,10 @@ import net.croz.nrich.formconfiguration.service.FieldErrorMessageResolverService; import net.croz.nrich.formconfiguration.service.MessageSourceFieldErrorMessageResolverService; import net.croz.nrich.formconfiguration.starter.properties.NrichFormConfigurationProperties; -import net.croz.nrich.javascript.converter.DefaultJavaToJavascriptTypeConverter; import net.croz.nrich.javascript.api.converter.JavaToJavascriptTypeConverter; -import net.croz.nrich.javascript.service.DefaultJavaToJavascriptTypeConversionService; import net.croz.nrich.javascript.api.service.JavaToJavascriptTypeConversionService; +import net.croz.nrich.javascript.converter.DefaultJavaToJavascriptTypeConverter; +import net.croz.nrich.javascript.service.DefaultJavaToJavascriptTypeConversionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; @@ -95,10 +95,10 @@ public FormConfigurationService formConfigurationService(@Lazy Validator validat @Autowired(required = false) List formConfigurationCustomizerList, JavaToJavascriptTypeConversionService formJavaToJavascriptTypeConversionService) { Map> formConfigurationMapping = FormConfigurationMappingCustomizerUtil.applyCustomizerList( - configurationProperties.getFormConfigurationMapping(), formConfigurationCustomizerList + configurationProperties.formConfigurationMapping(), formConfigurationCustomizerList ); - List packageList = configurationProperties.getFormValidationConfigurationClassesPackageList(); + List packageList = configurationProperties.formValidationConfigurationClassesPackageList(); if (!CollectionUtils.isEmpty(packageList)) { Map> classPathFormConfiguration = formConfigurationAnnotationResolvingService.resolveFormConfigurations(packageList); diff --git a/nrich-form-configuration-spring-boot-starter/src/main/java/net/croz/nrich/formconfiguration/starter/properties/NrichFormConfigurationProperties.java b/nrich-form-configuration-spring-boot-starter/src/main/java/net/croz/nrich/formconfiguration/starter/properties/NrichFormConfigurationProperties.java index 59fa202f5..fb74b9308 100644 --- a/nrich-form-configuration-spring-boot-starter/src/main/java/net/croz/nrich/formconfiguration/starter/properties/NrichFormConfigurationProperties.java +++ b/nrich-form-configuration-spring-boot-starter/src/main/java/net/croz/nrich/formconfiguration/starter/properties/NrichFormConfigurationProperties.java @@ -17,44 +17,22 @@ package net.croz.nrich.formconfiguration.starter.properties; -import lombok.Getter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.bind.DefaultValue; import java.util.List; import java.util.Map; -@Getter +/** + * @param defaultConverterEnabled Whether default converter service ({@link net.croz.nrich.formconfiguration.service.DefaultConstrainedPropertyValidatorConverterService}) + * for converting {@link net.croz.nrich.formconfiguration.api.model.ConstrainedProperty} instances + * to client {@link net.croz.nrich.formconfiguration.api.model.ConstrainedPropertyClientValidatorConfiguration} list is enabled. + * @param defaultJavaToJavascriptConverterEnabled Whether default Java to Javascript type converter ({@link net.croz.nrich.javascript.converter.DefaultJavaToJavascriptTypeConverter}) used for converting Java to Javascript types is enabled. + * @param formConfigurationMapping Mapping between a client side form identifier and class holding the constraints for the form (usually the class accepted as input on the server side). + * @param formValidationConfigurationClassesPackageList Optional package list to scan for {@link net.croz.nrich.formconfiguration.api.annotation.FormValidationConfiguration} annotated classes (if not set annotated classes won't be searched). + */ @ConfigurationProperties("nrich.form-configuration") -public class NrichFormConfigurationProperties { - - /** - * Whether default converter service ({@link net.croz.nrich.formconfiguration.service.DefaultConstrainedPropertyValidatorConverterService}) - * for converting {@link net.croz.nrich.formconfiguration.api.model.ConstrainedProperty} instances - * to client {@link net.croz.nrich.formconfiguration.api.model.ConstrainedPropertyClientValidatorConfiguration} list is enabled. - */ - private final boolean defaultConverterEnabled; - - /** - * Whether default Java to Javascript type converter ({@link net.croz.nrich.javascript.converter.DefaultJavaToJavascriptTypeConverter}) used for converting Java to Javascript types is enabled. - */ - private final boolean defaultJavaToJavascriptConverterEnabled; - - /** - * Mapping between a client side form identifier and class holding the constraints for the form (usually the class accepted as input on the server side). - */ - private final Map> formConfigurationMapping; - - /** - * Optional package list to scan for {@link net.croz.nrich.formconfiguration.api.annotation.FormValidationConfiguration} annotated classes (if not set annotated classes won't be searched). - */ - private final List formValidationConfigurationClassesPackageList; +public record NrichFormConfigurationProperties(@DefaultValue("true") boolean defaultConverterEnabled, @DefaultValue("true") boolean defaultJavaToJavascriptConverterEnabled, + Map> formConfigurationMapping, List formValidationConfigurationClassesPackageList) { - public NrichFormConfigurationProperties(@DefaultValue("true") boolean defaultConverterEnabled, @DefaultValue("true") boolean defaultJavaToJavascriptConverterEnabled, - Map> formConfigurationMapping, List formValidationConfigurationClassesPackageList) { - this.defaultConverterEnabled = defaultConverterEnabled; - this.defaultJavaToJavascriptConverterEnabled = defaultJavaToJavascriptConverterEnabled; - this.formConfigurationMapping = formConfigurationMapping; - this.formValidationConfigurationClassesPackageList = formValidationConfigurationClassesPackageList; - } } diff --git a/nrich-form-configuration-spring-boot-starter/src/test/java/net/croz/nrich/formconfiguration/starter/configuration/NrichFormConfigurationAutoConfigurationTest.java b/nrich-form-configuration-spring-boot-starter/src/test/java/net/croz/nrich/formconfiguration/starter/configuration/NrichFormConfigurationAutoConfigurationTest.java index 9ff632aef..45b02c773 100644 --- a/nrich-form-configuration-spring-boot-starter/src/test/java/net/croz/nrich/formconfiguration/starter/configuration/NrichFormConfigurationAutoConfigurationTest.java +++ b/nrich-form-configuration-spring-boot-starter/src/test/java/net/croz/nrich/formconfiguration/starter/configuration/NrichFormConfigurationAutoConfigurationTest.java @@ -52,6 +52,7 @@ void shouldConfigureDefaultConfiguration() { assertThat(context).hasSingleBean(FormConfigurationService.class); assertThat(context).hasSingleBean(FormConfigurationController.class); assertThat(context).hasSingleBean(JavaToJavascriptTypeConversionService.class); + assertThat(context).hasSingleBean(NrichFormConfigurationProperties.class); }); } @@ -87,11 +88,11 @@ void shouldRegisterFormConfigurationMapping() { String createKey = "create-form"; String updateKey = "update-form"; Class requestType = FormConfigurationTestRequest.class; - String[] propertyValues = new String[] { String.format(ENTRY_FORMAT, createKey, requestType.getName()), String.format(ENTRY_FORMAT, updateKey, requestType.getName()) }; + String[] propertyValues = { String.format(ENTRY_FORMAT, createKey, requestType.getName()), String.format(ENTRY_FORMAT, updateKey, requestType.getName()) }; contextRunner.withBean(LocalValidatorFactoryBean.class).withPropertyValues(propertyValues).run(context -> { // when - Map> formConfigurationMapping = context.getBean(NrichFormConfigurationProperties.class).getFormConfigurationMapping(); + Map> formConfigurationMapping = context.getBean(NrichFormConfigurationProperties.class).formConfigurationMapping(); // then assertThat(formConfigurationMapping).containsEntry(createKey, requestType).containsEntry(updateKey, requestType); @@ -103,12 +104,12 @@ void shouldAllowForCustomizationOfFormConfigurationMapping() { // given String createKey = "create-form-customized"; Class requestType = FormConfigurationTestRequest.class; - String[] propertyValues = new String[] { String.format(ENTRY_FORMAT, createKey, requestType.getName()) }; + String[] propertyValues = { String.format(ENTRY_FORMAT, createKey, requestType.getName()) }; Supplier supplier = () -> formConfigurationMapping -> formConfigurationMapping.put(createKey, requestType); contextRunner.withBean(LocalValidatorFactoryBean.class).withBean(FormConfigurationMappingCustomizer.class, supplier).withPropertyValues(propertyValues).run(context -> { // when - Map> formConfigurationMapping = context.getBean(NrichFormConfigurationProperties.class).getFormConfigurationMapping(); + Map> formConfigurationMapping = context.getBean(NrichFormConfigurationProperties.class).formConfigurationMapping(); // then assertThat(formConfigurationMapping).containsEntry(createKey, requestType); diff --git a/nrich-form-configuration/src/main/java/net/croz/nrich/formconfiguration/service/DefaultConstrainedPropertyValidatorConverterService.java b/nrich-form-configuration/src/main/java/net/croz/nrich/formconfiguration/service/DefaultConstrainedPropertyValidatorConverterService.java index d2107f1bf..ecf53105b 100644 --- a/nrich-form-configuration/src/main/java/net/croz/nrich/formconfiguration/service/DefaultConstrainedPropertyValidatorConverterService.java +++ b/nrich-form-configuration/src/main/java/net/croz/nrich/formconfiguration/service/DefaultConstrainedPropertyValidatorConverterService.java @@ -24,7 +24,6 @@ import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.core.annotation.Order; -import java.util.Collections; import java.util.List; @RequiredArgsConstructor @@ -40,7 +39,7 @@ public List convert(Constrained constrainedProperty.getConstraintName(), constrainedProperty.getConstraintArgumentMap(), message ); - return Collections.singletonList(validator); + return List.of(validator); } @Override diff --git a/nrich-form-configuration/src/main/java/net/croz/nrich/formconfiguration/service/DefaultFormConfigurationService.java b/nrich-form-configuration/src/main/java/net/croz/nrich/formconfiguration/service/DefaultFormConfigurationService.java index 6aa0f7ca0..f97943bdf 100644 --- a/nrich-form-configuration/src/main/java/net/croz/nrich/formconfiguration/service/DefaultFormConfigurationService.java +++ b/nrich-form-configuration/src/main/java/net/croz/nrich/formconfiguration/service/DefaultFormConfigurationService.java @@ -37,7 +37,6 @@ import java.util.Map; import java.util.Optional; import java.util.Set; -import java.util.stream.Collectors; @RequiredArgsConstructor public class DefaultFormConfigurationService implements FormConfigurationService { @@ -57,7 +56,7 @@ public class DefaultFormConfigurationService implements FormConfigurationService public List fetchFormConfigurationList() { return formIdConstraintHolderMap.keySet().stream() .map(this::resolveFormConfiguration) - .collect(Collectors.toList()); + .toList(); } @Cacheable(value = "nrich.formConfiguration.cache", key = "#formIdList.hashCode() + T(org.springframework.context.i18n.LocaleContextHolder).locale.toLanguageTag()") @@ -65,7 +64,7 @@ public List fetchFormConfigurationList() { public List fetchFormConfigurationList(List formIdList) { return formIdList.stream() .map(this::resolveFormConfiguration) - .collect(Collectors.toList()); + .toList(); } private FormConfiguration resolveFormConfiguration(String formId) { @@ -112,7 +111,7 @@ private List resolvePropertyVal return constraintDescriptorList.stream() .map(constraintDescriptor -> convertProperty(constraintDescriptor, parentType, propertyPath, propertyDescriptor)) .flatMap(List::stream) - .collect(Collectors.toList()); + .toList(); } private List convertProperty(ConstraintDescriptor constraintDescriptor, Class parentType, String propertyPath, diff --git a/nrich-form-configuration/src/main/java/net/croz/nrich/formconfiguration/service/MessageSourceFieldErrorMessageResolverService.java b/nrich-form-configuration/src/main/java/net/croz/nrich/formconfiguration/service/MessageSourceFieldErrorMessageResolverService.java index c27f5c175..b9eedb3fb 100644 --- a/nrich-form-configuration/src/main/java/net/croz/nrich/formconfiguration/service/MessageSourceFieldErrorMessageResolverService.java +++ b/nrich-form-configuration/src/main/java/net/croz/nrich/formconfiguration/service/MessageSourceFieldErrorMessageResolverService.java @@ -77,7 +77,7 @@ private Object[] convertArraysInArgumentList(Object[] argumentList) { } return Arrays.stream(argumentList) - .map(value -> value instanceof Object[] ? convertToString((Object[]) value) : value) + .map(value -> value instanceof Object[] objectArray ? convertToString(objectArray) : value) .toArray(); } diff --git a/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/FormConfigurationTestConfiguration.java b/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/FormConfigurationTestConfiguration.java index 7487a633e..b125c8dbe 100644 --- a/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/FormConfigurationTestConfiguration.java +++ b/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/FormConfigurationTestConfiguration.java @@ -28,16 +28,15 @@ import net.croz.nrich.formconfiguration.stub.FormConfigurationServiceNestedIgnoredTestRequest; import net.croz.nrich.formconfiguration.stub.FormConfigurationServiceNestedTestRequest; import net.croz.nrich.formconfiguration.stub.FormConfigurationServiceTestRequest; +import net.croz.nrich.javascript.api.service.JavaToJavascriptTypeConversionService; import net.croz.nrich.javascript.converter.DefaultJavaToJavascriptTypeConverter; import net.croz.nrich.javascript.service.DefaultJavaToJavascriptTypeConversionService; -import net.croz.nrich.javascript.api.service.JavaToJavascriptTypeConversionService; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; -import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -77,14 +76,14 @@ public FormConfigurationAnnotationResolvingService formConfigurationAnnotationRe @Bean public JavaToJavascriptTypeConversionService javaToJavascriptTypeConversionService() { - return new DefaultJavaToJavascriptTypeConversionService(Collections.singletonList(new DefaultJavaToJavascriptTypeConverter())); + return new DefaultJavaToJavascriptTypeConversionService(List.of(new DefaultJavaToJavascriptTypeConverter())); } @Bean public FormConfigurationService formConfigurationService(LocalValidatorFactoryBean validator, List constrainedPropertyValidatorConverterServiceList, FormConfigurationAnnotationResolvingService formConfigurationAnnotationResolvingService, JavaToJavascriptTypeConversionService javaToJavascriptTypeConversionService) { - Map> formIdConstraintHolderMap = new LinkedHashMap<>(formConfigurationAnnotationResolvingService.resolveFormConfigurations(Collections.singletonList("net.croz"))); + Map> formIdConstraintHolderMap = new LinkedHashMap<>(formConfigurationAnnotationResolvingService.resolveFormConfigurations(List.of("net.croz"))); formIdConstraintHolderMap.put(SIMPLE_FORM_CONFIGURATION_FORM_ID, FormConfigurationServiceTestRequest.class); formIdConstraintHolderMap.put(NESTED_FORM_CONFIGURATION_FORM_ID, FormConfigurationServiceNestedTestRequest.class); diff --git a/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/controller/FormConfigurationControllerTest.java b/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/controller/FormConfigurationControllerTest.java index 7c74ba36c..e35934639 100644 --- a/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/controller/FormConfigurationControllerTest.java +++ b/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/controller/FormConfigurationControllerTest.java @@ -34,7 +34,7 @@ import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import java.util.Collections; +import java.util.List; import static net.croz.nrich.formconfiguration.testutil.FormConfigurationGeneratingUtil.createFetchFormConfigurationRequest; import static net.croz.nrich.formconfiguration.testutil.FormConfigurationGeneratingUtil.createFormConfiguration; @@ -64,8 +64,8 @@ void shouldReturnFormConfiguration(String endpointPath, String uri) throws Excep FetchFormConfigurationRequest request = createFetchFormConfigurationRequest(); FormConfiguration formConfiguration = createFormConfiguration(); - doReturn(Collections.singletonList(formConfiguration)).when(formConfigurationService).fetchFormConfigurationList(request.getFormIdList()); - doReturn(Collections.singletonList(formConfiguration)).when(formConfigurationService).fetchFormConfigurationList(); + doReturn(List.of(formConfiguration)).when(formConfigurationService).fetchFormConfigurationList(request.getFormIdList()); + doReturn(List.of(formConfiguration)).when(formConfigurationService).fetchFormConfigurationList(); // when ResultActions result = mockMvc.perform(post(uri) @@ -75,6 +75,6 @@ void shouldReturnFormConfiguration(String endpointPath, String uri) throws Excep // then result.andExpect(status().isOk()) - .andExpect(jsonPath("$[*].formId").value(formConfiguration.getFormId())); + .andExpect(jsonPath("$[*].formId").value(formConfiguration.formId())); } } diff --git a/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/service/DefaultConstrainedPropertyValidatorConverterServiceTest.java b/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/service/DefaultConstrainedPropertyValidatorConverterServiceTest.java index 43cb4ed4f..885fd8f6c 100644 --- a/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/service/DefaultConstrainedPropertyValidatorConverterServiceTest.java +++ b/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/service/DefaultConstrainedPropertyValidatorConverterServiceTest.java @@ -53,9 +53,9 @@ void shouldConvertConstrainedPropertyToValidatorConfiguration() { // then assertThat(validatorConfiguration).isNotNull(); - assertThat(validatorConfiguration.getArgumentMap()).isEmpty(); - assertThat(validatorConfiguration.getName()).isEqualTo("NotNull"); - assertThat(validatorConfiguration.getErrorMessage()).isEqualTo("Really cannot be null"); + assertThat(validatorConfiguration.argumentMap()).isEmpty(); + assertThat(validatorConfiguration.name()).isEqualTo("NotNull"); + assertThat(validatorConfiguration.errorMessage()).isEqualTo("Really cannot be null"); } @Test diff --git a/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/service/DefaultFormConfigurationAnnotationResolvingServiceTest.java b/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/service/DefaultFormConfigurationAnnotationResolvingServiceTest.java index 8a382657b..dc0e73aac 100644 --- a/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/service/DefaultFormConfigurationAnnotationResolvingServiceTest.java +++ b/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/service/DefaultFormConfigurationAnnotationResolvingServiceTest.java @@ -20,7 +20,6 @@ import net.croz.nrich.formconfiguration.stub.FormConfigurationAnnotatedTestRequest; import org.junit.jupiter.api.Test; -import java.util.Collections; import java.util.List; import java.util.Map; @@ -43,7 +42,7 @@ void shouldNotFailOnNullPackageList() { @Test void shouldResolveAnnotatedFormConfigurationClasses() { // given - List packageList = Collections.singletonList("net.croz"); + List packageList = List.of("net.croz"); // when Map> result = defaultFormConfigurationAnnotationResolvingService.resolveFormConfigurations(packageList); diff --git a/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/service/DefaultFormConfigurationServiceTest.java b/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/service/DefaultFormConfigurationServiceTest.java index b837b2f9e..5041395d1 100644 --- a/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/service/DefaultFormConfigurationServiceTest.java +++ b/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/service/DefaultFormConfigurationServiceTest.java @@ -25,7 +25,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -import java.util.Collections; import java.util.Comparator; import java.util.List; @@ -55,7 +54,7 @@ void shouldFetchFormConfigurationList() { @Test void shouldThrowExceptionWhenNoFormConfigurationHasBeenDefinedForFormId() { // given - List formIdList = Collections.singletonList("invalidFormId"); + List formIdList = List.of("invalidFormId"); // when Throwable thrown = catchThrowable(() -> formConfigurationService.fetchFormConfigurationList(formIdList)); @@ -67,7 +66,7 @@ void shouldThrowExceptionWhenNoFormConfigurationHasBeenDefinedForFormId() { @Test void shouldFetchSimpleFormConfiguration() { // given - List formIdList = Collections.singletonList(FormConfigurationTestConfiguration.SIMPLE_FORM_CONFIGURATION_FORM_ID); + List formIdList = List.of(FormConfigurationTestConfiguration.SIMPLE_FORM_CONFIGURATION_FORM_ID); // when List resultList = formConfigurationService.fetchFormConfigurationList(formIdList); @@ -79,41 +78,41 @@ void shouldFetchSimpleFormConfiguration() { FormConfiguration formConfiguration = resultList.get(0); // then - assertThat(formConfiguration.getFormId()).isEqualTo(FormConfigurationTestConfiguration.SIMPLE_FORM_CONFIGURATION_FORM_ID); - assertThat(formConfiguration.getConstrainedPropertyConfigurationList()).hasSize(4); - assertThat(formConfiguration.getConstrainedPropertyConfigurationList()).extracting(ConstrainedPropertyConfiguration::getPath).containsExactlyInAnyOrder( + assertThat(formConfiguration.formId()).isEqualTo(FormConfigurationTestConfiguration.SIMPLE_FORM_CONFIGURATION_FORM_ID); + assertThat(formConfiguration.constrainedPropertyConfigurationList()).hasSize(4); + assertThat(formConfiguration.constrainedPropertyConfigurationList()).extracting(ConstrainedPropertyConfiguration::path).containsExactlyInAnyOrder( "name", "lastName", "timestamp", "value" ); - assertThat(formConfiguration.getConstrainedPropertyConfigurationList()).extracting(ConstrainedPropertyConfiguration::getJavascriptType).containsExactlyInAnyOrder( + assertThat(formConfiguration.constrainedPropertyConfigurationList()).extracting(ConstrainedPropertyConfiguration::javascriptType).containsExactlyInAnyOrder( "string", "string", "date", "number" ); // and when - ConstrainedPropertyConfiguration lastNameConstrainedPropertyConfiguration = formConfiguration.getConstrainedPropertyConfigurationList().stream() - .filter(constrainedPropertyConfiguration -> "lastName".equals(constrainedPropertyConfiguration.getPath())) + ConstrainedPropertyConfiguration lastNameConstrainedPropertyConfiguration = formConfiguration.constrainedPropertyConfigurationList().stream() + .filter(constrainedPropertyConfiguration -> "lastName".equals(constrainedPropertyConfiguration.path())) .findFirst() .orElseThrow(() -> new IllegalStateException("Last name not found")); - assertThat(lastNameConstrainedPropertyConfiguration.getValidatorList()).hasSize(1); - assertThat(lastNameConstrainedPropertyConfiguration.getPropertyType()).isEqualTo(String.class); + assertThat(lastNameConstrainedPropertyConfiguration.validatorList()).hasSize(1); + assertThat(lastNameConstrainedPropertyConfiguration.propertyType()).isEqualTo(String.class); - formConfiguration.getConstrainedPropertyConfigurationList().sort(Comparator.comparing(ConstrainedPropertyConfiguration::getPath)); + formConfiguration.constrainedPropertyConfigurationList().sort(Comparator.comparing(ConstrainedPropertyConfiguration::path)); // and when - ConstrainedPropertyClientValidatorConfiguration lastNameValidatorConfiguration = lastNameConstrainedPropertyConfiguration.getValidatorList().get(0); + ConstrainedPropertyClientValidatorConfiguration lastNameValidatorConfiguration = lastNameConstrainedPropertyConfiguration.validatorList().get(0); // then assertThat(lastNameValidatorConfiguration).isNotNull(); - assertThat(lastNameValidatorConfiguration.getName()).isEqualTo("Size"); - assertThat(lastNameValidatorConfiguration.getArgumentMap().values()).containsExactly(1, 5); - assertThat(lastNameValidatorConfiguration.getErrorMessage()).isEqualTo("Size must be between: 1 and 5"); + assertThat(lastNameValidatorConfiguration.name()).isEqualTo("Size"); + assertThat(lastNameValidatorConfiguration.argumentMap().values()).containsExactly(1, 5); + assertThat(lastNameValidatorConfiguration.errorMessage()).isEqualTo("Size must be between: 1 and 5"); } @Test void shouldFetchNestedFormConfiguration() { // given - List formIdList = Collections.singletonList(FormConfigurationTestConfiguration.NESTED_FORM_CONFIGURATION_FORM_ID); + List formIdList = List.of(FormConfigurationTestConfiguration.NESTED_FORM_CONFIGURATION_FORM_ID); // when List resultList = formConfigurationService.fetchFormConfigurationList(formIdList); @@ -125,31 +124,31 @@ void shouldFetchNestedFormConfiguration() { FormConfiguration formConfiguration = resultList.get(0); // then - assertThat(formConfiguration.getFormId()).isEqualTo(FormConfigurationTestConfiguration.NESTED_FORM_CONFIGURATION_FORM_ID); - assertThat(formConfiguration.getConstrainedPropertyConfigurationList()).hasSize(5); - assertThat(formConfiguration.getConstrainedPropertyConfigurationList()).extracting(ConstrainedPropertyConfiguration::getPath).containsExactlyInAnyOrder( + assertThat(formConfiguration.formId()).isEqualTo(FormConfigurationTestConfiguration.NESTED_FORM_CONFIGURATION_FORM_ID); + assertThat(formConfiguration.constrainedPropertyConfigurationList()).hasSize(5); + assertThat(formConfiguration.constrainedPropertyConfigurationList()).extracting(ConstrainedPropertyConfiguration::path).containsExactlyInAnyOrder( "name", "request.name", "request.lastName", "request.timestamp", "request.value" ); - formConfiguration.getConstrainedPropertyConfigurationList().sort(Comparator.comparing(ConstrainedPropertyConfiguration::getPath)); + formConfiguration.constrainedPropertyConfigurationList().sort(Comparator.comparing(ConstrainedPropertyConfiguration::path)); - assertThat(formConfiguration.getConstrainedPropertyConfigurationList().get(4).getValidatorList()).hasSize(1); + assertThat(formConfiguration.constrainedPropertyConfigurationList().get(4).validatorList()).hasSize(1); // and when - ConstrainedPropertyClientValidatorConfiguration valueValidatorConfiguration = formConfiguration.getConstrainedPropertyConfigurationList().get(4).getValidatorList().get(0); + ConstrainedPropertyClientValidatorConfiguration valueValidatorConfiguration = formConfiguration.constrainedPropertyConfigurationList().get(4).validatorList().get(0); // then assertThat(valueValidatorConfiguration).isNotNull(); - assertThat(valueValidatorConfiguration.getName()).isEqualTo("Min"); - assertThat(valueValidatorConfiguration.getArgumentMap().values()).containsExactly(10L); - assertThat(valueValidatorConfiguration.getErrorMessage()).isEqualTo("Minimum value is: 10"); + assertThat(valueValidatorConfiguration.name()).isEqualTo("Min"); + assertThat(valueValidatorConfiguration.argumentMap().values()).containsExactly(10L); + assertThat(valueValidatorConfiguration.errorMessage()).isEqualTo("Minimum value is: 10"); } @Test void shouldIgnoreNestedFieldConfigurationWhenFieldIsNotValidated() { // given - List formIdList = Collections.singletonList(FormConfigurationTestConfiguration.NESTED_FORM_NOT_VALIDATED_CONFIGURATION_FORM_ID); + List formIdList = List.of(FormConfigurationTestConfiguration.NESTED_FORM_NOT_VALIDATED_CONFIGURATION_FORM_ID); // when List resultList = formConfigurationService.fetchFormConfigurationList(formIdList); @@ -161,7 +160,7 @@ void shouldIgnoreNestedFieldConfigurationWhenFieldIsNotValidated() { FormConfiguration formConfiguration = resultList.get(0); // then - assertThat(formConfiguration.getFormId()).isEqualTo(FormConfigurationTestConfiguration.NESTED_FORM_NOT_VALIDATED_CONFIGURATION_FORM_ID); - assertThat(formConfiguration.getConstrainedPropertyConfigurationList()).isEmpty(); + assertThat(formConfiguration.formId()).isEqualTo(FormConfigurationTestConfiguration.NESTED_FORM_NOT_VALIDATED_CONFIGURATION_FORM_ID); + assertThat(formConfiguration.constrainedPropertyConfigurationList()).isEmpty(); } } diff --git a/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/service/MessageSourceFieldErrorMessageResolverServiceTest.java b/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/service/MessageSourceFieldErrorMessageResolverServiceTest.java index 82823f1d7..31cfb5ab3 100644 --- a/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/service/MessageSourceFieldErrorMessageResolverServiceTest.java +++ b/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/service/MessageSourceFieldErrorMessageResolverServiceTest.java @@ -26,7 +26,6 @@ import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import java.util.Collections; -import java.util.HashMap; import java.util.Locale; import java.util.Map; @@ -69,8 +68,7 @@ void shouldResolveValidationMessageInMediumFormatForConstrainedProperty() { @Test void shouldConvertArraysToStringWhenResolvingMessage() { // given - Map argumentMap = new HashMap<>(); - argumentMap.put("value", new String[] { "one", "two " }); + Map argumentMap = Map.of("value", new String[] { "one", "two " }); ConstrainedProperty constrainedProperty = createConstrainedProperty(MessageSourceFieldErrorMessageResolverServiceTestRequest.class, argumentMap); diff --git a/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/stub/FormConfigurationServiceTestSubclassRequest.java b/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/stub/FormConfigurationServiceTestSubclassRequest.java new file mode 100644 index 000000000..27b8b4058 --- /dev/null +++ b/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/stub/FormConfigurationServiceTestSubclassRequest.java @@ -0,0 +1,32 @@ +/* + * Copyright 2020-2023 CROZ d.o.o, the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package net.croz.nrich.formconfiguration.stub; + +import lombok.Getter; +import lombok.Setter; + +import jakarta.validation.constraints.Size; + +@Setter +@Getter +public class FormConfigurationServiceTestSubclassRequest extends FormConfigurationServiceTestRequest { + + @Size(min = 10, max = 100) + private String lastName; + +} diff --git a/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/testutil/FormConfigurationGeneratingUtil.java b/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/testutil/FormConfigurationGeneratingUtil.java index 51e2d2308..fa3165ba7 100644 --- a/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/testutil/FormConfigurationGeneratingUtil.java +++ b/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/testutil/FormConfigurationGeneratingUtil.java @@ -24,8 +24,8 @@ import jakarta.validation.constraints.NotNull; import jakarta.validation.metadata.ConstraintDescriptor; import java.lang.annotation.Annotation; -import java.util.Arrays; import java.util.Collections; +import java.util.List; import java.util.Map; import static org.mockito.Mockito.doReturn; @@ -67,7 +67,7 @@ public static ConstrainedProperty createConstrainedProperty(Class parentType, public static FetchFormConfigurationRequest createFetchFormConfigurationRequest() { FetchFormConfigurationRequest request = new FetchFormConfigurationRequest(); - request.setFormIdList(Arrays.asList("formId1", "formId2")); + request.setFormIdList(List.of("formId1", "formId2")); return request; } diff --git a/nrich-jackson-spring-boot-starter/src/main/java/net/croz/nrich/jackson/starter/configuration/NrichJacksonAutoConfiguration.java b/nrich-jackson-spring-boot-starter/src/main/java/net/croz/nrich/jackson/starter/configuration/NrichJacksonAutoConfiguration.java index f0f5cc16a..e96f9322c 100644 --- a/nrich-jackson-spring-boot-starter/src/main/java/net/croz/nrich/jackson/starter/configuration/NrichJacksonAutoConfiguration.java +++ b/nrich-jackson-spring-boot-starter/src/main/java/net/croz/nrich/jackson/starter/configuration/NrichJacksonAutoConfiguration.java @@ -45,7 +45,7 @@ public Module convertEmptyStringsToNullModule() { @Bean public Module classNameSerializerModule(NrichJacksonProperties nrichJacksonProperties) { return JacksonModuleUtil.classNameSerializerModule( - nrichJacksonProperties.isSerializeClassNameForEntityAnnotatedClasses(), nrichJacksonProperties.getAdditionalPackageListForClassNameSerialization() + nrichJacksonProperties.serializeClassNameForEntityAnnotatedClasses(), nrichJacksonProperties.additionalPackageListForClassNameSerialization() ); } } diff --git a/nrich-jackson-spring-boot-starter/src/main/java/net/croz/nrich/jackson/starter/properties/NrichJacksonProperties.java b/nrich-jackson-spring-boot-starter/src/main/java/net/croz/nrich/jackson/starter/properties/NrichJacksonProperties.java index 23be62c9c..160212fb6 100644 --- a/nrich-jackson-spring-boot-starter/src/main/java/net/croz/nrich/jackson/starter/properties/NrichJacksonProperties.java +++ b/nrich-jackson-spring-boot-starter/src/main/java/net/croz/nrich/jackson/starter/properties/NrichJacksonProperties.java @@ -17,41 +17,19 @@ package net.croz.nrich.jackson.starter.properties; -import lombok.Getter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.bind.DefaultValue; import java.util.List; -@Getter +/** + * @param convertEmptyStringsToNull Whether empty strings should be converted to null values. + * @param serializeClassName Whether class name should be serialized. + * @param serializeClassNameForEntityAnnotatedClasses Whether class name should be serialized for classes annotated with JPA Entity annotation. + * @param additionalPackageListForClassNameSerialization Package list for which class name should be also be serialized. + */ @ConfigurationProperties("nrich.jackson") -public class NrichJacksonProperties { - - /** - * Whether empty strings should be converted to null values. - */ - private final boolean convertEmptyStringsToNull; - - /** - * Whether class name should be serialized. - */ - private final boolean serializeClassName; - - /** - * Whether class name should be serialized for classes annotated with JPA Entity annotation. - */ - private final boolean serializeClassNameForEntityAnnotatedClasses; - - /** - * Package list for which class name should be also be serialized. - */ - private final List additionalPackageListForClassNameSerialization; +public record NrichJacksonProperties(@DefaultValue("true") boolean convertEmptyStringsToNull, @DefaultValue("true") boolean serializeClassName, + @DefaultValue("true") boolean serializeClassNameForEntityAnnotatedClasses, List additionalPackageListForClassNameSerialization) { - public NrichJacksonProperties(@DefaultValue("true") boolean convertEmptyStringsToNull, @DefaultValue("true") boolean serializeClassName, - @DefaultValue("true") boolean serializeClassNameForEntityAnnotatedClasses, List additionalPackageListForClassNameSerialization) { - this.convertEmptyStringsToNull = convertEmptyStringsToNull; - this.serializeClassName = serializeClassName; - this.serializeClassNameForEntityAnnotatedClasses = serializeClassNameForEntityAnnotatedClasses; - this.additionalPackageListForClassNameSerialization = additionalPackageListForClassNameSerialization; - } } diff --git a/nrich-jackson-spring-boot-starter/src/test/java/net/croz/nrich/jackson/starter/configuration/NrichJacksonAutoConfigurationTest.java b/nrich-jackson-spring-boot-starter/src/test/java/net/croz/nrich/jackson/starter/configuration/NrichJacksonAutoConfigurationTest.java index e326cc710..2417d3b84 100644 --- a/nrich-jackson-spring-boot-starter/src/test/java/net/croz/nrich/jackson/starter/configuration/NrichJacksonAutoConfigurationTest.java +++ b/nrich-jackson-spring-boot-starter/src/test/java/net/croz/nrich/jackson/starter/configuration/NrichJacksonAutoConfigurationTest.java @@ -23,6 +23,7 @@ import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; +import net.croz.nrich.jackson.starter.properties.NrichJacksonProperties; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; @@ -37,9 +38,10 @@ class NrichJacksonAutoConfigurationTest { @Test void shouldConfigureDefaultConfiguration() { // expect - contextRunner.run(context -> - assertThat(context).hasBean("convertEmptyStringsToNullModule") - ); + contextRunner.run(context -> { + assertThat(context).hasBean("convertEmptyStringsToNullModule"); + assertThat(context).hasSingleBean(NrichJacksonProperties.class); + }); } @Test diff --git a/nrich-jackson/src/test/java/net/croz/nrich/jackson/deserializer/ConvertEmptyStringToNullDeserializerTest.java b/nrich-jackson/src/test/java/net/croz/nrich/jackson/deserializer/ConvertEmptyStringToNullDeserializerTest.java index c515672b7..c0e9d7e1a 100644 --- a/nrich-jackson/src/test/java/net/croz/nrich/jackson/deserializer/ConvertEmptyStringToNullDeserializerTest.java +++ b/nrich-jackson/src/test/java/net/croz/nrich/jackson/deserializer/ConvertEmptyStringToNullDeserializerTest.java @@ -22,14 +22,13 @@ import net.croz.nrich.jackson.module.JacksonModuleUtil; import org.junit.jupiter.api.Test; -import java.util.HashMap; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; class ConvertEmptyStringToNullDeserializerTest { - private static final TypeReference> MAP_TYPE_REFERENCE = new TypeReference>() { + private static final TypeReference> MAP_TYPE_REFERENCE = new TypeReference<>() { }; private final ObjectMapper objectMapper = new ObjectMapper().registerModule(JacksonModuleUtil.convertEmptyStringToNullModule()); @@ -39,10 +38,7 @@ void shouldConvertEmptyStringsToNull() throws Exception { // given String emptyKey = "emptyKey"; String nonEmptyKey = "nonEmptyKey"; - Map testMap = new HashMap<>(); - - testMap.put(emptyKey, ""); - testMap.put(nonEmptyKey, "non empty"); + Map testMap = Map.of(emptyKey, "", nonEmptyKey, "non empty"); // when Map deserialized = objectMapper.readValue(objectMapper.writeValueAsString(testMap), MAP_TYPE_REFERENCE); diff --git a/nrich-jackson/src/test/java/net/croz/nrich/jackson/serializer/EntityClassSerializerModifierTest.java b/nrich-jackson/src/test/java/net/croz/nrich/jackson/serializer/EntityClassSerializerModifierTest.java index 1476260db..abd3cc56a 100644 --- a/nrich-jackson/src/test/java/net/croz/nrich/jackson/serializer/EntityClassSerializerModifierTest.java +++ b/nrich-jackson/src/test/java/net/croz/nrich/jackson/serializer/EntityClassSerializerModifierTest.java @@ -28,7 +28,6 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Stream; @@ -38,7 +37,7 @@ class EntityClassSerializerModifierTest { - private static final TypeReference> MAP_TYPE_REFERENCE = new TypeReference>() { + private static final TypeReference> MAP_TYPE_REFERENCE = new TypeReference<>() { }; @Test @@ -71,7 +70,7 @@ void shouldNotSerializeWhenSerializationIsNotEnabled(boolean serializeEntityAnno private static Stream shouldNotSerializeWhenSerializationIsNotEnabledMethodSource() { return Stream.of( arguments(false, null, new EntityClassSerializerModifierTestEntity()), - arguments(false, Collections.singletonList("java.lang"), new EntityClassSerializerModifierTestEntity()), + arguments(false, List.of("java.lang"), new EntityClassSerializerModifierTestEntity()), arguments(true, null, new EntityClassSerializerModifierTestEntityWithoutAnnotation()) ); } @@ -80,7 +79,7 @@ private static Stream shouldNotSerializeWhenSerializationIsNotEnabled void shouldSerializeClassNameForPackage() throws Exception { // given ObjectMapper objectMapper = new ObjectMapper(); - Module module = JacksonModuleUtil.classNameSerializerModule(false, Collections.singletonList(EntityClassSerializerModifierTestEntity.class.getPackage().getName())); + Module module = JacksonModuleUtil.classNameSerializerModule(false, List.of(EntityClassSerializerModifierTestEntity.class.getPackage().getName())); objectMapper.registerModule(module); diff --git a/nrich-jackson/src/test/java/net/croz/nrich/jackson/serializer/stub/EntityClassSerializerModifierTestEntity.java b/nrich-jackson/src/test/java/net/croz/nrich/jackson/serializer/stub/EntityClassSerializerModifierTestEntity.java index 8ca2106fb..20c58ecd8 100644 --- a/nrich-jackson/src/test/java/net/croz/nrich/jackson/serializer/stub/EntityClassSerializerModifierTestEntity.java +++ b/nrich-jackson/src/test/java/net/croz/nrich/jackson/serializer/stub/EntityClassSerializerModifierTestEntity.java @@ -21,12 +21,16 @@ import lombok.Setter; import jakarta.persistence.Entity; +import jakarta.persistence.Id; @Setter @Getter @Entity public class EntityClassSerializerModifierTestEntity { + @Id + private Long id; + private String name; } diff --git a/nrich-jackson/src/test/java/net/croz/nrich/jackson/util/JacksonModuleUtilTest.java b/nrich-jackson/src/test/java/net/croz/nrich/jackson/util/JacksonModuleUtilTest.java index ba9b007c6..958c83a59 100644 --- a/nrich-jackson/src/test/java/net/croz/nrich/jackson/util/JacksonModuleUtilTest.java +++ b/nrich-jackson/src/test/java/net/croz/nrich/jackson/util/JacksonModuleUtilTest.java @@ -22,7 +22,7 @@ import net.croz.nrich.jackson.module.JacksonModuleUtil; import org.junit.jupiter.api.Test; -import java.util.Collections; +import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @@ -41,7 +41,7 @@ void shouldCreateConvertEmptyStringToNullModule() { @Test void shouldCreateClassNameSerializerModule() { // when - Module module = JacksonModuleUtil.classNameSerializerModule(true, Collections.singletonList("net.croz.nrich")); + Module module = JacksonModuleUtil.classNameSerializerModule(true, List.of("net.croz.nrich")); // then assertThat(module.getModuleName()).isEqualTo(JacksonModuleUtil.CLASS_NAME_SERIALIZER_MODULE); diff --git a/nrich-javascript/src/main/java/net/croz/nrich/javascript/converter/DefaultJavaToJavascriptTypeConverter.java b/nrich-javascript/src/main/java/net/croz/nrich/javascript/converter/DefaultJavaToJavascriptTypeConverter.java index c6c26c511..2fdc7c760 100644 --- a/nrich-javascript/src/main/java/net/croz/nrich/javascript/converter/DefaultJavaToJavascriptTypeConverter.java +++ b/nrich-javascript/src/main/java/net/croz/nrich/javascript/converter/DefaultJavaToJavascriptTypeConverter.java @@ -25,26 +25,23 @@ import java.util.Calendar; import java.util.Collection; import java.util.Date; -import java.util.HashMap; import java.util.Locale; import java.util.Map; @Order public class DefaultJavaToJavascriptTypeConverter implements JavaToJavascriptTypeConverter { - private static final Map, JavascriptType> CLASS_JAVASCRIPT_TYPE_MAP = new HashMap<>(); - - static { - CLASS_JAVASCRIPT_TYPE_MAP.put(Boolean.class, JavascriptType.BOOLEAN); - CLASS_JAVASCRIPT_TYPE_MAP.put(String.class, JavascriptType.STRING); - CLASS_JAVASCRIPT_TYPE_MAP.put(Character.class, JavascriptType.STRING); - CLASS_JAVASCRIPT_TYPE_MAP.put(Calendar.class, JavascriptType.DATE); - CLASS_JAVASCRIPT_TYPE_MAP.put(Date.class, JavascriptType.DATE); - CLASS_JAVASCRIPT_TYPE_MAP.put(Temporal.class, JavascriptType.DATE); - CLASS_JAVASCRIPT_TYPE_MAP.put(Number.class, JavascriptType.NUMBER); - CLASS_JAVASCRIPT_TYPE_MAP.put(Enum.class, JavascriptType.STRING); - CLASS_JAVASCRIPT_TYPE_MAP.put(Collection.class, JavascriptType.ARRAY); - } + private static final Map, JavascriptType> CLASS_JAVASCRIPT_TYPE_MAP = Map.of( + Boolean.class, JavascriptType.BOOLEAN, + String.class, JavascriptType.STRING, + Character.class, JavascriptType.STRING, + Calendar.class, JavascriptType.DATE, + Date.class, JavascriptType.DATE, + Temporal.class, JavascriptType.DATE, + Number.class, JavascriptType.NUMBER, + Enum.class, JavascriptType.STRING, + Collection.class, JavascriptType.ARRAY + ); @Override public boolean supports(Class type) { diff --git a/nrich-javascript/src/test/java/net/croz/nrich/javascript/service/DefaultJavaToJavascriptTypeConversionServiceTest.java b/nrich-javascript/src/test/java/net/croz/nrich/javascript/service/DefaultJavaToJavascriptTypeConversionServiceTest.java index 4c583cfd2..e13c4a692 100644 --- a/nrich-javascript/src/test/java/net/croz/nrich/javascript/service/DefaultJavaToJavascriptTypeConversionServiceTest.java +++ b/nrich-javascript/src/test/java/net/croz/nrich/javascript/service/DefaultJavaToJavascriptTypeConversionServiceTest.java @@ -20,7 +20,7 @@ import net.croz.nrich.javascript.api.converter.JavaToJavascriptTypeConverter; import org.junit.jupiter.api.Test; -import java.util.Collections; +import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doReturn; @@ -49,7 +49,7 @@ void shouldConvertUsingRegisteredConverter() { doReturn(true).when(converter).supports(type); doReturn("number").when(converter).convert(type); - DefaultJavaToJavascriptTypeConversionService service = new DefaultJavaToJavascriptTypeConversionService(Collections.singletonList(converter)); + DefaultJavaToJavascriptTypeConversionService service = new DefaultJavaToJavascriptTypeConversionService(List.of(converter)); // when String result = service.convert(type); diff --git a/nrich-logging/src/test/java/net/croz/nrich/logging/testutil/Slf4jLoggingServiceGeneratingUtil.java b/nrich-logging/src/test/java/net/croz/nrich/logging/testutil/Slf4jLoggingServiceGeneratingUtil.java index bc559a994..51abf0aa3 100644 --- a/nrich-logging/src/test/java/net/croz/nrich/logging/testutil/Slf4jLoggingServiceGeneratingUtil.java +++ b/nrich-logging/src/test/java/net/croz/nrich/logging/testutil/Slf4jLoggingServiceGeneratingUtil.java @@ -25,7 +25,6 @@ import org.slf4j.LoggerFactory; import org.springframework.context.MessageSourceResolvable; -import java.util.HashMap; import java.util.Map; import java.util.Objects; @@ -53,11 +52,7 @@ public static Answer returnsFirstMessageCode() { } public static Map createAuxiliaryExceptionData() { - Map auxiliaryExceptionData = new HashMap<>(); - - auxiliaryExceptionData.put("key", "value"); - - return auxiliaryExceptionData; + return Map.of("key", "value"); } } diff --git a/nrich-notification-api/src/main/java/net/croz/nrich/notification/api/model/ValidationError.java b/nrich-notification-api/src/main/java/net/croz/nrich/notification/api/model/ValidationError.java index fb7ded9f7..9ecd31bf7 100644 --- a/nrich-notification-api/src/main/java/net/croz/nrich/notification/api/model/ValidationError.java +++ b/nrich-notification-api/src/main/java/net/croz/nrich/notification/api/model/ValidationError.java @@ -17,28 +17,16 @@ package net.croz.nrich.notification.api.model; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - import java.util.List; /** * Represents validation error on a object. Returned with {@link ValidationFailureNotification} instance. + * + * @param objectName If validation error occurred on a property then name of a property otherwise
CONTAINING_OBJECT
. + * @param errorMessageList List of validation failed messages. */ -@RequiredArgsConstructor -@Getter -public class ValidationError { +public record ValidationError(String objectName, List errorMessageList) { public static final String CONTAINING_OBJECT_NAME = "CONTAINING_OBJECT"; - /** - * If validation error occurred on a property then name of a property otherwise
CONTAINING_OBJECT
. - */ - private final String objectName; - - /** - * List of validation failed messages. - */ - private final List errorMessageList; - } diff --git a/nrich-notification-spring-boot-starter/src/main/java/net/croz/nrich/notification/starter/configuration/NrichNotificationAutoConfiguration.java b/nrich-notification-spring-boot-starter/src/main/java/net/croz/nrich/notification/starter/configuration/NrichNotificationAutoConfiguration.java index a4d555e60..e38b47513 100644 --- a/nrich-notification-spring-boot-starter/src/main/java/net/croz/nrich/notification/starter/configuration/NrichNotificationAutoConfiguration.java +++ b/nrich-notification-spring-boot-starter/src/main/java/net/croz/nrich/notification/starter/configuration/NrichNotificationAutoConfiguration.java @@ -18,10 +18,10 @@ package net.croz.nrich.notification.starter.configuration; import lombok.RequiredArgsConstructor; +import net.croz.nrich.notification.api.service.BaseNotificationResponseService; import net.croz.nrich.notification.api.service.ConstraintConversionService; import net.croz.nrich.notification.api.service.NotificationMessageResolverService; import net.croz.nrich.notification.api.service.NotificationResolverService; -import net.croz.nrich.notification.api.service.BaseNotificationResponseService; import net.croz.nrich.notification.api.service.NotificationResponseService; import net.croz.nrich.notification.service.DefaultConstraintConversionService; import net.croz.nrich.notification.service.DefaultNotificationResolverService; @@ -79,8 +79,8 @@ public static class NotificationMessageSourceRegistrar implements InitializingBe @Override public void afterPropertiesSet() { - if (messageSource instanceof AbstractResourceBasedMessageSource) { - ((AbstractResourceBasedMessageSource) messageSource).addBasenames(NOTIFICATION_MESSAGES_NAME); + if (messageSource instanceof AbstractResourceBasedMessageSource resourceBasedMessageSource) { + resourceBasedMessageSource.addBasenames(NOTIFICATION_MESSAGES_NAME); } } } diff --git a/nrich-notification/src/main/java/net/croz/nrich/notification/service/DefaultNotificationResolverService.java b/nrich-notification/src/main/java/net/croz/nrich/notification/service/DefaultNotificationResolverService.java index f48f15479..57620968e 100644 --- a/nrich-notification/src/main/java/net/croz/nrich/notification/service/DefaultNotificationResolverService.java +++ b/nrich-notification/src/main/java/net/croz/nrich/notification/service/DefaultNotificationResolverService.java @@ -36,13 +36,11 @@ import jakarta.validation.ConstraintViolationException; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.stream.Collectors; import java.util.stream.Stream; @RequiredArgsConstructor @@ -71,10 +69,10 @@ public ValidationFailureNotification createNotificationForValidationFailure(Erro List validationErrorList = convertValidationErrorsToMessageList(errors, validationFailedOwningType); List additionalNotificationDataMessageList = resolveMessageListFromNotificationData(additionalNotificationData.getMessageListDataMap()); List validationMessageList = validationErrorList.stream() - .flatMap(value -> value.getErrorMessageList().stream()) - .collect(Collectors.toList()); + .flatMap(value -> value.errorMessageList().stream()) + .toList(); - List messageList = Stream.concat(additionalNotificationDataMessageList.stream(), validationMessageList.stream()).collect(Collectors.toList()); + List messageList = Stream.concat(additionalNotificationDataMessageList.stream(), validationMessageList.stream()).toList(); return new ValidationFailureNotification(title, content, messageList, severity, additionalNotificationData.getUxNotificationOptions(), validationErrorList); } @@ -132,7 +130,7 @@ private List convertValidationErrorsToMessageList(Errors errors return resultMap.entrySet().stream() .map(value -> new ValidationError(value.getKey(), value.getValue())) - .collect(Collectors.toList()); + .toList(); } private List resolveMessageListFromNotificationData(Map additionalNotificationData) { @@ -143,11 +141,11 @@ private List resolveMessageListFromNotificationData(Map addit return additionalNotificationData.entrySet().stream() .map(this::resolveMessageForAdditionalData) .filter(message -> !NotificationConstants.UNDEFINED_MESSAGE_VALUE.equals(message)) - .collect(Collectors.toList()); + .toList(); } private String constraintFieldNameOrDefault(ObjectError objectError) { - return objectError instanceof FieldError ? ((FieldError) objectError).getField() : ValidationError.CONTAINING_OBJECT_NAME; + return objectError instanceof FieldError fieldError ? fieldError.getField() : ValidationError.CONTAINING_OBJECT_NAME; } private String resolveMessageForAdditionalData(Map.Entry additionalDataEntry) { @@ -190,6 +188,6 @@ private List toList(T... codeList) { return Collections.emptyList(); } - return Arrays.asList(codeList); + return List.of(codeList); } } diff --git a/nrich-notification/src/main/java/net/croz/nrich/notification/service/MessageSourceNotificationMessageResolverService.java b/nrich-notification/src/main/java/net/croz/nrich/notification/service/MessageSourceNotificationMessageResolverService.java index 9a1d165c1..793920628 100644 --- a/nrich-notification/src/main/java/net/croz/nrich/notification/service/MessageSourceNotificationMessageResolverService.java +++ b/nrich-notification/src/main/java/net/croz/nrich/notification/service/MessageSourceNotificationMessageResolverService.java @@ -32,7 +32,6 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; -import java.util.stream.Collectors; @RequiredArgsConstructor public class MessageSourceNotificationMessageResolverService implements NotificationMessageResolverService { @@ -53,7 +52,7 @@ public String resolveMessage(List messageCodeList, List argument @Override public String resolveMessageForObjectError(Class validationFailedOwningType, ObjectError objectError) { String constraintName = objectError.getCode(); - String fieldName = objectError instanceof FieldError ? ((FieldError) objectError).getField() : null; + String fieldName = objectError instanceof FieldError fieldError ? fieldError.getField() : null; String name = validationFailedOwningType == null ? NotificationConstants.EMPTY_NAME : StringUtils.uncapitalize(validationFailedOwningType.getName()); String shortName = validationFailedOwningType == null ? NotificationConstants.EMPTY_NAME : StringUtils.uncapitalize(validationFailedOwningType.getSimpleName()); @@ -101,8 +100,8 @@ private List argumentsWithoutMessageCodeResolvable(Object[] arguments) { } return Arrays.stream(filteredArguments) - .map(value -> value instanceof Object[] ? convertToString((Object[]) value) : value) - .collect(Collectors.toList()); + .map(value -> value instanceof Object[] objectArray ? convertToString(objectArray) : value) + .toList(); } private String convertToString(Object[] value) { diff --git a/nrich-notification/src/test/java/net/croz/nrich/notification/service/DefaultNotificationResolverServiceTest.java b/nrich-notification/src/test/java/net/croz/nrich/notification/service/DefaultNotificationResolverServiceTest.java index 2d0bfadde..a311b9ae1 100644 --- a/nrich-notification/src/test/java/net/croz/nrich/notification/service/DefaultNotificationResolverServiceTest.java +++ b/nrich-notification/src/test/java/net/croz/nrich/notification/service/DefaultNotificationResolverServiceTest.java @@ -46,7 +46,6 @@ import java.util.Map; import java.util.Set; -import static net.croz.nrich.notification.testutil.NotificationGeneratingUtil.additionalDataMap; import static net.croz.nrich.notification.testutil.NotificationGeneratingUtil.invalidNotificationResolverServiceRequestBindingMap; import static net.croz.nrich.notification.testutil.NotificationGeneratingUtil.invalidNotificationResolverServiceTestRequest; import static org.assertj.core.api.Assertions.assertThat; @@ -81,7 +80,7 @@ void shouldConvertValidationFailureToNotificationErrorResponse() { "timestamp: Timestamp has to be in the future", "value: Minimum value for value field is: 10" ); assertThat(notification.getValidationErrorList()).isNotEmpty(); - assertThat(notification.getValidationErrorList().stream().map(ValidationError::getObjectName)).containsExactlyInAnyOrder("name", "lastName", "value", "timestamp"); + assertThat(notification.getValidationErrorList().stream().map(ValidationError::objectName)).containsExactlyInAnyOrder("name", "lastName", "value", "timestamp"); } @Test @@ -123,7 +122,7 @@ void shouldConvertObjectErrorsToValidationMessages() { assertThat(notification.getMessageList()).contains("Object error occurred"); assertThat(notification.getValidationErrorList()).isNotEmpty(); - assertThat(notification.getValidationErrorList().stream().map(ValidationError::getObjectName)).contains(ValidationError.CONTAINING_OBJECT_NAME); + assertThat(notification.getValidationErrorList().stream().map(ValidationError::objectName)).contains(ValidationError.CONTAINING_OBJECT_NAME); } @Test @@ -244,7 +243,7 @@ void shouldCreateSuccessfulNotificationWithCustomTitle() { @Test void shouldAddAdditionalDataToValidationFailureNotification() { // given - AdditionalNotificationData notificationData = AdditionalNotificationData.builder().messageListDataMap(additionalDataMap("data", "1")).build(); + AdditionalNotificationData notificationData = AdditionalNotificationData.builder().messageListDataMap(Map.of("data", "1")).build(); Map invalidBindingMap = invalidNotificationResolverServiceRequestBindingMap(); BindingResult result = validate(new NotificationResolverServiceTestRequest(), invalidBindingMap); @@ -260,7 +259,7 @@ void shouldAddAdditionalDataToValidationFailureNotification() { @Test void shouldAddAdditionalDataToExceptionNotification() { // given - AdditionalNotificationData notificationData = AdditionalNotificationData.builder().messageListDataMap(additionalDataMap("data", "1")).build(); + AdditionalNotificationData notificationData = AdditionalNotificationData.builder().messageListDataMap(Map.of("data", "1")).build(); Exception exception = new NotificationResolverServiceTestExceptionWithCustomTitle(); // when @@ -274,7 +273,7 @@ void shouldAddAdditionalDataToExceptionNotification() { @Test void shouldAddAdditionalDataToSuccessNotification() { // given - AdditionalNotificationData notificationData = AdditionalNotificationData.builder().messageListDataMap(additionalDataMap("success", "ok")).build(); + AdditionalNotificationData notificationData = AdditionalNotificationData.builder().messageListDataMap(Map.of("success", "ok")).build(); String actionName = "upload.finished"; // when @@ -288,7 +287,7 @@ void shouldAddAdditionalDataToSuccessNotification() { @Test void shouldIgnoreNotFoundAdditionalDataMessages() { // given - AdditionalNotificationData notificationData = AdditionalNotificationData.builder().messageListDataMap(additionalDataMap("notFound", "ok")).build(); + AdditionalNotificationData notificationData = AdditionalNotificationData.builder().messageListDataMap(Map.of("notFound", "ok")).build(); String actionName = "upload.finished"; // when @@ -319,7 +318,7 @@ void shouldConvertConstraintViolationExceptionTooNotificationErrorResponse() { "timestamp: Timestamp has to be in the future", "value: Minimum value for value field is: 10" ); assertThat(notification.getValidationErrorList()).isNotEmpty(); - assertThat(notification.getValidationErrorList().stream().map(ValidationError::getObjectName)).containsExactlyInAnyOrder("name", "lastName", "value", "timestamp"); + assertThat(notification.getValidationErrorList().stream().map(ValidationError::objectName)).containsExactlyInAnyOrder("name", "lastName", "value", "timestamp"); } @Test diff --git a/nrich-notification/src/test/java/net/croz/nrich/notification/service/MessageSourceNotificationMessageResolverServiceTest.java b/nrich-notification/src/test/java/net/croz/nrich/notification/service/MessageSourceNotificationMessageResolverServiceTest.java index 202ee0394..b398d893e 100644 --- a/nrich-notification/src/test/java/net/croz/nrich/notification/service/MessageSourceNotificationMessageResolverServiceTest.java +++ b/nrich-notification/src/test/java/net/croz/nrich/notification/service/MessageSourceNotificationMessageResolverServiceTest.java @@ -29,8 +29,7 @@ import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; -import java.util.Arrays; -import java.util.Collections; +import java.util.List; import static net.croz.nrich.notification.testutil.DefaultMessageSourceResolvableGeneratingUtil.createMessageSourceNotificationMessageResolverServiceTestRequestFieldErrorLabelMessageSourceResolvable; import static net.croz.nrich.notification.testutil.DefaultMessageSourceResolvableGeneratingUtil.createMessageSourceNotificationMessageResolverServiceTestRequestFieldErrorMessageSourceResolvable; @@ -51,15 +50,15 @@ class MessageSourceNotificationMessageResolverServiceTest { @Test void shouldResolveMessage() { // given - String[] codeList = new String[] { "message.code" }; - Object[] argumentList = new Object[] { "argument" }; + String[] codeList = { "message.code" }; + Object[] argumentList = { "argument" }; DefaultMessageSourceResolvable messageSourceResolvable = new DefaultMessageSourceResolvable(codeList, argumentList); String message = "message"; doReturn(message).when(messageSource).getMessage(messageSourceResolvable, LocaleContextHolder.getLocale()); // when - String result = messageResolverService.resolveMessage(Arrays.asList(codeList), Arrays.asList(argumentList), null); + String result = messageResolverService.resolveMessage(List.of(codeList), List.of(argumentList), null); // then assertThat(result).isEqualTo(message); @@ -68,7 +67,7 @@ void shouldResolveMessage() { @Test void shouldNotFailOnNullArguments() { // when - Throwable thrown = catchThrowable(() -> messageResolverService.resolveMessage(Collections.singletonList("message.code"), null, null)); + Throwable thrown = catchThrowable(() -> messageResolverService.resolveMessage(List.of("message.code"), null, null)); // then assertThat(thrown).isNull(); @@ -116,7 +115,7 @@ void shouldResolveMessageForFieldError() { void shouldConvertArrayArgumentsString() { // given Class requestType = MessageSourceNotificationMessageResolverServiceTestRequest.class; - Object[] arguments = new Object[] { new Object[] { "first", "second" } }; + Object[] arguments = { new Object[] { "first", "second" } }; ObjectError error = new ObjectError("target", new String[] { "code" }, arguments, "message"); DefaultMessageSourceResolvable messageSourceResolvable = createMessageSourceNotificationMessageResolverServiceTestRequestObjectErrorMessageSourceResolvable(new Object[] { "first, second" }); String message = "message"; diff --git a/nrich-notification/src/test/java/net/croz/nrich/notification/testutil/DefaultMessageSourceResolvableGeneratingUtil.java b/nrich-notification/src/test/java/net/croz/nrich/notification/testutil/DefaultMessageSourceResolvableGeneratingUtil.java index c41425f9e..e232fdc36 100644 --- a/nrich-notification/src/test/java/net/croz/nrich/notification/testutil/DefaultMessageSourceResolvableGeneratingUtil.java +++ b/nrich-notification/src/test/java/net/croz/nrich/notification/testutil/DefaultMessageSourceResolvableGeneratingUtil.java @@ -29,7 +29,7 @@ public static DefaultMessageSourceResolvable createMessageSourceNotificationMess } public static DefaultMessageSourceResolvable createMessageSourceNotificationMessageResolverServiceTestRequestObjectErrorMessageSourceResolvable(Object[] arguments) { - String[] codeList = new String[] { + String[] codeList = { "net.croz.nrich.notification.stub.MessageSourceNotificationMessageResolverServiceTestRequest.code.invalid", "messageSourceNotificationMessageResolverServiceTestRequest.code.invalid", "code.invalid" }; @@ -38,7 +38,7 @@ public static DefaultMessageSourceResolvable createMessageSourceNotificationMess } public static DefaultMessageSourceResolvable createMessageSourceNotificationMessageResolverServiceTestRequestFieldErrorMessageSourceResolvable() { - String[] fieldCodeList = new String[] { + String[] fieldCodeList = { "net.croz.nrich.notification.stub.MessageSourceNotificationMessageResolverServiceTestRequest.field.code.invalid", "messageSourceNotificationMessageResolverServiceTestRequest.field.code.invalid", "field.code.invalid", "code.invalid" }; @@ -47,7 +47,7 @@ public static DefaultMessageSourceResolvable createMessageSourceNotificationMess } public static DefaultMessageSourceResolvable createMessageSourceNotificationMessageResolverServiceTestRequestFieldErrorLabelMessageSourceResolvable() { - String[] fieldLabelCodeList = new String[] { + String[] fieldLabelCodeList = { "net.croz.nrich.notification.stub.MessageSourceNotificationMessageResolverServiceTestRequest.field.label", "messageSourceNotificationMessageResolverServiceTestRequest.field.label", "field.code.label" }; diff --git a/nrich-notification/src/test/java/net/croz/nrich/notification/testutil/NotificationGeneratingUtil.java b/nrich-notification/src/test/java/net/croz/nrich/notification/testutil/NotificationGeneratingUtil.java index 412e4c503..745b9b820 100644 --- a/nrich-notification/src/test/java/net/croz/nrich/notification/testutil/NotificationGeneratingUtil.java +++ b/nrich-notification/src/test/java/net/croz/nrich/notification/testutil/NotificationGeneratingUtil.java @@ -21,7 +21,6 @@ import java.time.Instant; import java.time.temporal.ChronoUnit; -import java.util.HashMap; import java.util.Map; public final class NotificationGeneratingUtil { @@ -30,21 +29,11 @@ private NotificationGeneratingUtil() { } public static Map invalidNotificationResolverServiceRequestBindingMap() { - Map invalidBindingMap = new HashMap<>(); - - invalidBindingMap.put("lastName", "too long last name"); - invalidBindingMap.put("timestamp", Instant.now().minus(1, ChronoUnit.DAYS)); - invalidBindingMap.put("value", 5); - - return invalidBindingMap; - } - - public static Map additionalDataMap(String key, String value) { - Map additionalDataMap = new HashMap<>(); - - additionalDataMap.put(key, value); - - return additionalDataMap; + return Map.of( + "lastName", "too long last name", + "timestamp", Instant.now().minus(1, ChronoUnit.DAYS), + "value", 5 + ); } public static NotificationResolverServiceTestRequest invalidNotificationResolverServiceTestRequest() { diff --git a/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/configuration/model/RegistryGroupConfiguration.java b/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/configuration/model/RegistryGroupConfiguration.java index 4b668d256..d178d2114 100644 --- a/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/configuration/model/RegistryGroupConfiguration.java +++ b/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/configuration/model/RegistryGroupConfiguration.java @@ -17,31 +17,15 @@ package net.croz.nrich.registry.api.configuration.model; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - import java.util.List; /** * Configuration for registry group (a group of registry entities). + * + * @param groupId Unique id of group. + * @param groupIdDisplayName Display label for group. + * @param entityConfigurationList List of entity configurations belonging to this group. */ -@RequiredArgsConstructor -@Getter -public class RegistryGroupConfiguration { - - /** - * Unique id of group. - */ - private final String groupId; - - /** - * Display label for group. - */ - private final String groupIdDisplayName; - - /** - * List of entity configurations belonging to this group. - */ - private final List entityConfigurationList; +public record RegistryGroupConfiguration(String groupId, String groupIdDisplayName, List entityConfigurationList) { } diff --git a/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/data/request/ListBulkRegistryRequest.java b/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/data/request/ListBulkRegistryRequest.java index 183a5f75f..d7a628c29 100644 --- a/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/data/request/ListBulkRegistryRequest.java +++ b/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/data/request/ListBulkRegistryRequest.java @@ -17,9 +17,6 @@ package net.croz.nrich.registry.api.data.request; -import lombok.Getter; -import lombok.Setter; - import jakarta.validation.Valid; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; @@ -27,17 +24,10 @@ /** * Request holding data for fetching a list of different registry entities. + * + * @param registryRequestList List of {@link ListRegistryRequest} instances. */ -@Setter -@Getter -public class ListBulkRegistryRequest { - /** - * List of {@link ListRegistryRequest} instances. - */ - @Size(min = 1) - @Valid - @NotNull - private List registryRequestList; +public record ListBulkRegistryRequest(@Size(min = 1) @Valid @NotNull List registryRequestList) { } diff --git a/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/data/request/ListRegistryRequest.java b/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/data/request/ListRegistryRequest.java index fb62bb657..2d0775dbb 100644 --- a/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/data/request/ListRegistryRequest.java +++ b/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/data/request/ListRegistryRequest.java @@ -17,8 +17,6 @@ package net.croz.nrich.registry.api.data.request; -import lombok.Getter; -import lombok.Setter; import net.croz.nrich.search.api.model.sort.SortProperty; import jakarta.validation.constraints.Max; @@ -29,38 +27,7 @@ /** * Request holding data for fetching a list of registry entities. */ -@Setter -@Getter -public class ListRegistryRequest { - - /** - * Class name of registry entity. - */ - @NotNull - private String classFullName; - - /** - * Page number. - */ - @Min(0) - @NotNull - private Integer pageNumber; - - /** - * Number of entities to fetch. - */ - @Max(5000) - @NotNull - private Integer pageSize; - - /** - * Search parameters. - */ - private SearchParameter searchParameter; - - /** - * List of {@link SortProperty} instances. - */ - private List sortPropertyList; +public record ListRegistryRequest(@NotNull String classFullName, @Max(50_000) @Min(0) @NotNull Integer pageNumber, @Max(5000) @Min(1) @NotNull Integer pageSize, SearchParameter searchParameter, + List sortPropertyList) { } diff --git a/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/data/request/SearchParameter.java b/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/data/request/SearchParameter.java index 642d95e75..f0db3d961 100644 --- a/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/data/request/SearchParameter.java +++ b/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/data/request/SearchParameter.java @@ -17,26 +17,15 @@ package net.croz.nrich.registry.api.data.request; -import lombok.Getter; -import lombok.Setter; - import java.util.List; /** * Registry entity search parameters. + * + * @param propertyNameList List of properties to search. + * @param query Search query. */ -@Setter -@Getter -public class SearchParameter { - - /** - * List of properties to search. - */ - private List propertyNameList; - /** - * Search query. - */ - private String query; +public record SearchParameter(List propertyNameList, String query) { } diff --git a/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/enumdata/model/EnumResult.java b/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/enumdata/model/EnumResult.java index 6dfbbedd2..220c11ecd 100644 --- a/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/enumdata/model/EnumResult.java +++ b/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/enumdata/model/EnumResult.java @@ -17,21 +17,8 @@ package net.croz.nrich.registry.api.enumdata.model; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - import java.util.Map; -@RequiredArgsConstructor -@Getter -public class EnumResult { - - private final String id; - - private final String description; - - private final Enum value; - - private final Map additionalData; +public record EnumResult(String id, String description, Enum value, Map additionalData) { } diff --git a/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/enumdata/request/ListBulkRegistryEnumRequest.java b/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/enumdata/request/ListBulkRegistryEnumRequest.java index 0ed6eea7d..c47e924bb 100644 --- a/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/enumdata/request/ListBulkRegistryEnumRequest.java +++ b/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/enumdata/request/ListBulkRegistryEnumRequest.java @@ -17,9 +17,6 @@ package net.croz.nrich.registry.api.enumdata.request; -import lombok.Getter; -import lombok.Setter; - import jakarta.validation.Valid; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; @@ -27,16 +24,9 @@ /** * Request holding data for fetching a list of different enum data. + * + * @param registryRequestList List of {@link ListRegistryEnumRequest} instances. */ -@Setter -@Getter -public class ListBulkRegistryEnumRequest { +public record ListBulkRegistryEnumRequest(@Valid @Size(min = 1) @NotNull List registryRequestList) { - /** - * List of {@link ListRegistryEnumRequest} instances. - */ - @Valid - @Size(min = 1) - @NotNull - private List registryRequestList; } diff --git a/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/enumdata/request/ListRegistryEnumRequest.java b/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/enumdata/request/ListRegistryEnumRequest.java index b21149f78..064fd3117 100644 --- a/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/enumdata/request/ListRegistryEnumRequest.java +++ b/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/enumdata/request/ListRegistryEnumRequest.java @@ -17,27 +17,14 @@ package net.croz.nrich.registry.api.enumdata.request; -import lombok.Getter; -import lombok.Setter; - import jakarta.validation.constraints.NotBlank; /** * Request holding data for fetching a list of enum data. + * + * @param classFullName Enum class name. + * @param query Search query. */ -@Setter -@Getter -public class ListRegistryEnumRequest { - - /** - * Enum class name. - */ - @NotBlank - private String classFullName; - - /** - * Search query. - */ - private String query; +public record ListRegistryEnumRequest(@NotBlank String classFullName, String query) { } diff --git a/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/history/model/EntityWithRevision.java b/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/history/model/EntityWithRevision.java index 39f4c8e4e..2360bec36 100644 --- a/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/history/model/EntityWithRevision.java +++ b/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/history/model/EntityWithRevision.java @@ -17,26 +17,13 @@ package net.croz.nrich.registry.api.history.model; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - /** * Holds entity with its revision data. * - * @param entity type + * @param entity type + * @param entity Registry entity. + * @param revisionInfo Entity revision information. */ -@RequiredArgsConstructor -@Getter -public class EntityWithRevision { - - /** - * Registry entity. - */ - private final T entity; - - /** - * Entity revision information. - */ - private final RevisionInfo revisionInfo; +public record EntityWithRevision(T entity, RevisionInfo revisionInfo) { } diff --git a/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/history/model/RevisionInfo.java b/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/history/model/RevisionInfo.java index 6c1ea4d4f..7bb3f8f6a 100644 --- a/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/history/model/RevisionInfo.java +++ b/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/history/model/RevisionInfo.java @@ -17,37 +17,17 @@ package net.croz.nrich.registry.api.history.model; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - import java.time.Instant; import java.util.Map; /** * Entity revision information. + * + * @param revisionNumber Number of revision. + * @param revisionTimestamp Revision timestamp. + * @param revisionType Revision type (ADD, MOD, DEL) + * @param additionalRevisionPropertyMap Additional revision properties. */ -@RequiredArgsConstructor -@Getter -public class RevisionInfo { - - /** - * Number of revision. - */ - private final Long revisionNumber; - - /** - * Revision timestamp. - */ - private final Instant revisionTimestamp; - - /** - * Revision type (ADD, MOD, DEL) - */ - private final String revisionType; - - /** - * Additional revision properties. - */ - private final Map additionalRevisionPropertyMap; +public record RevisionInfo(Long revisionNumber, Instant revisionTimestamp, String revisionType, Map additionalRevisionPropertyMap) { } diff --git a/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/history/request/ListRegistryHistoryRequest.java b/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/history/request/ListRegistryHistoryRequest.java index 82cc08e7c..8b86aef9a 100644 --- a/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/history/request/ListRegistryHistoryRequest.java +++ b/nrich-registry-api/src/main/java/net/croz/nrich/registry/api/history/request/ListRegistryHistoryRequest.java @@ -17,8 +17,6 @@ package net.croz.nrich.registry.api.history.request; -import lombok.Getter; -import lombok.Setter; import net.croz.nrich.search.api.model.sort.SortProperty; import jakarta.validation.constraints.Max; @@ -28,39 +26,14 @@ /** * Request holding data for fetching history list of registry entities. + * + * @param classFullName Class name of registry entity. + * @param pageNumber Page number. + * @param pageSize Number of entities to fetch. + * @param registryRecordId Optional id of registry if not set history for all registry entities of specific type will be fetched. + * @param sortPropertyList List of {@link SortProperty} instances. */ -@Setter -@Getter -public class ListRegistryHistoryRequest { - - /** - * Class name of registry entity. - */ - @NotNull - private String classFullName; - - /** - * Page number. - */ - @Min(0) - @NotNull - private Integer pageNumber; - - /** - * Number of entities to fetch. - */ - @Max(100) - @NotNull - private Integer pageSize; - - /** - * Optional id of registry if not set history for all registry entities of specific type will be fetched. - */ - private Object registryRecordId; - - /** - * List of {@link SortProperty} instances. - */ - private List sortPropertyList; +public record ListRegistryHistoryRequest(@NotNull String classFullName, @Min(0) @NotNull Integer pageNumber, @Max(100) @NotNull Integer pageSize, Object registryRecordId, + List sortPropertyList) { } diff --git a/nrich-registry-spring-boot-starter/src/main/java/net/croz/nrich/registry/starter/configuration/NrichRegistryAutoConfiguration.java b/nrich-registry-spring-boot-starter/src/main/java/net/croz/nrich/registry/starter/configuration/NrichRegistryAutoConfiguration.java index f1461bd86..4f501455c 100644 --- a/nrich-registry-spring-boot-starter/src/main/java/net/croz/nrich/registry/starter/configuration/NrichRegistryAutoConfiguration.java +++ b/nrich-registry-spring-boot-starter/src/main/java/net/croz/nrich/registry/starter/configuration/NrichRegistryAutoConfiguration.java @@ -94,7 +94,7 @@ import java.util.stream.Collectors; @AutoConfigureAfter({ ValidationAutoConfiguration.class, HibernateJpaAutoConfiguration.class }) -@ConditionalOnBean({ EntityManagerFactory.class }) +@ConditionalOnBean(EntityManagerFactory.class) @ConditionalOnPropertyNotEmpty("nrich.registry.registry-configuration.group-definition-configuration-list") @EnableConfigurationProperties(NrichRegistryProperties.class) @Configuration(proxyBeanMethods = false) @@ -149,14 +149,15 @@ public ObjectMapper registryObjectMapper(List moduleList) { @Bean public StringToTypeConverter registryDefaultStringToTypeConverter(NrichRegistryProperties registryProperties) { return new DefaultStringToTypeConverter( - registryProperties.getRegistrySearch().getDateFormatList(), registryProperties.getRegistrySearch().getDecimalNumberFormatList(), - registryProperties.getRegistrySearch().getBooleanTrueRegexPattern(), registryProperties.getRegistrySearch().getBooleanFalseRegexPattern() + registryProperties.registrySearch().dateFormatList(), registryProperties.registrySearch().decimalNumberFormatList(), + registryProperties.registrySearch().booleanTrueRegexPattern(), registryProperties.registrySearch().booleanFalseRegexPattern() ); } @ConditionalOnMissingBean(name = "registryStringToEntityPropertyMapConverter") @Bean public StringToEntityPropertyMapConverter registryStringToEntityPropertyMapConverter(@Lazy @Autowired(required = false) Map> stringToTypeConverterList) { + @SuppressWarnings("java:S6204") List> registryConverters = stringToTypeConverterList.entrySet().stream() .filter(entry -> entry.getKey().toLowerCase(Locale.ROOT).contains(REGISTRY_CONVERTER)) .map(Map.Entry::getValue) @@ -170,7 +171,7 @@ public StringToEntityPropertyMapConverter registryStringToEntityPropertyMapConve public RegistryConfigurationResolverService registryConfigurationResolverService(NrichRegistryProperties registryProperties, @Autowired(required = false) List registryOverrideConfigurationHolderList) { - List overrideConfigurationHolderList = registryProperties.getRegistryConfiguration().getOverrideConfigurationHolderList(); + List overrideConfigurationHolderList = registryProperties.registryConfiguration().getOverrideConfigurationHolderList(); if (overrideConfigurationHolderList == null) { overrideConfigurationHolderList = new ArrayList<>(); @@ -179,9 +180,9 @@ public RegistryConfigurationResolverService registryConfigurationResolverService overrideConfigurationHolderList.addAll(registryOverrideConfigurationHolderList); } - registryProperties.getRegistryConfiguration().setOverrideConfigurationHolderList(overrideConfigurationHolderList); + registryProperties.registryConfiguration().setOverrideConfigurationHolderList(overrideConfigurationHolderList); - return new DefaultRegistryConfigurationResolverService(entityManager, registryProperties.getRegistryConfiguration()); + return new DefaultRegistryConfigurationResolverService(entityManager, registryProperties.registryConfiguration()); } @ConditionalOnMissingBean @@ -207,7 +208,7 @@ public JavaToJavascriptTypeConversionService registryJavaToJavascriptTypeConvers @Bean public RegistryConfigurationService registryConfigurationService(MessageSource messageSource, RegistryConfigurationResolverService registryConfigurationResolverService, NrichRegistryProperties registryProperties, JavaToJavascriptTypeConversionService registryJavaToJavascriptTypeConversionService) { - List readOnlyPropertyList = Optional.ofNullable(registryProperties.getDefaultReadOnlyPropertyList()).orElse(Collections.emptyList()); + List readOnlyPropertyList = Optional.ofNullable(registryProperties.defaultReadOnlyPropertyList()).orElse(Collections.emptyList()); RegistryGroupDefinitionHolder registryGroupDefinitionHolder = registryConfigurationResolverService.resolveRegistryGroupDefinition(); RegistryHistoryConfigurationHolder registryHistoryConfigurationHolder = registryConfigurationResolverService.resolveRegistryHistoryConfiguration(); Map, RegistryOverrideConfiguration> registryOverrideConfigurationMap = registryConfigurationResolverService.resolveRegistryOverrideConfigurationMap(); @@ -227,7 +228,7 @@ public RegistryConfigurationController registryConfigurationController(RegistryC @ConditionalOnMissingBean @Bean public RegistryEntityFinderService registryEntityFinderService(ModelMapper registryBaseModelMapper, RegistryConfigurationResolverService registryConfigurationResolverService) { - Map managedTypeWrapperMap = registryConfigurationResolverService.resolveRegistryDataConfiguration().getClassNameManagedTypeWrapperMap(); + Map managedTypeWrapperMap = registryConfigurationResolverService.resolveRegistryDataConfiguration().classNameManagedTypeWrapperMap(); return new EntityManagerRegistryEntityFinderService(entityManager, registryBaseModelMapper, managedTypeWrapperMap); } @@ -249,8 +250,8 @@ public DefaultRegistryDataService registryDataService(ModelMapper registryDataMo @ConditionalOnMissingBean @Bean public RegistryClassResolvingService registryClassResolvingService(RegistryConfigurationResolverService registryConfigurationResolverService, NrichRegistryProperties registryProperties) { - Map> createRegistryClassMapping = registryProperties.getRegistryConfiguration().getCreateRegistryClassMapping(); - Map> updateRegistryClassMapping = registryProperties.getRegistryConfiguration().getUpdateRegistryClassMapping(); + Map> createRegistryClassMapping = registryProperties.registryConfiguration().getCreateRegistryClassMapping(); + Map> updateRegistryClassMapping = registryProperties.registryConfiguration().getUpdateRegistryClassMapping(); return new DefaultRegistryClassResolvingService(registryConfigurationResolverService.resolveRegistryDataConfiguration(), createRegistryClassMapping, updateRegistryClassMapping); } @@ -291,8 +292,9 @@ public RegistryHistoryController registryHistoryController(RegistryHistoryServic @Bean public FormConfigurationMappingCustomizer registryDataFormConfigurationMappingCustomizer(RegistryConfigurationResolverService registryConfigurationResolverService, RegistryClassResolvingService registryClassResolvingService) { - List> registryClassList = registryConfigurationResolverService.resolveRegistryDataConfiguration().getRegistryDataConfigurationList().stream() - .map(RegistryDataConfiguration::getRegistryType) + @SuppressWarnings("java:S6204") + List> registryClassList = registryConfigurationResolverService.resolveRegistryDataConfiguration().registryDataConfigurationList().stream() + .map(RegistryDataConfiguration::registryType) .collect(Collectors.toList()); return new RegistryDataFormConfigurationMappingCustomizer(registryClassResolvingService, registryClassList); diff --git a/nrich-registry-spring-boot-starter/src/main/java/net/croz/nrich/registry/starter/properties/NrichRegistryProperties.java b/nrich-registry-spring-boot-starter/src/main/java/net/croz/nrich/registry/starter/properties/NrichRegistryProperties.java index efd7554e0..e088cc1dd 100644 --- a/nrich-registry-spring-boot-starter/src/main/java/net/croz/nrich/registry/starter/properties/NrichRegistryProperties.java +++ b/nrich-registry-spring-boot-starter/src/main/java/net/croz/nrich/registry/starter/properties/NrichRegistryProperties.java @@ -17,7 +17,6 @@ package net.croz.nrich.registry.starter.properties; -import lombok.Getter; import net.croz.nrich.registry.api.core.model.RegistryConfiguration; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; @@ -25,76 +24,27 @@ import java.util.List; -@Getter +/** + * @param defaultReadOnlyPropertyList List of property names that should always be marked as readonly. + * @param registrySearch Registry search configuration used by {@link net.croz.nrich.search.converter.DefaultStringToTypeConverter}. + * @param defaultConverterEnabled Whether default string to type converter ({@link net.croz.nrich.search.converter.DefaultStringToTypeConverter}) used for converting strings to property values when searching registry is enabled. + * @param defaultJavaToJavascriptConverterEnabled Whether default Java to Javascript type converter ({@link net.croz.nrich.javascript.converter.DefaultJavaToJavascriptTypeConverter}) used for converting Java to Javascript types is enabled. + * @param registryConfiguration Registry configuration used for defining entities and groups which will be managed. + */ @ConfigurationProperties("nrich.registry") -public class NrichRegistryProperties { - - /** - * List of property names that should always be marked as readonly. - */ - private final List defaultReadOnlyPropertyList; +public record NrichRegistryProperties(List defaultReadOnlyPropertyList, @DefaultValue @NestedConfigurationProperty RegistrySearchProperties registrySearch, + @DefaultValue("true") boolean defaultConverterEnabled, + @DefaultValue("true") boolean defaultJavaToJavascriptConverterEnabled, + RegistryConfiguration registryConfiguration) { /** - * Registry search configuration used by {@link net.croz.nrich.search.converter.DefaultStringToTypeConverter}. + * @param dateFormatList List of date formats used by {@link net.croz.nrich.search.converter.DefaultStringToTypeConverter} to convert string to date values. + * @param decimalNumberFormatList List of decimal formats used by {@link net.croz.nrich.search.converter.DefaultStringToTypeConverter} to convert string to decimal value. + * @param booleanTrueRegexPattern Regexp pattern that is used by {@link net.croz.nrich.search.converter.DefaultStringToTypeConverter} to match boolean true values. + * @param booleanFalseRegexPattern Regexp pattern that is used by {@link net.croz.nrich.search.converter.DefaultStringToTypeConverter} to match boolean false values. */ - @NestedConfigurationProperty - private final RegistrySearchProperties registrySearch; - - /** - * Whether default string to type converter ({@link net.croz.nrich.search.converter.DefaultStringToTypeConverter}) used for converting strings to property values when searching registry is enabled. - */ - private final boolean defaultConverterEnabled; - - /** - * Whether default Java to Javascript type converter ({@link net.croz.nrich.javascript.converter.DefaultJavaToJavascriptTypeConverter}) used for converting Java to Javascript types is enabled. - */ - private final boolean defaultJavaToJavascriptConverterEnabled; - - /** - * Registry configuration used for defining entities and groups which will be managed. - */ - @NestedConfigurationProperty - private final RegistryConfiguration registryConfiguration; - - public NrichRegistryProperties(List defaultReadOnlyPropertyList, @DefaultValue RegistrySearchProperties registrySearch, @DefaultValue("true") boolean defaultConverterEnabled, - @DefaultValue("true") boolean defaultJavaToJavascriptConverterEnabled, - RegistryConfiguration registryConfiguration) { - this.defaultReadOnlyPropertyList = defaultReadOnlyPropertyList; - this.registrySearch = registrySearch; - this.defaultConverterEnabled = defaultConverterEnabled; - this.defaultJavaToJavascriptConverterEnabled = defaultJavaToJavascriptConverterEnabled; - this.registryConfiguration = registryConfiguration; - } - - @Getter - public static class RegistrySearchProperties { - - /** - * List of date formats used by {@link net.croz.nrich.search.converter.DefaultStringToTypeConverter} to convert string to date values. - */ - private final List dateFormatList; - - /** - * List of decimal formats used by {@link net.croz.nrich.search.converter.DefaultStringToTypeConverter} to convert string to decimal value. - */ - private final List decimalNumberFormatList; - - /** - * Regexp pattern that is used by {@link net.croz.nrich.search.converter.DefaultStringToTypeConverter} to match boolean true values. - */ - private final String booleanTrueRegexPattern; - - /** - * Regexp pattern that is used by {@link net.croz.nrich.search.converter.DefaultStringToTypeConverter} to match boolean false values. - */ - private final String booleanFalseRegexPattern; - - public RegistrySearchProperties(@DefaultValue({ "dd.MM.yyyy.", "dd.MM.yyyy.'T'HH:mm", "dd.MM.yyyy.'T'HH:mm'Z'" }) List dateFormatList, @DefaultValue({ "#0.00", "#0,00" }) List decimalNumberFormatList, - @DefaultValue("^(?i)\\s*(true|yes|da)\\s*$") String booleanTrueRegexPattern, @DefaultValue("^(?i)\\s*(false|no|ne)\\s*$") String booleanFalseRegexPattern) { - this.dateFormatList = dateFormatList; - this.decimalNumberFormatList = decimalNumberFormatList; - this.booleanTrueRegexPattern = booleanTrueRegexPattern; - this.booleanFalseRegexPattern = booleanFalseRegexPattern; - } + public record RegistrySearchProperties(@DefaultValue({ "dd.MM.yyyy.", "dd.MM.yyyy.'T'HH:mm", "dd.MM.yyyy.'T'HH:mm'Z'" }) List dateFormatList, + @DefaultValue({ "#0.00", "#0,00" }) List decimalNumberFormatList, + @DefaultValue("^(?i)\\s*(true|yes|da)\\s*$") String booleanTrueRegexPattern, @DefaultValue("^(?i)\\s*(false|no|ne)\\s*$") String booleanFalseRegexPattern) { } } diff --git a/nrich-registry-spring-boot-starter/src/test/java/net/croz/nrich/registry/starter/configuration/NrichRegistryAutoConfigurationTest.java b/nrich-registry-spring-boot-starter/src/test/java/net/croz/nrich/registry/starter/configuration/NrichRegistryAutoConfigurationTest.java index eab60a6d5..cec347447 100644 --- a/nrich-registry-spring-boot-starter/src/test/java/net/croz/nrich/registry/starter/configuration/NrichRegistryAutoConfigurationTest.java +++ b/nrich-registry-spring-boot-starter/src/test/java/net/croz/nrich/registry/starter/configuration/NrichRegistryAutoConfigurationTest.java @@ -52,7 +52,7 @@ class NrichRegistryAutoConfigurationTest { - private static final String[] REGISTRY_CONFIGURATION = new String[] { + private static final String[] REGISTRY_CONFIGURATION = { "nrich.registry.registry-configuration.group-definition-configuration-list[0].group-id=DATA", "nrich.registry.registry-configuration.group-definition-configuration-list[0].include-entity-pattern-list=^net.croz.nrich.registry.data.stub.*$" }; @@ -85,7 +85,7 @@ void shouldNotRegisterConfigurationWhenNoPropertyValuesHaveBeenConfigured() { @Test void shouldMapConfigurationProperties() { // given - String[] properties = new String[] { + String[] properties = { "nrich.registry.default-read-only-property-list=id,version", "nrich.registry.registry-search.date-format-list=dd.mm.YYYY", "nrich.registry.registry-search.decimal-number-format-list=#0.00", @@ -105,25 +105,25 @@ void shouldMapConfigurationProperties() { NrichRegistryProperties registryProperties = context.getBean(NrichRegistryProperties.class); // then - assertThat(registryProperties.getDefaultReadOnlyPropertyList()).containsExactly("id", "version"); + assertThat(registryProperties.defaultReadOnlyPropertyList()).containsExactly("id", "version"); - assertThat(registryProperties.getRegistrySearch()).isNotNull(); + assertThat(registryProperties.registrySearch()).isNotNull(); - NrichRegistryProperties.RegistrySearchProperties registrySearchProperties = registryProperties.getRegistrySearch(); + NrichRegistryProperties.RegistrySearchProperties registrySearchProperties = registryProperties.registrySearch(); - assertThat(registrySearchProperties.getDateFormatList()).containsExactly("dd.mm.YYYY"); - assertThat(registrySearchProperties.getDecimalNumberFormatList()).containsExactly("#0.00"); - assertThat(registrySearchProperties.getBooleanTrueRegexPattern()).isEqualTo("^(?i)\\s*(true|yes)\\s*$"); - assertThat(registrySearchProperties.getBooleanFalseRegexPattern()).isEqualTo("^(?i)\\s*(false|no)\\s*$"); + assertThat(registrySearchProperties.dateFormatList()).containsExactly("dd.mm.YYYY"); + assertThat(registrySearchProperties.decimalNumberFormatList()).containsExactly("#0.00"); + assertThat(registrySearchProperties.booleanTrueRegexPattern()).isEqualTo("^(?i)\\s*(true|yes)\\s*$"); + assertThat(registrySearchProperties.booleanFalseRegexPattern()).isEqualTo("^(?i)\\s*(false|no)\\s*$"); - assertThat(registryProperties.getRegistryConfiguration()).isNotNull(); + assertThat(registryProperties.registryConfiguration()).isNotNull(); - RegistryConfiguration registryConfiguration = registryProperties.getRegistryConfiguration(); + RegistryConfiguration registryConfiguration = registryProperties.registryConfiguration(); assertThat(registryConfiguration.getGroupDisplayOrderList()).containsExactly("DATA"); assertThat(registryConfiguration.getHistoryDisplayOrderList()).containsExactly("id", "name"); - List registryGroupDefinitionList = registryProperties.getRegistryConfiguration().getGroupDefinitionConfigurationList(); + List registryGroupDefinitionList = registryProperties.registryConfiguration().getGroupDefinitionConfigurationList(); assertThat(registryGroupDefinitionList).extracting("groupId").containsExactly("DATA"); assertThat(registryGroupDefinitionList).flatExtracting("includeEntityPatternList").containsExactly("^net.croz.nrich.registry.data.stub.*$"); @@ -153,6 +153,8 @@ void shouldConfigureDefaultConfiguration() { assertThat(context).hasSingleBean(FormConfigurationMappingCustomizer.class); assertThat(context).hasSingleBean(JavaToJavascriptTypeConversionService.class); assertThat(context).hasSingleBean(RegistryEnumService.class); + assertThat(context).hasSingleBean(NrichRegistryProperties.class); + assertThat(context.getBean(NrichRegistryProperties.class).registrySearch()).isNotNull(); assertThat(context).doesNotHaveBean(RegistryConfigurationController.class); assertThat(context).doesNotHaveBean(RegistryDataController.class); @@ -197,7 +199,7 @@ void shouldRegisterRegistryOverrideConfiguration() { NrichRegistryProperties registryProperties = context.getBean(NrichRegistryProperties.class); // then - assertThat(registryProperties.getRegistryConfiguration().getOverrideConfigurationHolderList()).containsExactly(holder); + assertThat(registryProperties.registryConfiguration().getOverrideConfigurationHolderList()).containsExactly(holder); }); } } diff --git a/nrich-registry/src/main/java/net/croz/nrich/registry/configuration/comparator/DisplayOrderComparator.java b/nrich-registry/src/main/java/net/croz/nrich/registry/configuration/comparator/DisplayOrderComparator.java index 7d17ff903..8c13d32c8 100644 --- a/nrich-registry/src/main/java/net/croz/nrich/registry/configuration/comparator/DisplayOrderComparator.java +++ b/nrich-registry/src/main/java/net/croz/nrich/registry/configuration/comparator/DisplayOrderComparator.java @@ -20,6 +20,7 @@ import lombok.Getter; import lombok.RequiredArgsConstructor; +import java.io.Serial; import java.io.Serializable; import java.util.List; @@ -27,6 +28,7 @@ @Getter public class DisplayOrderComparator implements Serializable { + @Serial private static final long serialVersionUID = 4980226671627040327L; private final List propertyDisplayOrderList; diff --git a/nrich-registry/src/main/java/net/croz/nrich/registry/configuration/comparator/RegistryGroupConfigurationComparator.java b/nrich-registry/src/main/java/net/croz/nrich/registry/configuration/comparator/RegistryGroupConfigurationComparator.java index 6ceef1e8b..d4ba6d1c3 100644 --- a/nrich-registry/src/main/java/net/croz/nrich/registry/configuration/comparator/RegistryGroupConfigurationComparator.java +++ b/nrich-registry/src/main/java/net/croz/nrich/registry/configuration/comparator/RegistryGroupConfigurationComparator.java @@ -31,8 +31,8 @@ public RegistryGroupConfigurationComparator(List propertyDisplayOrderLis @Override public int compare(RegistryGroupConfiguration firstConfiguration, RegistryGroupConfiguration secondConfiguration) { - String firstGroupId = firstConfiguration.getGroupId(); - String secondGroupId = secondConfiguration.getGroupId(); + String firstGroupId = firstConfiguration.groupId(); + String secondGroupId = secondConfiguration.groupId(); if (CollectionUtils.isEmpty(getPropertyDisplayOrderList())) { return firstGroupId.compareTo(secondGroupId); diff --git a/nrich-registry/src/main/java/net/croz/nrich/registry/configuration/service/DefaultRegistryConfigurationService.java b/nrich-registry/src/main/java/net/croz/nrich/registry/configuration/service/DefaultRegistryConfigurationService.java index 04ba688f8..022fc5848 100644 --- a/nrich-registry/src/main/java/net/croz/nrich/registry/configuration/service/DefaultRegistryConfigurationService.java +++ b/nrich-registry/src/main/java/net/croz/nrich/registry/configuration/service/DefaultRegistryConfigurationService.java @@ -53,7 +53,6 @@ import java.util.Map; import java.util.Optional; import java.util.function.Predicate; - import java.util.stream.Collectors; @RequiredArgsConstructor public class DefaultRegistryConfigurationService implements RegistryConfigurationService { @@ -77,20 +76,20 @@ public List fetchRegistryGroupConfigurationList() { List registryPropertyHistoryConfigurationList = resolveHistoryPropertyList(registryHistoryConfiguration); - registryGroupDefinitionHolder.getGroupDefinitionList().forEach(registryGroupDefinition -> { - String registryGroupIdDisplayName = groupDisplayLabel(registryGroupDefinition.getRegistryGroupId()); + registryGroupDefinitionHolder.groupDefinitionList().forEach(registryGroupDefinition -> { + String registryGroupIdDisplayName = groupDisplayLabel(registryGroupDefinition.registryGroupId()); - List configurationList = registryGroupDefinition.getRegistryEntityList().stream() - .map(managedType -> resolveRegistryConfiguration(registryGroupDefinition.getRegistryGroupId(), managedType, registryPropertyHistoryConfigurationList)) + List configurationList = registryGroupDefinition.registryEntityList().stream() + .map(managedType -> resolveRegistryConfiguration(registryGroupDefinition.registryGroupId(), managedType, registryPropertyHistoryConfigurationList)) .sorted(Comparator.comparing(RegistryEntityConfiguration::getClassFullName)) - .collect(Collectors.toList()); + .toList(); - RegistryGroupConfiguration registryConfiguration = new RegistryGroupConfiguration(registryGroupDefinition.getRegistryGroupId(), registryGroupIdDisplayName, configurationList); + RegistryGroupConfiguration registryConfiguration = new RegistryGroupConfiguration(registryGroupDefinition.registryGroupId(), registryGroupIdDisplayName, configurationList); registryGroupConfigurationList.add(registryConfiguration); }); - registryGroupConfigurationList.sort(new RegistryGroupConfigurationComparator(registryGroupDefinitionHolder.getGroupDisplayOrderList())); + registryGroupConfigurationList.sort(new RegistryGroupConfigurationComparator(registryGroupDefinitionHolder.groupDisplayOrderList())); return registryGroupConfigurationList; } @@ -189,19 +188,19 @@ private List resolveManagedTypePropertyList(Manag private List resolveHistoryPropertyList(RegistryHistoryConfigurationHolder registryHistoryConfiguration) { List historyPropertyList = new ArrayList<>(); - historyPropertyList.add(registryHistoryConfiguration.getRevisionNumberProperty()); - historyPropertyList.add(registryHistoryConfiguration.getRevisionTimestampProperty()); - historyPropertyList.add(registryHistoryConfiguration.getRevisionTypeProperty()); - historyPropertyList.addAll(registryHistoryConfiguration.getRevisionAdditionalPropertyList()); + historyPropertyList.add(registryHistoryConfiguration.revisionNumberProperty()); + historyPropertyList.add(registryHistoryConfiguration.revisionTimestampProperty()); + historyPropertyList.add(registryHistoryConfiguration.revisionTypeProperty()); + historyPropertyList.addAll(registryHistoryConfiguration.revisionAdditionalPropertyList()); return historyPropertyList.stream() .map(propertyWithType -> resolveRegistryPropertyConfiguration( - RegistryConfigurationConstants.REGISTRY_REVISION_ENTITY_PREFIX, propertyWithType.getType(), propertyWithType.getName(), false, false, + RegistryConfigurationConstants.REGISTRY_REVISION_ENTITY_PREFIX, propertyWithType.type(), propertyWithType.name(), false, false, null, true, true, false ) ) - .sorted(new RegistryPropertyComparator(registryHistoryConfiguration.getPropertyDisplayList())) - .collect(Collectors.toList()); + .sorted(new RegistryPropertyComparator(registryHistoryConfiguration.propertyDisplayList())) + .toList(); } private RegistryPropertyConfiguration resolveRegistryPropertyConfiguration(String entityTypePrefix, Class attributeType, String attributeName, boolean isIdAttribute, @@ -267,7 +266,7 @@ private String columnHeader(String entityTypePrefix, Class attributeType, Str } private List labelMessageCodeList(String entityTypePrefix, Class attributeType, String attributeName) { - return Arrays.asList( + return List.of( String.format(RegistryConfigurationConstants.REGISTRY_FIELD_DISPLAY_LABEL_FORMAT, entityTypePrefix, attributeName), String.format(RegistryConfigurationConstants.REGISTRY_FIELD_DISPLAY_LABEL_FORMAT, attributeName, attributeType.getName()), String.format(RegistryConfigurationConstants.REGISTRY_FIELD_DISPLAY_LABEL_SHORT_FORMAT, attributeType.getName()) @@ -294,7 +293,7 @@ private String convertToDisplayValue(String attributeName) { List attributeWordList = Arrays.stream(StringUtils.splitByCharacterTypeCamelCase(attributeName)) .map(value -> value.trim().toLowerCase(Locale.ROOT)) .filter(value -> !RegistryCoreConstants.DOT.equals(value)) - .collect(Collectors.toList()); + .toList(); return StringUtils.capitalize(String.join(RegistryCoreConstants.SPACE, attributeWordList)); } diff --git a/nrich-registry/src/main/java/net/croz/nrich/registry/core/constants/RegistryClassResolvingConstants.java b/nrich-registry/src/main/java/net/croz/nrich/registry/core/constants/RegistryClassResolvingConstants.java index 223ce222f..60b2aaac4 100644 --- a/nrich-registry/src/main/java/net/croz/nrich/registry/core/constants/RegistryClassResolvingConstants.java +++ b/nrich-registry/src/main/java/net/croz/nrich/registry/core/constants/RegistryClassResolvingConstants.java @@ -17,8 +17,6 @@ package net.croz.nrich.registry.core.constants; -import java.util.Arrays; -import java.util.Collections; import java.util.List; public final class RegistryClassResolvingConstants { @@ -39,7 +37,7 @@ public final class RegistryClassResolvingConstants { public static final String PACKAGE_SEPARATOR = "\\."; - public static final List CLASS_NAME_SUFFIX_LIST_TO_REPLACE = Collections.unmodifiableList(Arrays.asList("model", "entity")); + public static final List CLASS_NAME_SUFFIX_LIST_TO_REPLACE = List.of("model", "entity"); private RegistryClassResolvingConstants() { } diff --git a/nrich-registry/src/main/java/net/croz/nrich/registry/core/model/PropertyWithType.java b/nrich-registry/src/main/java/net/croz/nrich/registry/core/model/PropertyWithType.java index fcc65fbae..f55df850c 100644 --- a/nrich-registry/src/main/java/net/croz/nrich/registry/core/model/PropertyWithType.java +++ b/nrich-registry/src/main/java/net/croz/nrich/registry/core/model/PropertyWithType.java @@ -17,17 +17,6 @@ package net.croz.nrich.registry.core.model; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - -@RequiredArgsConstructor -@Getter -public class PropertyWithType { - - private final String name; - - private final String originalName; - - private final Class type; +public record PropertyWithType(String name, String originalName, Class type) { } diff --git a/nrich-registry/src/main/java/net/croz/nrich/registry/core/model/RegistryDataConfiguration.java b/nrich-registry/src/main/java/net/croz/nrich/registry/core/model/RegistryDataConfiguration.java index 2eef5dc2f..bc6f793f8 100644 --- a/nrich-registry/src/main/java/net/croz/nrich/registry/core/model/RegistryDataConfiguration.java +++ b/nrich-registry/src/main/java/net/croz/nrich/registry/core/model/RegistryDataConfiguration.java @@ -17,18 +17,10 @@ package net.croz.nrich.registry.core.model; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.search.api.model.SearchConfiguration; import java.util.Map; -@RequiredArgsConstructor -@Getter -public class RegistryDataConfiguration { - - private final Class registryType; - - private final SearchConfiguration> searchConfiguration; +public record RegistryDataConfiguration(Class registryType, SearchConfiguration> searchConfiguration) { } diff --git a/nrich-registry/src/main/java/net/croz/nrich/registry/core/model/RegistryDataConfigurationHolder.java b/nrich-registry/src/main/java/net/croz/nrich/registry/core/model/RegistryDataConfigurationHolder.java index 126e17612..4cded7fb5 100644 --- a/nrich-registry/src/main/java/net/croz/nrich/registry/core/model/RegistryDataConfigurationHolder.java +++ b/nrich-registry/src/main/java/net/croz/nrich/registry/core/model/RegistryDataConfigurationHolder.java @@ -17,20 +17,12 @@ package net.croz.nrich.registry.core.model; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.registry.core.support.ManagedTypeWrapper; import java.util.List; import java.util.Map; -@RequiredArgsConstructor -@Getter -public class RegistryDataConfigurationHolder { - - private final Map classNameManagedTypeWrapperMap; - - private final List> registryDataConfigurationList; +public record RegistryDataConfigurationHolder(Map classNameManagedTypeWrapperMap, List> registryDataConfigurationList) { public void verifyConfigurationExists(String classFullName) { findRegistryConfigurationForClass(classFullName); @@ -38,7 +30,7 @@ public void verifyConfigurationExists(String classFullName) { public RegistryDataConfiguration findRegistryConfigurationForClass(String classFullName) { return registryDataConfigurationList.stream() - .filter(configuration -> configuration.getRegistryType().getName().equals(classFullName)) + .filter(configuration -> configuration.registryType().getName().equals(classFullName)) .findFirst() .orElseThrow(() -> new IllegalArgumentException(String.format("Configuration for registry entity %s is not defined!", classFullName))); } diff --git a/nrich-registry/src/main/java/net/croz/nrich/registry/core/model/RegistryGroupDefinition.java b/nrich-registry/src/main/java/net/croz/nrich/registry/core/model/RegistryGroupDefinition.java index e4f9b44da..39bf82a47 100644 --- a/nrich-registry/src/main/java/net/croz/nrich/registry/core/model/RegistryGroupDefinition.java +++ b/nrich-registry/src/main/java/net/croz/nrich/registry/core/model/RegistryGroupDefinition.java @@ -17,18 +17,10 @@ package net.croz.nrich.registry.core.model; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.registry.core.support.ManagedTypeWrapper; import java.util.List; -@RequiredArgsConstructor -@Getter -public class RegistryGroupDefinition { - - private final String registryGroupId; - - private final List registryEntityList; +public record RegistryGroupDefinition(String registryGroupId, List registryEntityList) { } diff --git a/nrich-registry/src/main/java/net/croz/nrich/registry/core/model/RegistryGroupDefinitionHolder.java b/nrich-registry/src/main/java/net/croz/nrich/registry/core/model/RegistryGroupDefinitionHolder.java index d5a5d1e9f..f98397cf7 100644 --- a/nrich-registry/src/main/java/net/croz/nrich/registry/core/model/RegistryGroupDefinitionHolder.java +++ b/nrich-registry/src/main/java/net/croz/nrich/registry/core/model/RegistryGroupDefinitionHolder.java @@ -17,17 +17,8 @@ package net.croz.nrich.registry.core.model; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - import java.util.List; -@RequiredArgsConstructor -@Getter -public class RegistryGroupDefinitionHolder { - - private final List groupDefinitionList; - - private final List groupDisplayOrderList; +public record RegistryGroupDefinitionHolder(List groupDefinitionList, List groupDisplayOrderList) { } diff --git a/nrich-registry/src/main/java/net/croz/nrich/registry/core/model/RegistryHistoryConfigurationHolder.java b/nrich-registry/src/main/java/net/croz/nrich/registry/core/model/RegistryHistoryConfigurationHolder.java index f33c7c6f8..e03ab7bbe 100644 --- a/nrich-registry/src/main/java/net/croz/nrich/registry/core/model/RegistryHistoryConfigurationHolder.java +++ b/nrich-registry/src/main/java/net/croz/nrich/registry/core/model/RegistryHistoryConfigurationHolder.java @@ -17,23 +17,9 @@ package net.croz.nrich.registry.core.model; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - import java.util.List; -@RequiredArgsConstructor -@Getter -public class RegistryHistoryConfigurationHolder { - - private final PropertyWithType revisionNumberProperty; - - private final PropertyWithType revisionTimestampProperty; - - private final PropertyWithType revisionTypeProperty; - - private final List revisionAdditionalPropertyList; - - private final List propertyDisplayList; +public record RegistryHistoryConfigurationHolder(PropertyWithType revisionNumberProperty, PropertyWithType revisionTimestampProperty, PropertyWithType revisionTypeProperty, + List revisionAdditionalPropertyList, List propertyDisplayList) { } diff --git a/nrich-registry/src/main/java/net/croz/nrich/registry/core/service/DefaultRegistryClassResolvingService.java b/nrich-registry/src/main/java/net/croz/nrich/registry/core/service/DefaultRegistryClassResolvingService.java index 134b4d488..53d015dbb 100644 --- a/nrich-registry/src/main/java/net/croz/nrich/registry/core/service/DefaultRegistryClassResolvingService.java +++ b/nrich-registry/src/main/java/net/croz/nrich/registry/core/service/DefaultRegistryClassResolvingService.java @@ -25,7 +25,6 @@ import org.springframework.cache.annotation.Cacheable; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; @@ -70,7 +69,7 @@ public Class resolveUpdateClass(String registryClassName) { } private Class resolveClassByPackage(String registryFullClassName, String requestClassNameFormat) { - List registryClassNameList = new ArrayList<>(Arrays.asList(registryFullClassName.split(RegistryClassResolvingConstants.PACKAGE_SEPARATOR))); + List registryClassNameList = new ArrayList<>(List.of(registryFullClassName.split(RegistryClassResolvingConstants.PACKAGE_SEPARATOR))); int indexOfLastPackage = registryClassNameList.size() - 2; if (RegistryClassResolvingConstants.CLASS_NAME_SUFFIX_LIST_TO_REPLACE.contains(registryClassNameList.get(indexOfLastPackage))) { @@ -85,7 +84,7 @@ private Class resolveClassByPackage(String registryFullClassName, String requ } private Class resolveClass(String fullClassName, String fullClassNameWithRequestPackage, String requestClassNameFormat) { - List classNameList = Arrays.asList( + List classNameList = List.of( String.format(requestClassNameFormat, fullClassNameWithRequestPackage), String.format(RegistryClassResolvingConstants.REQUEST_CLASS_NAME_FORMAT, fullClassNameWithRequestPackage), String.format(requestClassNameFormat, fullClassName), diff --git a/nrich-registry/src/main/java/net/croz/nrich/registry/core/service/DefaultRegistryConfigurationResolverService.java b/nrich-registry/src/main/java/net/croz/nrich/registry/core/service/DefaultRegistryConfigurationResolverService.java index 4776f0566..7d8b114ab 100644 --- a/nrich-registry/src/main/java/net/croz/nrich/registry/core/service/DefaultRegistryConfigurationResolverService.java +++ b/nrich-registry/src/main/java/net/croz/nrich/registry/core/service/DefaultRegistryConfigurationResolverService.java @@ -70,7 +70,7 @@ public RegistryGroupDefinitionHolder resolveRegistryGroupDefinition() { List includedManagedTypeList = managedTypeList.stream() .filter(managedType -> includeManagedType(managedType, registryGroupDefinition.getIncludeEntityPatternList(), registryGroupDefinition.getExcludeEntityPatternList())) .map(ManagedTypeWrapper::new) - .collect(Collectors.toList()); + .toList(); if (CollectionUtils.isEmpty(includedManagedTypeList)) { return; @@ -94,10 +94,10 @@ public Map, RegistryOverrideConfiguration> resolveRegistryOverrideConfi public RegistryDataConfigurationHolder resolveRegistryDataConfiguration() { RegistryGroupDefinitionHolder groupDefinitionHolder = resolveRegistryGroupDefinition(); - List managedTypeWrapperList = groupDefinitionHolder.getGroupDefinitionList().stream() - .map(RegistryGroupDefinition::getRegistryEntityList) + List managedTypeWrapperList = groupDefinitionHolder.groupDefinitionList().stream() + .map(RegistryGroupDefinition::registryEntityList) .flatMap(List::stream) - .collect(Collectors.toList()); + .toList(); List> registryDataConfigurationList = new ArrayList<>(); @@ -135,12 +135,10 @@ public RegistryHistoryConfigurationHolder resolveRegistryHistoryConfiguration() String attributeName = attribute.getName(); Class attributeType = attribute.getJavaType(); - if (!(attribute.getJavaMember() instanceof Field)) { + if (!(attribute.getJavaMember() instanceof Field attributeField)) { continue; } - Field attributeField = (Field) attribute.getJavaMember(); - if (AnnotationUtil.isAnnotationPresent(attributeField, RegistryEnversConstants.ENVERS_REVISION_NUMBER_ANNOTATION)) { revisionNumberPropertyName = attributeName; revisionNumberPropertyType = attributeType; @@ -195,7 +193,7 @@ private SearchConfiguration> emptySearchConf List>> searchJoinList = Stream.concat( createSearchJoinStreamFromAssociationList(managedTypeWrapper.getSingularAssociationList(), RegistryCoreConstants.BLANK), createSearchJoinStreamFromAssociationList(managedTypeWrapper.getSingularEmbeddedTypeAssociationList(), managedTypeWrapper.getIdAttributeName() + RegistryCoreConstants.DOT)) - .collect(Collectors.toList()); + .toList(); searchConfiguration.setJoinList(searchJoinList); @@ -204,6 +202,6 @@ private SearchConfiguration> emptySearchConf private Stream>> createSearchJoinStreamFromAssociationList(List associationList, String prefix) { return associationList.stream() - .map(attribute -> attribute.isOptional() ? SearchJoin.leftJoinFetch(prefix + attribute.getPath()) : SearchJoin.innerJoinFetch(prefix + attribute.getPath())); + .map(attribute -> attribute.optional() ? SearchJoin.leftJoinFetch(prefix + attribute.path()) : SearchJoin.innerJoinFetch(prefix + attribute.path())); } } diff --git a/nrich-registry/src/main/java/net/croz/nrich/registry/core/service/EntityManagerRegistryEntityFinderService.java b/nrich-registry/src/main/java/net/croz/nrich/registry/core/service/EntityManagerRegistryEntityFinderService.java index 44beec3de..c350f56a7 100644 --- a/nrich-registry/src/main/java/net/croz/nrich/registry/core/service/EntityManagerRegistryEntityFinderService.java +++ b/nrich-registry/src/main/java/net/croz/nrich/registry/core/service/EntityManagerRegistryEntityFinderService.java @@ -17,7 +17,6 @@ package net.croz.nrich.registry.core.service; -import lombok.Getter; import lombok.RequiredArgsConstructor; import net.croz.nrich.registry.api.core.service.RegistryEntityFinderService; import net.croz.nrich.registry.core.constants.RegistryQueryConstants; @@ -126,13 +125,7 @@ private String toParameterVariable(String key, boolean convertParameterToQueryFo .collect(Collectors.joining()); } - @RequiredArgsConstructor - @Getter - private static class QueryCondition { - - private final String wherePart; - - private final Map parameterMap; + private record QueryCondition(String wherePart, Map parameterMap) { } } diff --git a/nrich-registry/src/main/java/net/croz/nrich/registry/core/support/ManagedTypeWrapper.java b/nrich-registry/src/main/java/net/croz/nrich/registry/core/support/ManagedTypeWrapper.java index d70fca2c6..5fac9a48d 100644 --- a/nrich-registry/src/main/java/net/croz/nrich/registry/core/support/ManagedTypeWrapper.java +++ b/nrich-registry/src/main/java/net/croz/nrich/registry/core/support/ManagedTypeWrapper.java @@ -79,7 +79,7 @@ public Class getJavaType() { } private EmbeddableType resolveEmbeddedIdentifierType(IdentifiableType identifiableType) { - return identifiableType.getIdType() instanceof EmbeddableType ? (EmbeddableType) identifiableType.getIdType() : null; + return identifiableType.getIdType() instanceof EmbeddableType embeddableType ? embeddableType : null; } private String resolveIdAttributeName(IdentifiableType identifiableType) { @@ -109,9 +109,10 @@ private List resolveSingularAssociationList(ManagedType } private void resolveSingularAssociationList(ManagedType managedType, Boolean isCurrentAssociationPathOptional, String currentPrefix, Map singularAssociationMap) { - List> currentAssociations = managedType.getSingularAttributes().stream() + @SuppressWarnings("unchecked") + List> currentAssociations = (List>) managedType.getSingularAttributes().stream() .filter(Attribute::isAssociation) - .collect(Collectors.toList()); + .toList(); for (SingularAttribute association : currentAssociations) { String associationName = currentPrefix == null ? association.getName() : String.format(RegistryCoreConstants.PREFIX_FORMAT, currentPrefix, association.getName()); diff --git a/nrich-registry/src/main/java/net/croz/nrich/registry/core/support/SingularAssociation.java b/nrich-registry/src/main/java/net/croz/nrich/registry/core/support/SingularAssociation.java index 42196ddfd..edc7a3ff4 100644 --- a/nrich-registry/src/main/java/net/croz/nrich/registry/core/support/SingularAssociation.java +++ b/nrich-registry/src/main/java/net/croz/nrich/registry/core/support/SingularAssociation.java @@ -17,15 +17,6 @@ package net.croz.nrich.registry.core.support; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - -@Getter -@RequiredArgsConstructor -public class SingularAssociation { - - private final String path; - - private final boolean optional; +public record SingularAssociation(String path, boolean optional) { } diff --git a/nrich-registry/src/main/java/net/croz/nrich/registry/data/controller/RegistryDataController.java b/nrich-registry/src/main/java/net/croz/nrich/registry/data/controller/RegistryDataController.java index c1d72fec5..0bd16c431 100644 --- a/nrich-registry/src/main/java/net/croz/nrich/registry/data/controller/RegistryDataController.java +++ b/nrich-registry/src/main/java/net/croz/nrich/registry/data/controller/RegistryDataController.java @@ -62,7 +62,7 @@ public

Page

list(@RequestBody @Valid ListRegistryRequest request) { @PostMapping("delete") public void delete(@RequestBody @Valid DeleteRegistryRequest request) { - registryDataService.delete(request.getClassFullName(), request.getId()); + registryDataService.delete(request.classFullName(), request.id()); } @PostMapping("create") @@ -71,7 +71,7 @@ public T create(@RequestBody @Valid CreateRegistryRequest request) { validateEntityData(entityData); - return registryDataService.create(request.getClassFullName(), entityData); + return registryDataService.create(request.classFullName(), entityData); } @PostMapping("update") @@ -80,7 +80,7 @@ public T update(@RequestBody @Valid UpdateRegistryRequest request) { validateEntityData(entityData); - return registryDataService.update(request.getClassFullName(), request.getId(), entityData); + return registryDataService.update(request.classFullName(), request.id(), entityData); } @SneakyThrows diff --git a/nrich-registry/src/main/java/net/croz/nrich/registry/data/request/CreateRegistryRequest.java b/nrich-registry/src/main/java/net/croz/nrich/registry/data/request/CreateRegistryRequest.java index d3a2f9690..feda1fdc9 100644 --- a/nrich-registry/src/main/java/net/croz/nrich/registry/data/request/CreateRegistryRequest.java +++ b/nrich-registry/src/main/java/net/croz/nrich/registry/data/request/CreateRegistryRequest.java @@ -17,19 +17,8 @@ package net.croz.nrich.registry.data.request; -import lombok.Getter; -import lombok.Setter; - import jakarta.validation.constraints.NotNull; -@Setter -@Getter -public class CreateRegistryRequest { - - @NotNull - private String classFullName; - - @NotNull - private String jsonEntityData; +public record CreateRegistryRequest(@NotNull String classFullName, @NotNull String jsonEntityData) { } diff --git a/nrich-registry/src/main/java/net/croz/nrich/registry/data/request/DeleteRegistryRequest.java b/nrich-registry/src/main/java/net/croz/nrich/registry/data/request/DeleteRegistryRequest.java index 94ea0c7a2..1fa65534c 100644 --- a/nrich-registry/src/main/java/net/croz/nrich/registry/data/request/DeleteRegistryRequest.java +++ b/nrich-registry/src/main/java/net/croz/nrich/registry/data/request/DeleteRegistryRequest.java @@ -17,28 +17,14 @@ package net.croz.nrich.registry.data.request; -import lombok.Getter; -import lombok.Setter; - import jakarta.validation.constraints.NotNull; /** * Request holding data for registry entity deletion. + * + * @param classFullName Class name of registry entity. + * @param id Registry entity id. */ -@Setter -@Getter -public class DeleteRegistryRequest { - - /** - * Class name of registry entity. - */ - @NotNull - private String classFullName; - - /** - * Registry entity id. - */ - @NotNull - private Object id; +public record DeleteRegistryRequest(@NotNull String classFullName, @NotNull Object id) { } diff --git a/nrich-registry/src/main/java/net/croz/nrich/registry/data/request/UpdateRegistryRequest.java b/nrich-registry/src/main/java/net/croz/nrich/registry/data/request/UpdateRegistryRequest.java index 33b79cd9a..bb783e1b3 100644 --- a/nrich-registry/src/main/java/net/croz/nrich/registry/data/request/UpdateRegistryRequest.java +++ b/nrich-registry/src/main/java/net/croz/nrich/registry/data/request/UpdateRegistryRequest.java @@ -17,22 +17,8 @@ package net.croz.nrich.registry.data.request; -import lombok.Getter; -import lombok.Setter; - import jakarta.validation.constraints.NotNull; -@Setter -@Getter -public class UpdateRegistryRequest { - - @NotNull - private String classFullName; - - @NotNull - private Object id; - - @NotNull - private String jsonEntityData; +public record UpdateRegistryRequest(@NotNull String classFullName, @NotNull Object id, @NotNull String jsonEntityData) { } diff --git a/nrich-registry/src/main/java/net/croz/nrich/registry/data/service/DefaultRegistryDataRequestConversionService.java b/nrich-registry/src/main/java/net/croz/nrich/registry/data/service/DefaultRegistryDataRequestConversionService.java index f566c9776..86ca5a319 100644 --- a/nrich-registry/src/main/java/net/croz/nrich/registry/data/service/DefaultRegistryDataRequestConversionService.java +++ b/nrich-registry/src/main/java/net/croz/nrich/registry/data/service/DefaultRegistryDataRequestConversionService.java @@ -33,16 +33,16 @@ public class DefaultRegistryDataRequestConversionService implements RegistryData @Override public Object convertEntityDataToTyped(CreateRegistryRequest request) { - Class type = registryClassResolvingService.resolveCreateClass(request.getClassFullName()); + Class type = registryClassResolvingService.resolveCreateClass(request.classFullName()); - return convertStringToInstance(request.getJsonEntityData(), type); + return convertStringToInstance(request.jsonEntityData(), type); } @Override public Object convertEntityDataToTyped(UpdateRegistryRequest request) { - Class type = registryClassResolvingService.resolveUpdateClass(request.getClassFullName()); + Class type = registryClassResolvingService.resolveUpdateClass(request.classFullName()); - return convertStringToInstance(request.getJsonEntityData(), type); + return convertStringToInstance(request.jsonEntityData(), type); } @SneakyThrows diff --git a/nrich-registry/src/main/java/net/croz/nrich/registry/data/service/DefaultRegistryDataService.java b/nrich-registry/src/main/java/net/croz/nrich/registry/data/service/DefaultRegistryDataService.java index 380e8c006..102208f51 100644 --- a/nrich-registry/src/main/java/net/croz/nrich/registry/data/service/DefaultRegistryDataService.java +++ b/nrich-registry/src/main/java/net/croz/nrich/registry/data/service/DefaultRegistryDataService.java @@ -81,8 +81,8 @@ public DefaultRegistryDataService(EntityManager entityManager, ModelMapper model @Transactional(readOnly = true) @Override public Map> listBulk(ListBulkRegistryRequest request) { - return request.getRegistryRequestList().stream() - .collect(Collectors.toMap(ListRegistryRequest::getClassFullName, this::list)); + return request.registryRequestList().stream() + .collect(Collectors.toMap(ListRegistryRequest::classFullName, this::list)); } @Transactional(readOnly = true) @@ -101,7 +101,7 @@ public T create(String classFullName, Object entityData) { @SuppressWarnings("unchecked") RegistryDataConfiguration registryDataConfiguration = (RegistryDataConfiguration) registryDataConfigurationHolder.findRegistryConfigurationForClass(classFullName); - T instance = resolveEntityInstance(registryDataConfiguration.getRegistryType(), entityData); + T instance = resolveEntityInstance(registryDataConfiguration.registryType(), entityData); modelMapper.map(entityData, instance); @@ -118,11 +118,11 @@ public T update(String classFullName, Object id, Object entityData) { ManagedTypeWrapper wrapper = registryDataConfigurationHolder.resolveManagedTypeWrapper(classFullName); - T instance = registryEntityFinderService.findEntityInstance(registryDataConfiguration.getRegistryType(), id); + T instance = registryEntityFinderService.findEntityInstance(registryDataConfiguration.registryType(), id); if (wrapper.isIdClassIdentifier() || wrapper.isEmbeddedIdentifier()) { entityManager.remove(instance); - instance = resolveEntityInstance(registryDataConfiguration.getRegistryType(), entityData); + instance = resolveEntityInstance(registryDataConfiguration.registryType(), entityData); } else { setIdFieldToOriginalValue(wrapper, entityData, id); @@ -141,7 +141,7 @@ public T delete(String classFullName, Object id) { @SuppressWarnings("unchecked") RegistryDataConfiguration registryDataConfiguration = (RegistryDataConfiguration) registryDataConfigurationHolder.findRegistryConfigurationForClass(classFullName); - T instance = registryEntityFinderService.findEntityInstance(registryDataConfiguration.getRegistryType(), id); + T instance = registryEntityFinderService.findEntityInstance(registryDataConfiguration.registryType(), id); entityManager.remove(instance); @@ -149,9 +149,9 @@ public T delete(String classFullName, Object id) { } private Map> initializeQueryBuilderMap(RegistryDataConfigurationHolder registryDataConfigurationHolder) { - return registryDataConfigurationHolder.getRegistryDataConfigurationList().stream() - .collect(Collectors.toMap(registryDataConfiguration -> registryDataConfiguration.getRegistryType().getName(), - registryDataConfiguration -> new JpaQueryBuilder<>(entityManager, registryDataConfiguration.getRegistryType())) + return registryDataConfigurationHolder.registryDataConfigurationList().stream() + .collect(Collectors.toMap(registryDataConfiguration -> registryDataConfiguration.registryType().getName(), + registryDataConfiguration -> new JpaQueryBuilder<>(entityManager, registryDataConfiguration.registryType())) ); } @@ -161,17 +161,17 @@ private List interceptorList() { private Page

registryListInternal(ListRegistryRequest request) { @SuppressWarnings("unchecked") - RegistryDataConfiguration registryDataConfiguration = (RegistryDataConfiguration) registryDataConfigurationHolder.findRegistryConfigurationForClass(request.getClassFullName()); - SearchConfiguration> searchConfiguration = registryDataConfiguration.getSearchConfiguration(); + RegistryDataConfiguration registryDataConfiguration = (RegistryDataConfiguration) registryDataConfigurationHolder.findRegistryConfigurationForClass(request.classFullName()); + SearchConfiguration> searchConfiguration = registryDataConfiguration.searchConfiguration(); @SuppressWarnings("unchecked") - JpaQueryBuilder queryBuilder = (JpaQueryBuilder) classNameQueryBuilderMap.get(request.getClassFullName()); + JpaQueryBuilder queryBuilder = (JpaQueryBuilder) classNameQueryBuilderMap.get(request.classFullName()); - ManagedTypeWrapper managedTypeWrapper = registryDataConfigurationHolder.resolveManagedTypeWrapper(request.getClassFullName()); + ManagedTypeWrapper managedTypeWrapper = registryDataConfigurationHolder.resolveManagedTypeWrapper(request.classFullName()); String idAttributeName = Optional.ofNullable(managedTypeWrapper.getIdAttributeName()).orElseGet(() -> managedTypeWrapper.getIdClassPropertyNameList().get(0)); - Pageable pageable = PageableUtil.convertToPageable(request.getPageNumber(), request.getPageSize(), new SortProperty(idAttributeName, SortDirection.ASC), request.getSortPropertyList()); + Pageable pageable = PageableUtil.convertToPageable(request.pageNumber(), request.pageSize(), new SortProperty(idAttributeName, SortDirection.ASC), request.sortPropertyList()); Map searchRequestMap = resolveSearchRequestMap(managedTypeWrapper, request, searchConfiguration.getSearchPropertyConfiguration()); CriteriaQuery

query = queryBuilder.buildQuery(searchRequestMap, searchConfiguration, pageable.getSort()); @@ -185,9 +185,9 @@ private Page

registryListInternal(ListRegistryRequest request) { private Map resolveSearchRequestMap(ManagedTypeWrapper managedTypeWrapper, ListRegistryRequest request, SearchPropertyConfiguration searchPropertyConfiguration) { Map searchRequestMap = Collections.emptyMap(); - if (request.getSearchParameter() != null) { + if (request.searchParameter() != null) { searchRequestMap = stringToEntityPropertyMapConverter.convert( - request.getSearchParameter().getQuery(), request.getSearchParameter().getPropertyNameList(), managedTypeWrapper.getIdentifiableType(), + request.searchParameter().query(), request.searchParameter().propertyNameList(), managedTypeWrapper.getIdentifiableType(), searchPropertyConfiguration ); } diff --git a/nrich-registry/src/main/java/net/croz/nrich/registry/enumdata/service/DefaultRegistryEnumService.java b/nrich-registry/src/main/java/net/croz/nrich/registry/enumdata/service/DefaultRegistryEnumService.java index 61f8e77d0..f595767a2 100644 --- a/nrich-registry/src/main/java/net/croz/nrich/registry/enumdata/service/DefaultRegistryEnumService.java +++ b/nrich-registry/src/main/java/net/croz/nrich/registry/enumdata/service/DefaultRegistryEnumService.java @@ -52,17 +52,17 @@ public class DefaultRegistryEnumService implements RegistryEnumService { @Override public Map> listBulk(ListBulkRegistryEnumRequest request) { - return request.getRegistryRequestList().stream().collect(Collectors.toMap(ListRegistryEnumRequest::getClassFullName, this::list)); + return request.registryRequestList().stream().collect(Collectors.toMap(ListRegistryEnumRequest::classFullName, this::list)); } @Override public List list(ListRegistryEnumRequest request) { - boolean isEmptyQuery = !StringUtils.hasText(request.getQuery()); - List enumResults = loadEnumRegistry(request.getClassFullName(), LocaleContextHolder.getLocale()); + boolean isEmptyQuery = !StringUtils.hasText(request.query()); + List enumResults = loadEnumRegistry(request.classFullName(), LocaleContextHolder.getLocale()); List foundEnums = new ArrayList<>(); enumResults.forEach(enumResult -> { - if (isEmptyQuery || enumResult.getDescription().toLowerCase().contains(request.getQuery().toLowerCase())) { + if (isEmptyQuery || enumResult.description().toLowerCase().contains(request.query().toLowerCase())) { foundEnums.add(enumResult); } }); diff --git a/nrich-registry/src/main/java/net/croz/nrich/registry/history/service/DefaultRegistryHistoryService.java b/nrich-registry/src/main/java/net/croz/nrich/registry/history/service/DefaultRegistryHistoryService.java index b437a6470..1554f8b8d 100644 --- a/nrich-registry/src/main/java/net/croz/nrich/registry/history/service/DefaultRegistryHistoryService.java +++ b/nrich-registry/src/main/java/net/croz/nrich/registry/history/service/DefaultRegistryHistoryService.java @@ -84,36 +84,36 @@ public DefaultRegistryHistoryService(EntityManager entityManager, RegistryDataCo public Page> historyList(ListRegistryHistoryRequest request) { AuditQuery auditQuery = createAuditQuery(request); - addOrder(auditQuery, request.getSortPropertyList()); + addOrder(auditQuery, request.sortPropertyList()); List resultList = auditQuery - .setFirstResult(request.getPageNumber()) - .setMaxResults(request.getPageSize()).getResultList(); + .setFirstResult(request.pageNumber()) + .setMaxResults(request.pageSize()).getResultList(); List> entityWithRevisionList = convertToEntityRevisionList(resultList); - Pageable pageable = PageableUtil.convertToPageable(request.getPageNumber(), request.getPageSize()); + Pageable pageable = PageableUtil.convertToPageable(request.pageNumber(), request.pageSize()); return PageableExecutionUtils.getPage(entityWithRevisionList, pageable, () -> executeCountQuery(createAuditQuery(request))); } private Map, ManagedType> initializeManagedTypeMap(RegistryDataConfigurationHolder registryDataConfigurationHolder) { - if (registryDataConfigurationHolder.getRegistryDataConfigurationList() == null) { + if (registryDataConfigurationHolder.registryDataConfigurationList() == null) { return Collections.emptyMap(); } - return registryDataConfigurationHolder.getRegistryDataConfigurationList().stream() - .collect(Collectors.toMap(RegistryDataConfiguration::getRegistryType, registryDataConfiguration -> entityManager.getMetamodel().managedType(registryDataConfiguration.getRegistryType()))); + return registryDataConfigurationHolder.registryDataConfigurationList().stream() + .collect(Collectors.toMap(RegistryDataConfiguration::registryType, registryDataConfiguration -> entityManager.getMetamodel().managedType(registryDataConfiguration.registryType()))); } private AuditQuery createAuditQuery(ListRegistryHistoryRequest request) { @SuppressWarnings("unchecked") - Class type = (Class) registryDataConfigurationHolder.findRegistryConfigurationForClass(request.getClassFullName()).getRegistryType(); + Class type = (Class) registryDataConfigurationHolder.findRegistryConfigurationForClass(request.classFullName()).registryType(); AuditQuery auditQuery = AuditReaderFactory.get(entityManager).createQuery().forRevisionsOfEntity(type, false, true); - if (request.getRegistryRecordId() != null) { - addIdCondition(type, auditQuery, request.getRegistryRecordId()); + if (request.registryRecordId() != null) { + addIdCondition(type, auditQuery, request.registryRecordId()); } return auditQuery; @@ -131,7 +131,7 @@ private List> convertToEntityRevisionList(List resu return Optional.ofNullable(objectResultList).orElse(Collections.emptyList()).stream() .map(value -> new EntityWithRevision<>(initializeEntitySingularAssociations((T) value[0]), convertToRevisionInfo(value[1], (RevisionType) value[2]))) - .collect(Collectors.toList()); + .toList(); } private void addIdCondition(Class type, AuditQuery auditQuery, Object id) { @@ -173,10 +173,10 @@ else if (RegistryEnversConstants.REVISION_TYPE_PROPERTY_NAME.equals(sortProperty auditProperty = AuditEntity.revisionType(); } else if (RegistryEnversConstants.REVISION_TIMESTAMP_PROPERTY_NAME.equals(sortProperty)) { - auditProperty = AuditEntity.revisionProperty(registryHistoryConfigurationHolder.getRevisionTimestampProperty().getOriginalName()); + auditProperty = AuditEntity.revisionProperty(registryHistoryConfigurationHolder.revisionTimestampProperty().originalName()); } else if (revisionProperty != null) { - auditProperty = AuditEntity.revisionProperty(revisionProperty.getOriginalName()); + auditProperty = AuditEntity.revisionProperty(revisionProperty.originalName()); } else { auditProperty = AuditEntity.property(sortProperty); @@ -188,15 +188,15 @@ else if (revisionProperty != null) { private RevisionInfo convertToRevisionInfo(Object revisionEntity, RevisionType revisionType) { MapSupportingDirectFieldAccessFallbackBeanWrapper directFieldAccessFallbackBeanWrapper = new MapSupportingDirectFieldAccessFallbackBeanWrapper(revisionEntity); - Object revisionNumber = directFieldAccessFallbackBeanWrapper.getPropertyValue(registryHistoryConfigurationHolder.getRevisionNumberProperty().getOriginalName()); - Object revisionDate = directFieldAccessFallbackBeanWrapper.getPropertyValue(registryHistoryConfigurationHolder.getRevisionTimestampProperty().getOriginalName()); + Object revisionNumber = directFieldAccessFallbackBeanWrapper.getPropertyValue(registryHistoryConfigurationHolder.revisionNumberProperty().originalName()); + Object revisionDate = directFieldAccessFallbackBeanWrapper.getPropertyValue(registryHistoryConfigurationHolder.revisionTimestampProperty().originalName()); Assert.isTrue(revisionNumber != null && revisionDate != null, "Revision number or revision date are empty!"); - Instant revisionDateAsInstant = revisionDate instanceof Long ? Instant.ofEpochMilli((long) revisionDate) : ((Date) revisionDate).toInstant(); + Instant revisionDateAsInstant = revisionDate instanceof Long revisionDateMillis ? Instant.ofEpochMilli(revisionDateMillis) : ((Date) revisionDate).toInstant(); - Map additionalRevisionPropertyMap = registryHistoryConfigurationHolder.getRevisionAdditionalPropertyList().stream() - .collect(Collectors.toMap(PropertyWithType::getName, propertyWithType -> directFieldAccessFallbackBeanWrapper.getPropertyValue(propertyWithType.getOriginalName()))); + Map additionalRevisionPropertyMap = registryHistoryConfigurationHolder.revisionAdditionalPropertyList().stream() + .collect(Collectors.toMap(PropertyWithType::name, propertyWithType -> directFieldAccessFallbackBeanWrapper.getPropertyValue(propertyWithType.originalName()))); return new RevisionInfo(Long.valueOf(revisionNumber.toString()), revisionDateAsInstant, revisionType.name(), additionalRevisionPropertyMap); } @@ -226,8 +226,8 @@ private T initializeEntitySingularAssociations(T entity) { } private PropertyWithType findByName(String name) { - return registryHistoryConfigurationHolder.getRevisionAdditionalPropertyList().stream() - .filter(value -> name.equals(value.getName())) + return registryHistoryConfigurationHolder.revisionAdditionalPropertyList().stream() + .filter(value -> name.equals(value.name())) .findFirst() .orElse(null); } diff --git a/nrich-registry/src/test/java/net/croz/nrich/registry/RegistryTestConfiguration.java b/nrich-registry/src/test/java/net/croz/nrich/registry/RegistryTestConfiguration.java index 44577eb97..09a7182fd 100644 --- a/nrich-registry/src/test/java/net/croz/nrich/registry/RegistryTestConfiguration.java +++ b/nrich-registry/src/test/java/net/croz/nrich/registry/RegistryTestConfiguration.java @@ -88,7 +88,6 @@ import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; import javax.sql.DataSource; -import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; @@ -173,8 +172,8 @@ public RegistryWebMvcTestConfiguration registryWebMvcConfiguration(ObjectMapper @Bean public StringToTypeConverter defaultStringToTypeConverter() { - List dateFormatList = Arrays.asList("dd.MM.yyyy.", "dd.MM.yyyy.'T'HH:mm", "dd.MM.yyyy.'T'HH:mm'Z'"); - List decimalFormatList = Arrays.asList("#0.00", "#0,00"); + List dateFormatList = List.of("dd.MM.yyyy.", "dd.MM.yyyy.'T'HH:mm", "dd.MM.yyyy.'T'HH:mm'Z'"); + List decimalFormatList = List.of("#0.00", "#0,00"); String booleanTrueRegexPattern = "^(?i)\\s*(true|yes)\\s*$"; String booleanFalseRegexPattern = "^(?i)\\s*(false|no)\\s*$"; @@ -191,7 +190,7 @@ public RegistryConfiguration registryConfiguration() { RegistryConfiguration registryConfiguration = new RegistryConfiguration(); registryConfiguration.setGroupDefinitionConfigurationList(createRegistryGroupDefinitionConfigurationList()); - registryConfiguration.setGroupDisplayOrderList(Arrays.asList("CONFIGURATION", "DATA", "HISTORY")); + registryConfiguration.setGroupDisplayOrderList(List.of("CONFIGURATION", "DATA", "HISTORY")); registryConfiguration.setOverrideConfigurationHolderList(createRegistryOverrideConfigurationList()); @@ -210,13 +209,13 @@ public RegistryConfigurationUpdateInterceptor registryConfigurationUpdateInterce @Bean public JavaToJavascriptTypeConversionService javaToJavascriptTypeConversionService() { - return new DefaultJavaToJavascriptTypeConversionService(Collections.singletonList(new DefaultJavaToJavascriptTypeConverter())); + return new DefaultJavaToJavascriptTypeConversionService(List.of(new DefaultJavaToJavascriptTypeConverter())); } @Bean public RegistryConfigurationService registryConfigurationService(MessageSource messageSource, RegistryConfigurationResolverService registryConfigurationResolverService, JavaToJavascriptTypeConversionService javaToJavascriptTypeConversionService) { - List defaultReadOnlyPropertyList = Arrays.asList("id", "version"); + List defaultReadOnlyPropertyList = List.of("id", "version"); RegistryGroupDefinitionHolder registryGroupDefinitionHolder = registryConfigurationResolverService.resolveRegistryGroupDefinition(); RegistryHistoryConfigurationHolder registryHistoryConfigurationHolder = registryConfigurationResolverService.resolveRegistryHistoryConfiguration(); Map, RegistryOverrideConfiguration> registryOverrideConfigurationMap = registryConfigurationResolverService.resolveRegistryOverrideConfigurationMap(); @@ -234,7 +233,7 @@ public RegistryConfigurationController registryConfigurationController(RegistryC @Bean public RegistryEntityFinderService registryEntityFinderService(EntityManager entityManager, ModelMapper registryBaseModelMapper, RegistryConfigurationResolverService registryConfigurationResolverService) { - Map managedTypeWrapperMap = registryConfigurationResolverService.resolveRegistryDataConfiguration().getClassNameManagedTypeWrapperMap(); + Map managedTypeWrapperMap = registryConfigurationResolverService.resolveRegistryDataConfiguration().classNameManagedTypeWrapperMap(); return new EntityManagerRegistryEntityFinderService(entityManager, registryBaseModelMapper, managedTypeWrapperMap); } @@ -292,29 +291,29 @@ private List createRegistryGroupDefinition RegistryGroupDefinitionConfiguration registryDataConfigurationGroup = new RegistryGroupDefinitionConfiguration(); registryDataConfigurationGroup.setGroupId("DATA"); - registryDataConfigurationGroup.setIncludeEntityPatternList(Collections.singletonList("^net.croz.nrich.registry.data.stub.*$")); - registryDataConfigurationGroup.setExcludeEntityPatternList(Collections.singletonList("^net.croz.nrich.registry.data.stub.RegistryTestEmbeddedUserGroupId")); + registryDataConfigurationGroup.setIncludeEntityPatternList(List.of("^net.croz.nrich.registry.data.stub.*$")); + registryDataConfigurationGroup.setExcludeEntityPatternList(List.of("^net.croz.nrich.registry.data.stub.RegistryTestEmbeddedUserGroupId")); RegistryGroupDefinitionConfiguration registryConfigurationConfigurationGroup = new RegistryGroupDefinitionConfiguration(); registryConfigurationConfigurationGroup.setGroupId("CONFIGURATION"); - registryConfigurationConfigurationGroup.setIncludeEntityPatternList(Collections.singletonList("^net.croz.nrich.registry.configuration.stub.*$")); + registryConfigurationConfigurationGroup.setIncludeEntityPatternList(List.of("^net.croz.nrich.registry.configuration.stub.*$")); RegistryGroupDefinitionConfiguration registryHistoryConfigurationGroup = new RegistryGroupDefinitionConfiguration(); registryHistoryConfigurationGroup.setGroupId("HISTORY"); - registryHistoryConfigurationGroup.setIncludeEntityPatternList(Collections.singletonList("^net.croz.nrich.registry.history.stub.*$")); + registryHistoryConfigurationGroup.setIncludeEntityPatternList(List.of("^net.croz.nrich.registry.history.stub.*$")); - return Arrays.asList(registryDataConfigurationGroup, registryConfigurationConfigurationGroup, registryHistoryConfigurationGroup); + return List.of(registryDataConfigurationGroup, registryConfigurationConfigurationGroup, registryHistoryConfigurationGroup); } private List createRegistryOverrideConfigurationList() { RegistryOverrideConfiguration configurationEntityConfiguration = new RegistryOverrideConfiguration(); - configurationEntityConfiguration.setPropertyDisplayOrderList(Arrays.asList("name", "id", "nonEditableProperty", "floatNumber", "doubleNumber")); - configurationEntityConfiguration.setIgnoredPropertyList(Collections.singletonList("skippedProperty")); - configurationEntityConfiguration.setNonEditablePropertyList(Collections.singletonList("nonEditableProperty")); - configurationEntityConfiguration.setNonSortablePropertyList(Collections.singletonList("nonEditableProperty")); + configurationEntityConfiguration.setPropertyDisplayOrderList(List.of("name", "id", "nonEditableProperty", "floatNumber", "doubleNumber")); + configurationEntityConfiguration.setIgnoredPropertyList(List.of("skippedProperty")); + configurationEntityConfiguration.setNonEditablePropertyList(List.of("nonEditableProperty")); + configurationEntityConfiguration.setNonSortablePropertyList(List.of("nonEditableProperty")); configurationEntityConfiguration.setDeletable(false); RegistryOverrideConfigurationHolder configurationEntityConfigurationHolder = RegistryOverrideConfigurationHolder.builder() @@ -336,7 +335,7 @@ private List createRegistryOverrideConfigur .type(RegistryConfigurationUpdateInterceptorNonModifiableEntity.class).overrideConfiguration(InterceptorTestNonEntityNonModifiableConfiguration).build(); SearchConfiguration> searchConfiguration = SearchConfiguration.emptyConfiguration(); - searchConfiguration.setSearchOperatorOverrideList(Collections.singletonList(SearchOperatorOverride.forType(String.class, DefaultSearchOperator.EQ))); + searchConfiguration.setSearchOperatorOverrideList(List.of(SearchOperatorOverride.forType(String.class, DefaultSearchOperator.EQ))); RegistryOverrideConfigurationHolder searchConfigurationHolder = RegistryOverrideConfigurationHolder.builder() .type(RegistryTestEntityWithOverriddenSearchConfiguration.class).overrideSearchConfiguration(searchConfiguration).build(); @@ -348,7 +347,7 @@ private List createRegistryOverrideConfigur RegistryOverrideConfigurationHolder embeddedEntityOverrideConfigurationHolder = RegistryOverrideConfigurationHolder.builder() .type(RegistryConfigurationTestEntityWithAssociationAndEmbeddedId.class).overrideConfiguration(embeddedEntityOverrideConfiguration).build(); - return Arrays.asList( + return List.of( interceptorTestEntityConfigurationHolder, InterceptorTestNonEntityNonModifiableConfigurationHolder, searchConfigurationHolder, configurationEntityConfigurationHolder, embeddedEntityOverrideConfigurationHolder ); diff --git a/nrich-registry/src/test/java/net/croz/nrich/registry/configuration/comparator/DisplayOrderComparatorTest.java b/nrich-registry/src/test/java/net/croz/nrich/registry/configuration/comparator/DisplayOrderComparatorTest.java index 943ff8685..9ee1eeea4 100644 --- a/nrich-registry/src/test/java/net/croz/nrich/registry/configuration/comparator/DisplayOrderComparatorTest.java +++ b/nrich-registry/src/test/java/net/croz/nrich/registry/configuration/comparator/DisplayOrderComparatorTest.java @@ -20,13 +20,13 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; -import java.util.Arrays; +import java.util.List; import static org.assertj.core.api.Assertions.assertThat; class DisplayOrderComparatorTest { - private final DisplayOrderComparator displayOrderComparator = new DisplayOrderComparator(Arrays.asList("first", "second")); + private final DisplayOrderComparator displayOrderComparator = new DisplayOrderComparator(List.of("first", "second")); @CsvSource({ "first,second,-1", "third,second,1", "first,third,-1" }) @ParameterizedTest diff --git a/nrich-registry/src/test/java/net/croz/nrich/registry/configuration/comparator/RegistryGroupConfigurationComparatorTest.java b/nrich-registry/src/test/java/net/croz/nrich/registry/configuration/comparator/RegistryGroupConfigurationComparatorTest.java index 6941ef3d0..eb960f0f1 100644 --- a/nrich-registry/src/test/java/net/croz/nrich/registry/configuration/comparator/RegistryGroupConfigurationComparatorTest.java +++ b/nrich-registry/src/test/java/net/croz/nrich/registry/configuration/comparator/RegistryGroupConfigurationComparatorTest.java @@ -20,8 +20,8 @@ import net.croz.nrich.registry.api.configuration.model.RegistryGroupConfiguration; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.Collections; +import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @@ -46,7 +46,7 @@ void shouldCompareByDisplayOrderWhenItExists() { // given RegistryGroupConfiguration firstGroup = new RegistryGroupConfiguration("first", "2.display", Collections.emptyList()); RegistryGroupConfiguration secondGroup = new RegistryGroupConfiguration("second", "1.display", Collections.emptyList()); - RegistryGroupConfigurationComparator comparator = new RegistryGroupConfigurationComparator(Arrays.asList("1.display", "2.display")); + RegistryGroupConfigurationComparator comparator = new RegistryGroupConfigurationComparator(List.of("1.display", "2.display")); // when Integer result = comparator.compare(firstGroup, secondGroup); diff --git a/nrich-registry/src/test/java/net/croz/nrich/registry/configuration/comparator/RegistryPropertyComparatorTest.java b/nrich-registry/src/test/java/net/croz/nrich/registry/configuration/comparator/RegistryPropertyComparatorTest.java index e02fa80c5..15b9c9b4f 100644 --- a/nrich-registry/src/test/java/net/croz/nrich/registry/configuration/comparator/RegistryPropertyComparatorTest.java +++ b/nrich-registry/src/test/java/net/croz/nrich/registry/configuration/comparator/RegistryPropertyComparatorTest.java @@ -22,7 +22,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; -import java.util.Arrays; +import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @@ -46,7 +46,7 @@ void shouldCompareByPropertyNameWhenDisplayOrderIsEmpty(boolean isFirstId, boole @Test void shouldCompareByDisplayOrderWhenPresent() { // given - RegistryPropertyComparator registryPropertyComparator = new RegistryPropertyComparator(Arrays.asList("first", "second")); + RegistryPropertyComparator registryPropertyComparator = new RegistryPropertyComparator(List.of("first", "second")); // when Integer result = registryPropertyComparator.compare(RegistryPropertyConfiguration.builder().name("first").build(), RegistryPropertyConfiguration.builder().name("second").build()); diff --git a/nrich-registry/src/test/java/net/croz/nrich/registry/configuration/service/DefaultRegistryConfigurationServiceTest.java b/nrich-registry/src/test/java/net/croz/nrich/registry/configuration/service/DefaultRegistryConfigurationServiceTest.java index b09a662ca..bff485bdb 100644 --- a/nrich-registry/src/test/java/net/croz/nrich/registry/configuration/service/DefaultRegistryConfigurationServiceTest.java +++ b/nrich-registry/src/test/java/net/croz/nrich/registry/configuration/service/DefaultRegistryConfigurationServiceTest.java @@ -54,7 +54,7 @@ void shouldResolveConfigurationWithOverrideDefined() { // when List result = registryConfigurationService.fetchRegistryGroupConfigurationList(); RegistryGroupConfiguration registryTestEntityConfiguration = result.get(0); - RegistryEntityConfiguration registryEntityConfiguration = registryTestEntityConfiguration.getEntityConfigurationList().stream() + RegistryEntityConfiguration registryEntityConfiguration = registryTestEntityConfiguration.entityConfigurationList().stream() .filter(entityConfig -> RegistryConfigurationTestEntity.class.getName().equals(entityConfig.getClassFullName())) .findFirst() .orElse(null); @@ -137,7 +137,7 @@ void shouldResolveRegistryConfigurationForComplexEntitiesWithAssociationsAndEmbe // when List result = registryConfigurationService.fetchRegistryGroupConfigurationList(); RegistryGroupConfiguration registryTestEntityConfiguration = result.get(0); - RegistryEntityConfiguration registryEntityConfiguration = registryTestEntityConfiguration.getEntityConfigurationList().stream() + RegistryEntityConfiguration registryEntityConfiguration = registryTestEntityConfiguration.entityConfigurationList().stream() .filter(entityConfig -> RegistryConfigurationTestEntityWithAssociationAndEmbeddedId.class.getName().equals(entityConfig.getClassFullName())) .findFirst() .orElse(null); @@ -183,7 +183,7 @@ void shouldResolveRegistryConfigurationForComplexEntitiesWithIdClass() { // when List result = registryConfigurationService.fetchRegistryGroupConfigurationList(); RegistryGroupConfiguration registryTestEntityConfiguration = result.get(0); - RegistryEntityConfiguration registryEntityConfiguration = registryTestEntityConfiguration.getEntityConfigurationList().stream() + RegistryEntityConfiguration registryEntityConfiguration = registryTestEntityConfiguration.entityConfigurationList().stream() .filter(entityConfig -> RegistryConfigurationTestEntityWithIdClass.class.getName().equals(entityConfig.getClassFullName())) .findFirst() .orElse(null); diff --git a/nrich-registry/src/test/java/net/croz/nrich/registry/core/service/DefaultRegistryConfigurationResolverServiceTest.java b/nrich-registry/src/test/java/net/croz/nrich/registry/core/service/DefaultRegistryConfigurationResolverServiceTest.java index 687ae7f71..e5efec98a 100644 --- a/nrich-registry/src/test/java/net/croz/nrich/registry/core/service/DefaultRegistryConfigurationResolverServiceTest.java +++ b/nrich-registry/src/test/java/net/croz/nrich/registry/core/service/DefaultRegistryConfigurationResolverServiceTest.java @@ -69,13 +69,13 @@ void shouldResolveRegistryGroupDefinition() { // then assertThat(result).isNotNull(); - assertThat(result.getGroupDefinitionList()).hasSize(1); + assertThat(result.groupDefinitionList()).hasSize(1); - RegistryGroupDefinition groupDefinition = result.getGroupDefinitionList().get(0); + RegistryGroupDefinition groupDefinition = result.groupDefinitionList().get(0); - assertThat(groupDefinition.getRegistryGroupId()).isEqualTo("groupId"); - assertThat(groupDefinition.getRegistryEntityList()).hasSize(1); - assertThat(groupDefinition.getRegistryEntityList()).extracting("identifiableType.javaType").containsExactly(RegistryConfigurationRegularTestEntity.class); + assertThat(groupDefinition.registryGroupId()).isEqualTo("groupId"); + assertThat(groupDefinition.registryEntityList()).hasSize(1); + assertThat(groupDefinition.registryEntityList()).extracting("identifiableType.javaType").containsExactly(RegistryConfigurationRegularTestEntity.class); } @Test @@ -90,7 +90,7 @@ void shouldExcludeRegistryGroupConfiguration() { // then assertThat(result).isNotNull(); - assertThat(result.getGroupDefinitionList()).isEmpty(); + assertThat(result.groupDefinitionList()).isEmpty(); } @Test @@ -132,12 +132,12 @@ void shouldResolveRegistryHistoryConfiguration() { // then assertThat(result).isNotNull(); - assertThat(result.getRevisionNumberProperty().getOriginalName()).isEqualTo("customRevisionNumber"); - assertThat(result.getRevisionNumberProperty().getType()).isEqualTo(Integer.class); - assertThat(result.getRevisionTimestampProperty().getOriginalName()).isEqualTo("customRevisionTimestamp"); - assertThat(result.getRevisionTimestampProperty().getType()).isEqualTo(Instant.class); - assertThat(result.getRevisionAdditionalPropertyList()).hasSize(1); - assertThat(result.getRevisionAdditionalPropertyList()).extracting("name").containsExactly("customProperty"); - assertThat(result.getRevisionAdditionalPropertyList()).extracting("type").containsExactly(String.class); + assertThat(result.revisionNumberProperty().originalName()).isEqualTo("customRevisionNumber"); + assertThat(result.revisionNumberProperty().type()).isEqualTo(Integer.class); + assertThat(result.revisionTimestampProperty().originalName()).isEqualTo("customRevisionTimestamp"); + assertThat(result.revisionTimestampProperty().type()).isEqualTo(Instant.class); + assertThat(result.revisionAdditionalPropertyList()).hasSize(1); + assertThat(result.revisionAdditionalPropertyList()).extracting("name").containsExactly("customProperty"); + assertThat(result.revisionAdditionalPropertyList()).extracting("type").containsExactly(String.class); } } diff --git a/nrich-registry/src/test/java/net/croz/nrich/registry/core/testutil/RegistryConfigurationGeneratingUtil.java b/nrich-registry/src/test/java/net/croz/nrich/registry/core/testutil/RegistryConfigurationGeneratingUtil.java index ffb92aae5..1219a9b85 100644 --- a/nrich-registry/src/test/java/net/croz/nrich/registry/core/testutil/RegistryConfigurationGeneratingUtil.java +++ b/nrich-registry/src/test/java/net/croz/nrich/registry/core/testutil/RegistryConfigurationGeneratingUtil.java @@ -55,7 +55,7 @@ public static Metamodel createMetamodel() { doReturn(createAttributeList()).when(enversEntity).getAttributes(); doReturn(RegistryConfigurationRegularTestEntity.class).when(entity).getJavaType(); - doReturn(new HashSet<>(Arrays.asList(enversEntity, nonIdentifiableEntity, entity))).when(metamodel).getManagedTypes(); + doReturn(new HashSet<>(List.of(enversEntity, nonIdentifiableEntity, entity))).when(metamodel).getManagedTypes(); return metamodel; } @@ -64,10 +64,10 @@ public static List createRegistryGroupDefi RegistryGroupDefinitionConfiguration groupDefinitionConfiguration = new RegistryGroupDefinitionConfiguration(); groupDefinitionConfiguration.setGroupId("groupId"); - groupDefinitionConfiguration.setIncludeEntityPatternList(Collections.singletonList(includePatterns)); - groupDefinitionConfiguration.setExcludeEntityPatternList(Collections.singletonList(excludePatterns)); + groupDefinitionConfiguration.setIncludeEntityPatternList(List.of(includePatterns)); + groupDefinitionConfiguration.setExcludeEntityPatternList(excludePatterns == null ? Collections.emptyList() : List.of(excludePatterns)); - return Collections.singletonList(groupDefinitionConfiguration); + return List.of(groupDefinitionConfiguration); } public static List createRegistryOverrideConfigurationList() { @@ -78,7 +78,7 @@ public static List createRegistryOverrideCo .overrideConfiguration(overrideConfiguration) .build(); - return Collections.singletonList(registryOverrideConfigurationHolder); + return List.of(registryOverrideConfigurationHolder); } private static Set> createAttributeList() { diff --git a/nrich-registry/src/test/java/net/croz/nrich/registry/data/customizer/RegistryDataFormConfigurationMappingCustomizerTest.java b/nrich-registry/src/test/java/net/croz/nrich/registry/data/customizer/RegistryDataFormConfigurationMappingCustomizerTest.java index fee8a06b2..54e62c065 100644 --- a/nrich-registry/src/test/java/net/croz/nrich/registry/data/customizer/RegistryDataFormConfigurationMappingCustomizerTest.java +++ b/nrich-registry/src/test/java/net/croz/nrich/registry/data/customizer/RegistryDataFormConfigurationMappingCustomizerTest.java @@ -20,7 +20,6 @@ import net.croz.nrich.registry.api.core.service.RegistryClassResolvingService; import net.croz.nrich.registry.core.constants.RegistryClassResolvingConstants; import net.croz.nrich.registry.data.stub.RegistryTestEntity; -import net.croz.nrich.registry.data.stub.RegistryTestEntityUpdateRequest; import net.croz.nrich.registry.data.stub.RegistryTestEntityWithOverriddenFormConfiguration; import net.croz.nrich.registry.data.stub.model.RegistryCustomizerTestEntity; import org.junit.jupiter.api.BeforeEach; @@ -29,7 +28,6 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -41,7 +39,7 @@ @ExtendWith(MockitoExtension.class) class RegistryDataFormConfigurationMappingCustomizerTest { - private static final List> REGISTRY_CLASS_LIST = Arrays.asList( + private static final List> REGISTRY_CLASS_LIST = List.of( RegistryTestEntity.class, RegistryTestEntityWithOverriddenFormConfiguration.class, RegistryCustomizerTestEntity.class ); diff --git a/nrich-registry/src/test/java/net/croz/nrich/registry/data/service/DefaultRegistryDataRequestConversionServiceTest.java b/nrich-registry/src/test/java/net/croz/nrich/registry/data/service/DefaultRegistryDataRequestConversionServiceTest.java index b231fdcbe..ec59d20ac 100644 --- a/nrich-registry/src/test/java/net/croz/nrich/registry/data/service/DefaultRegistryDataRequestConversionServiceTest.java +++ b/nrich-registry/src/test/java/net/croz/nrich/registry/data/service/DefaultRegistryDataRequestConversionServiceTest.java @@ -52,7 +52,7 @@ void shouldConvertRequestDataToTypedInstance() throws Exception { CreateRegistryRequest request = createCreateRegistryRequest(entity.getClass()); String className = DefaultRegistryDataRequestConversionServiceTestEntity.class.getName(); - doReturn(entity).when(objectMapper).readValue(request.getJsonEntityData(), entity.getClass()); + doReturn(entity).when(objectMapper).readValue(request.jsonEntityData(), entity.getClass()); doReturn(DefaultRegistryDataRequestConversionServiceTestEntity.class).when(registryClassResolvingService).resolveCreateClass(className); // when @@ -69,7 +69,7 @@ void shouldConvertUpdateRequestDataToTypedInstance() throws Exception { UpdateRegistryRequest request = createUpdateRegistryRequest(entity.getClass()); String className = DefaultRegistryDataRequestConversionServiceTestEntity.class.getName(); - doReturn(entity).when(objectMapper).readValue(request.getJsonEntityData(), entity.getClass()); + doReturn(entity).when(objectMapper).readValue(request.jsonEntityData(), entity.getClass()); doReturn(DefaultRegistryDataRequestConversionServiceTestEntity.class).when(registryClassResolvingService).resolveUpdateClass(className); // when diff --git a/nrich-registry/src/test/java/net/croz/nrich/registry/data/stub/RegistryTestEmbeddedUserGroupId.java b/nrich-registry/src/test/java/net/croz/nrich/registry/data/stub/RegistryTestEmbeddedUserGroupId.java index dc56c2080..772658b01 100644 --- a/nrich-registry/src/test/java/net/croz/nrich/registry/data/stub/RegistryTestEmbeddedUserGroupId.java +++ b/nrich-registry/src/test/java/net/croz/nrich/registry/data/stub/RegistryTestEmbeddedUserGroupId.java @@ -42,13 +42,11 @@ public boolean equals(Object object) { if (this == object) { return true; } - if (!(object instanceof RegistryTestEmbeddedUserGroupId)) { + if (!(object instanceof RegistryTestEmbeddedUserGroupId registryTestEmbeddedUserGroupId)) { return false; } - RegistryTestEmbeddedUserGroupId that = (RegistryTestEmbeddedUserGroupId) object; - - return Objects.equals(user.getId(), that.user.getId()) && Objects.equals(group.getId(), that.group.getId()); + return Objects.equals(user.getId(), registryTestEmbeddedUserGroupId.user.getId()) && Objects.equals(group.getId(), registryTestEmbeddedUserGroupId.group.getId()); } @Override diff --git a/nrich-registry/src/test/java/net/croz/nrich/registry/data/stub/RegistryTestEntityWithEmbeddedId.java b/nrich-registry/src/test/java/net/croz/nrich/registry/data/stub/RegistryTestEntityWithEmbeddedId.java index b2dd4eca3..1b71ef711 100644 --- a/nrich-registry/src/test/java/net/croz/nrich/registry/data/stub/RegistryTestEntityWithEmbeddedId.java +++ b/nrich-registry/src/test/java/net/croz/nrich/registry/data/stub/RegistryTestEntityWithEmbeddedId.java @@ -26,7 +26,6 @@ import jakarta.persistence.EmbeddedId; import jakarta.persistence.Entity; import java.io.Serializable; -import java.util.HashMap; import java.util.Map; @Setter @@ -51,13 +50,7 @@ public static class RegistryTestEntityWithEmbeddedIdPrimaryKey implements Serial private Long secondId; public Map asMap() { - Map mapKey = new HashMap<>(); - - mapKey.put("firstId", firstId.intValue()); - mapKey.put("secondId", secondId.intValue()); - - return mapKey; + return Map.of("firstId", firstId.intValue(), "secondId", secondId.intValue()); } - } } diff --git a/nrich-registry/src/test/java/net/croz/nrich/registry/data/testutil/RegistryDataGeneratingUtil.java b/nrich-registry/src/test/java/net/croz/nrich/registry/data/testutil/RegistryDataGeneratingUtil.java index eec100a54..03da243be 100644 --- a/nrich-registry/src/test/java/net/croz/nrich/registry/data/testutil/RegistryDataGeneratingUtil.java +++ b/nrich-registry/src/test/java/net/croz/nrich/registry/data/testutil/RegistryDataGeneratingUtil.java @@ -41,12 +41,9 @@ import net.croz.nrich.registry.data.stub.request.CreateEntityRequest; import jakarta.persistence.EntityManager; -import java.util.Arrays; import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; import java.util.stream.IntStream; public final class RegistryDataGeneratingUtil { @@ -88,7 +85,7 @@ public static RegistryTestEntityWithoutAssociation createRegistryTestEntityWitho public static List createRegistryTestEntityList(EntityManager entityManager) { List testEntityList = IntStream.range(0, 5) .mapToObj(value -> createRegistryTestEntity("name " + value, 50 + value, null)) - .collect(Collectors.toList()); + .toList(); testEntityList.forEach(entityManager::persist); @@ -98,7 +95,7 @@ public static List createRegistryTestEntityList(EntityManage public static List createRegistryTestEntityWithDifferentIdNameList(EntityManager entityManager) { List testEntityList = IntStream.range(0, 5) .mapToObj(value -> createRegistryTestEntityWithDifferentIdName("name " + value)) - .collect(Collectors.toList()); + .toList(); testEntityList.forEach(entityManager::persist); @@ -122,57 +119,34 @@ public static RegistryTestEntityWithEmbeddedId createRegistryTestEntityWithEmbed } public static ListBulkRegistryRequest createBulkListRegistryRequest(String classFullName, String query) { - ListBulkRegistryRequest listBulkRegistryRequest = new ListBulkRegistryRequest(); - - listBulkRegistryRequest.setRegistryRequestList(Collections.singletonList(createListRegistryRequest(classFullName, query))); - - return listBulkRegistryRequest; + return new ListBulkRegistryRequest(List.of(createListRegistryRequest(classFullName, query))); } - public static ListRegistryRequest createListRegistryRequest(String classFullName, String query, int pageNumber, int pageSize) { - ListRegistryRequest request = createListRegistryRequest(classFullName, query); - - request.setPageNumber(pageNumber); - request.setPageSize(pageSize); - - return request; + public static ListRegistryRequest createListRegistryRequest(String classFullName, String query) { + return createListRegistryRequest(classFullName, query, 0, 10); } public static List createRegistryTestEntityWithOverriddenSearchConfigurationList(EntityManager entityManager) { List testEntityList = IntStream.range(0, 5) .mapToObj(value -> createRegistryTestEntityWithOverriddenSearchConfiguration("name " + value)) - .collect(Collectors.toList()); + .toList(); testEntityList.forEach(entityManager::persist); return testEntityList; } - public static ListRegistryRequest createListRegistryRequest(String classFullName, String query) { + public static ListRegistryRequest createListRegistryRequest(String classFullName, String query, int pageNumber, int pageSize) { SearchParameter searchParameter = null; if (query != null) { - searchParameter = new SearchParameter(); - searchParameter.setPropertyNameList(Arrays.asList("age", "name")); - searchParameter.setQuery(query); + searchParameter = new SearchParameter(List.of("age", "name"), query); } - ListRegistryRequest request = new ListRegistryRequest(); - - request.setClassFullName(classFullName); - request.setPageNumber(0); - request.setPageSize(10); - request.setSearchParameter(searchParameter); - - return request; + return new ListRegistryRequest(classFullName, pageNumber, pageSize, searchParameter, Collections.emptyList()); } public static DeleteRegistryRequest createDeleteRegistryRequest(String classFullName, Object id) { - DeleteRegistryRequest request = new DeleteRegistryRequest(); - - request.setClassFullName(classFullName); - request.setId(id); - - return request; + return new DeleteRegistryRequest(classFullName, id); } @SneakyThrows @@ -182,44 +156,30 @@ public static CreateRegistryRequest createRegistryRequest(ObjectMapper objectMap @SneakyThrows public static CreateRegistryRequest createRegistryRequestWithAssociation(ObjectMapper objectMapper, String classFullName, RegistryTestEntity parent) { - CreateRegistryRequest request = new CreateRegistryRequest(); - - request.setClassFullName(classFullName); - request.setJsonEntityData(objectMapper.writeValueAsString(Map.of("name", "name", "age", 40, "parent", parent))); + String jsonEntityData = objectMapper.writeValueAsString(Map.of("name", "name", "age", 40, "parent", parent)); - return request; + return new CreateRegistryRequest(classFullName, jsonEntityData); } @SneakyThrows public static CreateRegistryRequest createRegistryRequest(ObjectMapper objectMapper, String classFullName, String name, Integer age) { - CreateRegistryRequest request = new CreateRegistryRequest(); + String jsonData = objectMapper.writeValueAsString(createRegistryTestEntityRequest(name, age)); - request.setClassFullName(classFullName); - request.setJsonEntityData(objectMapper.writeValueAsString(createRegistryTestEntityRequest(name, age))); - - return request; + return new CreateRegistryRequest(classFullName, jsonData); } @SneakyThrows public static UpdateRegistryRequest updateRegistryRequest(ObjectMapper objectMapper, String classFullName, Long id, String name) { - UpdateRegistryRequest request = new UpdateRegistryRequest(); + String jsonData = objectMapper.writeValueAsString(createRegistryTestEntityRequest(name, 50)); - request.setClassFullName(classFullName); - request.setId(id); - request.setJsonEntityData(objectMapper.writeValueAsString(createRegistryTestEntityRequest(name, 50))); - - return request; + return new UpdateRegistryRequest(classFullName, id, jsonData); } @SneakyThrows public static UpdateRegistryRequest updateRegistryRequestWithId(ObjectMapper objectMapper, String classFullName, Long id) { - UpdateRegistryRequest request = new UpdateRegistryRequest(); - - request.setClassFullName(classFullName); - request.setId(id); - request.setJsonEntityData(objectMapper.writeValueAsString(createUpdateRegistryTestEntityRequest(id))); + String jsonData = objectMapper.writeValueAsString(createUpdateRegistryTestEntityRequest(id)); - return request; + return new UpdateRegistryRequest(classFullName, id, jsonData); } public static RegistryTestEmbeddedUserGroup createAndSaveRegistryTestEmbeddedUserGroup(EntityManager entityManager) { @@ -275,44 +235,26 @@ public static RegistryTestEntityWithIdClass createRegistryTestEntityWithIdClass( } public static DeleteRegistryRequest createDeleteEmbeddedUserGroupRequest(RegistryTestEmbeddedUserGroupId id) { - DeleteRegistryRequest request = new DeleteRegistryRequest(); - - Map idMap = new HashMap<>(); - - idMap.put("user", id.getUser()); - idMap.put("group", id.getGroup()); + Map idMap = Map.of("user", id.getUser(), "group", id.getGroup()); - request.setClassFullName(RegistryTestEmbeddedUserGroup.class.getName()); - request.setId(idMap); - - return request; + return new DeleteRegistryRequest(RegistryTestEmbeddedUserGroup.class.getName(), idMap); } public static UpdateRegistryRequest createUpdateEmbeddedUserGroupRequest(ObjectMapper objectMapper, RegistryTestEmbeddedUserGroup registryTestEmbeddedUserGroup) throws Exception { - UpdateRegistryRequest request = new UpdateRegistryRequest(); - - Map idMap = new HashMap<>(); - - idMap.put("user", registryTestEmbeddedUserGroup.getUserGroupId().getUser()); - idMap.put("group", registryTestEmbeddedUserGroup.getUserGroupId().getGroup()); + Map idMap = Map.of( + "user", registryTestEmbeddedUserGroup.getUserGroupId().getUser(), + "group", registryTestEmbeddedUserGroup.getUserGroupId().getGroup() + ); registryTestEmbeddedUserGroup.setJoinedPropertyValue("updated"); - request.setClassFullName(RegistryTestEmbeddedUserGroup.class.getName()); - request.setId(idMap); - request.setJsonEntityData(objectMapper.writeValueAsString(registryTestEmbeddedUserGroup)); + String jsonData = objectMapper.writeValueAsString(registryTestEmbeddedUserGroup); - return request; + return new UpdateRegistryRequest(RegistryTestEmbeddedUserGroup.class.getName(), idMap, jsonData); } public static Map registryTestEntityWithIdClassId(RegistryTestEntityWithIdClass entity) { - - Map idMap = new HashMap<>(); - - idMap.put("firstId", entity.getFirstId()); - idMap.put("secondId", entity.getSecondId()); - - return idMap; + return Map.of("firstId", entity.getFirstId(), "secondId", entity.getSecondId()); } public static CreateRegistryTestEntityRequest createRegistryTestEntityRequest(String name, Long parentId) { @@ -347,19 +289,9 @@ public static UpdateRegistryTestEntityRequest createUpdateRegistryTestEntityRequ } public static ListRegistryRequest createEmbeddedIdSearchRequest(RegistryTestEmbeddedUserGroup entity) { - SearchParameter searchParameter = new SearchParameter(); - - searchParameter.setPropertyNameList(List.of("userGroupId.user")); - searchParameter.setQuery(entity.getUserGroupId().getGroup().getId().toString()); - - ListRegistryRequest request = new ListRegistryRequest(); + SearchParameter searchParameter = new SearchParameter(List.of("userGroupId.user"), entity.getUserGroupId().getGroup().getId().toString()); - request.setClassFullName(RegistryTestEmbeddedUserGroup.class.getName()); - request.setPageNumber(0); - request.setPageSize(10); - request.setSearchParameter(searchParameter); - - return request; + return new ListRegistryRequest(RegistryTestEmbeddedUserGroup.class.getName(), 0, 10, searchParameter, Collections.emptyList()); } private static RegistryTestEntity createRegistryTestEntity(String name, Integer age, RegistryTestEntity parent) { diff --git a/nrich-registry/src/test/java/net/croz/nrich/registry/data/testutil/RegistryDataMapGeneratingUtil.java b/nrich-registry/src/test/java/net/croz/nrich/registry/data/testutil/RegistryDataMapGeneratingUtil.java index d4fc91278..de86f1072 100644 --- a/nrich-registry/src/test/java/net/croz/nrich/registry/data/testutil/RegistryDataMapGeneratingUtil.java +++ b/nrich-registry/src/test/java/net/croz/nrich/registry/data/testutil/RegistryDataMapGeneratingUtil.java @@ -26,10 +26,6 @@ private RegistryDataMapGeneratingUtil() { } public static Map> createFormConfigurationMap(String key, Class value) { - Map> formConfigurationMap = new HashMap<>(); - - formConfigurationMap.put(key, value); - - return formConfigurationMap; + return new HashMap<>(Map.of(key, value)); } } diff --git a/nrich-registry/src/test/java/net/croz/nrich/registry/data/testutil/RegistryRequestGeneratingUtil.java b/nrich-registry/src/test/java/net/croz/nrich/registry/data/testutil/RegistryRequestGeneratingUtil.java index 09ec1d40d..d5ce2152b 100644 --- a/nrich-registry/src/test/java/net/croz/nrich/registry/data/testutil/RegistryRequestGeneratingUtil.java +++ b/nrich-registry/src/test/java/net/croz/nrich/registry/data/testutil/RegistryRequestGeneratingUtil.java @@ -26,20 +26,10 @@ private RegistryRequestGeneratingUtil() { } public static CreateRegistryRequest createCreateRegistryRequest(Class type) { - CreateRegistryRequest request = new CreateRegistryRequest(); - - request.setClassFullName(type.getName()); - request.setJsonEntityData("{}"); - - return request; + return new CreateRegistryRequest(type.getName(), "{}"); } public static UpdateRegistryRequest createUpdateRegistryRequest(Class type) { - UpdateRegistryRequest request = new UpdateRegistryRequest(); - - request.setClassFullName(type.getName()); - request.setJsonEntityData("{}"); - - return request; + return new UpdateRegistryRequest(type.getName(), null, "{}"); } } diff --git a/nrich-registry/src/test/java/net/croz/nrich/registry/data/util/ClassLoadingUtilTest.java b/nrich-registry/src/test/java/net/croz/nrich/registry/data/util/ClassLoadingUtilTest.java index 419c4b59c..edbc5f69e 100644 --- a/nrich-registry/src/test/java/net/croz/nrich/registry/data/util/ClassLoadingUtilTest.java +++ b/nrich-registry/src/test/java/net/croz/nrich/registry/data/util/ClassLoadingUtilTest.java @@ -19,7 +19,6 @@ import org.junit.jupiter.api.Test; -import java.util.Collections; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @@ -29,7 +28,7 @@ class ClassLoadingUtilTest { @Test void shouldLoadClass() { // given - List classNameList = Collections.singletonList(String.class.getName()); + List classNameList = List.of(String.class.getName()); // when Class result = ClassLoadingUtil.loadClassFromList(classNameList); @@ -41,7 +40,7 @@ void shouldLoadClass() { @Test void shouldReturnNullForNonExistingClass() { // given - List classNameList = Collections.singletonList("non.existing.Class"); + List classNameList = List.of("non.existing.Class"); // when Class result = ClassLoadingUtil.loadClassFromList(classNameList); diff --git a/nrich-registry/src/test/java/net/croz/nrich/registry/enumadata/service/DefaultRegistryEnumServiceTest.java b/nrich-registry/src/test/java/net/croz/nrich/registry/enumadata/service/DefaultRegistryEnumServiceTest.java index ef7ac4798..00416d915 100644 --- a/nrich-registry/src/test/java/net/croz/nrich/registry/enumadata/service/DefaultRegistryEnumServiceTest.java +++ b/nrich-registry/src/test/java/net/croz/nrich/registry/enumadata/service/DefaultRegistryEnumServiceTest.java @@ -57,10 +57,10 @@ void shouldBulkList() { EnumResult enumResult = result.get(classFullName).get(0); - assertThat(enumResult.getId()).isEqualTo(classFullName); - assertThat(enumResult.getDescription()).isEqualTo("First description"); - assertThat(enumResult.getValue()).isEqualTo(RegistryTestEnum.FIRST); - assertThat(enumResult.getAdditionalData()).isEmpty(); + assertThat(enumResult.id()).isEqualTo(classFullName); + assertThat(enumResult.description()).isEqualTo("First description"); + assertThat(enumResult.value()).isEqualTo(RegistryTestEnum.FIRST); + assertThat(enumResult.additionalData()).isEmpty(); } @Test @@ -77,9 +77,9 @@ void shouldList() { EnumResult enumResult = result.get(0); - assertThat(enumResult.getDescription()).isEqualTo("Second with additional methods description"); - assertThat(enumResult.getValue()).isEqualTo(RegistryTestEnumWithAdditionalData.SECOND_WITH_ADDITIONAL_METHODS); - assertThat(enumResult.getAdditionalData()).isEqualTo(Map.of("firstAdditionalMethod", List.of("additional method second value"))); + assertThat(enumResult.description()).isEqualTo("Second with additional methods description"); + assertThat(enumResult.value()).isEqualTo(RegistryTestEnumWithAdditionalData.SECOND_WITH_ADDITIONAL_METHODS); + assertThat(enumResult.additionalData()).isEqualTo(Map.of("firstAdditionalMethod", List.of("additional method second value"))); } @Test @@ -119,6 +119,6 @@ void shouldReturnEnumNameWhenDescriptionIsNotDefined() { // then assertThat(result).hasSize(2); - assertThat(result.get(0).getDescription()).isEqualTo("FIRST"); + assertThat(result.get(0).description()).isEqualTo("FIRST"); } } diff --git a/nrich-registry/src/test/java/net/croz/nrich/registry/enumadata/testutil/RegistryEnumGeneratingUtil.java b/nrich-registry/src/test/java/net/croz/nrich/registry/enumadata/testutil/RegistryEnumGeneratingUtil.java index 75d4b6f8b..9006f7df3 100644 --- a/nrich-registry/src/test/java/net/croz/nrich/registry/enumadata/testutil/RegistryEnumGeneratingUtil.java +++ b/nrich-registry/src/test/java/net/croz/nrich/registry/enumadata/testutil/RegistryEnumGeneratingUtil.java @@ -20,7 +20,7 @@ import net.croz.nrich.registry.api.enumdata.request.ListBulkRegistryEnumRequest; import net.croz.nrich.registry.api.enumdata.request.ListRegistryEnumRequest; -import java.util.Collections; +import java.util.List; public final class RegistryEnumGeneratingUtil { @@ -28,19 +28,10 @@ private RegistryEnumGeneratingUtil() { } public static ListBulkRegistryEnumRequest createBulkListEnumRequest(String classFullName, String query) { - ListBulkRegistryEnumRequest request = new ListBulkRegistryEnumRequest(); - - request.setRegistryRequestList(Collections.singletonList(createListEnumRequest(classFullName, query))); - - return request; + return new ListBulkRegistryEnumRequest(List.of(createListEnumRequest(classFullName, query))); } public static ListRegistryEnumRequest createListEnumRequest(String classFullName, String query) { - ListRegistryEnumRequest request = new ListRegistryEnumRequest(); - - request.setClassFullName(classFullName); - request.setQuery(query); - - return request; + return new ListRegistryEnumRequest(classFullName, query); } } diff --git a/nrich-registry/src/test/java/net/croz/nrich/registry/history/controller/RegistryHistoryControllerEndpointTest.java b/nrich-registry/src/test/java/net/croz/nrich/registry/history/controller/RegistryHistoryControllerEndpointTest.java index 16984d66c..a3da89d39 100644 --- a/nrich-registry/src/test/java/net/croz/nrich/registry/history/controller/RegistryHistoryControllerEndpointTest.java +++ b/nrich-registry/src/test/java/net/croz/nrich/registry/history/controller/RegistryHistoryControllerEndpointTest.java @@ -24,7 +24,7 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.web.servlet.ResultActions; -import static net.croz.nrich.registry.history.testutil.RegistryHistoryGeneratingUtil.listRegistryHistoryRequest; +import static net.croz.nrich.registry.history.testutil.RegistryHistoryGeneratingUtil.listRegistryHistoryRequestWithDefaultSort; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @TestPropertySource(properties = "nrich.registry.history.endpoint-path=api/registry/history") @@ -34,7 +34,7 @@ class RegistryHistoryControllerEndpointTest extends BaseControllerTest { void shouldFetchRegistryHistoryList() throws Exception { // given String requestUrl = "/api/registry/history/list"; - ListRegistryHistoryRequest request = listRegistryHistoryRequest(RegistryHistoryTestEntity.class.getName(), 1L); + ListRegistryHistoryRequest request = listRegistryHistoryRequestWithDefaultSort(RegistryHistoryTestEntity.class.getName(), 1L); // when ResultActions result = performPostRequest(requestUrl, request); diff --git a/nrich-registry/src/test/java/net/croz/nrich/registry/history/controller/RegistryHistoryControllerTest.java b/nrich-registry/src/test/java/net/croz/nrich/registry/history/controller/RegistryHistoryControllerTest.java index 7f40e8b84..5b1f4ebe2 100644 --- a/nrich-registry/src/test/java/net/croz/nrich/registry/history/controller/RegistryHistoryControllerTest.java +++ b/nrich-registry/src/test/java/net/croz/nrich/registry/history/controller/RegistryHistoryControllerTest.java @@ -30,7 +30,7 @@ import jakarta.persistence.PersistenceContext; import static net.croz.nrich.registry.history.testutil.RegistryHistoryGeneratingUtil.creteRegistryHistoryTestEntityRevisionList; -import static net.croz.nrich.registry.history.testutil.RegistryHistoryGeneratingUtil.listRegistryHistoryRequest; +import static net.croz.nrich.registry.history.testutil.RegistryHistoryGeneratingUtil.listRegistryHistoryRequestWithDefaultSort; import static net.croz.nrich.registry.testutil.PersistenceTestUtil.executeInTransaction; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -48,7 +48,7 @@ void shouldFetchRegistryHistoryList() throws Exception { // given String requestUrl = "/nrich/registry/history/list"; RegistryHistoryTestEntity entity = creteRegistryHistoryTestEntityRevisionList(entityManager, platformTransactionManager); - ListRegistryHistoryRequest request = listRegistryHistoryRequest(RegistryHistoryTestEntity.class.getName(), entity.getId()); + ListRegistryHistoryRequest request = listRegistryHistoryRequestWithDefaultSort(RegistryHistoryTestEntity.class.getName(), entity.getId()); // when ResultActions result = performPostRequest(requestUrl, request); diff --git a/nrich-registry/src/test/java/net/croz/nrich/registry/history/service/DefaultRegistryHistoryServiceTest.java b/nrich-registry/src/test/java/net/croz/nrich/registry/history/service/DefaultRegistryHistoryServiceTest.java index 0fbc8b1cc..2b50c080e 100644 --- a/nrich-registry/src/test/java/net/croz/nrich/registry/history/service/DefaultRegistryHistoryServiceTest.java +++ b/nrich-registry/src/test/java/net/croz/nrich/registry/history/service/DefaultRegistryHistoryServiceTest.java @@ -41,6 +41,7 @@ import static net.croz.nrich.registry.history.testutil.RegistryHistoryGeneratingUtil.creteRegistryHistoryTestEntityWithEmbeddedIdRevisionList; import static net.croz.nrich.registry.history.testutil.RegistryHistoryGeneratingUtil.creteRegistryHistoryTestEntityWithEmbeddedObjectIdRevisionList; import static net.croz.nrich.registry.history.testutil.RegistryHistoryGeneratingUtil.listRegistryHistoryRequest; +import static net.croz.nrich.registry.history.testutil.RegistryHistoryGeneratingUtil.listRegistryHistoryRequestWithDefaultSort; import static net.croz.nrich.registry.history.testutil.RegistryHistoryGeneratingUtil.listRegistryHistoryRequestWithSort; import static net.croz.nrich.registry.testutil.PersistenceTestUtil.executeInTransaction; import static org.assertj.core.api.Assertions.assertThat; @@ -62,7 +63,7 @@ class DefaultRegistryHistoryServiceTest { void shouldReturnAllRevisionsOfEntity() { // given RegistryHistoryTestEntity entity = creteRegistryHistoryTestEntityRevisionList(entityManager, platformTransactionManager); - ListRegistryHistoryRequest request = listRegistryHistoryRequest(RegistryHistoryTestEntity.class.getName(), entity.getId()); + ListRegistryHistoryRequest request = listRegistryHistoryRequestWithDefaultSort(RegistryHistoryTestEntity.class.getName(), entity.getId()); // when Page> resultList = registryHistoryService.historyList(request); @@ -77,24 +78,24 @@ void shouldReturnAllRevisionsOfEntity() { EntityWithRevision firstResult = resultList.getContent().get(0); // then - assertThat(firstResult.getEntity().getParent()).isNotNull(); - assertThat(firstResult.getEntity().getParent().getName()).isNotNull(); + assertThat(firstResult.entity().getParent()).isNotNull(); + assertThat(firstResult.entity().getParent().getName()).isNotNull(); - assertThat(firstResult.getRevisionInfo()).isNotNull(); + assertThat(firstResult.revisionInfo()).isNotNull(); - assertThat(firstResult.getRevisionInfo().getRevisionType()).isEqualTo(RevisionType.ADD.name()); - assertThat(firstResult.getRevisionInfo().getRevisionTimestamp()).isNotNull(); - assertThat(firstResult.getRevisionInfo().getRevisionNumber()).isNotNull(); + assertThat(firstResult.revisionInfo().revisionType()).isEqualTo(RevisionType.ADD.name()); + assertThat(firstResult.revisionInfo().revisionTimestamp()).isNotNull(); + assertThat(firstResult.revisionInfo().revisionNumber()).isNotNull(); - assertThat(firstResult.getRevisionInfo().getAdditionalRevisionPropertyMap()).isNotNull(); - assertThat(firstResult.getRevisionInfo().getAdditionalRevisionPropertyMap()).containsEntry("revisionProperty", "revision property value"); + assertThat(firstResult.revisionInfo().additionalRevisionPropertyMap()).isNotNull(); + assertThat(firstResult.revisionInfo().additionalRevisionPropertyMap()).containsEntry("revisionProperty", "revision property value"); } @Test void shouldReturnAllRevisionsOfEntityWithoutId() { // given creteRegistryHistoryTestEntityRevisionList(entityManager, platformTransactionManager); - ListRegistryHistoryRequest request = listRegistryHistoryRequest(RegistryHistoryTestEntity.class.getName(), null); + ListRegistryHistoryRequest request = listRegistryHistoryRequestWithDefaultSort(RegistryHistoryTestEntity.class.getName(), null); // when Page> resultList = registryHistoryService.historyList(request); @@ -111,7 +112,6 @@ void shouldReturnAllRevisionsOfEntityUnsorted() { // given creteRegistryHistoryTestEntityRevisionList(entityManager, platformTransactionManager); ListRegistryHistoryRequest request = listRegistryHistoryRequest(RegistryHistoryTestEntity.class.getName(), null); - request.setSortPropertyList(null); // when Page> resultList = registryHistoryService.historyList(request); @@ -132,41 +132,41 @@ void shouldSupportSortingByAllProperties() { // then assertThat(resultList).isNotEmpty(); - assertThat(resultList.getContent().get(0).getEntity().getName()).isEqualTo("name 19"); + assertThat(resultList.getContent().get(0).entity().getName()).isEqualTo("name 19"); } @Test void shouldSupportFetchingEntityHistoryDataByEmbeddedId() { // given RegistryHistoryTestEntityWithEmbeddedId entity = creteRegistryHistoryTestEntityWithEmbeddedIdRevisionList(entityManager, platformTransactionManager); - ListRegistryHistoryRequest request = listRegistryHistoryRequest(RegistryHistoryTestEntityWithEmbeddedId.class.getName(), entity.getId().asMap()); + ListRegistryHistoryRequest request = listRegistryHistoryRequestWithDefaultSort(RegistryHistoryTestEntityWithEmbeddedId.class.getName(), entity.getId().asMap()); // when Page> resultList = registryHistoryService.historyList(request); // then assertThat(resultList).isNotEmpty(); - assertThat(resultList.getContent().get(0).getEntity().getAmount()).isEqualByComparingTo(BigDecimal.ONE); + assertThat(resultList.getContent().get(0).entity().getAmount()).isEqualByComparingTo(BigDecimal.ONE); } @Test void shouldSupportFetchingEntityHistoryDataByEmbeddedObjectId() { // given RegistryHistoryTestEntityWithEmbeddedObject entity = creteRegistryHistoryTestEntityWithEmbeddedObjectIdRevisionList(entityManager, platformTransactionManager); - ListRegistryHistoryRequest request = listRegistryHistoryRequest(RegistryHistoryTestEntityWithEmbeddedObject.class.getName(), entity.getId().asMap()); + ListRegistryHistoryRequest request = listRegistryHistoryRequestWithDefaultSort(RegistryHistoryTestEntityWithEmbeddedObject.class.getName(), entity.getId().asMap()); // when Page> resultList = registryHistoryService.historyList(request); // then assertThat(resultList).isNotEmpty(); - assertThat(resultList.getContent().get(0).getEntity().getAmount()).isEqualByComparingTo(BigDecimal.ONE); + assertThat(resultList.getContent().get(0).entity().getAmount()).isEqualByComparingTo(BigDecimal.ONE); } @Test void shouldThrowExceptionOnInvalidIdType() { // given - ListRegistryHistoryRequest request = listRegistryHistoryRequest(RegistryHistoryTestEntityWithEmbeddedId.class.getName(), new Object()); + ListRegistryHistoryRequest request = listRegistryHistoryRequestWithDefaultSort(RegistryHistoryTestEntityWithEmbeddedId.class.getName(), new Object()); // when Throwable thrown = catchThrowable(() -> registryHistoryService.historyList(request)); diff --git a/nrich-registry/src/test/java/net/croz/nrich/registry/history/stub/RegistryHistoryTestEntityWithEmbeddedId.java b/nrich-registry/src/test/java/net/croz/nrich/registry/history/stub/RegistryHistoryTestEntityWithEmbeddedId.java index 11e05fa44..d194d2c7b 100644 --- a/nrich-registry/src/test/java/net/croz/nrich/registry/history/stub/RegistryHistoryTestEntityWithEmbeddedId.java +++ b/nrich-registry/src/test/java/net/croz/nrich/registry/history/stub/RegistryHistoryTestEntityWithEmbeddedId.java @@ -27,7 +27,6 @@ import jakarta.persistence.Entity; import java.io.Serializable; import java.math.BigDecimal; -import java.util.HashMap; import java.util.Map; @Setter @@ -52,12 +51,7 @@ public static class RegistryHistoryTestEntityWithEmbeddedIdPrimaryKey implements private Long secondId; public Map asMap() { - Map mapKey = new HashMap<>(); - - mapKey.put("firstId", firstId); - mapKey.put("secondId", secondId); - - return mapKey; + return Map.of("firstId", firstId, "secondId", secondId); } } diff --git a/nrich-registry/src/test/java/net/croz/nrich/registry/history/stub/RegistryHistoryTestEntityWithEmbeddedObject.java b/nrich-registry/src/test/java/net/croz/nrich/registry/history/stub/RegistryHistoryTestEntityWithEmbeddedObject.java index d34b78b5c..c7bf2c008 100644 --- a/nrich-registry/src/test/java/net/croz/nrich/registry/history/stub/RegistryHistoryTestEntityWithEmbeddedObject.java +++ b/nrich-registry/src/test/java/net/croz/nrich/registry/history/stub/RegistryHistoryTestEntityWithEmbeddedObject.java @@ -28,7 +28,6 @@ import jakarta.persistence.ManyToOne; import java.io.Serializable; import java.math.BigDecimal; -import java.util.HashMap; import java.util.Map; @Setter @@ -55,12 +54,7 @@ public static class RegistryHistoryTestEntityWithEmbeddedObjectId implements Ser private RegistryHistoryTestEntityWithEmbeddedObjectSecondKey secondKey; public Map asMap() { - Map mapKey = new HashMap<>(); - - mapKey.put("firstKey", firstKey); - mapKey.put("secondKey", secondKey); - - return mapKey; + return Map.of("firstKey", firstKey, "secondKey", secondKey); } } diff --git a/nrich-registry/src/test/java/net/croz/nrich/registry/history/testutil/RegistryHistoryGeneratingUtil.java b/nrich-registry/src/test/java/net/croz/nrich/registry/history/testutil/RegistryHistoryGeneratingUtil.java index 4729ecfa3..815bee87c 100644 --- a/nrich-registry/src/test/java/net/croz/nrich/registry/history/testutil/RegistryHistoryGeneratingUtil.java +++ b/nrich-registry/src/test/java/net/croz/nrich/registry/history/testutil/RegistryHistoryGeneratingUtil.java @@ -30,8 +30,8 @@ import jakarta.persistence.EntityManager; import java.math.BigDecimal; -import java.util.Arrays; import java.util.Collections; +import java.util.List; import java.util.stream.IntStream; import static net.croz.nrich.registry.testutil.PersistenceTestUtil.executeInTransactionWithoutResult; @@ -116,28 +116,23 @@ public static RegistryHistoryTestEntityWithEmbeddedObject creteRegistryHistoryTe } public static ListRegistryHistoryRequest listRegistryHistoryRequestWithSort(String className, Object id) { - ListRegistryHistoryRequest request = listRegistryHistoryRequest(className, id); - - request.setSortPropertyList(Arrays.asList( + List sortPropertyList = List.of( new SortProperty(RegistryEnversConstants.REVISION_NUMBER_PROPERTY_NAME, SortDirection.DESC), new SortProperty(RegistryEnversConstants.REVISION_TYPE_PROPERTY_NAME, SortDirection.DESC), new SortProperty(RegistryEnversConstants.REVISION_TIMESTAMP_PROPERTY_NAME, SortDirection.DESC), new SortProperty("name", SortDirection.DESC), new SortProperty("revisionProperty", SortDirection.ASC) - )); + ); - return request; + return new ListRegistryHistoryRequest(className, 0, 10, id, sortPropertyList); } - public static ListRegistryHistoryRequest listRegistryHistoryRequest(String className, Object id) { - ListRegistryHistoryRequest request = new ListRegistryHistoryRequest(); - - request.setSortPropertyList(Collections.singletonList(new SortProperty(RegistryEnversConstants.REVISION_NUMBER_PROPERTY_NAME, SortDirection.ASC))); + public static ListRegistryHistoryRequest listRegistryHistoryRequestWithDefaultSort(String className, Object id) { + List sortPropertyList = List.of(new SortProperty(RegistryEnversConstants.REVISION_NUMBER_PROPERTY_NAME, SortDirection.ASC)); - request.setClassFullName(className); - request.setRegistryRecordId(id); - request.setPageNumber(0); - request.setPageSize(10); + return new ListRegistryHistoryRequest(className, 0, 10, id, sortPropertyList); + } - return request; + public static ListRegistryHistoryRequest listRegistryHistoryRequest(String className, Object id) { + return new ListRegistryHistoryRequest(className, 0, 10, id, Collections.emptyList()); } private static RegistryHistoryTestEntity createRegistryHistoryTestEntity(String name, RegistryHistoryTestEntity parent, RegistryHistoryTestEntity related) { diff --git a/nrich-search-api/src/main/java/net/croz/nrich/search/api/annotation/Projection.java b/nrich-search-api/src/main/java/net/croz/nrich/search/api/annotation/Projection.java index fbe675b24..7615530ca 100644 --- a/nrich-search-api/src/main/java/net/croz/nrich/search/api/annotation/Projection.java +++ b/nrich-search-api/src/main/java/net/croz/nrich/search/api/annotation/Projection.java @@ -28,7 +28,7 @@ * Annotation that indicates a projected value. Only necessary when projecting properties from assocations or embedded class. As an alternative Spring's @Value annotation * can also be used but this one allows for specifying condition. */ -@Target({ ElementType.FIELD }) +@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Projection { diff --git a/nrich-search-api/src/main/java/net/croz/nrich/search/api/model/operator/DefaultSearchOperator.java b/nrich-search-api/src/main/java/net/croz/nrich/search/api/model/operator/DefaultSearchOperator.java index ab32472eb..56bc681c8 100644 --- a/nrich-search-api/src/main/java/net/croz/nrich/search/api/model/operator/DefaultSearchOperator.java +++ b/nrich-search-api/src/main/java/net/croz/nrich/search/api/model/operator/DefaultSearchOperator.java @@ -49,7 +49,7 @@ public Predicate asPredicate(CriteriaBuilder criteriaBuilder, Path path, Obje LIKE { @Override public Predicate asPredicate(CriteriaBuilder criteriaBuilder, Path path, Object value) { - return criteriaBuilder.like((Expression) path, Objects.requireNonNull(value).toString() + "%"); + return criteriaBuilder.like((Expression) path, Objects.requireNonNull(value) + "%"); } }, diff --git a/nrich-search-api/src/main/java/net/croz/nrich/search/api/model/property/SearchPropertyConfiguration.java b/nrich-search-api/src/main/java/net/croz/nrich/search/api/model/property/SearchPropertyConfiguration.java index f9dfe92af..2a758fa96 100644 --- a/nrich-search-api/src/main/java/net/croz/nrich/search/api/model/property/SearchPropertyConfiguration.java +++ b/nrich-search-api/src/main/java/net/croz/nrich/search/api/model/property/SearchPropertyConfiguration.java @@ -23,7 +23,6 @@ import java.sql.Date; import java.time.temporal.Temporal; -import java.util.Arrays; import java.util.List; /** @@ -76,7 +75,7 @@ public class SearchPropertyConfiguration { public static SearchPropertyConfiguration defaultSearchPropertyConfiguration() { return new SearchPropertyConfigurationBuilder() - .rangeQuerySupportedClassList(Arrays.asList(Date.class, java.util.Date.class, Temporal.class, Number.class)) + .rangeQuerySupportedClassList(List.of(Date.class, java.util.Date.class, Temporal.class, Number.class)) .defaultSubqueryJoinAttribute("id") .rangeQueryFromIncludingSuffix("FromIncluding") .rangeQueryFromSuffix("From") diff --git a/nrich-search-api/src/main/java/net/croz/nrich/search/api/model/property/SearchPropertyJoin.java b/nrich-search-api/src/main/java/net/croz/nrich/search/api/model/property/SearchPropertyJoin.java index ac7b49428..7c4c1609b 100644 --- a/nrich-search-api/src/main/java/net/croz/nrich/search/api/model/property/SearchPropertyJoin.java +++ b/nrich-search-api/src/main/java/net/croz/nrich/search/api/model/property/SearchPropertyJoin.java @@ -17,24 +17,12 @@ package net.croz.nrich.search.api.model.property; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - /** * Represents a join between two entities. If entities are to be joined by another property (different from id). Then it needs to be specified. + * + * @param parentProperty Parent (root class) property name. + * @param childProperty Child property name. */ -@RequiredArgsConstructor -@Getter -public class SearchPropertyJoin { - - /** - * Parent (root class) property name. - */ - private final String parentProperty; - - /** - * Child property name. - */ - private final String childProperty; +public record SearchPropertyJoin(String parentProperty, String childProperty) { } diff --git a/nrich-search-api/src/main/java/net/croz/nrich/search/api/model/property/SearchPropertyMapping.java b/nrich-search-api/src/main/java/net/croz/nrich/search/api/model/property/SearchPropertyMapping.java index fe5c7a0d2..bc2200ef4 100644 --- a/nrich-search-api/src/main/java/net/croz/nrich/search/api/model/property/SearchPropertyMapping.java +++ b/nrich-search-api/src/main/java/net/croz/nrich/search/api/model/property/SearchPropertyMapping.java @@ -17,24 +17,12 @@ package net.croz.nrich.search.api.model.property; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - /** * Mapping of request property to entity property. + * + * @param name Name of property on search request class. + * @param path Path on entity for specified property. */ -@RequiredArgsConstructor -@Getter -public class SearchPropertyMapping { - - /** - * Name of property on search request class. - */ - private final String name; - - /** - * Path on entity for specified property. - */ - private final String path; +public record SearchPropertyMapping(String name, String path) { } diff --git a/nrich-search-repository-api/src/main/java/net/croz/nrich/search/api/util/PageableUtil.java b/nrich-search-repository-api/src/main/java/net/croz/nrich/search/api/util/PageableUtil.java index 68322d5f8..ed1172564 100644 --- a/nrich-search-repository-api/src/main/java/net/croz/nrich/search/api/util/PageableUtil.java +++ b/nrich-search-repository-api/src/main/java/net/croz/nrich/search/api/util/PageableUtil.java @@ -25,8 +25,8 @@ import org.springframework.data.domain.Sort; import org.springframework.util.CollectionUtils; +import java.util.ArrayList; import java.util.List; -import java.util.stream.Collectors; // TODO maybe another project? search-util? @@ -76,9 +76,11 @@ public static Pageable convertToPageable(Integer pageNumber, Integer pageSize, S } } else { - List orderList = sortPropertyList.stream() + List sortPropertyOrderList = sortPropertyList.stream() .map(PageableUtil::convertToSortOrder) - .collect(Collectors.toList()); + .toList(); + + List orderList = new ArrayList<>(sortPropertyOrderList); if (uniqueSortOrder != null && sortPropertyList.stream().map(SortProperty::getProperty).noneMatch(value -> value.equals(uniqueSortProperty.getProperty()))) { orderList.add(uniqueSortOrder); diff --git a/nrich-search-repository-api/src/test/java/net/croz/nrich/search/api/util/PageableUtilTest.java b/nrich-search-repository-api/src/test/java/net/croz/nrich/search/api/util/PageableUtilTest.java index 9df16733e..8b557f672 100644 --- a/nrich-search-repository-api/src/test/java/net/croz/nrich/search/api/util/PageableUtilTest.java +++ b/nrich-search-repository-api/src/test/java/net/croz/nrich/search/api/util/PageableUtilTest.java @@ -24,7 +24,6 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; -import java.util.Collections; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @@ -42,7 +41,7 @@ class PageableUtilTest { @Test void shouldConvertPageableSortableRequestWithUniqueSortPropertyToPageable() { // given - List sortPropertyList = Collections.singletonList(new SortProperty(SORT_PROPERTY, SortDirection.DESC)); + List sortPropertyList = List.of(new SortProperty(SORT_PROPERTY, SortDirection.DESC)); DefaultPageableSortableTestRequest request = new DefaultPageableSortableTestRequest(PAGE_NUMBER, PAGE_SIZE, sortPropertyList); // when @@ -60,7 +59,7 @@ void shouldConvertPageableSortableRequestWithUniqueSortPropertyToPageable() { @Test void shouldConvertPageableSortableRequestToPageable() { // given - List sortPropertyList = Collections.singletonList(new SortProperty(SORT_PROPERTY, SortDirection.DESC)); + List sortPropertyList = List.of(new SortProperty(SORT_PROPERTY, SortDirection.DESC)); DefaultPageableSortableTestRequest request = new DefaultPageableSortableTestRequest(PAGE_NUMBER, PAGE_SIZE, sortPropertyList); // when @@ -88,7 +87,7 @@ void shouldConvertUnsortedPageDataToPageable() { @Test void shouldConvertPageDataWithUniqueSortPropertyToPageable() { // given - List sortPropertyList = Collections.singletonList(new SortProperty(UNIQUE_SORT_PROPERTY, SortDirection.ASC)); + List sortPropertyList = List.of(new SortProperty(UNIQUE_SORT_PROPERTY, SortDirection.ASC)); // when Pageable pageable = PageableUtil.convertToPageable(PAGE_NUMBER, PAGE_SIZE, sortPropertyList); @@ -104,7 +103,7 @@ void shouldConvertPageDataWithUniqueSortPropertyToPageable() { @Test void shouldConvertPageDataWithSortPropertyToListPageable() { // given - List sortPropertyList = Collections.singletonList(new SortProperty(SORT_PROPERTY, SortDirection.DESC)); + List sortPropertyList = List.of(new SortProperty(SORT_PROPERTY, SortDirection.DESC)); // when Pageable pageable = PageableUtil.convertToPageable(PAGE_NUMBER, PAGE_SIZE, sortPropertyList); @@ -120,7 +119,7 @@ void shouldConvertPageDataWithSortPropertyToListPageable() { @Test void shouldConvertPageDataWithUniqueSortPropertyAndSortPropertyToListPageable() { // given - List sortPropertyList = Collections.singletonList(new SortProperty(SORT_PROPERTY, SortDirection.DESC)); + List sortPropertyList = List.of(new SortProperty(SORT_PROPERTY, SortDirection.DESC)); // when Pageable pageable = PageableUtil.convertToPageable(PAGE_NUMBER, PAGE_SIZE, new SortProperty(UNIQUE_SORT_PROPERTY, SortDirection.ASC), sortPropertyList); diff --git a/nrich-search-spring-boot-starter/src/main/java/net/croz/nrich/search/starter/configuration/NrichSearchAutoConfiguration.java b/nrich-search-spring-boot-starter/src/main/java/net/croz/nrich/search/starter/configuration/NrichSearchAutoConfiguration.java index d76f0c09c..008a86930 100644 --- a/nrich-search-spring-boot-starter/src/main/java/net/croz/nrich/search/starter/configuration/NrichSearchAutoConfiguration.java +++ b/nrich-search-spring-boot-starter/src/main/java/net/croz/nrich/search/starter/configuration/NrichSearchAutoConfiguration.java @@ -50,10 +50,10 @@ public class NrichSearchAutoConfiguration { @ConditionalOnMissingBean(name = "searchDefaultStringToTypeConverter") @Bean public StringToTypeConverter searchDefaultStringToTypeConverter(NrichSearchProperties searchProperties) { - List dateFormatList = searchProperties.getStringSearch().getDateFormatList(); - List decimalFormatList = searchProperties.getStringSearch().getDecimalNumberFormatList(); - String booleanTrueRegexPattern = searchProperties.getStringSearch().getBooleanTrueRegexPattern(); - String booleanFalseRegexPattern = searchProperties.getStringSearch().getBooleanFalseRegexPattern(); + List dateFormatList = searchProperties.stringSearch().dateFormatList(); + List decimalFormatList = searchProperties.stringSearch().decimalNumberFormatList(); + String booleanTrueRegexPattern = searchProperties.stringSearch().booleanTrueRegexPattern(); + String booleanFalseRegexPattern = searchProperties.stringSearch().booleanFalseRegexPattern(); return new DefaultStringToTypeConverter(dateFormatList, decimalFormatList, booleanTrueRegexPattern, booleanFalseRegexPattern); } @@ -61,6 +61,7 @@ public StringToTypeConverter searchDefaultStringToTypeConverter(NrichSea @ConditionalOnMissingBean(name = "searchStringToEntityPropertyMapConverter") @Bean public StringToEntityPropertyMapConverter searchStringToEntityPropertyMapConverter(@Lazy @Autowired(required = false) Map> stringToTypeConverterList) { + @SuppressWarnings("java:S6204") List> searchConverters = stringToTypeConverterList.entrySet().stream() .filter(entry -> entry.getKey().toLowerCase(Locale.ROOT).contains(SEARCH_CONVERTER)) .map(Map.Entry::getValue) diff --git a/nrich-search-spring-boot-starter/src/main/java/net/croz/nrich/search/starter/properties/NrichSearchProperties.java b/nrich-search-spring-boot-starter/src/main/java/net/croz/nrich/search/starter/properties/NrichSearchProperties.java index c057ae373..206770645 100644 --- a/nrich-search-spring-boot-starter/src/main/java/net/croz/nrich/search/starter/properties/NrichSearchProperties.java +++ b/nrich-search-spring-boot-starter/src/main/java/net/croz/nrich/search/starter/properties/NrichSearchProperties.java @@ -17,63 +17,31 @@ package net.croz.nrich.search.starter.properties; -import lombok.Getter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; import org.springframework.boot.context.properties.bind.DefaultValue; import java.util.List; -@Getter +/** + * @param stringSearch String search configuration used by {@link net.croz.nrich.search.converter.DefaultStringToTypeConverter} + * that is used for string search by {@link net.croz.nrich.search.api.repository.StringSearchExecutor}. + * @param defaultConverterEnabled Whether default string to type converter ({@link net.croz.nrich.search.converter.DefaultStringToTypeConverter}) used for converting strings to property values when querying is enabled. + */ @ConfigurationProperties("nrich.search") -public class NrichSearchProperties { +public record NrichSearchProperties(@DefaultValue @NestedConfigurationProperty StringSearchProperties stringSearch, + @DefaultValue("true") boolean defaultConverterEnabled) { - /** - * String search configuration used by {@link net.croz.nrich.search.converter.DefaultStringToTypeConverter} - * that is used for string search by {@link net.croz.nrich.search.api.repository.StringSearchExecutor}. - */ - @NestedConfigurationProperty - private final StringSearchProperties stringSearch; /** - * Whether default string to type converter ({@link net.croz.nrich.search.converter.DefaultStringToTypeConverter}) used for converting strings to property values when querying is enabled. + * @param dateFormatList List of date formats used by {@link net.croz.nrich.search.converter.DefaultStringToTypeConverter} to convert string to date values. + * @param decimalNumberFormatList List of decimal formats used by {@link net.croz.nrich.search.converter.DefaultStringToTypeConverter} to convert string to decimal value. + * @param booleanTrueRegexPattern Regexp pattern that is used by {@link net.croz.nrich.search.converter.DefaultStringToTypeConverter} to match boolean true values. + * @param booleanFalseRegexPattern Regexp pattern that is used by {@link net.croz.nrich.search.converter.DefaultStringToTypeConverter} to match boolean false values. */ - private final boolean defaultConverterEnabled; - - public NrichSearchProperties(@DefaultValue StringSearchProperties stringSearch, @DefaultValue("true") boolean defaultConverterEnabled) { - this.stringSearch = stringSearch; - this.defaultConverterEnabled = defaultConverterEnabled; - } - - @Getter - public static class StringSearchProperties { - - /** - * List of date formats used by {@link net.croz.nrich.search.converter.DefaultStringToTypeConverter} to convert string to date values. - */ - private final List dateFormatList; - - /** - * List of decimal formats used by {@link net.croz.nrich.search.converter.DefaultStringToTypeConverter} to convert string to decimal value. - */ - private final List decimalNumberFormatList; - - /** - * Regexp pattern that is used by {@link net.croz.nrich.search.converter.DefaultStringToTypeConverter} to match boolean true values. - */ - private final String booleanTrueRegexPattern; - - /** - * Regexp pattern that is used by {@link net.croz.nrich.search.converter.DefaultStringToTypeConverter} to match boolean false values. - */ - private final String booleanFalseRegexPattern; + public record StringSearchProperties(@DefaultValue({ "dd.MM.yyyy.", "dd.MM.yyyy.'T'HH:mm", "dd.MM.yyyy.'T'HH:mm'Z'" }) List dateFormatList, + @DefaultValue({ "#0.00", "#0,00" }) List decimalNumberFormatList, + @DefaultValue("^(?i)\\s*(true|yes|da)\\s*$") String booleanTrueRegexPattern, @DefaultValue("^(?i)\\s*(false|no|ne)\\s*$") String booleanFalseRegexPattern) { - public StringSearchProperties(@DefaultValue({ "dd.MM.yyyy.", "dd.MM.yyyy.'T'HH:mm", "dd.MM.yyyy.'T'HH:mm'Z'" }) List dateFormatList, @DefaultValue({ "#0.00", "#0,00" }) List decimalNumberFormatList, - @DefaultValue("^(?i)\\s*(true|yes|da)\\s*$") String booleanTrueRegexPattern, @DefaultValue("^(?i)\\s*(false|no|ne)\\s*$") String booleanFalseRegexPattern) { - this.dateFormatList = dateFormatList; - this.decimalNumberFormatList = decimalNumberFormatList; - this.booleanTrueRegexPattern = booleanTrueRegexPattern; - this.booleanFalseRegexPattern = booleanFalseRegexPattern; - } } } diff --git a/nrich-search-spring-boot-starter/src/test/java/net/croz/nrich/search/starter/configuration/NrichSearchAutoConfigurationTest.java b/nrich-search-spring-boot-starter/src/test/java/net/croz/nrich/search/starter/configuration/NrichSearchAutoConfigurationTest.java index 1ffd7b97a..7bd9aa036 100644 --- a/nrich-search-spring-boot-starter/src/test/java/net/croz/nrich/search/starter/configuration/NrichSearchAutoConfigurationTest.java +++ b/nrich-search-spring-boot-starter/src/test/java/net/croz/nrich/search/starter/configuration/NrichSearchAutoConfigurationTest.java @@ -38,6 +38,8 @@ void shouldConfigureDefaultConfiguration() { assertThat(context).hasSingleBean(StringToTypeConverter.class); assertThat(context).hasSingleBean(StringToEntityPropertyMapConverter.class); assertThat(context).hasSingleBean(RepositoryFactorySupportFactory.class); + assertThat(context).hasSingleBean(NrichSearchProperties.class); + assertThat(context.getBean(NrichSearchProperties.class).stringSearch()).isNotNull(); }); } @@ -56,9 +58,9 @@ void shouldAllowForOverridingStringSearchValues() { NrichSearchProperties searchProperties = context.getBean(NrichSearchProperties.class); // then - assertThat(searchProperties.getStringSearch()).isNotNull(); - assertThat(searchProperties.getStringSearch().getBooleanTrueRegexPattern()).isEqualTo("new"); - assertThat(searchProperties.getStringSearch().getBooleanFalseRegexPattern()).isEqualTo("^(?i)\\s*(false|no|ne)\\s*$"); + assertThat(searchProperties.stringSearch()).isNotNull(); + assertThat(searchProperties.stringSearch().booleanTrueRegexPattern()).isEqualTo("new"); + assertThat(searchProperties.stringSearch().booleanFalseRegexPattern()).isEqualTo("^(?i)\\s*(false|no|ne)\\s*$"); }); } } diff --git a/nrich-search/src/main/java/net/croz/nrich/search/bean/MapSupportingDirectFieldAccessFallbackBeanWrapper.java b/nrich-search/src/main/java/net/croz/nrich/search/bean/MapSupportingDirectFieldAccessFallbackBeanWrapper.java index 7058e0a08..300877f3e 100644 --- a/nrich-search/src/main/java/net/croz/nrich/search/bean/MapSupportingDirectFieldAccessFallbackBeanWrapper.java +++ b/nrich-search/src/main/java/net/croz/nrich/search/bean/MapSupportingDirectFieldAccessFallbackBeanWrapper.java @@ -27,7 +27,7 @@ public class MapSupportingDirectFieldAccessFallbackBeanWrapper extends DirectFie public MapSupportingDirectFieldAccessFallbackBeanWrapper(Object entity) { super(entity); - this.entityAsMap = entity instanceof Map ? asMap(entity) : null; + entityAsMap = entity instanceof Map ? asMap(entity) : null; } @Override diff --git a/nrich-search/src/main/java/net/croz/nrich/search/converter/DefaultStringToEntityPropertyMapConverter.java b/nrich-search/src/main/java/net/croz/nrich/search/converter/DefaultStringToEntityPropertyMapConverter.java index 65cbb9404..37151e49e 100644 --- a/nrich-search/src/main/java/net/croz/nrich/search/converter/DefaultStringToEntityPropertyMapConverter.java +++ b/nrich-search/src/main/java/net/croz/nrich/search/converter/DefaultStringToEntityPropertyMapConverter.java @@ -69,7 +69,7 @@ public Map convert(String value, List propertyToSearchLi return; } - Attribute attribute = attributeHolder.getAttribute(); + Attribute attribute = attributeHolder.attribute(); Object convertedValue = doConversion(value, attribute.getJavaType()); diff --git a/nrich-search/src/main/java/net/croz/nrich/search/converter/DefaultStringToTypeConverter.java b/nrich-search/src/main/java/net/croz/nrich/search/converter/DefaultStringToTypeConverter.java index ace4b7567..fe7b5e9f2 100644 --- a/nrich-search/src/main/java/net/croz/nrich/search/converter/DefaultStringToTypeConverter.java +++ b/nrich-search/src/main/java/net/croz/nrich/search/converter/DefaultStringToTypeConverter.java @@ -17,8 +17,6 @@ package net.croz.nrich.search.converter; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import net.croz.nrich.search.api.converter.StringToTypeConverter; import org.springframework.core.annotation.Order; @@ -35,7 +33,6 @@ import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalQuery; -import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Objects; @@ -71,11 +68,11 @@ public Object convert(String value, Class requiredType) { } Optional converterHolder = converterHolderList.stream() - .filter(holder -> holder.getType().isAssignableFrom(requiredType)) + .filter(holder -> holder.type().isAssignableFrom(requiredType)) .findFirst(); return converterHolder - .map(holder -> convertWithExceptionIgnored(() -> holder.getConversionFunction().apply(value, requiredType))) + .map(holder -> convertWithExceptionIgnored(() -> holder.conversionFunction().apply(value, requiredType))) .orElse(null); } @@ -94,7 +91,7 @@ private Object convertWithExceptionIgnored(Supplier conversionFunction) } private List initializeConverterList() { - return Arrays.asList( + return List.of( new ConverterHolder(Boolean.class, (value, type) -> booleanConverter(value)), new ConverterHolder(Long.class, (value, type) -> Long.valueOf(value)), new ConverterHolder(Integer.class, (value, type) -> Integer.valueOf(value)), @@ -176,13 +173,7 @@ private Object parseNumber(DecimalFormat format, String value) { return format.parse(value); } - @RequiredArgsConstructor - @Getter - public static class ConverterHolder { - - private final Class type; - - private final BiFunction, Object> conversionFunction; + public record ConverterHolder(Class type, BiFunction, Object> conversionFunction) { } } diff --git a/nrich-search/src/main/java/net/croz/nrich/search/model/AttributeHolder.java b/nrich-search/src/main/java/net/croz/nrich/search/model/AttributeHolder.java index 92af8cd37..639eaf3f6 100644 --- a/nrich-search/src/main/java/net/croz/nrich/search/model/AttributeHolder.java +++ b/nrich-search/src/main/java/net/croz/nrich/search/model/AttributeHolder.java @@ -17,21 +17,11 @@ package net.croz.nrich.search.model; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - import jakarta.persistence.metamodel.Attribute; import jakarta.persistence.metamodel.ManagedType; -@RequiredArgsConstructor -@Getter -public class AttributeHolder { - - private final Attribute attribute; - - private final ManagedType managedType; - private final boolean isPlural; +public record AttributeHolder(Attribute attribute, ManagedType managedType, boolean isPlural) { public boolean isFound() { return attribute != null; diff --git a/nrich-search/src/main/java/net/croz/nrich/search/model/AttributeHolderWithPath.java b/nrich-search/src/main/java/net/croz/nrich/search/model/AttributeHolderWithPath.java index d04e046cb..5d8cd52dd 100644 --- a/nrich-search/src/main/java/net/croz/nrich/search/model/AttributeHolderWithPath.java +++ b/nrich-search/src/main/java/net/croz/nrich/search/model/AttributeHolderWithPath.java @@ -17,16 +17,7 @@ package net.croz.nrich.search.model; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - -@RequiredArgsConstructor -@Getter -public class AttributeHolderWithPath { - - private final String path; - - private final AttributeHolder attributeHolder; +public record AttributeHolderWithPath(String path, AttributeHolder attributeHolder) { public boolean isFound() { return attributeHolder.isFound(); diff --git a/nrich-search/src/main/java/net/croz/nrich/search/model/Restriction.java b/nrich-search/src/main/java/net/croz/nrich/search/model/Restriction.java index 940b1f5bb..de7f51eb4 100644 --- a/nrich-search/src/main/java/net/croz/nrich/search/model/Restriction.java +++ b/nrich-search/src/main/java/net/croz/nrich/search/model/Restriction.java @@ -17,21 +17,11 @@ package net.croz.nrich.search.model; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.search.api.model.operator.SearchOperator; -@RequiredArgsConstructor -@Getter -public class Restriction { - - // TODO every aspect of path should have a marker if it is plural - private final String path; - - private final SearchOperator searchOperator; - - private final Object value; - - private final boolean isPluralAttribute; +/** + * @param path TODO every aspect of path should have a marker if it is plural + */ +public record Restriction(String path, SearchOperator searchOperator, Object value, boolean isPluralAttribute) { } diff --git a/nrich-search/src/main/java/net/croz/nrich/search/parser/SearchDataParser.java b/nrich-search/src/main/java/net/croz/nrich/search/parser/SearchDataParser.java index c2d3bcfe1..26c948a51 100644 --- a/nrich-search/src/main/java/net/croz/nrich/search/parser/SearchDataParser.java +++ b/nrich-search/src/main/java/net/croz/nrich/search/parser/SearchDataParser.java @@ -47,7 +47,6 @@ import java.util.Optional; import java.util.Set; import java.util.function.Predicate; -import java.util.stream.Collectors; @RequiredArgsConstructor public class SearchDataParser { @@ -84,24 +83,24 @@ private Set resolveRestrictionListInternal(MapSupportingDirectField if (attributeHolder.isFound()) { String currentPath = resolveCurrentPath(path, fieldNameWithoutPrefixAndSuffix); - if (attributeHolder.getManagedType() != null) { + if (attributeHolder.managedType() != null) { MapSupportingDirectFieldAccessFallbackBeanWrapper currentWrapper = new MapSupportingDirectFieldAccessFallbackBeanWrapper(value); - resolveRestrictionListInternal(currentWrapper, propertyPrefix, currentPath, attributeHolder.getManagedType(), restrictionList, attributeHolder.isPlural()); + resolveRestrictionListInternal(currentWrapper, propertyPrefix, currentPath, attributeHolder.managedType(), restrictionList, attributeHolder.isPlural()); return; } // element collections have null managed type but should be treated as plural attributes boolean isCurrentAttributePlural = attributeHolder.isPlural() || attributeHolder.isElementCollection() || isPluralAttribute; - restrictionList.add(createAttributeRestriction(attributeHolder.getAttribute().getJavaType(), originalFieldName, currentPath, value, isCurrentAttributePlural)); + restrictionList.add(createAttributeRestriction(attributeHolder.attribute().getJavaType(), originalFieldName, currentPath, value, isCurrentAttributePlural)); } else if (searchUsingPropertyMapping(searchConfiguration)) { AttributeHolderWithPath attributeWithPath = resolveAttributeFromSearchConfigurationOrPrefix(attributeResolver, originalFieldName); if (attributeWithPath.isFound()) { - attributeHolder = attributeWithPath.getAttributeHolder(); - restrictionList.add(createAttributeRestriction(attributeHolder.getAttribute().getJavaType(), originalFieldName, attributeWithPath.getPath(), value, attributeHolder.isPlural())); + attributeHolder = attributeWithPath.attributeHolder(); + restrictionList.add(createAttributeRestriction(attributeHolder.attribute().getJavaType(), originalFieldName, attributeWithPath.path(), value, attributeHolder.isPlural())); } } }); @@ -116,13 +115,13 @@ private List resolveFieldNameList(MapSupportingDirectFieldAccessFallback if (wrapper.getEntityAsMap() != null) { return wrapper.getEntityAsMap().keySet().stream() .filter(key -> !ignoredFieldList.contains(key)) - .collect(Collectors.toList()); + .toList(); } return FieldExtractionUtil.getAllFields(wrapper.getRootClass()).stream() .filter(field -> shouldIncludeField(ignoredFieldList, field)) .map(Field::getName) - .collect(Collectors.toList()); + .toList(); } private boolean shouldIncludeField(List ignoredFieldList, Field field) { @@ -142,8 +141,8 @@ private String fieldNameWithoutSuffixAndPrefix(String originalFieldName, String private boolean shouldSkipValue(Object value) { boolean skipValue; - if (value instanceof Collection) { - skipValue = CollectionUtils.isEmpty((Collection) value); + if (value instanceof Collection collection) { + skipValue = CollectionUtils.isEmpty(collection); } else { skipValue = value == null; @@ -205,7 +204,7 @@ private AttributeHolderWithPath resolveAttributeFromSearchConfigurationOrPrefix( } private AttributeHolderWithPath resolveAttributeByPrefix(JpaEntityAttributeResolver attributeResolver, String path, List previousPathList) { - String mappedPath = findPathUsingAttributePrefix(path, attributeResolver.getManagedType()); + String mappedPath = findPathUsingAttributePrefix(path, attributeResolver.managedType()); if (mappedPath == null) { return AttributeHolderWithPath.notFound(); @@ -227,7 +226,7 @@ private AttributeHolderWithPath resolveAttributeByPrefix(JpaEntityAttributeResol String leftOverPath = PathResolvingUtil.removeFirstPathElement(currentPath); previousPathList.add(currentPrefix); - return resolveAttributeByPrefix(new JpaEntityAttributeResolver(attributeHolder.getManagedType()), leftOverPath, previousPathList); + return resolveAttributeByPrefix(new JpaEntityAttributeResolver(attributeHolder.managedType()), leftOverPath, previousPathList); } } @@ -238,8 +237,8 @@ private String findPathUsingMapping(List propertyMappingL return Optional.ofNullable(propertyMappingList) .orElse(Collections.emptyList()) .stream() - .filter(mapping -> fieldName.equals(mapping.getName())) - .map(SearchPropertyMapping::getPath) + .filter(mapping -> fieldName.equals(mapping.name())) + .map(SearchPropertyMapping::path) .findAny() .orElse(null); } @@ -248,7 +247,7 @@ private String findPathUsingAttributePrefix(String originalFieldName, ManagedTyp List attributeNameList = managedType.getAttributes().stream() .filter(attribute -> attribute.isAssociation() || attribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.EMBEDDED) .map(Attribute::getName) - .collect(Collectors.toList()); + .toList(); return attributeNameList.stream() .filter(attribute -> isFieldNameValid(originalFieldName, attribute)) diff --git a/nrich-search/src/main/java/net/croz/nrich/search/support/JpaEntityAttributeResolver.java b/nrich-search/src/main/java/net/croz/nrich/search/support/JpaEntityAttributeResolver.java index 482c9cfb2..9806ae06b 100644 --- a/nrich-search/src/main/java/net/croz/nrich/search/support/JpaEntityAttributeResolver.java +++ b/nrich-search/src/main/java/net/croz/nrich/search/support/JpaEntityAttributeResolver.java @@ -17,8 +17,6 @@ package net.croz.nrich.search.support; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.search.model.AttributeHolder; import net.croz.nrich.search.util.AttributeResolvingUtil; import net.croz.nrich.search.util.PathResolvingUtil; @@ -30,11 +28,7 @@ import jakarta.persistence.metamodel.SingularAttribute; import java.util.Arrays; -@Getter -@RequiredArgsConstructor -public class JpaEntityAttributeResolver { - - private final ManagedType managedType; +public record JpaEntityAttributeResolver(ManagedType managedType) { public AttributeHolder resolveAttributeByPath(String path) { Assert.notNull(path, "Path must be defined when searching for attribute!"); @@ -65,11 +59,11 @@ public AttributeHolder resolveAttributeByPath(String path) { private ManagedType resolveManagedTypeFromAttribute(Attribute attribute) { ManagedType currentManagedType = null; - if (attribute instanceof SingularAttribute && ((SingularAttribute) attribute).getType() instanceof ManagedType) { - currentManagedType = ((ManagedType) ((SingularAttribute) attribute).getType()); + if (attribute instanceof SingularAttribute && ((SingularAttribute) attribute).getType() instanceof ManagedType attributeManagedType) { + currentManagedType = attributeManagedType; } - else if (attribute instanceof PluralAttribute && ((PluralAttribute) attribute).getElementType() instanceof ManagedType) { - currentManagedType = ((ManagedType) ((PluralAttribute) attribute).getElementType()); + else if (attribute instanceof PluralAttribute && ((PluralAttribute) attribute).getElementType() instanceof ManagedType attributeManagedType) { + currentManagedType = attributeManagedType; } return currentManagedType; diff --git a/nrich-search/src/main/java/net/croz/nrich/search/support/JpaQueryBuilder.java b/nrich-search/src/main/java/net/croz/nrich/search/support/JpaQueryBuilder.java index 876b862de..370d48469 100644 --- a/nrich-search/src/main/java/net/croz/nrich/search/support/JpaQueryBuilder.java +++ b/nrich-search/src/main/java/net/croz/nrich/search/support/JpaQueryBuilder.java @@ -192,6 +192,7 @@ private void applyJoinsOrFetchesToQuery(boolean applyFetch, R request, Root< .forEach(searchJoin -> applyJoinOrJoinFetch(existingFetches, existingJoins, root, searchJoin, applyFetch)); } + @SuppressWarnings("java:S6204") private List> resolveQueryProjectionList(Root root, JoinType defaultJoinType, List> projectionList, R request) { if (CollectionUtils.isEmpty(projectionList)) { return Collections.emptyList(); @@ -266,7 +267,9 @@ private List resolveQueryPredicateList(R request, SearchConfig } } - List> subqueryList = resolveSubqueryList(request, searchConfiguration.getSearchPropertyConfiguration(), searchConfiguration.getSubqueryConfigurationList(), root, query, criteriaBuilder); + List> subqueryList = resolveSubqueryList( + request, searchConfiguration.getSearchPropertyConfiguration(), searchConfiguration.getSubqueryConfigurationList(), root, query, criteriaBuilder + ); subqueryList.forEach(subquery -> mainQueryPredicateList.add(criteriaBuilder.exists(subquery))); @@ -284,8 +287,8 @@ private Subquery createSubqueryRestriction( List subQueryPredicateList = convertRestrictionListToPredicateList(restrictionList, subqueryRoot, criteriaBuilder, defaultJoinType); - Path parentPath = PathResolvingUtil.calculateFullPath(parent, defaultJoinType, PathResolvingUtil.convertToPathList(searchPropertyJoin.getParentProperty())); - Path subqueryPath = PathResolvingUtil.calculateFullPath(subqueryRoot, defaultJoinType, PathResolvingUtil.convertToPathList(searchPropertyJoin.getChildProperty())); + Path parentPath = PathResolvingUtil.calculateFullPath(parent, defaultJoinType, PathResolvingUtil.convertToPathList(searchPropertyJoin.parentProperty())); + Path subqueryPath = PathResolvingUtil.calculateFullPath(subqueryRoot, defaultJoinType, PathResolvingUtil.convertToPathList(searchPropertyJoin.childProperty())); subQueryPredicateList.add(criteriaBuilder.equal(parentPath, subqueryPath)); @@ -296,11 +299,11 @@ private List convertRestrictionListToPredicateList(Collection predicateList = new ArrayList<>(); restrictionList.stream().filter(Objects::nonNull).forEach(restriction -> { - String[] pathList = PathResolvingUtil.convertToPathList(restriction.getPath()); + String[] pathList = PathResolvingUtil.convertToPathList(restriction.path()); Path fullPath = PathResolvingUtil.calculateFullPath(rootPath, joinType, pathList); - predicateList.add(restriction.getSearchOperator().asPredicate(criteriaBuilder, fullPath, restriction.getValue())); + predicateList.add(restriction.searchOperator().asPredicate(criteriaBuilder, fullPath, restriction.value())); }); return predicateList; @@ -313,7 +316,7 @@ private SearchPropertyJoin resolveSearchPropertyJoin(Root root) { } // TODO enable join usage or subquery? - private List> resolveSubqueryList(R request, SearchPropertyConfiguration searchPropertyConfiguration, List subqueryConfigurationList, Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) { + private List> resolveSubqueryList(R request, SearchPropertyConfiguration searchPropertyConfiguration, List subqueryConfigurationList, Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) { if (CollectionUtils.isEmpty(subqueryConfigurationList)) { return Collections.emptyList(); } @@ -321,7 +324,7 @@ private List> resolveSubqueryList(R request, SearchPropertyConfi return subqueryConfigurationList.stream() .map(subqueryConfiguration -> buildSubquery(request, searchPropertyConfiguration, root, query, criteriaBuilder, subqueryConfiguration)) .filter(Objects::nonNull) - .collect(Collectors.toList()); + .toList(); } private Subquery buildSubquery( @@ -364,7 +367,8 @@ private Selection convertToSelectionExpression(JoinType defaultJoinType, } private List resolveInterceptorPredicateList(R request, List> additionalRestrictionResolverList, CriteriaBuilder criteriaBuilder, Root root, CriteriaQuery

query) { - return Optional.ofNullable(additionalRestrictionResolverList).orElse(Collections.emptyList()).stream().map(interceptor -> interceptor.resolvePredicateList(criteriaBuilder, query, root, request)).filter(Objects::nonNull).flatMap(List::stream).collect(Collectors.toList()); + return Optional.ofNullable(additionalRestrictionResolverList).orElse(Collections.emptyList()).stream().map(interceptor -> interceptor.resolvePredicateList(criteriaBuilder, query, root, request)).filter(Objects::nonNull).flatMap(List::stream) + .toList(); } private void applyPredicatesToQuery(CriteriaBuilder criteriaBuilder, CriteriaQuery query, boolean anyMatch, List requestPredicateList, List interceptorPredicateList) { diff --git a/nrich-search/src/main/java/net/croz/nrich/search/util/ProjectionListResolverUtil.java b/nrich-search/src/main/java/net/croz/nrich/search/util/ProjectionListResolverUtil.java index 01740eb6f..d311b0d37 100644 --- a/nrich-search/src/main/java/net/croz/nrich/search/util/ProjectionListResolverUtil.java +++ b/nrich-search/src/main/java/net/croz/nrich/search/util/ProjectionListResolverUtil.java @@ -30,7 +30,6 @@ import java.util.Arrays; import java.util.List; import java.util.function.Predicate; -import java.util.stream.Collectors; public final class ProjectionListResolverUtil { @@ -43,7 +42,7 @@ public static List> resolveSearchProjectionList(Class return Arrays.stream(projectionType.getDeclaredFields()) .filter(shouldIncludeField) .map(ProjectionListResolverUtil::convertToProjection) - .collect(Collectors.toList()); + .toList(); } private static SearchProjection convertToProjection(Field field) { @@ -85,12 +84,12 @@ else if (!Projection.DEFAULT.class.equals(conditionClass)) { private static Predicate createPredicateFromClosure(Class conditionClass) { Constructor closureConstructor = conditionClass.getDeclaredConstructor(Object.class, Object.class); - return (value) -> { + return value -> { try { return Boolean.TRUE.equals(conditionClass.getMethod("call", Object.class).invoke(closureConstructor.newInstance(value, value), value)); } - catch (Exception e) { - throw new RuntimeException("Error invoking closure", e); + catch (Exception exception) { + throw new IllegalArgumentException("Invalid closure provided", exception); } }; } diff --git a/nrich-search/src/main/java/net/croz/nrich/search/util/PropertyNameUtil.java b/nrich-search/src/main/java/net/croz/nrich/search/util/PropertyNameUtil.java index 0bfc73588..c63d724dc 100644 --- a/nrich-search/src/main/java/net/croz/nrich/search/util/PropertyNameUtil.java +++ b/nrich-search/src/main/java/net/croz/nrich/search/util/PropertyNameUtil.java @@ -25,7 +25,7 @@ private PropertyNameUtil() { } public static String propertyNameWithoutSuffix(String originalPropertyName, SearchPropertyConfiguration searchPropertyConfiguration) { - String[] suffixListToRemove = new String[] { + String[] suffixListToRemove = { searchPropertyConfiguration.getRangeQueryFromIncludingSuffix(), searchPropertyConfiguration.getRangeQueryFromSuffix(), searchPropertyConfiguration.getRangeQueryToIncludingSuffix(), searchPropertyConfiguration.getRangeQueryToSuffix(), searchPropertyConfiguration.getCollectionQuerySuffix() }; diff --git a/nrich-search/src/test/groovy/net/croz/nrich/search/util/GroovyUtilTest.groovy b/nrich-search/src/test/groovy/net/croz/nrich/search/util/GroovyUtilTest.groovy index 54dd87586..d1989b1a7 100644 --- a/nrich-search/src/test/groovy/net/croz/nrich/search/util/GroovyUtilTest.groovy +++ b/nrich-search/src/test/groovy/net/croz/nrich/search/util/GroovyUtilTest.groovy @@ -1,3 +1,20 @@ +/* + * Copyright 2020-2023 CROZ d.o.o, the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + package net.croz.nrich.search.util import org.junit.jupiter.params.ParameterizedTest @@ -31,7 +48,6 @@ class GroovyUtilTest { classUtilsMock.close() } - @MethodSource("shouldCheckIfGivenClassIsGroovyClosureMethodSource") @ParameterizedTest void shouldCheckIfGivenClassIsGroovyClosure(Class type, boolean expectedResult) { diff --git a/nrich-search/src/test/groovy/net/croz/nrich/search/util/ProjectionListResolverUtilWithGroovyClosureTest.groovy b/nrich-search/src/test/groovy/net/croz/nrich/search/util/ProjectionListResolverUtilWithGroovyClosureTest.groovy index ac222d436..45f323972 100644 --- a/nrich-search/src/test/groovy/net/croz/nrich/search/util/ProjectionListResolverUtilWithGroovyClosureTest.groovy +++ b/nrich-search/src/test/groovy/net/croz/nrich/search/util/ProjectionListResolverUtilWithGroovyClosureTest.groovy @@ -17,19 +17,16 @@ package net.croz.nrich.search.util -import net.croz.nrich.search.SearchTestConfiguration import net.croz.nrich.search.api.model.SearchProjection import net.croz.nrich.search.util.stub.ProjectionListResolverUtilWithGroovyClosureTestEntity import net.croz.nrich.search.util.stub.ProjectionListResolverUtilWithGroovyClosureWithExceptionTestEntity import org.junit.jupiter.api.Test import org.mockito.MockedStatic -import org.springframework.test.context.junit.jupiter.SpringJUnitConfig import static org.assertj.core.api.Assertions.assertThat import static org.assertj.core.api.Assertions.catchThrowable import static org.mockito.Mockito.mockStatic -@SpringJUnitConfig(SearchTestConfiguration) class ProjectionListResolverUtilWithGroovyClosureTest { @Test @@ -53,10 +50,10 @@ class ProjectionListResolverUtilWithGroovyClosureTest { assertThat(result).extracting("alias").containsExactly("name", "nestedName", "nestedId", "conditionalName") // and when - SearchProjection conditionalProjection = result.stream() - .filter(projection -> "conditionalName".equals(projection.getAlias())) - .findFirst() - .orElse(null) + SearchProjection conditionalProjection = result.stream() + .filter(projection -> "conditionalName" == projection.getAlias()) + .findFirst() + .orElse(null) // then assertThat(conditionalProjection).isNotNull() @@ -86,10 +83,10 @@ class ProjectionListResolverUtilWithGroovyClosureTest { List> result = ProjectionListResolverUtil .resolveSearchProjectionList(ProjectionListResolverUtilWithGroovyClosureWithExceptionTestEntity.class) - SearchProjection conditionalProjection = result.stream() - .filter(projection -> "conditionalName".equals(projection.getAlias())) - .findFirst() - .orElse(null) + SearchProjection conditionalProjection = result.stream() + .filter(projection -> "conditionalName" == projection.getAlias()) + .findFirst() + .orElse(null) // when Throwable thrown = catchThrowable(() -> conditionalProjection.getCondition().test(new ProjectionListResolverUtilWithGroovyClosureWithExceptionTestEntity())) diff --git a/nrich-search/src/test/groovy/net/croz/nrich/search/util/stub/ProjectionListResolverUtilWithGroovyClosureTestEntity.groovy b/nrich-search/src/test/groovy/net/croz/nrich/search/util/stub/ProjectionListResolverUtilWithGroovyClosureTestEntity.groovy index 1d0f25bbe..5be9eaced 100644 --- a/nrich-search/src/test/groovy/net/croz/nrich/search/util/stub/ProjectionListResolverUtilWithGroovyClosureTestEntity.groovy +++ b/nrich-search/src/test/groovy/net/croz/nrich/search/util/stub/ProjectionListResolverUtilWithGroovyClosureTestEntity.groovy @@ -22,18 +22,15 @@ import org.springframework.beans.factory.annotation.Value class ProjectionListResolverUtilWithGroovyClosureTestEntity { - private static String STATIC_PROPERTY = "value" - - private String name - - private transient String transientProperty + String name @Projection(path = "nestedEntity.nestedEntityName") - private String nestedName + String nestedName @Value("nestedEntity.id") - private Long nestedId + Long nestedId @Projection(path = "nestedEntity.anotherName", condition = { it == null }) - private String conditionalName + String conditionalName + } diff --git a/nrich-search/src/test/groovy/net/croz/nrich/search/util/stub/ProjectionListResolverUtilWithGroovyClosureWithExceptionTestEntity.groovy b/nrich-search/src/test/groovy/net/croz/nrich/search/util/stub/ProjectionListResolverUtilWithGroovyClosureWithExceptionTestEntity.groovy index 741bfd06a..a0c5bfa52 100644 --- a/nrich-search/src/test/groovy/net/croz/nrich/search/util/stub/ProjectionListResolverUtilWithGroovyClosureWithExceptionTestEntity.groovy +++ b/nrich-search/src/test/groovy/net/croz/nrich/search/util/stub/ProjectionListResolverUtilWithGroovyClosureWithExceptionTestEntity.groovy @@ -22,18 +22,15 @@ import org.springframework.beans.factory.annotation.Value class ProjectionListResolverUtilWithGroovyClosureWithExceptionTestEntity { - private static String STATIC_PROPERTY = "value" - - private String name - - private transient String transientProperty + String name @Projection(path = "nestedEntity.nestedEntityName") - private String nestedName + String nestedName @Value("nestedEntity.id") - private Long nestedId + Long nestedId @Projection(path = "nestedEntity.anotherName", condition = { throw new RuntimeException() }) - private String conditionalName + String conditionalName + } diff --git a/nrich-search/src/test/java/net/croz/nrich/search/SearchTestConfiguration.java b/nrich-search/src/test/java/net/croz/nrich/search/SearchTestConfiguration.java index 05a228d55..0e6bd97dc 100644 --- a/nrich-search/src/test/java/net/croz/nrich/search/SearchTestConfiguration.java +++ b/nrich-search/src/test/java/net/croz/nrich/search/SearchTestConfiguration.java @@ -36,7 +36,6 @@ import jakarta.persistence.EntityManagerFactory; import javax.sql.DataSource; -import java.util.Arrays; import java.util.List; import java.util.TimeZone; @@ -80,8 +79,8 @@ public JpaTransactionManager transactionManager(EntityManagerFactory entityManag @Bean public StringToTypeConverter defaultStringToTypeConverter() { - List dateFormatList = Arrays.asList("dd.MM.yyyy.", "dd.MM.yyyy.'T'HH:mm"); - List decimalFormatList = Arrays.asList("#0.00", "#0,00"); + List dateFormatList = List.of("dd.MM.yyyy.", "dd.MM.yyyy.'T'HH:mm"); + List decimalFormatList = List.of("#0.00", "#0,00"); String booleanTrueRegexPattern = "^(?i)\\s*(true|yes)\\s*$"; String booleanFalseRegexPattern = "^(?i)\\s*(false|no)\\s*$"; diff --git a/nrich-search/src/test/java/net/croz/nrich/search/converter/DefaultStringToEntityPropertyMapConverterTest.java b/nrich-search/src/test/java/net/croz/nrich/search/converter/DefaultStringToEntityPropertyMapConverterTest.java index 7048f9d16..6503ae246 100644 --- a/nrich-search/src/test/java/net/croz/nrich/search/converter/DefaultStringToEntityPropertyMapConverterTest.java +++ b/nrich-search/src/test/java/net/croz/nrich/search/converter/DefaultStringToEntityPropertyMapConverterTest.java @@ -27,7 +27,6 @@ import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import jakarta.persistence.metamodel.ManagedType; -import java.util.Arrays; import java.util.List; import java.util.Map; @@ -51,7 +50,7 @@ void shouldConvertStringToEntityPropertyMap() { String value = "01.01.1970."; // when - Map result = stringToEntityPropertyMapConverter.convert(value, Arrays.asList("name", "date", "nestedEntity.nestedName"), managedTypeOfTestEntity(), PROPERTY_CONFIGURATION); + Map result = stringToEntityPropertyMapConverter.convert(value, List.of("name", "date", "nestedEntity.nestedName"), managedTypeOfTestEntity(), PROPERTY_CONFIGURATION); // then assertThat(result).containsEntry("name", value).containsEntry("date", dateOf(value)).containsEntry("nestedEntity.nestedName", value); @@ -63,7 +62,7 @@ void shouldNotFailOnNonExistingAttributes() { String value = "name"; // when - Map result = stringToEntityPropertyMapConverter.convert(value, Arrays.asList("name", "nonExisting"), managedTypeOfTestEntity(), PROPERTY_CONFIGURATION); + Map result = stringToEntityPropertyMapConverter.convert(value, List.of("name", "nonExisting"), managedTypeOfTestEntity(), PROPERTY_CONFIGURATION); // then assertThat(result).containsEntry("name", value); @@ -76,7 +75,7 @@ void shouldReturnEmptyMapWhenValueIsNull() { String value = null; // when - Map result = stringToEntityPropertyMapConverter.convert(value, Arrays.asList("name", "nonExisting"), managedTypeOfTestEntity(), PROPERTY_CONFIGURATION); + Map result = stringToEntityPropertyMapConverter.convert(value, List.of("name", "nonExisting"), managedTypeOfTestEntity(), PROPERTY_CONFIGURATION); // then assertThat(result).isEmpty(); @@ -98,7 +97,7 @@ void shouldReturnEmptyMapWhenPropertyListIsEmpty() { void shouldConvertPropertyWithSuffix() { // given String value = "01.01.1970."; - List propertyToSearchList = Arrays.asList("dateFrom", "dateFromIncluding", "dateTo", "dateToIncluding"); + List propertyToSearchList = List.of("dateFrom", "dateFromIncluding", "dateTo", "dateToIncluding"); // when Map result = stringToEntityPropertyMapConverter.convert(value, propertyToSearchList, managedTypeOfTestEntity(), PROPERTY_CONFIGURATION); diff --git a/nrich-search/src/test/java/net/croz/nrich/search/converter/DefaultStringToTypeConverterTest.java b/nrich-search/src/test/java/net/croz/nrich/search/converter/DefaultStringToTypeConverterTest.java index 2d2c5cae2..61d85c3cf 100644 --- a/nrich-search/src/test/java/net/croz/nrich/search/converter/DefaultStringToTypeConverterTest.java +++ b/nrich-search/src/test/java/net/croz/nrich/search/converter/DefaultStringToTypeConverterTest.java @@ -29,8 +29,8 @@ import java.time.OffsetTime; import java.time.ZoneId; import java.time.ZonedDateTime; -import java.util.Arrays; import java.util.Date; +import java.util.List; import java.util.TimeZone; import java.util.stream.Stream; @@ -44,8 +44,8 @@ class DefaultStringToTypeConverterTest { private final DefaultStringToTypeConverter defaultStringToTypeConverter = new DefaultStringToTypeConverter( - Arrays.asList("dd.MM.yyyy.", "dd.MM.yyyy.'T'HH:mm", "dd.MM.yyyy.'T'HH:mm'Z'", "dd.MM.yyyy.'T'HH:mmXXX", "HH:mmXXX"), - Arrays.asList("#0.00", "#0,00"), "^(?i)\\s*(true|yes)\\s*$", "^(?i)\\s*(false|no)\\s*$" + List.of("dd.MM.yyyy.", "dd.MM.yyyy.'T'HH:mm", "dd.MM.yyyy.'T'HH:mm'Z'", "dd.MM.yyyy.'T'HH:mmXXX", "HH:mmXXX"), + List.of("#0.00", "#0,00"), "^(?i)\\s*(true|yes)\\s*$", "^(?i)\\s*(false|no)\\s*$" ); static { diff --git a/nrich-search/src/test/java/net/croz/nrich/search/repository/JpaSearchExecutorTest.java b/nrich-search/src/test/java/net/croz/nrich/search/repository/JpaSearchExecutorTest.java index 70a0807b7..33a84b2de 100644 --- a/nrich-search/src/test/java/net/croz/nrich/search/repository/JpaSearchExecutorTest.java +++ b/nrich-search/src/test/java/net/croz/nrich/search/repository/JpaSearchExecutorTest.java @@ -39,7 +39,6 @@ import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; -import java.util.Collections; import java.util.List; import java.util.Optional; @@ -176,7 +175,7 @@ void shouldCountDistinctEntities() { SearchConfiguration searchConfiguration = SearchConfiguration.builder() .distinct(true) - .joinList(Collections.singletonList(SearchJoin.leftJoin("collectionEntityList"))) + .joinList(List.of(SearchJoin.leftJoin("collectionEntityList"))) .build(); // when @@ -193,7 +192,7 @@ void shouldCountDistinctEntitiesWithJoinFetch() { SearchConfiguration searchConfiguration = SearchConfiguration.builder() .distinct(true) - .joinList(Collections.singletonList(SearchJoin.innerJoinFetch("collectionEntityList"))) + .joinList(List.of(SearchJoin.innerJoinFetch("collectionEntityList"))) .build(); // when long result = testEntitySearchRepository.count(request, searchConfiguration); @@ -211,7 +210,7 @@ void shouldCountWhenUsingSearchingSubEntity() { .joinBy(new SearchPropertyJoin("id", "testEntity.id")).build(); SearchConfiguration searchConfiguration = SearchConfiguration.builder() - .subqueryConfigurationList(Collections.singletonList(subqueryConfiguration)) + .subqueryConfigurationList(List.of(subqueryConfiguration)) .build(); TestEntitySearchRequest request = TestEntitySearchRequest.builder() diff --git a/nrich-search/src/test/java/net/croz/nrich/search/repository/JpaStringSearchExecutorTest.java b/nrich-search/src/test/java/net/croz/nrich/search/repository/JpaStringSearchExecutorTest.java index fcf4facce..0edf63f86 100644 --- a/nrich-search/src/test/java/net/croz/nrich/search/repository/JpaStringSearchExecutorTest.java +++ b/nrich-search/src/test/java/net/croz/nrich/search/repository/JpaStringSearchExecutorTest.java @@ -33,8 +33,6 @@ import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; @@ -62,7 +60,7 @@ void setup() { @Test void shouldFindOne() { // when - Optional result = testEntityStringSearchRepository.findOne("01.01.1970.", Collections.singletonList("localDate"), EMPTY_CONFIGURATION); + Optional result = testEntityStringSearchRepository.findOne("01.01.1970.", List.of("localDate"), EMPTY_CONFIGURATION); // then assertThat(result).isNotEmpty(); @@ -71,7 +69,7 @@ void shouldFindOne() { @Test void shouldReturnEmptyOptionalWhenNoResultsHaveBeenFound() { // when - Optional result = testEntityStringSearchRepository.findOne("01.01.2000.", Collections.singletonList("localDate"), EMPTY_CONFIGURATION); + Optional result = testEntityStringSearchRepository.findOne("01.01.2000.", List.of("localDate"), EMPTY_CONFIGURATION); // then assertThat(result).isEmpty(); @@ -83,7 +81,7 @@ void shouldFindOneMatchingAnyProperty() { SearchConfiguration> searchConfiguration = SearchConfiguration.emptyConfigurationMatchingAny(); // when - Optional result = testEntityStringSearchRepository.findOne("01.01.1970.", Arrays.asList("age", "localDate", "name"), searchConfiguration); + Optional result = testEntityStringSearchRepository.findOne("01.01.1970.", List.of("age", "localDate", "name"), searchConfiguration); // then assertThat(result).isNotEmpty(); @@ -92,7 +90,7 @@ void shouldFindOneMatchingAnyProperty() { @Test void shouldFindAll() { // when - List result = testEntityStringSearchRepository.findAll("name 1", Collections.singletonList("name"), EMPTY_CONFIGURATION); + List result = testEntityStringSearchRepository.findAll("name 1", List.of("name"), EMPTY_CONFIGURATION); // then assertThat(result).hasSize(1); @@ -101,7 +99,7 @@ void shouldFindAll() { @Test void shouldFindAllWithSort() { // when - List result = testEntityStringSearchRepository.findAll("name", Collections.singletonList("name"), EMPTY_CONFIGURATION, Sort.by(Sort.Order.desc("name"))); + List result = testEntityStringSearchRepository.findAll("name", List.of("name"), EMPTY_CONFIGURATION, Sort.by(Sort.Order.desc("name"))); // then assertThat(result).hasSize(5); @@ -111,7 +109,7 @@ void shouldFindAllWithSort() { @Test void shouldFindAllWithPaging() { // when - Page result = testEntityStringSearchRepository.findAll("51", Collections.singletonList("age"), EMPTY_CONFIGURATION, PageRequest.of(0, 1)); + Page result = testEntityStringSearchRepository.findAll("51", List.of("age"), EMPTY_CONFIGURATION, PageRequest.of(0, 1)); // then assertThat(result).hasSize(1); @@ -120,7 +118,7 @@ void shouldFindAllWithPaging() { @Test void shouldReturnWholeResultListWhenRequestIsUnpaged() { // when - Page result = testEntityStringSearchRepository.findAll("10", Collections.singletonList("ageFrom"), EMPTY_CONFIGURATION, Pageable.unpaged()); + Page result = testEntityStringSearchRepository.findAll("10", List.of("ageFrom"), EMPTY_CONFIGURATION, Pageable.unpaged()); // then assertThat(result).isNotEmpty(); @@ -131,7 +129,7 @@ void shouldReturnWholeResultListWhenRequestIsUnpaged() { @Test void shouldCount() { // when - long result = testEntityStringSearchRepository.count("51", Collections.singletonList("age"), EMPTY_CONFIGURATION); + long result = testEntityStringSearchRepository.count("51", List.of("age"), EMPTY_CONFIGURATION); // then assertThat(result).isEqualTo(1); @@ -140,7 +138,7 @@ void shouldCount() { @Test void shouldReturnZeroWhenThereAreNoResults() { // when - long result = testEntityStringSearchRepository.count("5555", Collections.singletonList("age"), EMPTY_CONFIGURATION); + long result = testEntityStringSearchRepository.count("5555", List.of("age"), EMPTY_CONFIGURATION); // then assertThat(result).isZero(); @@ -149,7 +147,7 @@ void shouldReturnZeroWhenThereAreNoResults() { @Test void shouldReturnTrueWhenEntityExists() { // when - boolean result = testEntityStringSearchRepository.exists("51", Collections.singletonList("age"), EMPTY_CONFIGURATION); + boolean result = testEntityStringSearchRepository.exists("51", List.of("age"), EMPTY_CONFIGURATION); // then assertThat(result).isTrue(); @@ -158,7 +156,7 @@ void shouldReturnTrueWhenEntityExists() { @Test void shouldReturnFalseWhenEntityDoesntExist() { // when - boolean result = testEntityStringSearchRepository.exists("51111", Collections.singletonList("age"), EMPTY_CONFIGURATION); + boolean result = testEntityStringSearchRepository.exists("51111", List.of("age"), EMPTY_CONFIGURATION); // then assertThat(result).isFalse(); @@ -167,7 +165,7 @@ void shouldReturnFalseWhenEntityDoesntExist() { @Test void shouldFindByRangeQuery() { // when - long result = testEntityStringSearchRepository.count("02.01.1970.", Collections.singletonList("localDateFrom"), EMPTY_CONFIGURATION); + long result = testEntityStringSearchRepository.count("02.01.1970.", List.of("localDateFrom"), EMPTY_CONFIGURATION); // then assertThat(result).isEqualTo(3); diff --git a/nrich-search/src/test/java/net/croz/nrich/search/repository/stub/TestEntityAdditionalRestrictionResolver.java b/nrich-search/src/test/java/net/croz/nrich/search/repository/stub/TestEntityAdditionalRestrictionResolver.java index 9db8be1e4..ea29b48b4 100644 --- a/nrich-search/src/test/java/net/croz/nrich/search/repository/stub/TestEntityAdditionalRestrictionResolver.java +++ b/nrich-search/src/test/java/net/croz/nrich/search/repository/stub/TestEntityAdditionalRestrictionResolver.java @@ -24,7 +24,6 @@ import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Predicate; import jakarta.persistence.criteria.Root; -import java.util.Collections; import java.util.List; @RequiredArgsConstructor @@ -35,7 +34,7 @@ public class TestEntityAdditionalRestrictionResolver implements AdditionalRestri @Override public List resolvePredicateList(CriteriaBuilder criteriaBuilder, CriteriaQuery query, Root root, TestEntitySearchRequest request) { if (appendAdditionalRestriction) { - return Collections.singletonList(criteriaBuilder.greaterThan(root.get("age"), 100)); + return List.of(criteriaBuilder.greaterThan(root.get("age"), 100)); } return null; diff --git a/nrich-search/src/test/java/net/croz/nrich/search/repository/stub/TestEntityDto.java b/nrich-search/src/test/java/net/croz/nrich/search/repository/stub/TestEntityDto.java index 468cc2361..7529cb920 100644 --- a/nrich-search/src/test/java/net/croz/nrich/search/repository/stub/TestEntityDto.java +++ b/nrich-search/src/test/java/net/croz/nrich/search/repository/stub/TestEntityDto.java @@ -17,15 +17,6 @@ package net.croz.nrich.search.repository.stub; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - -@RequiredArgsConstructor -@Getter -public class TestEntityDto { - - private final String name; - - private final String nestedName; +public record TestEntityDto(String name, String nestedName) { } diff --git a/nrich-search/src/test/java/net/croz/nrich/search/repository/stub/TestEntityProjectionDto.java b/nrich-search/src/test/java/net/croz/nrich/search/repository/stub/TestEntityProjectionDto.java index 007804655..985a63980 100644 --- a/nrich-search/src/test/java/net/croz/nrich/search/repository/stub/TestEntityProjectionDto.java +++ b/nrich-search/src/test/java/net/croz/nrich/search/repository/stub/TestEntityProjectionDto.java @@ -17,21 +17,9 @@ package net.croz.nrich.search.repository.stub; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.search.api.annotation.Projection; import org.springframework.beans.factory.annotation.Value; -@RequiredArgsConstructor -@Getter -public class TestEntityProjectionDto { - - private final String name; - - @Projection(path = "nestedEntity.nestedEntityName") - private final String nestedName; - - @Value("nestedEntity.id") - private final Long nestedId; +public record TestEntityProjectionDto(String name, @Projection(path = "nestedEntity.nestedEntityName") String nestedName, @Value("nestedEntity.id") Long nestedId) { } diff --git a/nrich-search/src/test/java/net/croz/nrich/search/repository/stub/TestEntitySearchRequest.java b/nrich-search/src/test/java/net/croz/nrich/search/repository/stub/TestEntitySearchRequest.java index 866b98202..8bc13c980 100644 --- a/nrich-search/src/test/java/net/croz/nrich/search/repository/stub/TestEntitySearchRequest.java +++ b/nrich-search/src/test/java/net/croz/nrich/search/repository/stub/TestEntitySearchRequest.java @@ -20,7 +20,6 @@ import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; -import lombok.RequiredArgsConstructor; import lombok.Setter; import java.util.List; @@ -79,27 +78,15 @@ public TestEntitySearchRequest(String name) { this.name = name; } - @RequiredArgsConstructor - @Getter - public static class TestNestedEntitySearchRequest { - - private final String nestedEntityName; + public record TestNestedEntitySearchRequest(String nestedEntityName) { } - @RequiredArgsConstructor - @Getter - public static class TestCollectionEntitySearchRequest { - - private final String name; + public record TestCollectionEntitySearchRequest(String name) { } - @RequiredArgsConstructor - @Getter - public static class TestEntityEmbeddedSearchRequest { - - private final String embeddedName; + public record TestEntityEmbeddedSearchRequest(String embeddedName) { } } diff --git a/nrich-search/src/test/java/net/croz/nrich/search/repository/support/JpaQueryBuilderTest.java b/nrich-search/src/test/java/net/croz/nrich/search/repository/support/JpaQueryBuilderTest.java index 9e0c49b60..846bc12b9 100644 --- a/nrich-search/src/test/java/net/croz/nrich/search/repository/support/JpaQueryBuilderTest.java +++ b/nrich-search/src/test/java/net/croz/nrich/search/repository/support/JpaQueryBuilderTest.java @@ -49,9 +49,7 @@ import jakarta.persistence.Tuple; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.JoinType; -import java.util.Arrays; import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Map; @@ -187,7 +185,7 @@ void shouldSearchByCollectionAssociationValuesByUsingPropertyMapping() { // given SearchConfiguration searchConfiguration = SearchConfiguration.builder() .pluralAssociationRestrictionType(PluralAssociationRestrictionType.JOIN) - .propertyMappingList(Collections.singletonList(new SearchPropertyMapping("collectionName", "collectionEntityList.name"))) + .propertyMappingList(List.of(new SearchPropertyMapping("collectionName", "collectionEntityList.name"))) .build(); TestEntitySearchRequest request = TestEntitySearchRequest.builder() @@ -252,7 +250,7 @@ void shouldSearchEntitiesWithoutAssociationByUsingSubquery() { .joinBy(new SearchPropertyJoin("id", "testEntity.id")).build(); SearchConfiguration searchConfiguration = SearchConfiguration.builder() - .subqueryConfigurationList(Collections.singletonList(subqueryConfiguration)) + .subqueryConfigurationList(List.of(subqueryConfiguration)) .build(); TestEntitySearchRequest request = TestEntitySearchRequest.builder() @@ -275,7 +273,7 @@ void shouldSearchEntitiesWithoutAssociationWithCriteriaDefinedInSeparateClassByU .joinBy(new SearchPropertyJoin("id", "testEntity.id")).build(); SearchConfiguration searchConfiguration = SearchConfiguration.builder() - .subqueryConfigurationList(Collections.singletonList(subqueryConfiguration)) + .subqueryConfigurationList(List.of(subqueryConfiguration)) .build(); TestEntitySearchRequest request = TestEntitySearchRequest.builder() @@ -341,7 +339,7 @@ void shouldReturnTupleListWhenUsingProjection() { SearchConfiguration searchConfiguration = SearchConfiguration.builder() .resultClass(Tuple.class) - .projectionList(Arrays.asList(nameProjection, nestedNameProjection)) + .projectionList(List.of(nameProjection, nestedNameProjection)) .build(); TestEntitySearchRequest request = new TestEntitySearchRequest(null); @@ -364,7 +362,7 @@ void shouldReturnDtoListWhenUsingProjection() { SearchConfiguration searchConfiguration = SearchConfiguration.builder() .resultClass(TestEntityDto.class) - .projectionList(Arrays.asList(nameProjection, nestedNameProjection)) + .projectionList(List.of(nameProjection, nestedNameProjection)) .build(); TestEntitySearchRequest request = new TestEntitySearchRequest(null); @@ -440,7 +438,7 @@ void shouldApplyJoinsToQuery() { SearchJoin nonAppliedJoin = createTestEntitySearchRequestJoin("nestedJoinAlias", "nonExistingPath", value -> false); SearchConfiguration searchConfiguration = SearchConfiguration.builder() - .joinList(Arrays.asList(nestedEntityJoin, nonAppliedJoin)) + .joinList(List.of(nestedEntityJoin, nonAppliedJoin)) .build(); // when @@ -456,7 +454,7 @@ void shouldApplyJoinsFetchToQuery() { TestEntitySearchRequest request = new TestEntitySearchRequest("FIRst1"); SearchConfiguration searchConfiguration = SearchConfiguration.builder() - .joinList(Collections.singletonList(SearchJoin.leftJoinFetch("nestedEntity"))) + .joinList(List.of(SearchJoin.leftJoinFetch("nestedEntity"))) .build(); // when @@ -472,7 +470,7 @@ void shouldRemoveFetchesWhenConvertingToCountQuery() { TestEntitySearchRequest request = new TestEntitySearchRequest("FIRst1"); SearchConfiguration searchConfiguration = SearchConfiguration.builder() - .joinList(Collections.singletonList(SearchJoin.leftJoinFetch("nestedEntity"))) + .joinList(List.of(SearchJoin.leftJoinFetch("nestedEntity"))) .build(); // when @@ -488,8 +486,8 @@ void shouldOverrideOperatorByTypeAndPath() { TestEntitySearchRequest request = new TestEntitySearchRequest("FIRst1"); SearchConfiguration searchConfiguration = SearchConfiguration.builder() - .propertyMappingList(Collections.singletonList(new SearchPropertyMapping("collectionName", "collectionEntityList.name"))) - .searchOperatorOverrideList(Arrays.asList( + .propertyMappingList(List.of(new SearchPropertyMapping("collectionName", "collectionEntityList.name"))) + .searchOperatorOverrideList(List.of( SearchOperatorOverride.forType(String.class, DefaultSearchOperator.EQ), SearchOperatorOverride.forPath("collectionEntityList.name", DefaultSearchOperator.LIKE)) ) .build(); @@ -516,8 +514,8 @@ void shouldNotFailWhenOverridingWithMultipleSearchParameters() { request.setAgeFrom(-1); SearchConfiguration searchConfiguration = SearchConfiguration.builder() - .propertyMappingList(Collections.singletonList(new SearchPropertyMapping("collectionName", "collectionEntityList.name"))) - .searchOperatorOverrideList(Collections.singletonList(SearchOperatorOverride.forPath("collectionEntityList.name", DefaultSearchOperator.LIKE))) + .propertyMappingList(List.of(new SearchPropertyMapping("collectionName", "collectionEntityList.name"))) + .searchOperatorOverrideList(List.of(SearchOperatorOverride.forPath("collectionEntityList.name", DefaultSearchOperator.LIKE))) .build(); // when @@ -533,7 +531,7 @@ void shouldSupportContainsSearch() { TestEntitySearchRequest request = new TestEntitySearchRequest("Rst"); SearchConfiguration searchConfiguration = SearchConfiguration.builder() - .searchOperatorOverrideList(Collections.singletonList(SearchOperatorOverride.forType(String.class, DefaultSearchOperator.CONTAINS))) + .searchOperatorOverrideList(List.of(SearchOperatorOverride.forType(String.class, DefaultSearchOperator.CONTAINS))) .build(); // when @@ -549,7 +547,7 @@ void shouldApplyAdditionalRestrictionsToQuery() { TestEntitySearchRequest request = new TestEntitySearchRequest("FIRst1"); SearchConfiguration searchConfiguration = SearchConfiguration.builder() - .additionalRestrictionResolverList(Collections.singletonList(new TestEntityAdditionalRestrictionResolver(true))) + .additionalRestrictionResolverList(List.of(new TestEntityAdditionalRestrictionResolver(true))) .build(); // when @@ -559,7 +557,7 @@ void shouldApplyAdditionalRestrictionsToQuery() { assertThat(results).isEmpty(); // and when - searchConfiguration.setAdditionalRestrictionResolverList(Collections.singletonList(new TestEntityAdditionalRestrictionResolver(false))); + searchConfiguration.setAdditionalRestrictionResolverList(List.of(new TestEntityAdditionalRestrictionResolver(false))); List resultsWithoutRestriction = executeQuery(request, searchConfiguration); // then @@ -569,8 +567,7 @@ void shouldApplyAdditionalRestrictionsToQuery() { @Test void shouldSupportSearchingByMap() { // given - Map mapSearchRequest = new HashMap<>(); - mapSearchRequest.put("name", "FIRst0"); + Map mapSearchRequest = Map.of("name", "FIRst0"); // when List results = executeQuery(mapSearchRequest, SearchConfiguration.emptyConfiguration()); @@ -582,9 +579,7 @@ void shouldSupportSearchingByMap() { @Test void shouldSupportSearchingByMapWithRange() { // given - Map mapSearchRequest = new HashMap<>(); - mapSearchRequest.put("ageFrom", 20); - mapSearchRequest.put("ageTo", 25); + Map mapSearchRequest = Map.of("ageFrom", 20, "ageTo", 25); // when List results = executeQuery(mapSearchRequest, SearchConfiguration.emptyConfiguration()); @@ -597,7 +592,7 @@ void shouldSupportSearchingByMapWithRange() { void shouldSupportSearchingByPropertyList() { // given TestEntitySearchRequest request = new TestEntitySearchRequest(null); - request.setNameSearchList(Arrays.asList("first1", "first2")); + request.setNameSearchList(List.of("first1", "first2")); // when List results = executeQuery(request, SearchConfiguration.emptyConfiguration()); @@ -632,15 +627,15 @@ void shouldResolveProjectionsFromClass() { // then assertThat(results).isNotEmpty(); - assertThat(results.get(0).getName()).isEqualTo("first0"); - assertThat(results.get(0).getNestedName()).isEqualTo("nested0"); - assertThat(results.get(0).getNestedId()).isNotNull(); + assertThat(results.get(0).name()).isEqualTo("first0"); + assertThat(results.get(0).nestedName()).isEqualTo("nested0"); + assertThat(results.get(0).nestedId()).isNotNull(); } @Test void shouldSupportSearchingByEmptyMapMatchingAny() { // given - Map mapSearchRequest = new HashMap<>(); + Map mapSearchRequest = Collections.emptyMap(); // when List results = executeQuery(mapSearchRequest, SearchConfiguration.emptyConfigurationMatchingAny()); @@ -672,8 +667,8 @@ void shouldThrowExceptionWhenUsingJoinFetchAndProjection() { SearchConfiguration searchConfiguration = SearchConfiguration.builder() .resultClass(TestEntityDto.class) - .projectionList(Arrays.asList(nameProjection, nestedNameProjection)) - .joinList(Collections.singletonList(SearchJoin.leftJoinFetch("nestedEntity"))) + .projectionList(List.of(nameProjection, nestedNameProjection)) + .joinList(List.of(SearchJoin.leftJoinFetch("nestedEntity"))) .build(); TestEntitySearchRequest request = new TestEntitySearchRequest(null); @@ -692,11 +687,10 @@ void shouldSupportNestedJoinFetchList() { JpaQueryBuilder testEntityWithEmbeddedIdJpaQueryBuilder = new JpaQueryBuilder<>(entityManager, TestEntityWithEmbeddedId.class); - Map mapSearchRequest = new HashMap<>(); - mapSearchRequest.put("name", "name0"); + Map mapSearchRequest = Map.of("name", "name0"); SearchConfiguration> searchConfiguration = SearchConfiguration.>builder() - .joinList(Arrays.asList(SearchJoin.innerJoinFetch("id.firstKey"), SearchJoin.innerJoin("id.secondKey"))) + .joinList(List.of(SearchJoin.innerJoinFetch("id.firstKey"), SearchJoin.innerJoin("id.secondKey"))) .build(); // when @@ -763,8 +757,7 @@ void shouldSupportJoinsByDifferentIdProperty() { JpaQueryBuilder testEntityWithCustomIdQueryBuilder = new JpaQueryBuilder<>(entityManager, TestEntityWithCustomId.class); - Map mapSearchRequest = new HashMap<>(); - mapSearchRequest.put("enumElementCollection", TestEntityEnum.FIRST); + Map mapSearchRequest = Map.of("enumElementCollection", TestEntityEnum.FIRST); SearchConfiguration> searchConfiguration = SearchConfiguration.>builder() .build(); @@ -783,7 +776,7 @@ void shouldUseSameJoinsForAllSubPaths() { .build(); SearchConfiguration searchConfiguration = SearchConfiguration.builder() - .joinList(Arrays.asList(SearchJoin.innerJoin("nestedEntity.doubleNestedEntity"), SearchJoin.innerJoin("nestedEntity.secondDoubleNestedEntity"))) + .joinList(List.of(SearchJoin.innerJoin("nestedEntity.doubleNestedEntity"), SearchJoin.innerJoin("nestedEntity.secondDoubleNestedEntity"))) .resolvePropertyMappingUsingPrefix(true) .build(); @@ -821,7 +814,7 @@ void shouldNotAddAdditionalJoinsForSelection() { SearchConfiguration searchConfiguration = SearchConfiguration.builder() .resultClass(TestEntityDto.class) .resolvePropertyMappingUsingPrefix(true) - .projectionList(Arrays.asList(nameProjection, nestedNameProjection)) + .projectionList(List.of(nameProjection, nestedNameProjection)) .build(); // when diff --git a/nrich-search/src/test/java/net/croz/nrich/search/repository/testutil/HibernateNaturalIdSearchExecutorGeneratingUtil.java b/nrich-search/src/test/java/net/croz/nrich/search/repository/testutil/HibernateNaturalIdSearchExecutorGeneratingUtil.java index c006c0033..ac3c45a3f 100644 --- a/nrich-search/src/test/java/net/croz/nrich/search/repository/testutil/HibernateNaturalIdSearchExecutorGeneratingUtil.java +++ b/nrich-search/src/test/java/net/croz/nrich/search/repository/testutil/HibernateNaturalIdSearchExecutorGeneratingUtil.java @@ -21,7 +21,6 @@ import net.croz.nrich.search.repository.stub.TestEntityWithSimpleNaturalId; import jakarta.persistence.EntityManager; -import java.util.HashMap; import java.util.Map; import java.util.stream.IntStream; @@ -45,12 +44,7 @@ public static void generateListForNaturalIdSearch(EntityManager entityManager) { } public static Map createNaturalId(Object firstValue, Object secondValue) { - Map naturalId = new HashMap<>(); - - naturalId.put("firstNaturalId", firstValue); - naturalId.put("secondNaturalId", secondValue); - - return naturalId; + return Map.of("firstNaturalId", firstValue, "secondNaturalId", secondValue); } private static TestEntityWithSimpleNaturalId createTestEntityWithSimpleNaturalId(int value) { diff --git a/nrich-search/src/test/java/net/croz/nrich/search/repository/testutil/JpaSearchRepositoryExecutorGeneratingUtil.java b/nrich-search/src/test/java/net/croz/nrich/search/repository/testutil/JpaSearchRepositoryExecutorGeneratingUtil.java index 84942b53f..e0403a529 100644 --- a/nrich-search/src/test/java/net/croz/nrich/search/repository/testutil/JpaSearchRepositoryExecutorGeneratingUtil.java +++ b/nrich-search/src/test/java/net/croz/nrich/search/repository/testutil/JpaSearchRepositoryExecutorGeneratingUtil.java @@ -35,11 +35,8 @@ import jakarta.persistence.criteria.JoinType; import java.time.LocalDate; import java.time.format.DateTimeFormatter; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.function.Predicate; -import java.util.stream.Collectors; import java.util.stream.IntStream; public final class JpaSearchRepositoryExecutorGeneratingUtil { @@ -54,7 +51,7 @@ public static List generateListForSearch(EntityManager entityManager public static List generateListForSearch(EntityManager entityManager, int numberOfCollectionEntities) { List testEntityList = IntStream.range(0, 5) .mapToObj(value -> createTestEntity(value, numberOfCollectionEntities)) - .collect(Collectors.toList()); + .toList(); testEntityList.get(1).setTestEntityEnum(TestEntityEnum.SECOND); @@ -73,7 +70,7 @@ public static List generateListForStringSearch(EntityMan LocalDate date = LocalDate.parse("01.01.1970", DateTimeFormatter.ofPattern("dd.MM.yyyy")); List testEntityList = IntStream.range(0, 5) .mapToObj(value -> createTestStringSearchEntity("name " + value, 50 + value, date.plusDays(value))) - .collect(Collectors.toList()); + .toList(); testEntityList.forEach(entityManager::persist); @@ -83,7 +80,7 @@ public static List generateListForStringSearch(EntityMan public static List generateTestEntityWithEmbeddedIdList(EntityManager entityManager) { return IntStream.range(0, 5) .mapToObj(value -> generateTestEntityWithEmbeddedId(entityManager, "name" + value)) - .collect(Collectors.toList()); + .toList(); } public static TestEntityWithEmbeddedId generateTestEntityWithEmbeddedId(EntityManager entityManager, String name) { @@ -120,7 +117,7 @@ public static void generateTestEntityWithCustomIdList(EntityManager entityManage IntStream.range(0, 3).forEach(value -> { TestEntityWithCustomId entity = new TestEntityWithCustomId(); - entity.setEnumElementCollection(Collections.singletonList(value % 2 == 0 ? TestEntityEnum.FIRST : TestEntityEnum.SECOND)); + entity.setEnumElementCollection(List.of(value % 2 == 0 ? TestEntityEnum.FIRST : TestEntityEnum.SECOND)); entityManager.persist(entity); }); @@ -150,7 +147,7 @@ private static TestEntity createTestEntity(Integer value, Integer numberOfCollec TestNestedEntity nestedEntity = createTestNestedEntity(value); List collectionEntityList = IntStream.range(0, numberOfCollectionEntities) .mapToObj(counter -> createTestCollectionEntity("collection" + (value + counter))) - .collect(Collectors.toList()); + .toList(); TestEntityEmbedded testEntityEmbedded = createTestEntityEmbedded("embedded" + value); TestEntity entity = new TestEntity(); @@ -161,7 +158,7 @@ private static TestEntity createTestEntity(Integer value, Integer numberOfCollec entity.setCollectionEntityList(collectionEntityList); entity.setTestEntityEnum(TestEntityEnum.FIRST); entity.setTestEntityEmbedded(testEntityEmbedded); - entity.setElementCollection(Arrays.asList("Element collection 1" + value, "Element collection 2" + value)); + entity.setElementCollection(List.of("Element collection 1" + value, "Element collection 2" + value)); return entity; } @@ -172,7 +169,7 @@ private static TestNestedEntity createTestNestedEntity(Integer value) { entity.setNestedEntityName("nested" + value); entity.setNestedEntityAliasName("nested alias" + value); entity.setDoubleNestedEntity(createTestDoubleNestedEntity(value)); - entity.setRelated(Collections.singletonList(createTestDoubleNestedEntity(value))); + entity.setRelated(List.of(createTestDoubleNestedEntity(value))); return entity; } diff --git a/nrich-search/src/test/java/net/croz/nrich/search/support/MapSupportingDirectFieldAccessFallbackBeanWrapperTest.java b/nrich-search/src/test/java/net/croz/nrich/search/support/MapSupportingDirectFieldAccessFallbackBeanWrapperTest.java index 3368a0d07..0d8d16851 100644 --- a/nrich-search/src/test/java/net/croz/nrich/search/support/MapSupportingDirectFieldAccessFallbackBeanWrapperTest.java +++ b/nrich-search/src/test/java/net/croz/nrich/search/support/MapSupportingDirectFieldAccessFallbackBeanWrapperTest.java @@ -24,7 +24,6 @@ import java.util.Map; import static net.croz.nrich.search.support.testutil.MapSupportingDirectFieldAccessFallbackBeanWrapperGeneratingUtil.entityWithPropertyValue; -import static net.croz.nrich.search.support.testutil.MapSupportingDirectFieldAccessFallbackBeanWrapperGeneratingUtil.mapOf; import static org.assertj.core.api.Assertions.assertThat; class MapSupportingDirectFieldAccessFallbackBeanWrapperTest { @@ -32,7 +31,7 @@ class MapSupportingDirectFieldAccessFallbackBeanWrapperTest { @Test void shouldGetPropertyValueFromMap() { // given - MapSupportingDirectFieldAccessFallbackBeanWrapper wrapper = new MapSupportingDirectFieldAccessFallbackBeanWrapper(mapOf("key", "value")); + MapSupportingDirectFieldAccessFallbackBeanWrapper wrapper = new MapSupportingDirectFieldAccessFallbackBeanWrapper(Map.of("key", "value")); // when Object value = wrapper.getPropertyValue("key"); diff --git a/nrich-search/src/test/java/net/croz/nrich/search/support/testutil/MapSupportingDirectFieldAccessFallbackBeanWrapperGeneratingUtil.java b/nrich-search/src/test/java/net/croz/nrich/search/support/testutil/MapSupportingDirectFieldAccessFallbackBeanWrapperGeneratingUtil.java index e725855f4..2c2005b5a 100644 --- a/nrich-search/src/test/java/net/croz/nrich/search/support/testutil/MapSupportingDirectFieldAccessFallbackBeanWrapperGeneratingUtil.java +++ b/nrich-search/src/test/java/net/croz/nrich/search/support/testutil/MapSupportingDirectFieldAccessFallbackBeanWrapperGeneratingUtil.java @@ -20,22 +20,11 @@ import lombok.Getter; import lombok.RequiredArgsConstructor; -import java.util.HashMap; -import java.util.Map; - public final class MapSupportingDirectFieldAccessFallbackBeanWrapperGeneratingUtil { private MapSupportingDirectFieldAccessFallbackBeanWrapperGeneratingUtil() { } - public static Map mapOf(String key, Object value) { - Map map = new HashMap<>(); - - map.put(key, value); - - return map; - } - public static Object entityWithPropertyValue(Object value) { return new Entity(value); } diff --git a/nrich-search/src/test/java/net/croz/nrich/search/util/PathResolvingUtilTest.java b/nrich-search/src/test/java/net/croz/nrich/search/util/PathResolvingUtilTest.java index bc3b079eb..258093074 100644 --- a/nrich-search/src/test/java/net/croz/nrich/search/util/PathResolvingUtilTest.java +++ b/nrich-search/src/test/java/net/croz/nrich/search/util/PathResolvingUtilTest.java @@ -25,7 +25,6 @@ import jakarta.persistence.criteria.JoinType; import jakarta.persistence.criteria.Path; import jakarta.persistence.criteria.Root; -import java.util.Arrays; import java.util.List; import static net.croz.nrich.search.util.testutil.PathResolvingUtilGeneratingUtil.createRootWithAssociationAttribute; @@ -63,7 +62,7 @@ void shouldJoinPath() { @Test void shouldJoinPathList() { // given - List path = Arrays.asList("first", "second"); + List path = List.of("first", "second"); String currentPath = "third"; // when diff --git a/nrich-security-csrf-spring-boot-starter/src/main/java/net/croz/nrich/security/csrf/configuration/NrichCsrfAutoConfiguration.java b/nrich-security-csrf-spring-boot-starter/src/main/java/net/croz/nrich/security/csrf/configuration/NrichCsrfAutoConfiguration.java index 519360966..ce88e8b64 100644 --- a/nrich-security-csrf-spring-boot-starter/src/main/java/net/croz/nrich/security/csrf/configuration/NrichCsrfAutoConfiguration.java +++ b/nrich-security-csrf-spring-boot-starter/src/main/java/net/croz/nrich/security/csrf/configuration/NrichCsrfAutoConfiguration.java @@ -41,7 +41,7 @@ public class NrichCsrfAutoConfiguration { @ConditionalOnMissingBean @Bean public CsrfTokenManagerService tokenManagerService(NrichCsrfProperties csrfProperties) { - return new AesCsrfTokenManagerService(csrfProperties.getTokenExpirationInterval(), csrfProperties.getTokenFutureThreshold(), csrfProperties.getCryptoKeyLength()); + return new AesCsrfTokenManagerService(csrfProperties.tokenExpirationInterval(), csrfProperties.tokenFutureThreshold(), csrfProperties.cryptoKeyLength()); } @ConditionalOnMissingBean @@ -55,7 +55,7 @@ public CsrfPingController csrfPingController() { @Bean public CsrfInterceptor csrfInterceptor(CsrfTokenManagerService csrfTokenManagerService, NrichCsrfProperties csrfProperties) { return new CsrfInterceptor( - csrfTokenManagerService, csrfProperties.getTokenKeyName(), csrfProperties.getInitialTokenUrl(), csrfProperties.getCsrfPingUri(), csrfProperties.getCsrfExcludeConfigList() + csrfTokenManagerService, csrfProperties.tokenKeyName(), csrfProperties.initialTokenUrl(), csrfProperties.csrfPingUri(), csrfProperties.csrfExcludeConfigList() ); } @@ -64,7 +64,7 @@ public CsrfInterceptor csrfInterceptor(CsrfTokenManagerService csrfTokenManagerS @Bean public CsrfWebFilter webFilter(CsrfTokenManagerService csrfTokenManagerService, NrichCsrfProperties csrfProperties) { return new CsrfWebFilter( - csrfTokenManagerService, csrfProperties.getTokenKeyName(), csrfProperties.getInitialTokenUrl(), csrfProperties.getCsrfPingUri(), csrfProperties.getCsrfExcludeConfigList() + csrfTokenManagerService, csrfProperties.tokenKeyName(), csrfProperties.initialTokenUrl(), csrfProperties.csrfPingUri(), csrfProperties.csrfExcludeConfigList() ); } diff --git a/nrich-security-csrf-spring-boot-starter/src/main/java/net/croz/nrich/security/csrf/properties/NrichCsrfProperties.java b/nrich-security-csrf-spring-boot-starter/src/main/java/net/croz/nrich/security/csrf/properties/NrichCsrfProperties.java index 68dc7fc5e..df56c8d30 100644 --- a/nrich-security-csrf-spring-boot-starter/src/main/java/net/croz/nrich/security/csrf/properties/NrichCsrfProperties.java +++ b/nrich-security-csrf-spring-boot-starter/src/main/java/net/croz/nrich/security/csrf/properties/NrichCsrfProperties.java @@ -17,7 +17,6 @@ package net.croz.nrich.security.csrf.properties; -import lombok.Getter; import net.croz.nrich.security.csrf.core.constants.CsrfConstants; import net.croz.nrich.security.csrf.core.model.CsrfExcludeConfig; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -26,60 +25,19 @@ import java.time.Duration; import java.util.List; -@Getter +/** + * @param active Whether CSRF is active. + * @param tokenExpirationInterval Duration of CSRF token. + * @param tokenFutureThreshold Duration of how long token can be in the future (can happen when server and client time is not in sync). + * @param tokenKeyName Name of CSRF token. + * @param cryptoKeyLength Length of crypto key (128, 256...). + * @param initialTokenUrl Initial application url (i.e. url that user is redirected after login). Token will be added to response from this url as
csrfInitialToken
parameter. + * @param csrfPingUri Uri used for CSRF ping request. + * @param csrfExcludeConfigList A list of {@link CsrfExcludeConfig} instances that contain urls or regexps excluded from CSRF check. + */ @ConfigurationProperties("nrich.security.csrf") -public class NrichCsrfProperties { - - /** - * Whether CSRF is active. - */ - private final boolean active; - - /** - * Duration of CSRF token. - */ - private final Duration tokenExpirationInterval; - - /** - * Duration of how long token can be in the future (can happen when server and client time is not in sync). - */ - private final Duration tokenFutureThreshold; - - /** - * Name of CSRF token. - */ - private final String tokenKeyName; - - /** - * Length of crypto key (128, 256...). - */ - private final Integer cryptoKeyLength; - - /** - * Initial application url (i.e. url that user is redirected after login). Token will be added to response from this url as
csrfInitialToken
parameter. - */ - private final String initialTokenUrl; - - /** - * Uri used for CSRF ping request. - */ - private final String csrfPingUri; - - /** - * A list of {@link CsrfExcludeConfig} instances that contain urls or regexps excluded from CSRF check. - */ - private final List csrfExcludeConfigList; +public record NrichCsrfProperties(@DefaultValue("true") boolean active, @DefaultValue("35m") Duration tokenExpirationInterval, @DefaultValue("1m") Duration tokenFutureThreshold, + @DefaultValue("X-CSRF-Token") String tokenKeyName, @DefaultValue("128") Integer cryptoKeyLength, String initialTokenUrl, + @DefaultValue(CsrfConstants.CSRF_DEFAULT_PING_URI) String csrfPingUri, List csrfExcludeConfigList) { - public NrichCsrfProperties(@DefaultValue("true") boolean active, @DefaultValue("35m") Duration tokenExpirationInterval, @DefaultValue("1m") Duration tokenFutureThreshold, - @DefaultValue("X-CSRF-Token") String tokenKeyName, @DefaultValue("128") Integer cryptoKeyLength, String initialTokenUrl, - @DefaultValue(CsrfConstants.CSRF_DEFAULT_PING_URI) String csrfPingUri, List csrfExcludeConfigList) { - this.active = active; - this.tokenExpirationInterval = tokenExpirationInterval; - this.tokenFutureThreshold = tokenFutureThreshold; - this.tokenKeyName = tokenKeyName; - this.cryptoKeyLength = cryptoKeyLength; - this.initialTokenUrl = initialTokenUrl; - this.csrfPingUri = csrfPingUri; - this.csrfExcludeConfigList = csrfExcludeConfigList; - } } diff --git a/nrich-security-csrf-spring-boot-starter/src/test/java/net/croz/nrich/excel/starter/configuration/NrichCsrfAutoConfigurationTest.java b/nrich-security-csrf-spring-boot-starter/src/test/java/net/croz/nrich/excel/starter/configuration/NrichCsrfAutoConfigurationTest.java index 6cf6d6caa..60f5ec125 100644 --- a/nrich-security-csrf-spring-boot-starter/src/test/java/net/croz/nrich/excel/starter/configuration/NrichCsrfAutoConfigurationTest.java +++ b/nrich-security-csrf-spring-boot-starter/src/test/java/net/croz/nrich/excel/starter/configuration/NrichCsrfAutoConfigurationTest.java @@ -20,6 +20,7 @@ import net.croz.nrich.security.csrf.api.service.CsrfTokenManagerService; import net.croz.nrich.security.csrf.configuration.NrichCsrfAutoConfiguration; import net.croz.nrich.security.csrf.core.controller.CsrfPingController; +import net.croz.nrich.security.csrf.properties.NrichCsrfProperties; import net.croz.nrich.security.csrf.webflux.filter.CsrfWebFilter; import net.croz.nrich.security.csrf.webmvc.interceptor.CsrfInterceptor; import org.junit.jupiter.api.Test; @@ -42,6 +43,7 @@ void shouldConfigureWebMvcConfiguration() { assertThat(context).hasSingleBean(CsrfTokenManagerService.class); assertThat(context).hasSingleBean(CsrfPingController.class); assertThat(context).hasSingleBean(CsrfInterceptor.class); + assertThat(context).hasSingleBean(NrichCsrfProperties.class); }); } diff --git a/nrich-security-csrf/src/main/java/net/croz/nrich/security/csrf/core/controller/CsrfPingController.java b/nrich-security-csrf/src/main/java/net/croz/nrich/security/csrf/core/controller/CsrfPingController.java index f255ecceb..35c4aa315 100644 --- a/nrich-security-csrf/src/main/java/net/croz/nrich/security/csrf/core/controller/CsrfPingController.java +++ b/nrich-security-csrf/src/main/java/net/croz/nrich/security/csrf/core/controller/CsrfPingController.java @@ -21,7 +21,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import java.util.HashMap; import java.util.Map; /** @@ -35,10 +34,6 @@ public class CsrfPingController { @RequestMapping("${nrich.security.csrf.endpoint-path:" + CsrfConstants.CSRF_DEFAULT_PING_URI + "}") public Map ping() { - Map result = new HashMap<>(); - - result.put(SUCCESS_KEY, true); - - return result; + return Map.of(SUCCESS_KEY, true); } } diff --git a/nrich-security-csrf/src/test/java/net/croz/nrich/security/csrf/core/util/CsrfUriUtilTest.java b/nrich-security-csrf/src/test/java/net/croz/nrich/security/csrf/core/util/CsrfUriUtilTest.java index 959ffbc59..bb6a3973e 100644 --- a/nrich-security-csrf/src/test/java/net/croz/nrich/security/csrf/core/util/CsrfUriUtilTest.java +++ b/nrich-security-csrf/src/test/java/net/croz/nrich/security/csrf/core/util/CsrfUriUtilTest.java @@ -20,7 +20,7 @@ import net.croz.nrich.security.csrf.core.model.CsrfExcludeConfig; import org.junit.jupiter.api.Test; -import java.util.Collections; +import java.util.List; import static net.croz.nrich.security.csrf.core.testutil.CsrfCoreGeneratingUtil.csrfExcludeConfig; import static org.assertj.core.api.Assertions.assertThat; @@ -42,7 +42,7 @@ void shouldReturnFalseWhenExcludedUriIsNotMatched() { CsrfExcludeConfig csrfExcludeConfig = csrfExcludeConfig("not-matched", null); // when - boolean result = CsrfUriUtil.excludeUri(Collections.singletonList(csrfExcludeConfig), "url"); + boolean result = CsrfUriUtil.excludeUri(List.of(csrfExcludeConfig), "url"); // then assertThat(result).isFalse(); @@ -54,7 +54,7 @@ void shouldReturnFalseWhenExcludedUriIsNotMatchedByRegex() { CsrfExcludeConfig csrfExcludeConfig = csrfExcludeConfig(null, "/*"); // when - boolean result = CsrfUriUtil.excludeUri(Collections.singletonList(csrfExcludeConfig), "url"); + boolean result = CsrfUriUtil.excludeUri(List.of(csrfExcludeConfig), "url"); // then assertThat(result).isFalse(); @@ -66,7 +66,7 @@ void shouldReturnTrueWhenExcludedUriIsMatched() { CsrfExcludeConfig csrfExcludeConfig = csrfExcludeConfig("url", null); // when - boolean result = CsrfUriUtil.excludeUri(Collections.singletonList(csrfExcludeConfig), "url"); + boolean result = CsrfUriUtil.excludeUri(List.of(csrfExcludeConfig), "url"); // then assertThat(result).isTrue(); @@ -78,7 +78,7 @@ void shouldReturnTrueWhenExcludedUriIsMatchedByRegex() { CsrfExcludeConfig csrfExcludeConfig = csrfExcludeConfig(null, ".*"); // when - boolean result = CsrfUriUtil.excludeUri(Collections.singletonList(csrfExcludeConfig), "url"); + boolean result = CsrfUriUtil.excludeUri(List.of(csrfExcludeConfig), "url"); // then assertThat(result).isTrue(); diff --git a/nrich-security-csrf/src/test/java/net/croz/nrich/security/csrf/webflux/filter/CsrfWebFilterTest.java b/nrich-security-csrf/src/test/java/net/croz/nrich/security/csrf/webflux/filter/CsrfWebFilterTest.java index 38da9b20e..d22440f18 100644 --- a/nrich-security-csrf/src/test/java/net/croz/nrich/security/csrf/webflux/filter/CsrfWebFilterTest.java +++ b/nrich-security-csrf/src/test/java/net/croz/nrich/security/csrf/webflux/filter/CsrfWebFilterTest.java @@ -44,7 +44,6 @@ import java.nio.charset.StandardCharsets; import java.time.Duration; -import java.util.Arrays; import java.util.List; import java.util.Objects; @@ -73,7 +72,7 @@ class CsrfWebFilterTest { @BeforeEach void setup() { CsrfTokenManagerService csrfTokenManagerService = new AesCsrfTokenManagerService(Duration.ofMinutes(35), Duration.ofMinutes(1), 128); - List csrfExcludeConfigList = Arrays.asList(csrfExcludeConfig(CSRF_EXCLUDED_URI, null), csrfExcludeConfig(CSRF_INITIAL_TOKEN_URL, null)); + List csrfExcludeConfigList = List.of(csrfExcludeConfig(CSRF_EXCLUDED_URI, null), csrfExcludeConfig(CSRF_INITIAL_TOKEN_URL, null)); csrfFilter = new CsrfWebFilter(csrfTokenManagerService, CSRF_TOKEN_KEY_NAME, CSRF_INITIAL_TOKEN_URL, CSRF_PING_URL, csrfExcludeConfigList); diff --git a/nrich-security-csrf/src/test/java/net/croz/nrich/security/csrf/webmvc/interceptor/CsrfInterceptorTest.java b/nrich-security-csrf/src/test/java/net/croz/nrich/security/csrf/webmvc/interceptor/CsrfInterceptorTest.java index a5dfe44b7..dcfe90df7 100644 --- a/nrich-security-csrf/src/test/java/net/croz/nrich/security/csrf/webmvc/interceptor/CsrfInterceptorTest.java +++ b/nrich-security-csrf/src/test/java/net/croz/nrich/security/csrf/webmvc/interceptor/CsrfInterceptorTest.java @@ -37,7 +37,6 @@ import jakarta.servlet.http.HttpServletRequest; import java.time.Duration; -import java.util.Arrays; import java.util.List; import static net.croz.nrich.security.csrf.core.testutil.CsrfCoreGeneratingUtil.csrfExcludeConfig; @@ -67,7 +66,7 @@ class CsrfInterceptorTest { @BeforeEach void setup() { CsrfTokenManagerService csrfTokenManagerService = new AesCsrfTokenManagerService(Duration.ofMinutes(35), Duration.ofMinutes(1), 128); - List csrfExcludeConfigList = Arrays.asList(csrfExcludeConfig(CSRF_EXCLUDED_URI, null), csrfExcludeConfig(CSRF_INITIAL_TOKEN_URL, null)); + List csrfExcludeConfigList = List.of(csrfExcludeConfig(CSRF_EXCLUDED_URI, null), csrfExcludeConfig(CSRF_INITIAL_TOKEN_URL, null)); csrfInterceptor = new CsrfInterceptor(csrfTokenManagerService, CSRF_TOKEN_KEY_NAME, CSRF_INITIAL_TOKEN_URL, CSRF_PING_URL, csrfExcludeConfigList); } diff --git a/nrich-validation-spring-boot-starter/src/main/java/net/croz/nrich/validation/starter/configuration/NrichValidationAutoConfiguration.java b/nrich-validation-spring-boot-starter/src/main/java/net/croz/nrich/validation/starter/configuration/NrichValidationAutoConfiguration.java index 4b5054469..9b65693c6 100644 --- a/nrich-validation-spring-boot-starter/src/main/java/net/croz/nrich/validation/starter/configuration/NrichValidationAutoConfiguration.java +++ b/nrich-validation-spring-boot-starter/src/main/java/net/croz/nrich/validation/starter/configuration/NrichValidationAutoConfiguration.java @@ -52,8 +52,8 @@ public static class ValidationMessageSourceRegistrar implements InitializingBean @Override public void afterPropertiesSet() { - if (messageSource instanceof AbstractResourceBasedMessageSource abstractResourceBasedMessageSource) { - abstractResourceBasedMessageSource.addBasenames(VALIDATION_MESSAGES_NAME); + if (messageSource instanceof AbstractResourceBasedMessageSource resourceBasedMessageSource) { + resourceBasedMessageSource.addBasenames(VALIDATION_MESSAGES_NAME); } } } diff --git a/nrich-validation/src/main/java/net/croz/nrich/validation/constraint/util/DateConverterUtil.java b/nrich-validation/src/main/java/net/croz/nrich/validation/constraint/util/DateConverterUtil.java index 3e999275e..e8879b5f8 100644 --- a/nrich-validation/src/main/java/net/croz/nrich/validation/constraint/util/DateConverterUtil.java +++ b/nrich-validation/src/main/java/net/croz/nrich/validation/constraint/util/DateConverterUtil.java @@ -1,7 +1,22 @@ +/* + * Copyright 2020-2023 CROZ d.o.o, the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + package net.croz.nrich.validation.constraint.util; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import org.springframework.util.ObjectUtils; import java.time.Instant; @@ -15,7 +30,6 @@ import java.time.YearMonth; import java.time.ZoneId; import java.time.ZonedDateTime; -import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.List; @@ -31,15 +45,15 @@ private DateConverterUtil() { public static Instant convertToInstant(Object date) { DateConverter dateConverter = Objects.requireNonNull(DATE_CONVERTER_LIST.stream() - .filter(converterHolder -> converterHolder.getType().isAssignableFrom(date.getClass())) + .filter(converterHolder -> converterHolder.type().isAssignableFrom(date.getClass())) .findFirst() .orElseThrow(() -> new IllegalArgumentException(String.format("Unsupported type defined for conversion: %s", ObjectUtils.nullSafeClassName(date))))); - return dateConverter.getConverterFunction().apply(date); + return dateConverter.converterFunction().apply(date); } private static List initializeConverterList() { - return Arrays.asList( + return List.of( new DateConverter(ZonedDateTime.class, value -> ((ZonedDateTime) value).toInstant()), new DateConverter(LocalDateTime.class, value -> ((LocalDateTime) value).atZone(ZoneId.systemDefault()).toInstant()), new DateConverter(LocalDate.class, value -> ((LocalDate) value).atTime(LocalTime.now()).atZone(ZoneId.systemDefault()).toInstant()), @@ -55,14 +69,7 @@ private static List initializeConverterList() { ); } - - @RequiredArgsConstructor - @Getter - public static class DateConverter { - - private final Class type; - - private final Function converterFunction; + public record DateConverter(Class type, Function converterFunction) { } } diff --git a/nrich-validation/src/main/java/net/croz/nrich/validation/constraint/util/GroovyUtil.java b/nrich-validation/src/main/java/net/croz/nrich/validation/constraint/util/GroovyUtil.java index 3171e6a1f..41a68b7b5 100644 --- a/nrich-validation/src/main/java/net/croz/nrich/validation/constraint/util/GroovyUtil.java +++ b/nrich-validation/src/main/java/net/croz/nrich/validation/constraint/util/GroovyUtil.java @@ -1,3 +1,20 @@ +/* + * Copyright 2020-2023 CROZ d.o.o, the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + package net.croz.nrich.validation.constraint.util; import org.springframework.util.ClassUtils; @@ -6,7 +23,7 @@ public final class GroovyUtil { - public GroovyUtil() { + private GroovyUtil() { } private static final Pattern GROOVY_CLOSURE_PATTERN = Pattern.compile(".*\\$_.*closure.*"); diff --git a/nrich-validation/src/main/java/net/croz/nrich/validation/constraint/util/ValidationReflectionUtil.java b/nrich-validation/src/main/java/net/croz/nrich/validation/constraint/util/ValidationReflectionUtil.java index 9c0bed38c..52fe0700c 100644 --- a/nrich-validation/src/main/java/net/croz/nrich/validation/constraint/util/ValidationReflectionUtil.java +++ b/nrich-validation/src/main/java/net/croz/nrich/validation/constraint/util/ValidationReflectionUtil.java @@ -23,6 +23,7 @@ import java.lang.reflect.Method; import java.util.Arrays; import java.util.Objects; +import java.util.stream.Stream; public final class ValidationReflectionUtil { @@ -32,10 +33,7 @@ private ValidationReflectionUtil() { } public static Method findGetterMethod(Class type, String fieldName) { - String capitalizedFieldName = StringUtils.capitalize(fieldName); - - return Arrays.stream(METHOD_PATTERN_LIST) - .map(value -> String.format(value, capitalizedFieldName)) + return getterMethodNames(fieldName) .map(methodName -> ReflectionUtils.findMethod(type, methodName)) .filter(Objects::nonNull) .findFirst() @@ -45,4 +43,10 @@ public static Method findGetterMethod(Class type, String fieldName) { public static Object invokeMethod(Method method, Object target) { return ReflectionUtils.invokeMethod(method, target); } + + private static Stream getterMethodNames(String fieldName) { + String capitalizedFieldName = StringUtils.capitalize(fieldName); + + return Stream.concat(Arrays.stream(METHOD_PATTERN_LIST).map(value -> String.format(value, capitalizedFieldName)), Stream.of(fieldName)); + } } diff --git a/nrich-validation/src/main/java/net/croz/nrich/validation/constraint/validator/BaseValidFileValidator.java b/nrich-validation/src/main/java/net/croz/nrich/validation/constraint/validator/BaseValidFileValidator.java index 4299ea435..124371ec4 100644 --- a/nrich-validation/src/main/java/net/croz/nrich/validation/constraint/validator/BaseValidFileValidator.java +++ b/nrich-validation/src/main/java/net/croz/nrich/validation/constraint/validator/BaseValidFileValidator.java @@ -21,6 +21,7 @@ import org.springframework.web.multipart.MultipartFile; import java.util.Arrays; +import java.util.List; import java.util.Objects; import java.util.Optional; @@ -45,13 +46,13 @@ protected boolean isValid(Object value) { String fileName; String fileContentType; - if (value instanceof MultipartFile) { - fileName = extractFileName(((MultipartFile) value).getOriginalFilename()); - fileContentType = ((MultipartFile) value).getContentType(); + if (value instanceof MultipartFile multipartFile) { + fileName = extractFileName(multipartFile.getOriginalFilename()); + fileContentType = multipartFile.getContentType(); } - else if (value instanceof FilePart) { - fileName = extractFileName(((FilePart) value).filename()); - fileContentType = Optional.ofNullable(((FilePart) value).headers().getContentType()) + else if (value instanceof FilePart filePart) { + fileName = extractFileName(filePart.filename()); + fileContentType = Optional.ofNullable(filePart.headers().getContentType()) .map(Objects::toString) .orElse(null); } @@ -61,7 +62,7 @@ else if (value instanceof FilePart) { boolean valid = true; if (fileContentType != null && allowedContentTypeList.length > 0) { - valid = Arrays.asList(allowedContentTypeList).contains(fileContentType); + valid = List.of(allowedContentTypeList).contains(fileContentType); } if (!allowedFileNameRegex.isEmpty()) { valid &= fileName.matches(allowedFileNameRegex); diff --git a/nrich-validation/src/main/java/net/croz/nrich/validation/constraint/validator/InListValidator.java b/nrich-validation/src/main/java/net/croz/nrich/validation/constraint/validator/InListValidator.java index dd4e3481a..261a1b543 100644 --- a/nrich-validation/src/main/java/net/croz/nrich/validation/constraint/validator/InListValidator.java +++ b/nrich-validation/src/main/java/net/croz/nrich/validation/constraint/validator/InListValidator.java @@ -21,7 +21,7 @@ import jakarta.validation.ConstraintValidator; import jakarta.validation.ConstraintValidatorContext; -import java.util.Arrays; +import java.util.List; public class InListValidator implements ConstraintValidator { @@ -38,6 +38,6 @@ public boolean isValid(Object value, ConstraintValidatorContext context) { return true; } - return Arrays.asList(stringList).contains(value.toString()); + return List.of(stringList).contains(value.toString()); } } diff --git a/nrich-validation/src/main/java/net/croz/nrich/validation/constraint/validator/ValidSearchPropertiesValidator.java b/nrich-validation/src/main/java/net/croz/nrich/validation/constraint/validator/ValidSearchPropertiesValidator.java index 9e493e49b..85ec37281 100644 --- a/nrich-validation/src/main/java/net/croz/nrich/validation/constraint/validator/ValidSearchPropertiesValidator.java +++ b/nrich-validation/src/main/java/net/croz/nrich/validation/constraint/validator/ValidSearchPropertiesValidator.java @@ -49,7 +49,7 @@ public boolean isValid(Object value, ConstraintValidatorContext context) { return propertyGroupMap.entrySet().stream().anyMatch(fieldGroup -> { List methodList = Arrays.stream(fieldGroup.getValue()) .map(fieldName -> ValidationReflectionUtil.findGetterMethod(type, fieldName)) - .collect(Collectors.toList()); + .toList(); return methodList.stream().allMatch(method -> ValidationReflectionUtil.invokeMethod(method, value) != null); }); diff --git a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/InListTestRequest.java b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/InListTestRequest.java index 5491483b9..aee6ddf6e 100644 --- a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/InListTestRequest.java +++ b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/InListTestRequest.java @@ -17,15 +17,8 @@ package net.croz.nrich.validation.constraint.stub; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.validation.api.constraint.InList; -@RequiredArgsConstructor -@Getter -public class InListTestRequest { - - @InList(value = "in list") - private final String value; +public record InListTestRequest(@InList("in list") String value) { } diff --git a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/LastTimestampInDayTestRequest.java b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/LastTimestampInDayTestRequest.java index df18bef3a..bb6ad3bbb 100644 --- a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/LastTimestampInDayTestRequest.java +++ b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/LastTimestampInDayTestRequest.java @@ -1,15 +1,9 @@ package net.croz.nrich.validation.constraint.stub; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.validation.api.constraint.LastTimestampInDay; import java.time.LocalDate; -@RequiredArgsConstructor -@Getter -public class LastTimestampInDayTestRequest { +public record LastTimestampInDayTestRequest(@LastTimestampInDay LocalDate localDate) { - @LastTimestampInDay - private final LocalDate localDate; } diff --git a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/MaxSizeInBytesTestRequest.java b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/MaxSizeInBytesTestRequest.java index 33a708a05..f707de6a1 100644 --- a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/MaxSizeInBytesTestRequest.java +++ b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/MaxSizeInBytesTestRequest.java @@ -17,15 +17,8 @@ package net.croz.nrich.validation.constraint.stub; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.validation.api.constraint.MaxSizeInBytes; -@RequiredArgsConstructor -@Getter -public class MaxSizeInBytesTestRequest { - - @MaxSizeInBytes(value = 5) - private final String value; +public record MaxSizeInBytesTestRequest(@MaxSizeInBytes(5) String value) { } diff --git a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/MinDateTestRequest.java b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/MinDateTestRequest.java index bc23c2d03..9cbfbcf83 100644 --- a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/MinDateTestRequest.java +++ b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/MinDateTestRequest.java @@ -1,16 +1,10 @@ package net.croz.nrich.validation.constraint.stub; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.validation.api.constraint.MinDate; import java.time.LocalDate; -@RequiredArgsConstructor -@Getter -public class MinDateTestRequest { +public record MinDateTestRequest(@MinDate("2023-10-10") LocalDate date) { - @MinDate("2023-10-10") - private final LocalDate date; } diff --git a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/NotNullWhenInvalidTestRequest.java b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/NotNullWhenInvalidTestRequest.java index a93eb302c..ac551203d 100644 --- a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/NotNullWhenInvalidTestRequest.java +++ b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/NotNullWhenInvalidTestRequest.java @@ -17,20 +17,12 @@ package net.croz.nrich.validation.constraint.stub; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.validation.api.constraint.NotNullWhen; import java.util.function.Predicate; -@RequiredArgsConstructor -@Getter @NotNullWhen(property = "nonExistingProperty", condition = NotNullWhenInvalidTestRequest.Condition.class) -public class NotNullWhenInvalidTestRequest { - - private final String property; - - private final String differentProperty; +public record NotNullWhenInvalidTestRequest(String property, String differentProperty) { public static class Condition implements Predicate { @Override diff --git a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/NotNullWhenTestRequest.java b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/NotNullWhenTestRequest.java index da099a74b..466639020 100644 --- a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/NotNullWhenTestRequest.java +++ b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/NotNullWhenTestRequest.java @@ -17,25 +17,17 @@ package net.croz.nrich.validation.constraint.stub; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.validation.api.constraint.NotNullWhen; import java.util.function.Predicate; -@RequiredArgsConstructor -@Getter @NotNullWhen(property = "property", condition = NotNullWhenTestRequest.Condition.class) -public class NotNullWhenTestRequest { - - private final String property; - - private final String differentProperty; +public record NotNullWhenTestRequest(String property, String differentProperty) { public static class Condition implements Predicate { @Override public boolean test(NotNullWhenTestRequest notNullWhenTestRequest) { - return "not null".equals(notNullWhenTestRequest.getDifferentProperty()); + return "not null".equals(notNullWhenTestRequest.differentProperty()); } } } diff --git a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/NullWhenTestRequest.java b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/NullWhenTestRequest.java index 7e11be12a..bbeabd39e 100644 --- a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/NullWhenTestRequest.java +++ b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/NullWhenTestRequest.java @@ -17,25 +17,17 @@ package net.croz.nrich.validation.constraint.stub; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.validation.api.constraint.NullWhen; import java.util.function.Predicate; -@RequiredArgsConstructor -@Getter @NullWhen(property = "property", condition = NullWhenTestRequest.Condition.class) -public class NullWhenTestRequest { - - private final String property; - - private final String differentProperty; +public record NullWhenTestRequest(String property, String differentProperty) { public static class Condition implements Predicate { @Override public boolean test(NullWhenTestRequest notNullWhenTestRequest) { - return "not null".equals(notNullWhenTestRequest.getDifferentProperty()); + return "not null".equals(notNullWhenTestRequest.differentProperty()); } } } diff --git a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/NullWhenTestRequestWithAutowiredService.java b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/NullWhenTestRequestWithAutowiredService.java index b6767f802..ec560ab16 100644 --- a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/NullWhenTestRequestWithAutowiredService.java +++ b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/NullWhenTestRequestWithAutowiredService.java @@ -17,20 +17,13 @@ package net.croz.nrich.validation.constraint.stub; -import lombok.Getter; import lombok.RequiredArgsConstructor; import net.croz.nrich.validation.api.constraint.NullWhen; import java.util.function.Predicate; -@RequiredArgsConstructor -@Getter @NullWhen(property = "property", condition = NullWhenTestRequestWithAutowiredService.Condition.class) -public class NullWhenTestRequestWithAutowiredService { - - private final String property; - - private final String differentProperty; +public record NullWhenTestRequestWithAutowiredService(String property, String differentProperty) { @RequiredArgsConstructor public static class Condition implements Predicate { diff --git a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/SpelExpressionEnvirnomentTestRequest.java b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/SpelExpressionEnvirnomentTestRequest.java index b1ec7ab59..252976562 100644 --- a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/SpelExpressionEnvirnomentTestRequest.java +++ b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/SpelExpressionEnvirnomentTestRequest.java @@ -17,15 +17,8 @@ package net.croz.nrich.validation.constraint.stub; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.validation.api.constraint.SpelExpression; -@RequiredArgsConstructor -@Getter -public class SpelExpressionEnvirnomentTestRequest { - - @SpelExpression("#environment['custom.spel.expresssion.value'] == #this") - private final String value; +public record SpelExpressionEnvirnomentTestRequest(@SpelExpression("#environment['custom.spel.expresssion.value'] == #this") String value) { } diff --git a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/SpelExpressionSystemPropertiesTestRequest.java b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/SpelExpressionSystemPropertiesTestRequest.java index 1734bc3e6..966d59ea6 100644 --- a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/SpelExpressionSystemPropertiesTestRequest.java +++ b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/SpelExpressionSystemPropertiesTestRequest.java @@ -17,15 +17,8 @@ package net.croz.nrich.validation.constraint.stub; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.validation.api.constraint.SpelExpression; -@RequiredArgsConstructor -@Getter -public class SpelExpressionSystemPropertiesTestRequest { - - @SpelExpression("#systemProperties['custom.system.property'].startsWith(#this)") - private final String value; +public record SpelExpressionSystemPropertiesTestRequest(@SpelExpression("#systemProperties['custom.system.property'].startsWith(#this)") String value) { } diff --git a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/SpelExpressionTestRequest.java b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/SpelExpressionTestRequest.java index d3f2387de..863cbb334 100644 --- a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/SpelExpressionTestRequest.java +++ b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/SpelExpressionTestRequest.java @@ -17,15 +17,8 @@ package net.croz.nrich.validation.constraint.stub; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.validation.api.constraint.SpelExpression; -@RequiredArgsConstructor -@Getter -public class SpelExpressionTestRequest { - - @SpelExpression("@spelValidationTestService.validateUuid(#this)") - private final String uuid; +public record SpelExpressionTestRequest(@SpelExpression("@spelValidationTestService.validateUuid(#this)") String uuid) { } diff --git a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileResolvableValidatorEmptyPropertyTestRequest.java b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileResolvableValidatorEmptyPropertyTestRequest.java index 0d00f6dff..d6aa280f5 100644 --- a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileResolvableValidatorEmptyPropertyTestRequest.java +++ b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileResolvableValidatorEmptyPropertyTestRequest.java @@ -17,16 +17,10 @@ package net.croz.nrich.validation.constraint.stub; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.validation.api.constraint.ValidFileResolvable; import org.springframework.web.multipart.MultipartFile; -@RequiredArgsConstructor -@Getter -public class ValidFileResolvableValidatorEmptyPropertyTestRequest { - - @ValidFileResolvable(allowedContentTypeListPropertyName = "", allowedExtensionListPropertyName = "", allowedFileNameRegexPropertyName = "") - private final MultipartFile file; +public record ValidFileResolvableValidatorEmptyPropertyTestRequest( + @ValidFileResolvable(allowedContentTypeListPropertyName = "", allowedExtensionListPropertyName = "", allowedFileNameRegexPropertyName = "") MultipartFile file) { } diff --git a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileResolvableValidatorFilePartTestRequest.java b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileResolvableValidatorFilePartTestRequest.java index 6ab32020f..c25016f5f 100644 --- a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileResolvableValidatorFilePartTestRequest.java +++ b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileResolvableValidatorFilePartTestRequest.java @@ -17,16 +17,9 @@ package net.croz.nrich.validation.constraint.stub; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.validation.api.constraint.ValidFileResolvable; import org.springframework.http.codec.multipart.FilePart; -@RequiredArgsConstructor -@Getter -public class ValidFileResolvableValidatorFilePartTestRequest { - - @ValidFileResolvable - private final FilePart file; +public record ValidFileResolvableValidatorFilePartTestRequest(@ValidFileResolvable FilePart file) { } diff --git a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileResolvableValidatorInvalidTypeFileTestRequest.java b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileResolvableValidatorInvalidTypeFileTestRequest.java index 59b035c64..d5d63c9be 100644 --- a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileResolvableValidatorInvalidTypeFileTestRequest.java +++ b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileResolvableValidatorInvalidTypeFileTestRequest.java @@ -17,15 +17,8 @@ package net.croz.nrich.validation.constraint.stub; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.validation.api.constraint.ValidFileResolvable; -@RequiredArgsConstructor -@Getter -public class ValidFileResolvableValidatorInvalidTypeFileTestRequest { - - @ValidFileResolvable - private final Object file; +public record ValidFileResolvableValidatorInvalidTypeFileTestRequest(@ValidFileResolvable Object file) { } diff --git a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileResolvableValidatorMultipartFileCustomTestRequest.java b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileResolvableValidatorMultipartFileCustomTestRequest.java index 40906d4e9..16e7165fa 100644 --- a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileResolvableValidatorMultipartFileCustomTestRequest.java +++ b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileResolvableValidatorMultipartFileCustomTestRequest.java @@ -17,20 +17,13 @@ package net.croz.nrich.validation.constraint.stub; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.validation.api.constraint.ValidFileResolvable; import org.springframework.web.multipart.MultipartFile; -@RequiredArgsConstructor -@Getter -public class ValidFileResolvableValidatorMultipartFileCustomTestRequest { - - @ValidFileResolvable( - allowedContentTypeListPropertyName = "my.custom.validation.file.allowed-content-type-list", - allowedExtensionListPropertyName = "my.custom.validation.file.allowed-extension-list", - allowedFileNameRegexPropertyName = "my.custom.validation.file.allowed-file-name-regex" - ) - private final MultipartFile file; +public record ValidFileResolvableValidatorMultipartFileCustomTestRequest(@ValidFileResolvable( + allowedContentTypeListPropertyName = "my.custom.validation.file.allowed-content-type-list", + allowedExtensionListPropertyName = "my.custom.validation.file.allowed-extension-list", + allowedFileNameRegexPropertyName = "my.custom.validation.file.allowed-file-name-regex" +) MultipartFile file) { } diff --git a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileResolvableValidatorMultipartFileTestRequest.java b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileResolvableValidatorMultipartFileTestRequest.java index 43d6761ca..a7edd578c 100644 --- a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileResolvableValidatorMultipartFileTestRequest.java +++ b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileResolvableValidatorMultipartFileTestRequest.java @@ -17,16 +17,9 @@ package net.croz.nrich.validation.constraint.stub; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.validation.api.constraint.ValidFileResolvable; import org.springframework.web.multipart.MultipartFile; -@RequiredArgsConstructor -@Getter -public class ValidFileResolvableValidatorMultipartFileTestRequest { - - @ValidFileResolvable - private final MultipartFile file; +public record ValidFileResolvableValidatorMultipartFileTestRequest(@ValidFileResolvable MultipartFile file) { } diff --git a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileValidatorFilePartTestRequest.java b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileValidatorFilePartTestRequest.java index 721ee7093..9fa19ba9f 100644 --- a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileValidatorFilePartTestRequest.java +++ b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileValidatorFilePartTestRequest.java @@ -17,16 +17,9 @@ package net.croz.nrich.validation.constraint.stub; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.validation.api.constraint.ValidFile; import org.springframework.http.codec.multipart.FilePart; -@RequiredArgsConstructor -@Getter -public class ValidFileValidatorFilePartTestRequest { - - @ValidFile(allowedContentTypeList = "text/plain", allowedExtensionList = "txt", allowedFileNameRegex = "(?U)[\\w-.]+") - private final FilePart file; +public record ValidFileValidatorFilePartTestRequest(@ValidFile(allowedContentTypeList = "text/plain", allowedExtensionList = "txt", allowedFileNameRegex = "(?U)[\\w-.]+") FilePart file) { } diff --git a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileValidatorInvalidTypeFileTestRequest.java b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileValidatorInvalidTypeFileTestRequest.java index 5eabef923..3f2c85091 100644 --- a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileValidatorInvalidTypeFileTestRequest.java +++ b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileValidatorInvalidTypeFileTestRequest.java @@ -17,15 +17,8 @@ package net.croz.nrich.validation.constraint.stub; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.validation.api.constraint.ValidFile; -@RequiredArgsConstructor -@Getter -public class ValidFileValidatorInvalidTypeFileTestRequest { - - @ValidFile - private final Object file; +public record ValidFileValidatorInvalidTypeFileTestRequest(@ValidFile Object file) { } diff --git a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileValidatorMultipartFileTestRequest.java b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileValidatorMultipartFileTestRequest.java index 275c3eeb0..b91230ced 100644 --- a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileValidatorMultipartFileTestRequest.java +++ b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidFileValidatorMultipartFileTestRequest.java @@ -17,16 +17,9 @@ package net.croz.nrich.validation.constraint.stub; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.validation.api.constraint.ValidFile; import org.springframework.web.multipart.MultipartFile; -@RequiredArgsConstructor -@Getter -public class ValidFileValidatorMultipartFileTestRequest { - - @ValidFile(allowedContentTypeList = "text/plain", allowedExtensionList = "txt", allowedFileNameRegex = "(?U)[\\w-.]+") - private final MultipartFile file; +public record ValidFileValidatorMultipartFileTestRequest(@ValidFile(allowedContentTypeList = "text/plain", allowedExtensionList = "txt", allowedFileNameRegex = "(?U)[\\w-.]+") MultipartFile file) { } diff --git a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidRangeValidatorDifferentTypeTestRequest.java b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidRangeValidatorDifferentTypeTestRequest.java index 81070186e..1fdf89102 100644 --- a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidRangeValidatorDifferentTypeTestRequest.java +++ b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidRangeValidatorDifferentTypeTestRequest.java @@ -17,19 +17,11 @@ package net.croz.nrich.validation.constraint.stub; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.validation.api.constraint.ValidRange; import java.time.Instant; -@RequiredArgsConstructor -@Getter @ValidRange(fromPropertyName = "firstField", toPropertyName = "secondField") -public class ValidRangeValidatorDifferentTypeTestRequest { - - private final Long firstField; - - private final Instant secondField; +public record ValidRangeValidatorDifferentTypeTestRequest(Long firstField, Instant secondField) { } diff --git a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidRangeValidatorInclusiveTestRequest.java b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidRangeValidatorInclusiveTestRequest.java index dec6cf258..15a6a74ca 100644 --- a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidRangeValidatorInclusiveTestRequest.java +++ b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidRangeValidatorInclusiveTestRequest.java @@ -17,17 +17,9 @@ package net.croz.nrich.validation.constraint.stub; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.validation.api.constraint.ValidRange; -@RequiredArgsConstructor -@Getter @ValidRange(fromPropertyName = "firstField", toPropertyName = "secondField", inclusive = true) -public class ValidRangeValidatorInclusiveTestRequest { - - private final Integer firstField; - - private final Integer secondField; +public record ValidRangeValidatorInclusiveTestRequest(Integer firstField, Integer secondField) { } diff --git a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidRangeValidatorNotComparableTestRequest.java b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidRangeValidatorNotComparableTestRequest.java index d3d083845..984e8c60f 100644 --- a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidRangeValidatorNotComparableTestRequest.java +++ b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidRangeValidatorNotComparableTestRequest.java @@ -17,18 +17,11 @@ package net.croz.nrich.validation.constraint.stub; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.validation.api.constraint.ValidRange; -@RequiredArgsConstructor -@Getter @ValidRange(fromPropertyName = "firstField", toPropertyName = "secondField") -public class ValidRangeValidatorNotComparableTestRequest { - - private final NotComparable firstField; - - private final NotComparable secondField; +public record ValidRangeValidatorNotComparableTestRequest(net.croz.nrich.validation.constraint.stub.ValidRangeValidatorNotComparableTestRequest.NotComparable firstField, + net.croz.nrich.validation.constraint.stub.ValidRangeValidatorNotComparableTestRequest.NotComparable secondField) { public static class NotComparable { diff --git a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidRangeValidatorTestRequest.java b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidRangeValidatorTestRequest.java index 742cafa49..d5fc949f1 100644 --- a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidRangeValidatorTestRequest.java +++ b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidRangeValidatorTestRequest.java @@ -17,19 +17,11 @@ package net.croz.nrich.validation.constraint.stub; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.validation.api.constraint.ValidRange; import java.time.Instant; -@RequiredArgsConstructor -@Getter @ValidRange(fromPropertyName = "firstField", toPropertyName = "secondField") -public class ValidRangeValidatorTestRequest { - - private final Instant firstField; - - private final Instant secondField; +public record ValidRangeValidatorTestRequest(Instant firstField, Instant secondField) { } diff --git a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidSearchFieldsValidatorTestRequest.java b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidSearchFieldsValidatorTestRequest.java index 7315dd358..4e025aa7f 100644 --- a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidSearchFieldsValidatorTestRequest.java +++ b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/stub/ValidSearchFieldsValidatorTestRequest.java @@ -17,21 +17,11 @@ package net.croz.nrich.validation.constraint.stub; -import lombok.Getter; -import lombok.RequiredArgsConstructor; import net.croz.nrich.validation.api.constraint.ValidSearchProperties; import java.time.Instant; -@RequiredArgsConstructor -@Getter @ValidSearchProperties(propertyGroup = { @ValidSearchProperties.PropertyGroup({ "firstGroupFieldOne", "firstGroupFieldTwo" }), @ValidSearchProperties.PropertyGroup("secondGroupFieldOne") }) -public class ValidSearchFieldsValidatorTestRequest { - - private final String firstGroupFieldOne; - - private final Instant firstGroupFieldTwo; - - private final Boolean secondGroupFieldOne; +public record ValidSearchFieldsValidatorTestRequest(String firstGroupFieldOne, Instant firstGroupFieldTwo, Boolean secondGroupFieldOne) { } diff --git a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/validator/ValidFileValidatorTest.java b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/validator/ValidFileValidatorTest.java index 0e1ea4331..44278f925 100644 --- a/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/validator/ValidFileValidatorTest.java +++ b/nrich-validation/src/test/java/net/croz/nrich/validation/constraint/validator/ValidFileValidatorTest.java @@ -23,6 +23,8 @@ import net.croz.nrich.validation.constraint.stub.ValidFileValidatorMultipartFileTestRequest; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; @@ -34,6 +36,7 @@ import jakarta.validation.Validator; import java.nio.charset.StandardCharsets; import java.util.Set; +import java.util.stream.Stream; import static net.croz.nrich.validation.constraint.testutil.ValidationConstraintGeneratingUtil.filePart; import static org.assertj.core.api.Assertions.assertThat; @@ -47,23 +50,10 @@ class ValidFileValidatorTest { @Autowired private Validator validator; - @Test - void shouldReportErrorWhenFileNameIsNotValidForMultipartFile() { - // given - MultipartFile file = new MockMultipartFile("file", "**.txt", null, FILE_BYTES); - ValidFileValidatorMultipartFileTestRequest request = new ValidFileValidatorMultipartFileTestRequest(file); - - // when - Set> constraintViolationList = validator.validate(request); - - // then - assertThat(constraintViolationList).isNotEmpty(); - } - - @Test - void shouldReportErrorWhenFileExtensionIsNotValidForMultipartFile() { + @MethodSource("shouldReportErrorForInvalidFileMetadataMethodSource") + @ParameterizedTest + void shouldReportErrorWhenFileHasInvalidData(MultipartFile file) { // given - MultipartFile file = new MockMultipartFile("file", "1.exe", null, FILE_BYTES); ValidFileValidatorMultipartFileTestRequest request = new ValidFileValidatorMultipartFileTestRequest(file); // when @@ -73,17 +63,13 @@ void shouldReportErrorWhenFileExtensionIsNotValidForMultipartFile() { assertThat(constraintViolationList).isNotEmpty(); } - @Test - void shouldReportErrorWhenContentTypeIsNotValidForMultipartFile() { - // given - MultipartFile file = new MockMultipartFile("1.txt", "1.txt", "application/json", FILE_BYTES); - ValidFileValidatorMultipartFileTestRequest request = new ValidFileValidatorMultipartFileTestRequest(file); - - // when - Set> constraintViolationList = validator.validate(request); + private static Stream shouldReportErrorForInvalidFileMetadataMethodSource() { + return Stream.of( + Arguments.of(new MockMultipartFile("file", "**.txt", null, FILE_BYTES)), + Arguments.of(new MockMultipartFile("file", "1.exe", null, FILE_BYTES)), + Arguments.of(new MockMultipartFile("1.txt", "1.txt", "application/json", FILE_BYTES)) - // then - assertThat(constraintViolationList).isNotEmpty(); + ); } @ValueSource(strings = { "1.txt", "1", "c:\\1.txt", "c:/1.txt" }) diff --git a/nrich-webmvc-spring-boot-starter/src/main/java/net/croz/nrich/webmvc/starter/configuration/NrichWebMvcAutoConfiguration.java b/nrich-webmvc-spring-boot-starter/src/main/java/net/croz/nrich/webmvc/starter/configuration/NrichWebMvcAutoConfiguration.java index ea3ec0c0d..3f6daaaa7 100644 --- a/nrich-webmvc-spring-boot-starter/src/main/java/net/croz/nrich/webmvc/starter/configuration/NrichWebMvcAutoConfiguration.java +++ b/nrich-webmvc-spring-boot-starter/src/main/java/net/croz/nrich/webmvc/starter/configuration/NrichWebMvcAutoConfiguration.java @@ -58,7 +58,7 @@ public ExceptionAuxiliaryDataResolverService exceptionAuxiliaryDataResolverServi @ConditionalOnMissingBean @Bean public ControllerEditorRegistrationAdvice controllerEditorRegistrationAdvice(NrichWebMvcProperties webMvcProperties, TransientPropertyResolverService transientPropertyResolverService) { - return new ControllerEditorRegistrationAdvice(webMvcProperties.isConvertEmptyStringsToNull(), webMvcProperties.isIgnoreTransientFields(), transientPropertyResolverService); + return new ControllerEditorRegistrationAdvice(webMvcProperties.convertEmptyStringsToNull(), webMvcProperties.ignoreTransientFields(), transientPropertyResolverService); } @ConditionalOnMissingBean @@ -73,7 +73,7 @@ public NotificationErrorHandlingRestControllerAdvice notificationRestControllerA LoggingService loggingService, ExceptionHttpStatusResolverService exceptionHttpStatusResolverService, @Autowired(required = false) ExceptionAuxiliaryDataResolverService exceptionAuxiliaryDataResolverService) { return new NotificationErrorHandlingRestControllerAdvice( - webMvcProperties.getExceptionToUnwrapList(), webMvcProperties.getExceptionAuxiliaryDataToIncludeInNotification(), notificationResponseService, loggingService, + webMvcProperties.exceptionToUnwrapList(), webMvcProperties.exceptionAuxiliaryDataToIncludeInNotification(), notificationResponseService, loggingService, exceptionAuxiliaryDataResolverService, exceptionHttpStatusResolverService ); } @@ -82,6 +82,6 @@ public NotificationErrorHandlingRestControllerAdvice notificationRestControllerA @ConditionalOnMissingBean @Bean public ConstrainedSessionLocaleResolver constrainedSessionLocaleResolver(NrichWebMvcProperties webMvcProperties) { - return new ConstrainedSessionLocaleResolver(webMvcProperties.getDefaultLocale(), webMvcProperties.getAllowedLocaleList()); + return new ConstrainedSessionLocaleResolver(webMvcProperties.defaultLocale(), webMvcProperties.allowedLocaleList()); } } diff --git a/nrich-webmvc-spring-boot-starter/src/main/java/net/croz/nrich/webmvc/starter/properties/NrichWebMvcProperties.java b/nrich-webmvc-spring-boot-starter/src/main/java/net/croz/nrich/webmvc/starter/properties/NrichWebMvcProperties.java index 74e78d282..423ab8c2b 100644 --- a/nrich-webmvc-spring-boot-starter/src/main/java/net/croz/nrich/webmvc/starter/properties/NrichWebMvcProperties.java +++ b/nrich-webmvc-spring-boot-starter/src/main/java/net/croz/nrich/webmvc/starter/properties/NrichWebMvcProperties.java @@ -17,67 +17,25 @@ package net.croz.nrich.webmvc.starter.properties; -import lombok.Getter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.bind.DefaultValue; import java.util.List; -@Getter +/** + * @param controllerAdviceEnabled Whether {@link net.croz.nrich.webmvc.advice.NotificationErrorHandlingRestControllerAdvice} controller advice is enabled. + * @param exceptionAuxiliaryDataResolvingEnabled Whether default {@link net.croz.nrich.webmvc.api.service.ExceptionAuxiliaryDataResolverService} is enabled. + * @param convertEmptyStringsToNull Whether empty strings should be converted to null when binding requests. + * @param ignoreTransientFields Whether transient fields should be ignored when binding requests. + * @param exceptionToUnwrapList List of exceptions that will be unwrapping their cause. + * @param exceptionAuxiliaryDataToIncludeInNotification List of exception auxiliary data to be included in notification sent to client. + * @param defaultLocale Optional property. Default locale. + * @param allowedLocaleList Optional property. List of locales users can set. + */ @ConfigurationProperties("nrich.webmvc") -public class NrichWebMvcProperties { - - /** - * Whether {@link net.croz.nrich.webmvc.advice.NotificationErrorHandlingRestControllerAdvice} controller advice is enabled. - */ - private final boolean controllerAdviceEnabled; - - /** - * Whether default {@link net.croz.nrich.webmvc.api.service.ExceptionAuxiliaryDataResolverService} is enabled. - */ - private final boolean exceptionAuxiliaryDataResolvingEnabled; - - /** - * Whether empty strings should be converted to null when binding requests. - */ - private final boolean convertEmptyStringsToNull; - - /** - * Whether transient fields should be ignored when binding requests. - */ - private final boolean ignoreTransientFields; - - /** - * List of exceptions that will be unwrapping their cause. - */ - private final List exceptionToUnwrapList; - - /** - * List of exception auxiliary data to be included in notification sent to client. - */ - private final List exceptionAuxiliaryDataToIncludeInNotification; - - /** - * Optional property. Default locale. - */ - private final String defaultLocale; - - /** - * Optional property. List of locales users can set. - */ - private final List allowedLocaleList; +public record NrichWebMvcProperties(@DefaultValue("true") boolean controllerAdviceEnabled, @DefaultValue("true") boolean exceptionAuxiliaryDataResolvingEnabled, + @DefaultValue("true") boolean convertEmptyStringsToNull, @DefaultValue("true") boolean ignoreTransientFields, + @DefaultValue("java.util.concurrent.ExecutionException") List exceptionToUnwrapList, + @DefaultValue("uuid") List exceptionAuxiliaryDataToIncludeInNotification, String defaultLocale, List allowedLocaleList) { - public NrichWebMvcProperties(@DefaultValue("true") boolean controllerAdviceEnabled, @DefaultValue("true") boolean exceptionAuxiliaryDataResolvingEnabled, - @DefaultValue("true") boolean convertEmptyStringsToNull, @DefaultValue("true") boolean ignoreTransientFields, - @DefaultValue("java.util.concurrent.ExecutionException") List exceptionToUnwrapList, - @DefaultValue("uuid") List exceptionAuxiliaryDataToIncludeInNotification, String defaultLocale, List allowedLocaleList) { - this.controllerAdviceEnabled = controllerAdviceEnabled; - this.exceptionAuxiliaryDataResolvingEnabled = exceptionAuxiliaryDataResolvingEnabled; - this.convertEmptyStringsToNull = convertEmptyStringsToNull; - this.ignoreTransientFields = ignoreTransientFields; - this.exceptionToUnwrapList = exceptionToUnwrapList; - this.exceptionAuxiliaryDataToIncludeInNotification = exceptionAuxiliaryDataToIncludeInNotification; - this.defaultLocale = defaultLocale; - this.allowedLocaleList = allowedLocaleList; - } } diff --git a/nrich-webmvc-spring-boot-starter/src/test/java/net/croz/nrich/webmvc/starter/configuration/NrichWebMvcAutoConfigurationTest.java b/nrich-webmvc-spring-boot-starter/src/test/java/net/croz/nrich/webmvc/starter/configuration/NrichWebMvcAutoConfigurationTest.java index cb7752a65..8b6e9e7e3 100644 --- a/nrich-webmvc-spring-boot-starter/src/test/java/net/croz/nrich/webmvc/starter/configuration/NrichWebMvcAutoConfigurationTest.java +++ b/nrich-webmvc-spring-boot-starter/src/test/java/net/croz/nrich/webmvc/starter/configuration/NrichWebMvcAutoConfigurationTest.java @@ -26,6 +26,7 @@ import net.croz.nrich.webmvc.api.service.ExceptionHttpStatusResolverService; import net.croz.nrich.webmvc.localeresolver.ConstrainedSessionLocaleResolver; import net.croz.nrich.webmvc.service.TransientPropertyResolverService; +import net.croz.nrich.webmvc.starter.properties.NrichWebMvcProperties; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; @@ -48,6 +49,7 @@ void shouldConfigureDefaultConfiguration() { assertThat(context).hasSingleBean(ControllerEditorRegistrationAdvice.class); assertThat(context).hasSingleBean(NotificationErrorHandlingRestControllerAdvice.class); assertThat(context).hasSingleBean(ExceptionHttpStatusResolverService.class); + assertThat(context).hasSingleBean(NrichWebMvcProperties.class); assertThat(context).doesNotHaveBean(ConstrainedSessionLocaleResolver.class); }); } diff --git a/nrich-webmvc/src/main/java/net/croz/nrich/webmvc/advice/NotificationErrorHandlingRestControllerAdvice.java b/nrich-webmvc/src/main/java/net/croz/nrich/webmvc/advice/NotificationErrorHandlingRestControllerAdvice.java index 4d6ee9e51..6de10d765 100644 --- a/nrich-webmvc/src/main/java/net/croz/nrich/webmvc/advice/NotificationErrorHandlingRestControllerAdvice.java +++ b/nrich-webmvc/src/main/java/net/croz/nrich/webmvc/advice/NotificationErrorHandlingRestControllerAdvice.java @@ -87,14 +87,14 @@ public ResponseEntity handleBindException(BindException exception, HttpS public ResponseEntity handleException(Exception exception, HttpServletRequest request) { Exception unwrappedException = unwrapException(exception); - if (unwrappedException instanceof MethodArgumentNotValidException) { - return handleMethodArgumentNotValidException((MethodArgumentNotValidException) unwrappedException, request); + if (unwrappedException instanceof MethodArgumentNotValidException methodArgumentNotValidException) { + return handleMethodArgumentNotValidException(methodArgumentNotValidException, request); } - else if (unwrappedException instanceof BindException) { - return handleBindException((BindException) unwrappedException, request); + else if (unwrappedException instanceof BindException bindException) { + return handleBindException(bindException, request); } - else if (unwrappedException instanceof ConstraintViolationException) { - return handleConstraintViolationException((ConstraintViolationException) unwrappedException, request); + else if (unwrappedException instanceof ConstraintViolationException constraintViolationException) { + return handleConstraintViolationException(constraintViolationException, request); } Map exceptionAuxiliaryData = resolveExceptionAuxiliaryData(exception, request); diff --git a/nrich-webmvc/src/main/java/net/croz/nrich/webmvc/service/DefaultTransientPropertyResolverService.java b/nrich-webmvc/src/main/java/net/croz/nrich/webmvc/service/DefaultTransientPropertyResolverService.java index 964fef7a8..72f1c44d5 100644 --- a/nrich-webmvc/src/main/java/net/croz/nrich/webmvc/service/DefaultTransientPropertyResolverService.java +++ b/nrich-webmvc/src/main/java/net/croz/nrich/webmvc/service/DefaultTransientPropertyResolverService.java @@ -24,7 +24,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import java.util.stream.Collectors; public class DefaultTransientPropertyResolverService implements TransientPropertyResolverService { @@ -38,7 +37,7 @@ public List resolveTransientPropertyList(Class type) { List currentTransientPropertyList = Arrays.stream(currentType.getDeclaredFields()) .filter(this::includeField) .map(Field::getName) - .collect(Collectors.toList()); + .toList(); transientPropertyList.addAll(currentTransientPropertyList); diff --git a/nrich-webmvc/src/test/java/net/croz/nrich/webmvc/WebmvcTestConfiguration.java b/nrich-webmvc/src/test/java/net/croz/nrich/webmvc/WebmvcTestConfiguration.java index 58ea35717..4f71e737d 100644 --- a/nrich-webmvc/src/test/java/net/croz/nrich/webmvc/WebmvcTestConfiguration.java +++ b/nrich-webmvc/src/test/java/net/croz/nrich/webmvc/WebmvcTestConfiguration.java @@ -47,7 +47,7 @@ import org.springframework.validation.beanvalidation.MethodValidationPostProcessor; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import java.util.Collections; +import java.util.List; import java.util.concurrent.ExecutionException; @ComponentScan("net.croz.nrich.webmvc") @@ -133,7 +133,7 @@ public NotificationErrorHandlingRestControllerAdvice notificationErrorHandlingRe ExceptionAuxiliaryDataResolverService exceptionAuxiliaryDataResolverService, ExceptionHttpStatusResolverService exceptionHttpStatusResolverService) { return new NotificationErrorHandlingRestControllerAdvice( - Collections.singletonList(ExecutionException.class.getName()), Collections.singletonList("uuid"), notificationResponseService, + List.of(ExecutionException.class.getName()), List.of("uuid"), notificationResponseService, loggingService, exceptionAuxiliaryDataResolverService, exceptionHttpStatusResolverService ); } diff --git a/nrich-webmvc/src/test/java/net/croz/nrich/webmvc/advice/testutil/MapGeneratingUtil.java b/nrich-webmvc/src/test/java/net/croz/nrich/webmvc/advice/testutil/MapGeneratingUtil.java index b0f06cbcc..761bf4e75 100644 --- a/nrich-webmvc/src/test/java/net/croz/nrich/webmvc/advice/testutil/MapGeneratingUtil.java +++ b/nrich-webmvc/src/test/java/net/croz/nrich/webmvc/advice/testutil/MapGeneratingUtil.java @@ -17,7 +17,6 @@ package net.croz.nrich.webmvc.advice.testutil; -import java.util.HashMap; import java.util.Map; public final class MapGeneratingUtil { @@ -26,11 +25,6 @@ private MapGeneratingUtil() { } public static Map createMap(String firstKey, String firstValue, String secondKey, String secondValue) { - Map map = new HashMap<>(); - - map.put(firstKey, firstValue); - map.put(secondKey, secondValue); - - return map; + return Map.of(firstKey, firstValue, secondKey, secondValue); } } diff --git a/nrich-webmvc/src/test/java/net/croz/nrich/webmvc/localeresolver/ConstrainedSessionLocaleResolverTest.java b/nrich-webmvc/src/test/java/net/croz/nrich/webmvc/localeresolver/ConstrainedSessionLocaleResolverTest.java index 9f4603b23..4bf5f64c1 100644 --- a/nrich-webmvc/src/test/java/net/croz/nrich/webmvc/localeresolver/ConstrainedSessionLocaleResolverTest.java +++ b/nrich-webmvc/src/test/java/net/croz/nrich/webmvc/localeresolver/ConstrainedSessionLocaleResolverTest.java @@ -23,7 +23,7 @@ import org.springframework.mock.web.MockHttpSession; import org.springframework.web.servlet.i18n.SessionLocaleResolver; -import java.util.Arrays; +import java.util.List; import java.util.Locale; import static org.assertj.core.api.Assertions.assertThat; @@ -33,7 +33,7 @@ class ConstrainedSessionLocaleResolverTest { @Test void shouldOnlyAllowSettingOfAllowedLocale() { // given - ConstrainedSessionLocaleResolver constrainedSessionLocaleResolver = new ConstrainedSessionLocaleResolver("hr", Arrays.asList("hr", "en")); + ConstrainedSessionLocaleResolver constrainedSessionLocaleResolver = new ConstrainedSessionLocaleResolver("hr", List.of("hr", "en")); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSession(new MockHttpSession()); @@ -55,7 +55,7 @@ void shouldOnlyAllowSettingOfAllowedLocale() { @Test void shouldSetDefaultLocaleWhenSettingNullLocale() { // given - ConstrainedSessionLocaleResolver constrainedSessionLocaleResolver = new ConstrainedSessionLocaleResolver(null, Arrays.asList("hr", "zh_CN", "en")); + ConstrainedSessionLocaleResolver constrainedSessionLocaleResolver = new ConstrainedSessionLocaleResolver(null, List.of("hr", "zh_CN", "en")); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSession(new MockHttpSession()); diff --git a/nrich-webmvc/src/test/java/net/croz/nrich/webmvc/service/stub/TransientPropertyResolverServiceImplTestRequest.java b/nrich-webmvc/src/test/java/net/croz/nrich/webmvc/service/stub/TransientPropertyResolverServiceImplTestRequest.java index 0bb8dec85..72240c850 100644 --- a/nrich-webmvc/src/test/java/net/croz/nrich/webmvc/service/stub/TransientPropertyResolverServiceImplTestRequest.java +++ b/nrich-webmvc/src/test/java/net/croz/nrich/webmvc/service/stub/TransientPropertyResolverServiceImplTestRequest.java @@ -20,7 +20,7 @@ @SuppressWarnings("unused") public class TransientPropertyResolverServiceImplTestRequest { - public class TransientPropertyResolverServiceImplTestInnerRequest extends TransientPropertyResolverServiceImplTestParentRequest { + public static class TransientPropertyResolverServiceImplTestInnerRequest extends TransientPropertyResolverServiceImplTestParentRequest { private transient int anotherValue; diff --git a/nrich-webmvc/src/test/java/net/croz/nrich/webmvc/test/BaseControllerTest.java b/nrich-webmvc/src/test/java/net/croz/nrich/webmvc/test/BaseControllerTest.java index 372f24f46..8a119d5ba 100644 --- a/nrich-webmvc/src/test/java/net/croz/nrich/webmvc/test/BaseControllerTest.java +++ b/nrich-webmvc/src/test/java/net/croz/nrich/webmvc/test/BaseControllerTest.java @@ -31,6 +31,7 @@ import org.springframework.web.context.WebApplicationContext; import java.util.Collections; +import java.util.List; import java.util.Map; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; @@ -76,7 +77,7 @@ protected ResultActions performFormPostRequest(String requestUrl, Map createFromMap(Map requestData) { MultiValueMap resultMap = new LinkedMultiValueMap<>(); - requestData.forEach((key, value) -> resultMap.put(key, Collections.singletonList(value))); + requestData.forEach((key, value) -> resultMap.put(key, List.of(value))); return resultMap; }