Skip to content

Commit

Permalink
Pattern matching for instanceof (#242)
Browse files Browse the repository at this point in the history
  • Loading branch information
altro3 authored Oct 30, 2023
1 parent 87fd4ed commit f3cce2f
Show file tree
Hide file tree
Showing 12 changed files with 51 additions and 51 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import java.util.Collections;
import java.util.stream.Collectors;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
Expand All @@ -19,6 +18,6 @@ class EmailSenderTest {
void defaultMessageIsUsed(EmailSender emailSender) {
Executable e = () -> emailSender.send(new Email("", ""));
ConstraintViolationException thrown = assertThrows(ConstraintViolationException.class, e);
assertEquals(Collections.singletonList(EmailMessages.ANY_RECIPIENT_MESSAGE), thrown.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.toList()));
assertEquals(Collections.singletonList(EmailMessages.ANY_RECIPIENT_MESSAGE), thrown.getConstraintViolations().stream().map(ConstraintViolation::getMessage).toList());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Internal
Expand All @@ -45,7 +44,7 @@ private static URL[] findUrls(DeploymentDir deploymentDir) throws IOException {
result.add(deploymentDir.target.toUri().toURL());

try (Stream<Path> stream = Files.walk(deploymentDir.lib)) {
List<Path> jars = stream.filter(p -> p.toString().endsWith(".jar")).collect(Collectors.toList());
List<Path> jars = stream.filter(p -> p.toString().endsWith(".jar")).toList();
for (Path jar : jars) {
result.add(jar.toUri().toURL());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,16 +111,16 @@ private static JavaArchive buildSupportLibrary() {

@Override
public ProtocolMetaData deploy(Archive<?> archive) {
if (archive instanceof LibraryContainer) {
((LibraryContainer<?>) archive).addAsLibrary(buildSupportLibrary());
if (archive instanceof LibraryContainer<?> libraryContainer) {
libraryContainer.addAsLibrary(buildSupportLibrary());
} else {
throw new IllegalStateException("Expected library container!");
}
old = Thread.currentThread().getContextClassLoader();
if (testClass.get() == null) {
throw new IllegalStateException("Test class not available");
}
Class testJavaClass = testClass.get().getJavaClass();
Class<?> testJavaClass = testClass.get().getJavaClass();
Objects.requireNonNull(testJavaClass);

try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,18 +119,18 @@ public Object intercept(MethodInvocationContext<Object, Object> context) {
throw new ConstraintViolationException(constraintViolations);
}
}
if (micronautValidator instanceof ReactiveValidator) {
if (micronautValidator instanceof ReactiveValidator reactiveValidator) {
InterceptedMethod interceptedMethod = InterceptedMethod.of(context, conversionService);
try {
return switch (interceptedMethod.resultType()) {
case PUBLISHER -> interceptedMethod.handleResult(
((ReactiveValidator) micronautValidator).validatePublisher(
reactiveValidator.validatePublisher(
context.getReturnType(),
interceptedMethod.interceptResultAsPublisher(),
getValidationGroups(context))
);
case COMPLETION_STAGE -> interceptedMethod.handleResult(
((ReactiveValidator) micronautValidator).validateCompletionStage(
reactiveValidator.validateCompletionStage(
(CompletionStage<Object>) interceptedMethod.interceptResultAsCompletionStage(),
(Argument<Object>) context.getReturnType().getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT),
getValidationGroups(context))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package io.micronaut.validation.exceptions;

import io.micronaut.context.annotation.Requires;
import io.micronaut.core.util.CollectionUtils;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.HttpStatus;
Expand All @@ -33,7 +34,6 @@
import jakarta.validation.Path;
import java.util.Iterator;
import java.util.Set;
import java.util.stream.Collectors;

/**
* Default {@link ExceptionHandler} for {@link ConstraintViolationException}.
Expand Down Expand Up @@ -62,7 +62,7 @@ public HttpResponse<?> handle(HttpRequest request, ConstraintViolationException
Set<ConstraintViolation<?>> constraintViolations = exception.getConstraintViolations();
MutableHttpResponse<?> response = HttpResponse.badRequest();
final ErrorContext.Builder contextBuilder = ErrorContext.builder(request).cause(exception);
if (constraintViolations == null || constraintViolations.isEmpty()) {
if (CollectionUtils.isEmpty(constraintViolations)) {
return responseProcessor.processResponse(contextBuilder.errorMessage(
exception.getMessage() == null ? HttpStatus.BAD_REQUEST.getReason() : exception.getMessage()
).build(), response);
Expand All @@ -72,7 +72,7 @@ public HttpResponse<?> handle(HttpRequest request, ConstraintViolationException
.stream()
.map(this::buildMessage)
.sorted()
.collect(Collectors.toList())
.toList()
).build(), response);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,7 @@ public ClockProvider getClockProvider() {

@Override
public ConstraintViolationBuilder buildConstraintViolationWithTemplate(String messageTemplate) {
return new DefaultConstraintViolationBuilder(messageTemplate, this, defaultValidator.messageInterpolator);
return new DefaultConstraintViolationBuilder<>(messageTemplate, this, defaultValidator.messageInterpolator);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1353,8 +1353,8 @@ private <R, E> void validateConstrains(DefaultConstraintValidatorContext<R> cont
} catch (Exception e) {
throw new ValidationException("Cannot initialize validator: " + beanIntrospection.getBeanType().getName());
}
if (constraintValidator instanceof ConstraintValidator<Annotation, E>) {
validator = (ConstraintValidator<Annotation, E>) constraintValidator;
if (constraintValidator instanceof ConstraintValidator<Annotation, E> cv) {
validator = cv;
} else {
validator = new ConstraintValidator<>() {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -454,11 +454,11 @@ private static void determineValueExtractorDefinitions(List<AnnotatedType> value
}

public static Class<?> getClassFromType(Type type) {
if (type instanceof Class) {
return (Class<?>) type;
if (type instanceof Class<?> classType) {
return classType;
}
if (type instanceof ParameterizedType) {
return getClassFromType(((ParameterizedType) type).getRawType());
if (type instanceof ParameterizedType parameterizedType) {
return getClassFromType(parameterizedType.getRawType());
}
if (type instanceof GenericArrayType) {
return Object[].class;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -510,6 +510,7 @@ public record DefaultContainerContext(@Nullable Class<?> containerClass,
/**
* Not in a container context.
*/
@SuppressWarnings("StaticVariableName")
static DefaultContainerContext NONE = new DefaultContainerContext(null, null, null, false, null);

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ public interface ConstraintValidatorContext extends jakarta.validation.Constrain
*
* @since 2.0
*/
@Override
@NonNull ClockProvider getClockProvider();

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ default boolean isValid(@Nullable T value, @NonNull AnnotationValue<Digits> anno
}

int intLen = bigDecimal.precision() - bigDecimal.scale();
int fracLen = bigDecimal.scale() < 0 ? 0 : bigDecimal.scale();
int fracLen = Math.max(bigDecimal.scale(), 0);

return intMax >= intLen && fracMax >= fracLen;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,8 @@ final class InternalConstraintValidators {
final DecimalMinValidator<Number> decimalMinValidatorNumber = InternalConstraintValidators::compareNumber;

final DigitsValidator<Number> digitsValidatorNumber = value -> {
if (value instanceof BigDecimal) {
return (BigDecimal) value;
if (value instanceof BigDecimal decimalValue) {
return decimalValue;
}
return new BigDecimal(value.toString());
};
Expand All @@ -109,10 +109,10 @@ final class InternalConstraintValidators {
new ValidationException("@Max annotation specified without value")
);

if (value instanceof BigInteger) {
return ((BigInteger) value).compareTo(BigInteger.valueOf(max)) <= 0;
} else if (value instanceof BigDecimal) {
return ((BigDecimal) value).compareTo(BigDecimal.valueOf(max)) <= 0;
if (value instanceof BigInteger intValue) {
return intValue.compareTo(BigInteger.valueOf(max)) <= 0;
} else if (value instanceof BigDecimal decimalValue) {
return decimalValue.compareTo(BigDecimal.valueOf(max)) <= 0;
}
return value.longValue() <= max;
};
Expand All @@ -126,10 +126,10 @@ final class InternalConstraintValidators {
new ValidationException("@Min annotation specified without value")
);

if (value instanceof BigInteger) {
return ((BigInteger) value).compareTo(BigInteger.valueOf(max)) >= 0;
} else if (value instanceof BigDecimal) {
return ((BigDecimal) value).compareTo(BigDecimal.valueOf(max)) >= 0;
if (value instanceof BigInteger intValue) {
return intValue.compareTo(BigInteger.valueOf(max)) >= 0;
} else if (value instanceof BigDecimal decimalValue) {
return decimalValue.compareTo(BigDecimal.valueOf(max)) >= 0;
}
return value.longValue() >= max;
};
Expand All @@ -140,11 +140,11 @@ final class InternalConstraintValidators {
if (value == null) {
return true;
}
if (value instanceof BigDecimal) {
return ((BigDecimal) value).signum() < 0;
if (value instanceof BigDecimal decimalValue) {
return decimalValue.signum() < 0;
}
if (value instanceof BigInteger) {
return ((BigInteger) value).signum() < 0;
if (value instanceof BigInteger intValue) {
return intValue.signum() < 0;
}
if (value instanceof Double ||
value instanceof Float ||
Expand All @@ -161,11 +161,11 @@ final class InternalConstraintValidators {
if (value == null) {
return true;
}
if (value instanceof BigDecimal) {
return ((BigDecimal) value).signum() <= 0;
if (value instanceof BigDecimal decimalValue) {
return decimalValue.signum() <= 0;
}
if (value instanceof BigInteger) {
return ((BigInteger) value).signum() <= 0;
if (value instanceof BigInteger intValue) {
return intValue.signum() <= 0;
}
if (value instanceof Double ||
value instanceof Float ||
Expand All @@ -182,11 +182,11 @@ final class InternalConstraintValidators {
if (value == null) {
return true;
}
if (value instanceof BigDecimal) {
return ((BigDecimal) value).signum() > 0;
if (value instanceof BigDecimal decimalValue) {
return decimalValue.signum() > 0;
}
if (value instanceof BigInteger) {
return ((BigInteger) value).signum() > 0;
if (value instanceof BigInteger intValue) {
return intValue.signum() > 0;
}
if (value instanceof Double ||
value instanceof Float ||
Expand All @@ -203,11 +203,11 @@ final class InternalConstraintValidators {
if (value == null) {
return true;
}
if (value instanceof BigDecimal) {
return ((BigDecimal) value).signum() >= 0;
if (value instanceof BigDecimal decimalValue) {
return decimalValue.signum() >= 0;
}
if (value instanceof BigInteger) {
return ((BigInteger) value).signum() >= 0;
if (value instanceof BigInteger intValue) {
return intValue.signum() >= 0;
}
if (value instanceof Double ||
value instanceof Float ||
Expand Down Expand Up @@ -410,10 +410,10 @@ final class InternalConstraintValidators {
*/
private static int compareNumber(@NonNull Number value, @NonNull BigDecimal bigDecimal) {
int result;
if (value instanceof BigDecimal) {
result = ((BigDecimal) value).compareTo(bigDecimal);
} else if (value instanceof BigInteger) {
result = new BigDecimal((BigInteger) value).compareTo(bigDecimal);
if (value instanceof BigDecimal decimalValue) {
result = decimalValue.compareTo(bigDecimal);
} else if (value instanceof BigInteger intValue) {
result = new BigDecimal(intValue).compareTo(bigDecimal);
} else {
result = BigDecimal.valueOf(value.doubleValue()).compareTo(bigDecimal);
}
Expand Down

0 comments on commit f3cce2f

Please sign in to comment.