Java Code Examples for io.micronaut.core.util.ArrayUtils#isNotEmpty()

The following examples show how to use io.micronaut.core.util.ArrayUtils#isNotEmpty() . 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: 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 2
Source File: JpaConfiguration.java    From micronaut-sql with Apache License 2.0 6 votes vote down vote up
/**
 * Find entities for the current configuration.
 *
 * @return The entities
 */
public Collection<Class<?>> findEntities() {
    Collection<Class<?>> entities = new HashSet<>();
    if (isClasspath()) {

        if (ArrayUtils.isNotEmpty(packages)) {
            environment.scan(Entity.class, packages).forEach(entities::add);
        } else {
            environment.scan(Entity.class).forEach(entities::add);
        }
    }

    if (isEnabled()) {
        Collection<BeanIntrospection<Object>> introspections;
        if (ArrayUtils.isNotEmpty(packages)) {
            introspections = BeanIntrospector.SHARED.findIntrospections(Entity.class, packages);
        } else {
            introspections = BeanIntrospector.SHARED.findIntrospections(Entity.class);
        }
        introspections
                .stream().map(BeanIntrospection::getBeanType)
                .forEach(entities::add);
    }
    return Collections.unmodifiableCollection(entities);
}
 
Example 3
Source File: ConsumerRecordBinderRegistry.java    From micronaut-kafka with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the registry for the given binders.
 *
 * @param binders The binders
 */
public ConsumerRecordBinderRegistry(ConsumerRecordBinder<?>... binders) {
    if (ArrayUtils.isNotEmpty(binders)) {
        for (ConsumerRecordBinder<?> binder : binders) {
            if (binder instanceof AnnotatedConsumerRecordBinder) {
                AnnotatedConsumerRecordBinder<?, ?> annotatedConsumerRecordBinder = (AnnotatedConsumerRecordBinder<?, ?>) binder;
                byAnnotation.put(
                        annotatedConsumerRecordBinder.annotationType(),
                        annotatedConsumerRecordBinder
                );
            } else if (binder instanceof TypedConsumerRecordBinder) {
                TypedConsumerRecordBinder typedConsumerRecordBinder = (TypedConsumerRecordBinder) binder;
                byType.put(
                        typedConsumerRecordBinder.argumentType().typeHashCode(),
                        typedConsumerRecordBinder
                );
            }
        }
    }
}
 
Example 4
Source File: MicronautBeanFactory.java    From micronaut-spring with Apache License 2.0 6 votes vote down vote up
@Override
public @Nonnull
<T> T getBean(@Nonnull Class<T> requiredType) throws BeansException {
    ArgumentUtils.requireNonNull("requiredType", requiredType);
    if (beanExcludes.contains(requiredType)) {
        throw new NoSuchBeanDefinitionException(requiredType);
    }
    // unfortunate hack
    try {
        final String[] beanNamesForType = super.getBeanNamesForType(requiredType, false, false);
        if (ArrayUtils.isNotEmpty(beanNamesForType)) {
            return getBean(beanNamesForType[0], requiredType);
        } else {
            return beanContext.getBean(requiredType);
        }
    } catch (NoSuchBeanException e) {
        throw new NoSuchBeanDefinitionException(requiredType, e.getMessage());
    }
}
 
Example 5
Source File: SourcePersistentEntity.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
/**
 * Obtains a PersistentProperty representing id or version property by name.
 *
 * @param name The name of the id or version property
 * @return The PersistentProperty used as id or version or null if it doesn't exist
 */
public SourcePersistentProperty getIdOrVersionPropertyByName(String name) {
    if (ArrayUtils.isNotEmpty(id)) {
        SourcePersistentProperty persistentProp = Arrays.stream(id)
                .filter(p -> p.getName().equals(name))
                .findFirst()
                .orElse(null);

        if (persistentProp != null) {
            return persistentProp;
        }
    }

    if (version != null && version.getName().equals(name)) {
        return version;
    }

    return null;
}
 
Example 6
Source File: Association.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
/**
 * Whether this association cascades the given types.
 * @param types The types
 * @return True if it does, false otherwise.
 */
default boolean doesCascade(Relation.Cascade... types) {
    if (ArrayUtils.isNotEmpty(types)) {
        final String[] cascades = getAnnotationMetadata().stringValues(Relation.class, "cascade");
        for (String cascade : cascades) {
            if (cascade.equals("ALL")) {
                return true;
            }
            for (Relation.Cascade type : types) {
                final String n = type.name();
                if (n.equals(cascade)) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 7
Source File: AbstractMicronautLambdaRuntime.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
private Class initTypeArgument(int index) {
    final Class[] args = GenericTypeUtils.resolveSuperTypeGenericArguments(
            getClass(),
            AbstractMicronautLambdaRuntime.class
    );
    if (ArrayUtils.isNotEmpty(args) && args.length > index) {
        return args[index];
    } else {
        return Object.class;
    }
}
 
Example 8
Source File: BindableRuleBasedTransactionAttribute.java    From micronaut-spring with Apache License 2.0 5 votes vote down vote up
/**
 * Configures the exceptions to rollback for.
 *
 * @param exceptions The exceptions to rollback for
 */
public final void setRollbackFor(Class<? extends Throwable>... exceptions) {
    if (ArrayUtils.isNotEmpty(exceptions)) {
        if (rollbackFor == null) {
            rollbackFor = new HashSet<>();
        }
        rollbackFor.addAll(Arrays.asList(exceptions));
    }
}
 
Example 9
Source File: MicronautBeanProcessor.java    From micronaut-spring with Apache License 2.0 5 votes vote down vote up
private String[] getProfiles() {
    if (ArrayUtils.isNotEmpty(environment.getActiveProfiles())) {
        return environment.getActiveProfiles();
    } else {
        return environment.getDefaultProfiles();
    }
}
 
Example 10
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 11
Source File: DefaultSaveAllReactiveInterceptor.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) {
    Object[] parameterValues = context.getParameterValues();
    if (ArrayUtils.isNotEmpty(parameterValues) && parameterValues[0] instanceof Iterable) {
        //noinspection unchecked
        BatchOperation<Object> batchOperation = getBatchOperation(context, (Iterable<Object>) parameterValues[0]);
        Publisher<Object> publisher = reactiveOperations.persistAll(batchOperation);
        return Publishers.convertPublisher(publisher, context.getReturnType().getType());
    } else {
        throw new IllegalArgumentException("First argument should be an iterable");
    }
}
 
Example 12
Source File: SaveEntityMethod.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public MethodMatchInfo buildMatchInfo(@NonNull MethodMatchContext matchContext) {
    VisitorContext visitorContext = matchContext.getVisitorContext();
    ParameterElement[] parameters = matchContext.getParameters();
    if (ArrayUtils.isNotEmpty(parameters)) {
        if (Arrays.stream(parameters).anyMatch(p -> p.getGenericType().hasAnnotation(MappedEntity.class))) {
            ClassElement returnType = matchContext.getReturnType();
            Class<? extends DataInterceptor> interceptor = pickSaveInterceptor(returnType);
            if (TypeUtils.isReactiveOrFuture(returnType)) {
                returnType = returnType.getGenericType().getFirstTypeArgument().orElse(returnType);
            }

            if (matchContext.supportsImplicitQueries()) {
                return new MethodMatchInfo(returnType, null, getInterceptorElement(matchContext, interceptor), MethodMatchInfo.OperationType.INSERT);
            } else {
                return new MethodMatchInfo(returnType,
                        QueryModel.from(matchContext.getRootEntity()),
                        getInterceptorElement(matchContext, interceptor),
                        MethodMatchInfo.OperationType.INSERT
                );
            }
        }
    }
    visitorContext.fail(
            "Cannot implement save method for specified arguments and return type",
            matchContext.getMethodElement()
    );
    return null;
}
 
Example 13
Source File: AnnotationMetadataHierarchy.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
/**
 * Default constructor.
 *
 * @param hierarchy The annotation hierarchy
 */
public AnnotationMetadataHierarchy(AnnotationMetadata... hierarchy) {
    if (ArrayUtils.isNotEmpty(hierarchy)) {
        // place the first in the hierarchy first
        final List<AnnotationMetadata> list = Arrays.asList(hierarchy);
        Collections.reverse(list);
        this.hierarchy = list.toArray(new AnnotationMetadata[0]);
    } else {
        this.hierarchy = new AnnotationMetadata[] { AnnotationMetadata.EMPTY_METADATA };
    }
}
 
Example 14
Source File: JpaConfiguration.java    From micronaut-sql with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the packages to scan.
 *
 * @param packagesToScan The packages to scan
 */
public void setPackagesToScan(String... packagesToScan) {
    if (ArrayUtils.isNotEmpty(packagesToScan)) {
        EntityScanConfiguration entityScanConfiguration = new EntityScanConfiguration(environment);
        entityScanConfiguration.setClasspath(true);
        entityScanConfiguration.setPackages(packagesToScan);
        this.entityScanConfiguration = entityScanConfiguration;
    }
}
 
Example 15
Source File: MicronautRequestHandler.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
private Class initTypeArgument() {
    final Class[] args = GenericTypeUtils.resolveSuperTypeGenericArguments(
            getClass(),
            MicronautRequestHandler.class
    );
    if (ArrayUtils.isNotEmpty(args)) {
        return args[0];
    } else {
        return Object.class;
    }
}
 
Example 16
Source File: AWSLambdaConfiguration.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
/**
 * @param handlers The {@link RequestHandler2}
 */
@Inject
public void setRequestHandlers(@Nullable RequestHandler2... handlers) {
    if (ArrayUtils.isNotEmpty(handlers)) {
        builder.setRequestHandlers(handlers);
    }
}
 
Example 17
Source File: UpdateEntityMethod.java    From micronaut-data with Apache License 2.0 4 votes vote down vote up
@Nullable
@Override
public MethodMatchInfo buildMatchInfo(@NonNull MethodMatchContext matchContext) {
    ParameterElement[] parameters = matchContext.getParameters();
    if (ArrayUtils.isNotEmpty(parameters)) {
        if (Arrays.stream(parameters).anyMatch(p -> p.getGenericType().hasAnnotation(MappedEntity.class))) {
            ClassElement returnType = matchContext.getReturnType();
            Class<? extends DataInterceptor> interceptor = pickSaveInterceptor(returnType);
            if (TypeUtils.isReactiveOrFuture(returnType)) {
                returnType = returnType.getGenericType().getFirstTypeArgument().orElse(returnType);
            }
            if (matchContext.supportsImplicitQueries()) {
                return new MethodMatchInfo(
                        returnType,
                        null, getInterceptorElement(matchContext, interceptor),
                        MethodMatchInfo.OperationType.UPDATE
                );
            } else {
                final SourcePersistentEntity rootEntity = matchContext.getRootEntity();
                final String idName;
                final SourcePersistentProperty identity = rootEntity.getIdentity();
                if (identity != null) {
                    idName = identity.getName();
                } else {
                    idName = TypeRole.ID;
                }
                final QueryModel queryModel = QueryModel.from(rootEntity)
                        .idEq(new QueryParameter(idName));
                String[] updateProperties = rootEntity.getPersistentProperties()
                        .stream().filter(p ->
                                !((p instanceof Association) && ((Association) p).isForeignKey()) &&
                                        p.booleanValue(AutoPopulated.class, "updateable").orElse(true)
                        )
                        .map(PersistentProperty::getName)
                        .toArray(String[]::new);
                if (ArrayUtils.isEmpty(updateProperties)) {
                    return new MethodMatchInfo(
                            returnType,
                            null,
                            getInterceptorElement(matchContext, interceptor),
                            MethodMatchInfo.OperationType.UPDATE
                    );
                } else {
                    return new MethodMatchInfo(
                            returnType,
                            queryModel,
                            getInterceptorElement(matchContext, interceptor),
                            MethodMatchInfo.OperationType.UPDATE,
                            updateProperties
                    );
                }

            }
        }
    }
    matchContext.fail("Cannot implement update method for specified arguments and return type");
    return null;
}
 
Example 18
Source File: EntitiesInPackageCondition.java    From micronaut-sql with Apache License 2.0 4 votes vote down vote up
@Override
public boolean matches(ConditionContext context) {
    final AnnotationMetadataProvider component = context.getComponent();
    if (component instanceof BeanDefinition) {
        BeanDefinition<?> definition = (BeanDefinition<?>) component;
        final BeanContext beanContext = context.getBeanContext();
        if (beanContext instanceof ApplicationContext) {

            final Optional<String> name = definition instanceof NameResolver ? ((NameResolver) definition).resolveName() : Optional.empty();
            final Qualifier<JpaConfiguration> q = Qualifiers.byName(name.orElse("default"));
            final Optional<JpaConfiguration> jpaConfiguration = beanContext.findBean(JpaConfiguration.class, q);
            JpaConfiguration.EntityScanConfiguration entityScanConfig = jpaConfiguration.map(JpaConfiguration::getEntityScanConfiguration).orElse(null);

            if (entityScanConfig == null) {
                return false;
            }

            boolean isClasspathScanEnabled = entityScanConfig.isClasspath();
            String[] packagesToScan = entityScanConfig.getPackages();
            boolean hasEntitiesOnClassPath = false;
            boolean hasIntrospections = false;
            if (isClasspathScanEnabled) {
                final Environment environment = ((ApplicationContext) beanContext).getEnvironment();
                if (ArrayUtils.isNotEmpty(packagesToScan)) {
                    hasEntitiesOnClassPath = environment.scan(Entity.class, packagesToScan).findAny().isPresent();
                } else {
                    hasEntitiesOnClassPath = environment.scan(Entity.class).findAny().isPresent();
                }
            } else {
                if (ArrayUtils.isNotEmpty(packagesToScan)) {
                    hasIntrospections = !BeanIntrospector.SHARED
                            .findIntrospections(Entity.class, packagesToScan).isEmpty();
                } else {
                    hasIntrospections = !BeanIntrospector.SHARED
                            .findIntrospections(Entity.class).isEmpty();
                }
            }

            return hasEntitiesOnClassPath || hasIntrospections;
        }
    }
    return true;
}
 
Example 19
Source File: DefaultTransactionAttribute.java    From micronaut-data with Apache License 2.0 4 votes vote down vote up
/**
 * Sets the exceptions that will not cause a rollback.
 * @param noRollbackFor The exceptions
 */
public void setNoRollbackFor(Class<? extends Throwable>... noRollbackFor) {
    if (ArrayUtils.isNotEmpty(noRollbackFor)) {
        this.noRollbackFor = CollectionUtils.setOf(noRollbackFor);
    }
}
 
Example 20
Source File: BindableRuleBasedTransactionAttribute.java    From micronaut-spring with Apache License 2.0 4 votes vote down vote up
/**
 * Configures the exceptions to not rollback for.
 *
 * @param exceptions The exceptions not to rollback for
 */
public final void setNoRollbackFor(Class<? extends Throwable>... exceptions) {
    if (ArrayUtils.isNotEmpty(exceptions)) {
        noRollbackFor.addAll(Arrays.asList(exceptions));
    }
}