Skip to content

Commit

Permalink
Migrate code to Java 17 standard and cleanup code
Browse files Browse the repository at this point in the history
  • Loading branch information
agrancaric committed Sep 23, 2024
1 parent b4b856d commit 7729d45
Show file tree
Hide file tree
Showing 212 changed files with 1,036 additions and 2,148 deletions.
14 changes: 7 additions & 7 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> propertyToEncryptDecryptList;

/**
* Whether to encrypt method result or decrypt method parameters.
*/
private final EncryptionOperation encryptionOperation;
public record EncryptionConfiguration(String methodToEncryptDecrypt, List<String> propertyToEncryptDecryptList, EncryptionOperation encryptionOperation) {

}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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()));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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<EncryptionConfiguration> 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<String> 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<EncryptionConfiguration> encryptionConfigurationList, List<String> ignoredMethodList, @DefaultValue("UTF-8") String textEncryptCharset,
@DefaultValue("true") boolean encryptAspectEnabled, @DefaultValue("true") boolean encryptAdvisorEnabled, String encryptPassword, String encryptSalt) {

public NrichEncryptProperties(List<EncryptionConfiguration> encryptionConfigurationList, List<String> 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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -84,21 +83,16 @@ private <T> T encryptCompletableFuture(EncryptionContext encryptionContext, List
return encryptedFuture;
}

@RequiredArgsConstructor
private static class ReactorEncryptor {
private record ReactorEncryptor(DataEncryptionService dataEncryptionService) {

private final DataEncryptionService dataEncryptionService;

public <T> T encryptReactorResult(EncryptionContext encryptionContext, List<String> pathToEncryptList, T forEncryption) {
if (forEncryption instanceof Mono) {
@SuppressWarnings("unchecked")
T encryptedMono = (T) ((Mono<?>) forEncryption).map(completedResult -> dataEncryptionService.encryptData(completedResult, pathToEncryptList, encryptionContext));
<T> T encryptReactorResult(EncryptionContext encryptionContext, List<String> 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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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();

Expand All @@ -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;
}
Expand All @@ -96,7 +95,7 @@ private DecryptArgument decryptArgumentAnnotation(Annotation[] annotationList) {
}

private EncryptionContext createEncryptionContext(Signature signature, Object[] arguments) {
List<Object> argumentList = Arrays.asList(arguments);
List<Object> argumentList = List.of(arguments);
String methodName = String.format(EncryptConstants.METHOD_NAME_FORMAT, signature.getDeclaringType().getName(), signature.getName());
String currentUsername = currentUsername();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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);

Expand All @@ -61,8 +58,8 @@ public Object invoke(MethodInvocation invocation) throws Throwable {
}

List<EncryptionConfiguration> 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);
Expand All @@ -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);
}
Expand All @@ -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());
}
}

Expand All @@ -107,13 +104,13 @@ private String anyClassMethod(MethodInvocation invocation) {

private EncryptionConfiguration findEncryptionConfigurationForOperation(List<EncryptionConfiguration> 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<Object> argumentList = Arrays.asList(arguments);
List<Object> argumentList = List.of(arguments);
String currentUsername = currentUsername();

return EncryptionContext.builder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down Expand Up @@ -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<String, Object>) holder).get(path);
if (holder instanceof Map<?, ?> map) {
return map.get(path);
}

try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ private PointcutResolvingUtil() {

public static String resolvePointcutFromEncryptionConfigurationList(List<EncryptionConfiguration> 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));
}
Expand Down
Loading

0 comments on commit 7729d45

Please sign in to comment.