io.micronaut.aop.MethodInvocationContext Java Examples

The following examples show how to use io.micronaut.aop.MethodInvocationContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SpringConfigurationInterceptor.java    From micronaut-spring with Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(MethodInvocationContext<Object, Object> context) {
    final AnnotationMetadata annotationMetadata = context.getAnnotationMetadata();
    final boolean isSingleton = MicronautBeanFactory.isSingleton(annotationMetadata);
    if (isSingleton) {
        final ExecutableMethod<Object, Object> method = context.getExecutableMethod();
        synchronized (computedSingletons) {
            Object o = computedSingletons.get(method);
            if (o == null) {
                o = context.proceed();
                if (o == null) {
                    throw new BeanCreationException("Bean factor method [" + method + "] returned null");
                }
                computedSingletons.put(method, o);
            }
            return o;
        }
    }
    return context.proceed();
}
 
Example #2
Source File: DefaultFindSliceAsyncInterceptor.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public CompletionStage<Slice<Object>> intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, CompletionStage<Slice<Object>>> context) {
    if (context.hasAnnotation(Query.class)) {
        PreparedQuery<?, ?> preparedQuery = prepareQuery(methodKey, context);
        Pageable pageable = preparedQuery.getPageable();
        return asyncDatastoreOperations.findAll(preparedQuery)
                .thenApply(objects ->
                        Slice.of((List<Object>) CollectionUtils.iterableToList(objects), pageable)
                );

    } else {
        PagedQuery<Object> pagedQuery = getPagedQuery(context);
        return asyncDatastoreOperations.findAll(pagedQuery).thenApply(objects ->
                Slice.of(CollectionUtils.iterableToList(objects), pagedQuery.getPageable())
        );
    }
}
 
Example #3
Source File: DefaultCountAsyncInterceptor.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@Override
public CompletionStage<Long> intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, CompletionStage<Long>> context) {
    if (context.hasAnnotation(Query.class)) {
        PreparedQuery<?, Long> preparedQuery = prepareQuery(methodKey, context, Long.class);
        return asyncDatastoreOperations.findAll(preparedQuery)
                .thenApply(longs -> {
                    long result = 0L;
                    Iterator<Long> i = longs.iterator();
                    if (i.hasNext()) {
                        result = i.next();
                    }
                    return result;
                });
    } else {
        return asyncDatastoreOperations.count(getPagedQuery(context));
    }
}
 
Example #4
Source File: DefaultFindPageAsyncInterceptor.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public CompletionStage<Page<Object>> intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, CompletionStage<Page<Object>>> context) {
    if (context.hasAnnotation(Query.class)) {
        PreparedQuery<?, ?> preparedQuery = prepareQuery(methodKey, context);
        PreparedQuery<?, Number> countQuery = prepareCountQuery(methodKey, context);

        return asyncDatastoreOperations.findOne(countQuery)
                .thenCompose(total -> asyncDatastoreOperations.findAll(preparedQuery)
                        .thenApply(objects -> {
                            List<Object> resultList = CollectionUtils.iterableToList((Iterable<Object>) objects);
                            return Page.of(resultList, getPageable(context), total.longValue());
                        }));

    } else {
        return asyncDatastoreOperations.findPage(getPagedQuery(context));
    }
}
 
Example #5
Source File: AbstractQueryInterceptor.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
/**
 * Obtains the root entity or throws an exception if it not available.
 * @param context The context
 * @return The root entity type
 * @throws IllegalStateException If the root entity is unavailable
 */
@NonNull
protected Class<?> getRequiredRootEntity(MethodInvocationContext context) {
    Class aClass = context.classValue(PREDATOR_ANN_NAME, DataMethod.META_MEMBER_ROOT_ENTITY).orElse(null);
    if (aClass != null) {
        return aClass;
    } else {
        final AnnotationValue<Annotation> ann = context.getDeclaredAnnotation(PREDATOR_ANN_NAME);
        if (ann != null) {
            aClass = ann.classValue(DataMethod.META_MEMBER_ROOT_ENTITY).orElse(null);
            if (aClass != null) {
                return aClass;
            }
        }

        throw new IllegalStateException("No root entity present in method");
    }
}
 
Example #6
Source File: AbstractQueryInterceptor.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve a parameter in the given role for the given type.
 * @param context The context
 * @param role The role
 * @param type The type
 * @param <RT> The generic type
 * @return An optional result
 */
private <RT> Optional<RT> getParameterInRole(MethodInvocationContext<?, ?> context, @NonNull String role, @NonNull Class<RT> type) {
    return context.stringValue(PREDATOR_ANN_NAME, role).flatMap(name -> {
        RT parameterValue = null;
        Map<String, MutableArgumentValue<?>> params = context.getParameters();
        MutableArgumentValue<?> arg = params.get(name);
        if (arg != null) {
            Object o = arg.getValue();
            if (o != null) {
                if (type.isInstance(o)) {
                    //noinspection unchecked
                    parameterValue = (RT) o;
                } else {
                    parameterValue = ConversionService.SHARED
                            .convert(o, type).orElse(null);
                }
            }
        }
        return Optional.ofNullable(parameterValue);
    });
}
 
Example #7
Source File: DefaultDeleteOneAsyncInterceptor.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@Override
public CompletionStage<Number> intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, CompletionStage<Number>> context) {
    Object[] parameterValues = context.getParameterValues();
    if (parameterValues.length == 1) {
        Object o = parameterValues[0];
        if (o != null) {
            BatchOperation<Object> batchOperation = getBatchOperation(context, Collections.singletonList(o));
            return asyncDatastoreOperations.deleteAll(batchOperation)
                    .thenApply(n -> convertNumberArgumentIfNecessary(n, context.getReturnType().asArgument()));
        } else {
            throw new IllegalArgumentException("Entity to delete cannot be null");
        }
    } else {
        throw new IllegalStateException("Expected exactly one argument");
    }
}
 
Example #8
Source File: DefaultFindAllAsyncInterceptor.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public CompletionStage<Iterable<Object>> intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, CompletionStage<Iterable<Object>>> context) {
    CompletionStage<? extends Iterable<?>> future;
    if (context.hasAnnotation(Query.class)) {
        PreparedQuery<?, ?> preparedQuery = prepareQuery(methodKey, context);
        future = asyncDatastoreOperations.findAll(preparedQuery);

    } else {
        future = asyncDatastoreOperations.findAll(getPagedQuery(context));
    }
    return future.thenApply((Function<Iterable<?>, Iterable<Object>>) iterable -> {
        Argument<CompletionStage<Iterable<Object>>> targetType = context.getReturnType().asArgument();
        Argument<?> argument = targetType.getFirstTypeVariable().orElse(Argument.listOf(Object.class));
        Iterable<Object> result = (Iterable<Object>) ConversionService.SHARED.convert(
                iterable,
                argument
        ).orElse(null);
        return result == null ? Collections.emptyList() : result;
    });
}
 
Example #9
Source File: DefaultSaveAllInterceptor.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@Override
public Iterable<R> intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, Iterable<R>> context) {
    Object[] parameterValues = context.getParameterValues();
    if (ArrayUtils.isNotEmpty(parameterValues) && parameterValues[0] instanceof Iterable) {
        //noinspection unchecked
        Iterable<R> iterable = (Iterable<R>) parameterValues[0];
        Iterable<R> rs = operations.persistAll(getBatchOperation(context, iterable));
        ReturnType<Iterable<R>> rt = context.getReturnType();
        if (!rt.getType().isInstance(rs)) {
            return ConversionService.SHARED.convert(rs, rt.asArgument())
                        .orElseThrow(() -> new IllegalStateException("Unsupported iterable return type: " + rs.getClass()));
        }
        return rs;
    } else {
        throw new IllegalArgumentException("First argument should be an iterable");
    }
}
 
Example #10
Source File: DefaultFindPageReactiveInterceptor.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    Publisher<Page<Object>> publisher;
    if (context.hasAnnotation(Query.class)) {
        PreparedQuery<?, ?> preparedQuery = prepareQuery(methodKey, context);
        PreparedQuery<?, Number> countQuery = prepareCountQuery(methodKey, context);

        publisher = Flowable.fromPublisher(reactiveOperations.findOne(countQuery))
                .flatMap(total -> {
                    Flowable<Object> resultList = Flowable.fromPublisher(reactiveOperations.findAll(preparedQuery));
                    return resultList.toList().map(list ->
                        Page.of(list, preparedQuery.getPageable(), total.longValue())
                    ).toFlowable();
                });
    } else {
        publisher = reactiveOperations.findPage(getPagedQuery(context));
    }
    return Publishers.convertPublisher(publisher, context.getReturnType().getType());
}
 
Example #11
Source File: DefaultUpdateInterceptor.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, Object> context) {
    PreparedQuery<?, Number> preparedQuery = (PreparedQuery<?, Number>) prepareQuery(methodKey, context);
    Number number = operations.executeUpdate(preparedQuery).orElse(null);
    final Argument<Object> returnType = context.getReturnType().asArgument();
    final Class<Object> type = ReflectionUtils.getWrapperType(returnType.getType());
    if (Number.class.isAssignableFrom(type)) {
        if (type.isInstance(number)) {
            return number;
        } else {
            return ConversionService.SHARED.
                    convert(number, returnType)
                    .orElse(0);
        }
    } else if (Boolean.class.isAssignableFrom(type)) {
        return number == null || number.longValue() < 0;
    } else {
        return null;
    }
}
 
Example #12
Source File: DefaultDeleteOneReactiveInterceptor.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    Object[] parameterValues = context.getParameterValues();
    if (parameterValues.length == 1) {
        Class<Object> rootEntity = (Class<Object>) getRequiredRootEntity(context);
        Object o = parameterValues[0];
        if (o != null) {
            BatchOperation<Object> batchOperation = getBatchOperation(context, rootEntity, Collections.singletonList(o));
            Publisher<Number> publisher = Publishers.map(reactiveOperations.deleteAll(batchOperation),
                    n -> convertNumberArgumentIfNecessary(n, context.getReturnType().asArgument())
            );
            return Publishers.convertPublisher(
                    publisher,
                    context.getReturnType().getType()
            );
        } else {
            throw new IllegalArgumentException("Entity to delete cannot be null");
        }
    } else {
        throw new IllegalStateException("Expected exactly one argument");
    }
}
 
Example #13
Source File: DefaultCountInterceptor.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@Override
public Number intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, Number> context) {
    long result;
    if (context.hasAnnotation(Query.class)) {
        PreparedQuery<?, Long> preparedQuery = prepareQuery(methodKey, context, Long.class);
        Iterable<Long> iterable = operations.findAll(preparedQuery);
        Iterator<Long> i = iterable.iterator();
        result = i.hasNext() ? i.next() : 0;
    } else {
        result = operations.count(getPagedQuery(context));
    }

    return ConversionService.SHARED.convert(
            result,
            context.getReturnType().asArgument()
    ).orElseThrow(() -> new IllegalStateException("Unsupported number type: " + context.getReturnType().getType()));
}
 
Example #14
Source File: DefaultFindOneInterceptor.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, Object> context) {
    PreparedQuery<?, ?> preparedQuery = prepareQuery(methodKey, context, null);
    Object result = operations.findOne(preparedQuery);

    if (result != null) {
        ReturnType<Object> returnType = context.getReturnType();
        if (!returnType.getType().isInstance(result)) {
            return ConversionService.SHARED.convert(result, returnType.asArgument())
                        .orElseThrow(() -> new IllegalStateException("Unexpected return type: " + result));
        } else {
            return result;
        }
    } else {
        if (!isNullable(context.getAnnotationMetadata())) {
            throw new EmptyResultException();
        }
    }
    return result;
}
 
Example #15
Source File: DefaultCountReactiveInterceptor.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    if (context.hasAnnotation(Query.class)) {
        PreparedQuery<?, Long> preparedQuery = prepareQuery(methodKey, context, Long.class);
        return Publishers.convertPublisher(
                reactiveOperations.findAll(preparedQuery),
                context.getReturnType().getType()
        );
    } else {
        Publisher<Long> result = reactiveOperations.count(getPagedQuery(context));
        return Publishers.convertPublisher(
                result,
                context.getReturnType().getType()
        );
    }
}
 
Example #16
Source File: DefaultFindSliceReactiveInterceptor.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    if (context.hasAnnotation(Query.class)) {
        PreparedQuery<Object, Object> preparedQuery = (PreparedQuery<Object, Object>) prepareQuery(methodKey, context);
        Pageable pageable = preparedQuery.getPageable();

        Single<Slice<Object>> publisher = Flowable.fromPublisher(reactiveOperations.findAll(preparedQuery))
                .toList().map(objects -> Slice.of(objects, pageable));
        return Publishers.convertPublisher(publisher, context.getReturnType().getType());

    } else {
        PagedQuery<Object> pagedQuery = getPagedQuery(context);
        Single<? extends Slice<?>> result = Flowable.fromPublisher(reactiveOperations.findAll(pagedQuery))
                .toList().map(objects ->
                        Slice.of(objects, pagedQuery.getPageable())
                );
        return Publishers.convertPublisher(result, context.getReturnType().getType());
    }
}
 
Example #17
Source File: DefaultSaveOneAsyncInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
public CompletionStage<Object> intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, CompletionStage<Object>> context) {
    Class<?> rootEntity = getRequiredRootEntity(context);
    Map<String, Object> parameterValueMap = context.getParameterValueMap();
    Executor executor = asyncDatastoreOperations.getExecutor();
    return CompletableFuture.supplyAsync(() -> {
        Object o = instantiateEntity(rootEntity, parameterValueMap);
        return getInsertOperation(context, o);
    }, executor).thenCompose(asyncDatastoreOperations::persist);
}
 
Example #18
Source File: DefaultSaveOneInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, Object> context) {
    Class<?> rootEntity = getRequiredRootEntity(context);
    Map<String, Object> parameterValueMap = context.getParameterValueMap();
    Object instance = instantiateEntity(rootEntity, parameterValueMap);
    return operations.persist(getInsertOperation(context, instance));
}
 
Example #19
Source File: DefaultSaveAllAsyncInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
public CompletionStage<Iterable<Object>> intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, CompletionStage<Iterable<Object>>> context) {
    Object[] parameterValues = context.getParameterValues();
    if (ArrayUtils.isNotEmpty(parameterValues) && parameterValues[0] instanceof Iterable) {
        //noinspection unchecked
        BatchOperation<Object> batchOperation = getBatchOperation(context, (Iterable<Object>) parameterValues[0]);
        return asyncDatastoreOperations.persistAll(batchOperation);
    } else {
        throw new IllegalArgumentException("First argument should be an iterable");
    }
}
 
Example #20
Source File: DefaultFindByIdAsyncInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public CompletionStage<Object> intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, CompletionStage<Object>> context) {
    Class<?> rootEntity = getRequiredRootEntity(context);
    Object id = context.getParameterValues()[0];
    if (!(id instanceof Serializable)) {
        throw new IllegalArgumentException("Entity IDs must be serializable!");
    }
    return asyncDatastoreOperations.findOne((Class<Object>) rootEntity, (Serializable) id);
}
 
Example #21
Source File: DefaultExistsByAsyncInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
public CompletionStage<Boolean> intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, CompletionStage<Boolean>> context) {
    Class idType = context.classValue(DataMethod.class, DataMethod.META_MEMBER_ID_TYPE)
            .orElseGet(() -> getRequiredRootEntity(context));
    PreparedQuery<?, Boolean> preparedQuery = prepareQuery(methodKey, context, idType);
    return asyncDatastoreOperations.exists(preparedQuery);
}
 
Example #22
Source File: DefaultFindOneAsyncInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public CompletionStage<Object> intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, CompletionStage<Object>> context) {
    PreparedQuery<Object, Object> preparedQuery = (PreparedQuery<Object, Object>) prepareQuery(methodKey, context);
    CompletionStage<Object> future = asyncDatastoreOperations.findOne(preparedQuery);
    Argument<?> type = context.getReturnType().asArgument().getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT);
    return future.thenApply(o -> {
        if (!type.getType().isInstance(o)) {
            return ConversionService.SHARED.convert(o, type)
                    .orElseThrow(() -> new IllegalStateException("Unexpected return type: " + o));
        }
        return o;
    });
}
 
Example #23
Source File: DefaultFindOneReactiveInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    PreparedQuery<Object, Object> preparedQuery = (PreparedQuery<Object, Object>) prepareQuery(methodKey, context);
    Publisher<Object> publisher = reactiveOperations.findOptional(preparedQuery);
    Argument<Object> returnType = context.getReturnType().asArgument();
    Argument<?> type = returnType.getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT);
    Publisher<Object> mappedPublisher = Publishers.map(publisher, o -> {
        if (!type.getType().isInstance(o)) {
            return ConversionService.SHARED.convert(o, type)
                    .orElseThrow(() -> new IllegalStateException("Unexpected return type: " + o));
        }
        return o;
    });
    return Publishers.convertPublisher(mappedPublisher, returnType.getType());
}
 
Example #24
Source File: DefaultFindByIdReactiveInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    Class<?> rootEntity = getRequiredRootEntity(context);
    Object id = context.getParameterValues()[0];
    if (!(id instanceof Serializable)) {
        throw new IllegalArgumentException("Entity IDs must be serializable!");
    }
    Publisher<Object> publisher = reactiveOperations.findOne((Class<Object>) rootEntity, (Serializable) id);
    return Publishers.convertPublisher(publisher, context.getReturnType().getType());
}
 
Example #25
Source File: CountSpecificationInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
public Number intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Number> context) {
    final Object parameterValue = context.getParameterValues()[0];
    if (parameterValue instanceof Specification) {
        Specification specification = (Specification) parameterValue;
        final EntityManager entityManager = jpaOperations.getCurrentEntityManager();
        final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        final CriteriaQuery<Long> query = criteriaBuilder.createQuery(Long.class);
        final Root<?> root = query.from(getRequiredRootEntity(context));
        final Predicate predicate = specification.toPredicate(root, query, criteriaBuilder);
        query.where(predicate);
        if (query.isDistinct()) {
            query.select(criteriaBuilder.countDistinct(root));
        } else {
            query.select(criteriaBuilder.count(root));
        }
        query.orderBy(Collections.emptyList());

        final TypedQuery<Long> typedQuery = entityManager.createQuery(query);
        final Long result = typedQuery.getSingleResult();
        final ReturnType<Number> rt = context.getReturnType();
        final Class<Number> returnType = rt.getType();
        if (returnType.isInstance(result)) {
            return result;
        } else {
            return ConversionService.SHARED.convertRequired(
                    result,
                    rt.asArgument()
            );
        }
    } else {
        throw new IllegalArgumentException("Argument must be an instance of: " + Specification.class);
    }
}
 
Example #26
Source File: DefaultUpdateReactiveInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    PreparedQuery<?, Number> preparedQuery = (PreparedQuery<?, Number>) prepareQuery(methodKey, context);
    ReturnType<Object> returnType = context.getReturnType();
    Publisher<Number> publisher = Publishers.map(reactiveOperations.executeUpdate(preparedQuery),
            n -> convertNumberArgumentIfNecessary(n, returnType.asArgument())
    );
    return Publishers.convertPublisher(publisher, returnType.getType());
}
 
Example #27
Source File: FindOneSpecificationInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    final Object parameterValue = context.getParameterValues()[0];
    if (parameterValue instanceof Specification) {
        Specification specification = (Specification) parameterValue;
        final EntityManager entityManager = jpaOperations.getCurrentEntityManager();
        final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        final CriteriaQuery<Object> query = criteriaBuilder.createQuery((Class<Object>) getRequiredRootEntity(context));
        final Root<Object> root = query.from((Class<Object>) getRequiredRootEntity(context));
        final Predicate predicate = specification.toPredicate(root, query, criteriaBuilder);
        query.where(predicate);
        query.select(root);

        final TypedQuery<?> typedQuery = entityManager.createQuery(query);
        try {
            final Object result = typedQuery.getSingleResult();
            final ReturnType<?> rt = context.getReturnType();
            final Class<?> returnType = rt.getType();
            if (returnType.isInstance(result)) {
                return result;
            } else {
                return ConversionService.SHARED.convertRequired(
                        result,
                        rt.asArgument()
                );
            }
        } catch (NoResultException e) {
            if (context.isNullable()) {
                return null;
            } else {
                throw new EmptyResultDataAccessException(1);
            }
        }
    } else {
        throw new IllegalArgumentException("Argument must be an instance of: " + Specification.class);
    }
}
 
Example #28
Source File: TransactionInterceptor.java    From micronaut-spring with Apache License 2.0 5 votes vote down vote up
@Override
public final Object intercept(MethodInvocationContext<Object, Object> context) {
    if (context.hasStereotype(Transactional.class)) {
        String transactionManagerName = context.stringValue(Transactional.class).orElse(null);
        if (StringUtils.isEmpty(transactionManagerName)) {
            transactionManagerName = null;
        }
        PlatformTransactionManager transactionManager = resolveTransactionManager(transactionManagerName);

        String finalTransactionManagerName = transactionManagerName;
        TransactionAttribute transactionDefinition = resolveTransactionAttribute(
            context.getExecutableMethod(),
            context,
            finalTransactionManagerName
        );

        final TransactionInfo transactionInfo = createTransactionIfNecessary(
                transactionManager,
                transactionDefinition,
                context.getDeclaringType().getName() + "." + context.getMethodName());
        Object retVal;
        try {
            retVal = context.proceed();
        } catch (Throwable ex) {
            completeTransactionAfterThrowing(transactionInfo, ex);
            throw ex;
        } finally {
            cleanupTransactionInfo(transactionInfo);
        }
        commitTransactionAfterReturning(transactionInfo);
        return retVal;
    } else {
        return context.proceed();
    }
}
 
Example #29
Source File: SchedulerLockInterceptor.java    From ShedLock with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(MethodInvocationContext<Object, Object> context) {
    Class<?> returnType = context.getReturnType().getType();
    if (!void.class.equals(returnType) && !Void.class.equals(returnType)) {
        throw new LockingNotSupportedException();
    }

    Optional<LockConfiguration> lockConfiguration = micronautLockConfigurationExtractor.getLockConfiguration(context.getExecutableMethod());
    if (lockConfiguration.isPresent()) {
        lockingTaskExecutor.executeWithLock((Runnable) context::proceed, lockConfiguration.get());
        return null;
    } else {
        return context.proceed();
    }
}
 
Example #30
Source File: DefaultSaveOneReactiveInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    Class<?> rootEntity = getRequiredRootEntity(context);
    Map<String, Object> parameterValueMap = context.getParameterValueMap();

    Flowable<Object> publisher = Flowable.fromCallable(() -> {
        Object o = instantiateEntity(rootEntity, parameterValueMap);
        return getInsertOperation(context, o);
    }).flatMap(reactiveOperations::persist);
    return Publishers.convertPublisher(publisher, context.getReturnType().getType());
}