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

The following examples show how to use io.micronaut.core.util.CollectionUtils#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: GrpcServerChannel.java    From micronaut-grpc with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a managed server channel.
 * @param server The server
 * @param executorService The executor service
 * @param clientInterceptors The client interceptors
 * @return The channel
 */
@Singleton
@Named(NAME)
@Requires(beans = GrpcEmbeddedServer.class)
@Bean(preDestroy = "shutdown")
protected ManagedChannel serverChannel(
        GrpcEmbeddedServer server,
        @javax.inject.Named(TaskExecutors.IO) ExecutorService executorService,
        List<ClientInterceptor> clientInterceptors) {
    final ManagedChannelBuilder<?> builder = ManagedChannelBuilder.forAddress(
            server.getHost(),
            server.getPort()
    ).executor(executorService);
    if (!server.getServerConfiguration().isSecure()) {
        builder.usePlaintext();
    }
    if (CollectionUtils.isNotEmpty(clientInterceptors)) {
        builder.intercept(clientInterceptors);
    }
    return builder.build();
}
 
Example 2
Source File: GrpcChannelBuilderFactory.java    From micronaut-grpc with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor a managed channel build for the given target name and interceptors.
 * @param target The target name
 * @param interceptors The interceptors
 * @return The channel builder
 */
@Bean
@Prototype
protected NettyChannelBuilder managedChannelBuilder(@Parameter String target, List<ClientInterceptor> interceptors) {
    GrpcManagedChannelConfiguration config = beanContext.findBean(GrpcManagedChannelConfiguration.class, Qualifiers.byName(target)).orElseGet(() -> {
                final GrpcDefaultManagedChannelConfiguration mcc = new GrpcDefaultManagedChannelConfiguration(
                        target,
                        beanContext.getEnvironment(),
                        executorService
                );
                beanContext.inject(mcc);
                return mcc;
            }
    );
    final NettyChannelBuilder channelBuilder = config.getChannelBuilder();
    if (CollectionUtils.isNotEmpty(interceptors)) {
        channelBuilder.intercept(interceptors);
    }
    return channelBuilder;
}
 
Example 3
Source File: GrpcServerInstance.java    From micronaut-grpc with Apache License 2.0 6 votes vote down vote up
/**
 * Default constructor.
 * @param embeddedServer The embedded server
 * @param id The ID
 * @param uri The URI
 * @param metadata The metadata
 * @param metadataContributors The metadata contributors
 */
GrpcServerInstance(
        EmbeddedServer embeddedServer,
        String id,
        URI uri,
        @Nullable Map<String, String> metadata,
        @javax.annotation.Nullable List<ServiceInstanceMetadataContributor> metadataContributors) {
    this.embeddedServer = embeddedServer;
    this.id = id;
    this.uri = uri;
    if (metadata == null) {
        metadata = new LinkedHashMap<>(5);
    }

    if (CollectionUtils.isNotEmpty(metadataContributors)) {
        for (ServiceInstanceMetadataContributor contributor : metadataContributors) {
            contributor.contribute(this, metadata);
        }
    }

    this.metadata = ConvertibleValues.of(metadata);
}
 
Example 4
Source File: GrpcServerChannel.java    From micronaut-grpc with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a managed server channel.
 * @param server The server
 * @param executorService The executor service
 * @param clientInterceptors The client interceptors
 * @return The channel
 */
@Singleton
@Named(NAME)
@Requires(beans = GrpcEmbeddedServer.class)
@Bean(preDestroy = "shutdown")
protected ManagedChannel serverChannel(
        GrpcEmbeddedServer server,
        @javax.inject.Named(TaskExecutors.IO) ExecutorService executorService,
        List<ClientInterceptor> clientInterceptors) {
    final ManagedChannelBuilder<?> builder = ManagedChannelBuilder.forAddress(
            server.getHost(),
            server.getPort()
    ).executor(executorService);
    if (!server.getServerConfiguration().isSecure()) {
        builder.usePlaintext();
    }
    if (CollectionUtils.isNotEmpty(clientInterceptors)) {
        builder.intercept(clientInterceptors);
    }
    return builder.build();
}
 
Example 5
Source File: GrpcServerInstance.java    From micronaut-grpc with Apache License 2.0 6 votes vote down vote up
/**
 * Default constructor.
 * @param embeddedServer The embedded server
 * @param id The ID
 * @param uri The URI
 * @param metadata The metadata
 * @param metadataContributors The metadata contributors
 */
GrpcServerInstance(
        EmbeddedServer embeddedServer,
        String id,
        URI uri,
        @Nullable Map<String, String> metadata,
        @javax.annotation.Nullable List<ServiceInstanceMetadataContributor> metadataContributors) {
    this.embeddedServer = embeddedServer;
    this.id = id;
    this.uri = uri;
    if (metadata == null) {
        metadata = new LinkedHashMap<>(5);
    }

    if (CollectionUtils.isNotEmpty(metadataContributors)) {
        for (ServiceInstanceMetadataContributor contributor : metadataContributors) {
            contributor.contribute(this, metadata);
        }
    }

    this.metadata = ConvertibleValues.of(metadata);
}
 
Example 6
Source File: GrpcChannelBuilderFactory.java    From micronaut-grpc with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor a managed channel build for the given target name and interceptors.
 * @param target The target name
 * @param interceptors The interceptors
 * @return The channel builder
 */
@Bean
@Prototype
protected NettyChannelBuilder managedChannelBuilder(@Parameter String target, List<ClientInterceptor> interceptors) {
    GrpcManagedChannelConfiguration config = beanContext.findBean(GrpcManagedChannelConfiguration.class, Qualifiers.byName(target)).orElseGet(() -> {
                final GrpcDefaultManagedChannelConfiguration mcc = new GrpcDefaultManagedChannelConfiguration(
                        target,
                        beanContext.getEnvironment(),
                        executorService
                );
                beanContext.inject(mcc);
                return mcc;
            }
    );
    final NettyChannelBuilder channelBuilder = config.getChannelBuilder();
    if (CollectionUtils.isNotEmpty(interceptors)) {
        channelBuilder.intercept(interceptors);
    }
    return channelBuilder;
}
 
Example 7
Source File: SqlResultEntityTypeMapper.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor used to customize the join paths.
 * @param entity The entity
 * @param resultReader The result reader
 * @param joinPaths The join paths
 */
private SqlResultEntityTypeMapper(
        @NonNull RuntimePersistentEntity<R> entity,
        @NonNull ResultReader<RS, String> resultReader,
        @Nullable Set<JoinPath> joinPaths,
        String startingPrefix,
        @Nullable MediaTypeCodec jsonCodec) {
    ArgumentUtils.requireNonNull("entity", entity);
    ArgumentUtils.requireNonNull("resultReader", resultReader);
    this.entity = entity;
    this.jsonCodec = jsonCodec;
    this.resultReader = resultReader;
    if (CollectionUtils.isNotEmpty(joinPaths)) {
        this.joinPaths = new HashMap<>(joinPaths.size());
        for (JoinPath joinPath : joinPaths) {
            this.joinPaths.put(joinPath.getPath(), joinPath);
        }
    } else {
        this.joinPaths = Collections.emptyMap();
    }
    this.startingPrefix = startingPrefix;
}
 
Example 8
Source File: MicronautAwsProxyRequest.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> getAll(CharSequence name) {
    if (StringUtils.isNotEmpty(name)) {
        final List<String> strings = multiValueHeaders.get(name.toString());
        if (CollectionUtils.isNotEmpty(strings)) {
            return strings;
        }
    }
    return Collections.emptyList();
}
 
Example 9
Source File: MicronautJunit5Extension.java    From micronaut-test with Apache License 2.0 5 votes vote down vote up
@Override
protected void resolveTestProperties(ExtensionContext context, MicronautTest testAnnotation, Map<String, Object> testProperties) {
    Object o = context.getTestInstance().orElse(null);
    if (o instanceof TestPropertyProvider) {
        Map<String, String> properties = ((TestPropertyProvider) o).getProperties();
        if (CollectionUtils.isNotEmpty(properties)) {
            testProperties.putAll(properties);
        }
    }
}
 
Example 10
Source File: MicronautSpockExtension.java    From micronaut-test with Apache License 2.0 5 votes vote down vote up
@Override
protected void resolveTestProperties(IMethodInvocation context, MicronautTest testAnnotation, Map<String, Object> testProperties) {
    Object sharedInstance = context.getSharedInstance();
    if (sharedInstance instanceof TestPropertyProvider) {
        Map<String, String> properties = ((TestPropertyProvider) sharedInstance).getProperties();
        if (CollectionUtils.isNotEmpty(properties)) {
            testProperties.putAll(properties);
        }
    }
}
 
Example 11
Source File: AbstractPatternBasedMethod.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
/**
 * Apply ordering.
 *
 * @param context   The context
 * @param query     The query
 * @param orderList The list mutate
 * @return True if an error occurred applying the order
 */
protected boolean applyOrderBy(@NonNull MethodMatchContext context, @NonNull QueryModel query, @NonNull List<Sort.Order> orderList) {
    if (CollectionUtils.isNotEmpty(orderList)) {
        SourcePersistentEntity entity = context.getRootEntity();
        for (Sort.Order order : orderList) {
            String prop = order.getProperty();
            if (!entity.getPath(prop).isPresent()) {
                context.fail("Cannot order by non-existent property: " + prop);
                return true;
            }
        }
        query.sort(Sort.of(orderList));
    }
    return false;
}
 
Example 12
Source File: JpaConfiguration.java    From micronaut-sql with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the standard service registry.
 *
 * @param additionalSettings Additional settings for the service registry
 * @return The standard service registry
 */
@SuppressWarnings("WeakerAccess")
public StandardServiceRegistry buildStandardServiceRegistry(@Nullable Map<String, Object> additionalSettings) {
    StandardServiceRegistryBuilder standardServiceRegistryBuilder = createStandServiceRegistryBuilder(bootstrapServiceRegistry);

    Map<String, Object> jpaProperties = getProperties();
    if (CollectionUtils.isNotEmpty(jpaProperties)) {
        standardServiceRegistryBuilder.applySettings(jpaProperties);
    }
    if (additionalSettings != null) {
        standardServiceRegistryBuilder.applySettings(additionalSettings);
    }
    return standardServiceRegistryBuilder.build();
}
 
Example 13
Source File: HibernateMetricsBinder.java    From micronaut-sql with Apache License 2.0 5 votes vote down vote up
/**
 * Default constructor.
 * @param meterRegistryProvider The meter registry provider
 * @param tags The tags
 */
public HibernateMetricsBinder(
        Provider<MeterRegistry> meterRegistryProvider,
        @Property(name = MICRONAUT_METRICS_BINDERS + ".hibernate.tags")
        @MapFormat(transformation = MapFormat.MapTransformation.FLAT)
        Map<String, String> tags) {
    this.meterRegistryProvider = meterRegistryProvider;
    if (CollectionUtils.isNotEmpty(tags)) {
        this.tags = tags.entrySet().stream().map(entry -> Tag.of(entry.getKey(), entry.getValue())).collect(Collectors.toList());
    } else {
        this.tags = Collections.emptyList();
    }

}
 
Example 14
Source File: MicronautAwsProxyRequest.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> getAll(CharSequence name) {
    if (StringUtils.isNotEmpty(name)) {
        final List<String> strings = params.get(name.toString());
        if (CollectionUtils.isNotEmpty(strings)) {
            return strings.stream().map(v -> decodeValue(name, v)).collect(Collectors.toList());
        }
    }
    return Collections.emptyList();
}
 
Example 15
Source File: DefaultSort.java    From micronaut-data with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isSorted() {
    return CollectionUtils.isNotEmpty(orderBy);
}
 
Example 16
Source File: SqlQueryBuilder.java    From micronaut-data with Apache License 2.0 4 votes vote down vote up
@Override
protected void selectAllColumns(QueryState queryState, StringBuilder queryBuffer) {
    PersistentEntity entity = queryState.getEntity();
    String alias = queryState.getCurrentAlias();
    selectAllColumns(entity, alias, queryBuffer);

    QueryModel queryModel = queryState.getQueryModel();

    Collection<JoinPath> allPaths = queryModel.getJoinPaths();
    if (CollectionUtils.isNotEmpty(allPaths)) {

        Collection<JoinPath> joinPaths = allPaths.stream().filter(jp -> {
            Join.Type jt = jp.getJoinType();
            return jt.name().contains("FETCH");
        }).collect(Collectors.toList());

        if (CollectionUtils.isNotEmpty(joinPaths)) {
            for (JoinPath joinPath : joinPaths) {
                Association association = joinPath.getAssociation();
                if (association instanceof Embedded) {
                    // joins on embedded don't make sense
                    continue;
                }
                PersistentEntity associatedEntity = association.getAssociatedEntity();
                List<PersistentProperty> associatedProperties = getPropertiesThatAreColumns(associatedEntity);
                if (association.isForeignKey()) {
                    // in the case of a foreign key association the ID is not in the table
                    // so we need to retrieve it
                    PersistentProperty identity = associatedEntity.getIdentity();
                    if (identity != null) {
                        associatedProperties.add(0, identity);
                    }
                }
                if (CollectionUtils.isNotEmpty(associatedProperties)) {
                    queryBuffer.append(COMMA);

                    String aliasName = getAliasName(joinPath);
                    String joinPathAlias = getPathOnlyAliasName(joinPath);
                    String columnNames = associatedProperties.stream()
                            .map(p -> {
                                String columnName = getColumnName(p);
                                return aliasName + DOT + quote(columnName) + AS_CLAUSE + joinPathAlias + columnName ;
                            })
                            .collect(Collectors.joining(","));
                    queryBuffer.append(columnNames);
                }

            }
        }
    }
}
 
Example 17
Source File: PersistentEntity.java    From micronaut-data with Apache License 2.0 4 votes vote down vote up
/**
 * Computes a dot separated property path for the given camel case path.
 * @param camelCasePath The camel case path
 * @return The dot separated version or null if it cannot be computed
 */
default Optional<String> getPath(String camelCasePath) {
    List<String> path = Arrays.stream(CAMEL_CASE_SPLIT_PATTERN.split(camelCasePath))
                              .map(NameUtils::decapitalize)
                              .collect(Collectors.toList());

    if (CollectionUtils.isNotEmpty(path)) {
        Iterator<String> i = path.iterator();
        StringBuilder b = new StringBuilder();
        PersistentEntity currentEntity = this;
        String name = null;
        while (i.hasNext()) {
            name = name == null ? i.next() : name + NameUtils.capitalize(i.next());
            PersistentProperty sp = currentEntity.getPropertyByName(name);
            if (sp == null) {
                PersistentProperty identity = currentEntity.getIdentity();
                if (identity != null) {
                    if (identity.getName().equals(name)) {
                        sp = identity;
                    } else if (identity instanceof Association) {
                        PersistentEntity idEntity = ((Association) identity).getAssociatedEntity();
                        sp = idEntity.getPropertyByName(name);
                    }
                }
            }
            if (sp != null) {
                b.append(name);
                if (i.hasNext()) {
                    b.append('.');
                }
                if (sp instanceof Association) {
                    currentEntity = ((Association) sp).getAssociatedEntity();
                    name = null;
                }
            }
        }

        return b.length() == 0 || b.charAt(b.length() - 1) == '.' ? Optional.empty() : Optional.of(b.toString());

    }
    return Optional.empty();
}
 
Example 18
Source File: AbstractSqlRepositoryOperations.java    From micronaut-data with Apache License 2.0 4 votes vote down vote up
private MediaTypeCodec resolveJsonCodec(List<MediaTypeCodec> codecs) {
    return CollectionUtils.isNotEmpty(codecs) ? codecs.stream().filter(c -> c.getMediaTypes().contains(MediaType.APPLICATION_JSON_TYPE)).findFirst().orElse(null) : null;
}
 
Example 19
Source File: EventIntegrator.java    From micronaut-data with Apache License 2.0 4 votes vote down vote up
@Override
public void integrate(
        Metadata metadata,
        SessionFactoryImplementor sessionFactory,
        SessionFactoryServiceRegistry serviceRegistry) {
    EventListenerRegistry eventListenerRegistry =
            serviceRegistry.getService(EventListenerRegistry.class);

    Collection<PersistentClass> entityBindings = metadata.getEntityBindings();
    Map<Class, BeanProperty> lastUpdates = new HashMap<>(entityBindings.size());
    Map<Class, BeanProperty> dateCreated = new HashMap<>(entityBindings.size());

    entityBindings.forEach(e -> {
                Class<?> mappedClass = e.getMappedClass();
                if (mappedClass != null) {
                    BeanIntrospection<?> introspection = BeanIntrospector.SHARED.findIntrospection(mappedClass).orElse(null);
                    if (introspection != null) {
                        introspection.getIndexedProperty(DateCreated.class).ifPresent(bp ->
                                dateCreated.put(mappedClass, bp)
                        );
                        introspection.getIndexedProperty(DateUpdated.class).ifPresent(bp ->
                                lastUpdates.put(mappedClass, bp)
                        );
                    }
                }
            }
    );

    ConversionService<?> conversionService = ConversionService.SHARED;

    if (CollectionUtils.isNotEmpty(dateCreated)) {

        eventListenerRegistry.getEventListenerGroup(EventType.PRE_INSERT)
                .appendListener((PreInsertEventListener) event -> {
                    Object[] state = event.getState();
                    timestampIfNecessary(
                            dateCreated,
                            lastUpdates,
                            conversionService,
                            event,
                            state,
                            true
                    );
                    return false;
                });
    }

    if (CollectionUtils.isNotEmpty(lastUpdates)) {

        eventListenerRegistry.getEventListenerGroup(EventType.PRE_UPDATE)
                .appendListener((PreUpdateEventListener) event -> {
                    timestampIfNecessary(
                            dateCreated, lastUpdates,
                            conversionService,
                            event,
                            event.getState(),
                            false
                    );
                    return false;
                });
    }
}
 
Example 20
Source File: UpdateByMethod.java    From micronaut-data with Apache License 2.0 4 votes vote down vote up
@Nullable
@Override
protected MethodMatchInfo buildInfo(
        MethodMatchContext matchContext,
        @NonNull ClassElement queryResultType,
        @Nullable QueryModel query) {
    if (query == null) {
        matchContext.fail("Cannot implement batch update operation that doesn't perform a query");
        return null;
    }
    if (CollectionUtils.isNotEmpty(query.getProjections())) {
        matchContext.fail("Projections are not supported on batch updates");
        return null;
    }
    String[] updateProperties;
    if (!(query instanceof RawQuery)) {

        List<QueryModel.Criterion> criterionList = query.getCriteria().getCriteria();
        if (CollectionUtils.isEmpty(criterionList)) {
            matchContext.fail("Cannot implement batch update operation that doesn't perform a query");
            return null;
        }
        Set<String> queryParameters = new HashSet<>();
        for (QueryModel.Criterion criterion : criterionList) {
            if (criterion instanceof QueryModel.PropertyCriterion) {
                QueryModel.PropertyCriterion pc = (QueryModel.PropertyCriterion) criterion;
                Object v = pc.getValue();
                if (v instanceof QueryParameter) {
                    queryParameters.add(((QueryParameter) v).getName());
                }
            }
        }
        List<Element> updateParameters = Arrays.stream(matchContext.getParameters()).filter(p -> !queryParameters.contains(p.getName()))
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(updateParameters)) {
            matchContext.fail("At least one parameter required to update");
            return null;
        }
        Element element = matchContext.getParametersInRole().get(TypeRole.LAST_UPDATED_PROPERTY);
        if (element instanceof PropertyElement) {
            updateParameters.add(element);
        }
        SourcePersistentEntity entity = matchContext.getRootEntity();
        updateProperties = new String[updateParameters.size()];
        for (int i = 0; i < updateProperties.length; i++) {
            Element parameter = updateParameters.get(i);
            String parameterName = parameter.stringValue(Parameter.class).orElse(parameter.getName());
            Optional<String> path = entity.getPath(parameterName);
            if (path.isPresent()) {
                updateProperties[i] = path.get();
            } else {
                matchContext.fail("Cannot perform batch update for non-existent property: " + parameterName);
                return null;
            }
        }
    } else {
        updateProperties = StringUtils.EMPTY_STRING_ARRAY;
    }
    return new MethodMatchInfo(
            queryResultType,
            query,
            getInterceptorElement(matchContext, UpdateMethod.pickUpdateInterceptor(matchContext.getReturnType())),
            MethodMatchInfo.OperationType.UPDATE,
            updateProperties
    );
}