Search in sources :

Example 11 with AnnotationValue

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)));
            }
        }
    }
}
Also used : Default(javax.validation.groups.Default) AnnotationMetadata(io.micronaut.core.annotation.AnnotationMetadata) Annotation(java.lang.annotation.Annotation) AnnotationValue(io.micronaut.core.annotation.AnnotationValue)

Example 12 with 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;
}
Also used : NonNull(io.micronaut.core.annotation.NonNull) BigDecimal(java.math.BigDecimal) ValidationException(javax.validation.ValidationException) AnnotationValue(io.micronaut.core.annotation.AnnotationValue) Nullable(io.micronaut.core.annotation.Nullable) DecimalMax(javax.validation.constraints.DecimalMax) ConversionService(io.micronaut.core.convert.ConversionService) ValidationException(javax.validation.ValidationException) BigDecimal(java.math.BigDecimal)

Example 13 with AnnotationValue

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;
}
Also used : NonNull(io.micronaut.core.annotation.NonNull) BigDecimal(java.math.BigDecimal) ValidationException(javax.validation.ValidationException) AnnotationValue(io.micronaut.core.annotation.AnnotationValue) Nullable(io.micronaut.core.annotation.Nullable) DecimalMin(javax.validation.constraints.DecimalMin) ConversionService(io.micronaut.core.convert.ConversionService) ValidationException(javax.validation.ValidationException) BigDecimal(java.math.BigDecimal)

Example 14 with AnnotationValue

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);
    });
}
Also used : Bindable(io.micronaut.core.bind.annotation.Bindable) Arrays(java.util.Arrays) BeanContext(io.micronaut.context.BeanContext) Date(java.util.Date) LoggerFactory(org.slf4j.LoggerFactory) MessageHeader(io.micronaut.messaging.annotation.MessageHeader) TaskExecutors(io.micronaut.scheduling.TaskExecutors) RabbitConnection(io.micronaut.rabbitmq.annotation.RabbitConnection) Map(java.util.Map) Qualifiers(io.micronaut.inject.qualifiers.Qualifiers) Singleton(jakarta.inject.Singleton) RabbitProperty(io.micronaut.rabbitmq.annotation.RabbitProperty) RabbitMessageSerDes(io.micronaut.rabbitmq.serdes.RabbitMessageSerDes) RabbitMessageSerDesRegistry(io.micronaut.rabbitmq.serdes.RabbitMessageSerDesRegistry) Objects(java.util.Objects) StringUtils(io.micronaut.core.util.StringUtils) List(java.util.List) RabbitClient(io.micronaut.rabbitmq.annotation.RabbitClient) MethodInvocationContext(io.micronaut.aop.MethodInvocationContext) AnnotationValue(io.micronaut.core.annotation.AnnotationValue) Optional(java.util.Optional) RabbitClientException(io.micronaut.rabbitmq.exception.RabbitClientException) MessageBody(io.micronaut.messaging.annotation.MessageBody) Named(jakarta.inject.Named) Binding(io.micronaut.rabbitmq.annotation.Binding) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Caffeine(io.micronaut.caffeine.cache.Caffeine) Scheduler(reactor.core.scheduler.Scheduler) InterceptedMethod(io.micronaut.aop.InterceptedMethod) ExecutableMethod(io.micronaut.inject.ExecutableMethod) MethodInterceptor(io.micronaut.aop.MethodInterceptor) BiConsumer(java.util.function.BiConsumer) Schedulers(reactor.core.scheduler.Schedulers) Argument(io.micronaut.core.type.Argument) RabbitPublishState(io.micronaut.rabbitmq.reactive.RabbitPublishState) ConversionService(io.micronaut.core.convert.ConversionService) Subscriber(org.reactivestreams.Subscriber) ExecutorService(java.util.concurrent.ExecutorService) Logger(org.slf4j.Logger) Mono(reactor.core.publisher.Mono) RabbitConsumerState(io.micronaut.rabbitmq.bind.RabbitConsumerState) Consumer(java.util.function.Consumer) AbstractMap(java.util.AbstractMap) ReactivePublisher(io.micronaut.rabbitmq.reactive.ReactivePublisher) Subscription(org.reactivestreams.Subscription) Cache(io.micronaut.caffeine.cache.Cache) Collections(java.util.Collections) AMQP(com.rabbitmq.client.AMQP) RabbitHeaders(io.micronaut.rabbitmq.annotation.RabbitHeaders) RabbitClient(io.micronaut.rabbitmq.annotation.RabbitClient) HashMap(java.util.HashMap) RabbitClientException(io.micronaut.rabbitmq.exception.RabbitClientException) ReactivePublisher(io.micronaut.rabbitmq.reactive.ReactivePublisher) AnnotationValue(io.micronaut.core.annotation.AnnotationValue)

Example 15 with AnnotationValue

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);
    }
}
Also used : ExecutableMethod(io.micronaut.inject.ExecutableMethod) InterceptedMethod(io.micronaut.aop.InterceptedMethod) RateLimiter(io.github.resilience4j.ratelimiter.RateLimiter) CompletionException(java.util.concurrent.CompletionException) CompletionException(java.util.concurrent.CompletionException) AnnotationValue(io.micronaut.core.annotation.AnnotationValue)

Aggregations

AnnotationValue (io.micronaut.core.annotation.AnnotationValue)52 AnnotationMetadata (io.micronaut.core.annotation.AnnotationMetadata)21 Optional (java.util.Optional)19 Argument (io.micronaut.core.type.Argument)18 ExecutableMethod (io.micronaut.inject.ExecutableMethod)18 StringUtils (io.micronaut.core.util.StringUtils)17 NonNull (io.micronaut.core.annotation.NonNull)16 Map (java.util.Map)16 Nullable (io.micronaut.core.annotation.Nullable)15 List (java.util.List)15 InterceptedMethod (io.micronaut.aop.InterceptedMethod)13 ConversionService (io.micronaut.core.convert.ConversionService)13 Singleton (jakarta.inject.Singleton)13 Logger (org.slf4j.Logger)13 LoggerFactory (org.slf4j.LoggerFactory)13 Annotation (java.lang.annotation.Annotation)12 Arrays (java.util.Arrays)11 Collections (java.util.Collections)11 BeanContext (io.micronaut.context.BeanContext)10 Qualifiers (io.micronaut.inject.qualifiers.Qualifiers)10