use of io.micronaut.core.annotation.AnnotationValue in project micronaut-core by micronaut-projects.
the class DefaultValidator method valueConstraintOnProperty.
@SuppressWarnings("unchecked")
private <T> void valueConstraintOnProperty(@Nullable Class<T> rootBeanClass, @Nullable T rootBean, @Nullable Object object, DefaultConstraintValidatorContext context, Set<ConstraintViolation<Object>> overallViolations, AnnotatedElement constrainedProperty, Class propertyType, @Nullable Object propertyValue, Class<? extends Annotation> constraintType) {
final AnnotationMetadata annotationMetadata = constrainedProperty.getAnnotationMetadata();
final List<? extends AnnotationValue<? extends Annotation>> annotationValues = annotationMetadata.getAnnotationValuesByType(constraintType);
Set<AnnotationValue<? extends Annotation>> constraints = new HashSet<>(3);
for (Class<?> group : context.groups) {
for (AnnotationValue<? extends Annotation> annotationValue : annotationValues) {
final Class<?>[] classValues = annotationValue.classValues("groups");
if (ArrayUtils.isEmpty(classValues)) {
if (context.groups == DEFAULT_GROUPS || group == Default.class) {
constraints.add(annotationValue);
}
} else {
final List<Class> constraintGroups = Arrays.asList(classValues);
if (constraintGroups.contains(group)) {
constraints.add(annotationValue);
}
}
}
}
@SuppressWarnings("unchecked") final Class<Object> targetType = propertyValue != null ? (Class<Object>) propertyValue.getClass() : propertyType;
final ConstraintValidator<? extends Annotation, Object> validator = constraintValidatorRegistry.findConstraintValidator(constraintType, targetType).orElse(null);
if (validator != null) {
for (AnnotationValue annotationValue : constraints) {
// noinspection unchecked
if (!validator.isValid(propertyValue, annotationValue, context)) {
final String messageTemplate = buildMessageTemplate(context, annotationValue, annotationMetadata);
Map<String, Object> variables = newConstraintVariables(annotationValue, propertyValue, annotationMetadata);
// noinspection unchecked
overallViolations.add(new DefaultConstraintViolation(rootBean, rootBeanClass, object, propertyValue, messageSource.interpolate(messageTemplate, MessageSource.MessageContext.of(variables)), messageTemplate, new PathImpl(context.currentPath), new DefaultConstraintDescriptor(annotationMetadata, constraintType, annotationValue)));
}
}
}
}
use of io.micronaut.core.annotation.AnnotationValue in project micronaut-core by micronaut-projects.
the class DecimalMaxValidator method isValid.
@Override
default boolean isValid(@Nullable T value, @NonNull AnnotationValue<DecimalMax> annotationMetadata, @NonNull ConstraintValidatorContext context) {
if (value == null) {
// null considered valid according to spec
return true;
}
final BigDecimal bigDecimal = annotationMetadata.getValue(String.class).map(s -> ConversionService.SHARED.convert(s, BigDecimal.class).orElseThrow(() -> new ValidationException(s + " does not represent a valid BigDecimal format."))).orElseThrow(() -> new ValidationException("null does not represent a valid BigDecimal format."));
int result;
try {
result = doComparison(value, bigDecimal);
} catch (NumberFormatException nfe) {
return false;
}
final boolean inclusive = annotationMetadata.get("inclusive", boolean.class).orElse(true);
return inclusive ? result <= 0 : result < 0;
}
use of io.micronaut.core.annotation.AnnotationValue in project micronaut-core by micronaut-projects.
the class DecimalMinValidator method isValid.
@Override
default boolean isValid(@Nullable T value, @NonNull AnnotationValue<DecimalMin> annotationMetadata, @NonNull ConstraintValidatorContext context) {
if (value == null) {
// null considered valid according to spec
return true;
}
final BigDecimal bigDecimal = annotationMetadata.getValue(String.class).map(s -> ConversionService.SHARED.convert(s, BigDecimal.class).orElseThrow(() -> new ValidationException(s + " does not represent a valid BigDecimal format."))).orElseThrow(() -> new ValidationException("null does not represent a valid BigDecimal format."));
int result;
try {
result = doComparison(value, bigDecimal);
} catch (NumberFormatException nfe) {
return false;
}
final boolean inclusive = annotationMetadata.get("inclusive", boolean.class).orElse(true);
return inclusive ? result >= 0 : result > 0;
}
use of io.micronaut.core.annotation.AnnotationValue in project micronaut-rabbitmq by micronaut-projects.
the class RabbitMQIntroductionAdvice method getPublisherState.
private StaticPublisherState getPublisherState(MethodInvocationContext<?, ?> context) {
return publisherCache.get(context.getExecutableMethod(), (method) -> {
AnnotationValue<RabbitClient> client = method.findAnnotation(RabbitClient.class).orElseThrow(() -> new IllegalStateException("No @RabbitClient annotation present on method: " + method));
String exchange = client.getValue(String.class).orElse("");
Optional<AnnotationValue<Binding>> bindingAnn = method.findAnnotation(Binding.class);
Optional<String> routingKey = bindingAnn.flatMap(b -> b.getValue(String.class));
String connection = method.findAnnotation(RabbitConnection.class).flatMap(conn -> conn.get("connection", String.class)).orElse(RabbitConnection.DEFAULT_CONNECTION);
Argument<?> bodyArgument = findBodyArgument(method).orElseThrow(() -> new RabbitClientException("No valid message body argument found for method: " + method));
Map<String, Object> methodHeaders = new HashMap<>();
List<AnnotationValue<MessageHeader>> headerAnnotations = method.getAnnotationValuesByType(MessageHeader.class);
// set the values in the class first so methods can override
Collections.reverse(headerAnnotations);
headerAnnotations.forEach((header) -> {
String name = header.get("name", String.class).orElse(null);
String value = header.getValue(String.class).orElse(null);
if (StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(value)) {
methodHeaders.put(name, value);
}
});
Map<String, String> methodProperties = new HashMap<>();
List<AnnotationValue<RabbitProperty>> propertyAnnotations = method.getAnnotationValuesByType(RabbitProperty.class);
// set the values in the class first so methods can override
Collections.reverse(propertyAnnotations);
propertyAnnotations.forEach((prop) -> {
String name = prop.get("name", String.class).orElse(null);
String value = prop.getValue(String.class).orElse(null);
if (StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(value)) {
if (this.properties.containsKey(name)) {
methodProperties.put(name, value);
} else {
throw new RabbitClientException(String.format("Attempted to set property [%s], but could not match the name to any of the com.rabbitmq.client.BasicProperties", name));
}
}
});
RabbitMessageSerDes<?> serDes = serDesRegistry.findSerdes(bodyArgument).orElseThrow(() -> new RabbitClientException(String.format("Could not find a serializer for the body argument of type [%s]", bodyArgument.getType().getName())));
ReactivePublisher reactivePublisher;
try {
reactivePublisher = beanContext.getBean(ReactivePublisher.class, Qualifiers.byName(connection));
} catch (Throwable e) {
throw new RabbitClientException(String.format("Failed to retrieve a publisher named [%s] to publish messages", connection), e);
}
return new StaticPublisherState(exchange, routingKey.orElse(null), bodyArgument, methodHeaders, methodProperties, method.getReturnType(), serDes, reactivePublisher);
});
}
use of io.micronaut.core.annotation.AnnotationValue in project resilience4j by resilience4j.
the class RateLimiterInterceptor method intercept.
@Override
public Object intercept(MethodInvocationContext<Object, Object> context) {
Optional<AnnotationValue<io.github.resilience4j.micronaut.annotation.RateLimiter>> opt = context.findAnnotation(io.github.resilience4j.micronaut.annotation.RateLimiter.class);
if (!opt.isPresent()) {
return context.proceed();
}
ExecutableMethod executableMethod = context.getExecutableMethod();
final String name = executableMethod.stringValue(io.github.resilience4j.micronaut.annotation.RateLimiter.class, "name").orElse("default");
RateLimiter rateLimiter = this.rateLimiterRegistry.rateLimiter(name);
InterceptedMethod interceptedMethod = InterceptedMethod.of(context);
try {
switch(interceptedMethod.resultType()) {
case PUBLISHER:
return interceptedMethod.handleResult(fallbackReactiveTypes(Flowable.fromPublisher(interceptedMethod.interceptResultAsPublisher()).compose(RateLimiterOperator.of(rateLimiter)), context));
case COMPLETION_STAGE:
return interceptedMethod.handleResult(fallbackForFuture(rateLimiter.executeCompletionStage(() -> {
try {
return interceptedMethod.interceptResultAsCompletionStage();
} catch (Exception e) {
throw new CompletionException(e);
}
}), context));
case SYNCHRONOUS:
try {
return rateLimiter.executeCheckedSupplier(context::proceed);
} catch (Throwable exception) {
return fallback(context, exception);
}
default:
return interceptedMethod.unsupported();
}
} catch (Exception e) {
return interceptedMethod.handleException(e);
}
}
Aggregations