io.micronaut.core.util.StringUtils Java Examples

The following examples show how to use io.micronaut.core.util.StringUtils. 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: BeanAnnotationMapper.java    From micronaut-spring with Apache License 2.0 6 votes vote down vote up
@Override
protected List<AnnotationValue<?>> mapInternal(AnnotationValue<Annotation> annotation, VisitorContext visitorContext) {
    List<AnnotationValue<?>> newAnnotations = new ArrayList<>(3);
    final AnnotationValueBuilder<Bean> beanAnn = AnnotationValue.builder(Bean.class);

    final Optional<String> destroyMethod = annotation.get("destroyMethod", String.class);
    destroyMethod.ifPresent(s -> beanAnn.member("preDestroy", s));
    newAnnotations.add(beanAnn.build());
    newAnnotations.add(AnnotationValue.builder(DefaultScope.class)
            .value(Singleton.class)
            .build());
    final String beanName = annotation.getValue(String.class).orElse(annotation.get("name", String.class).orElse(null));

    if (StringUtils.isNotEmpty(beanName)) {
        newAnnotations.add(AnnotationValue.builder(Named.class).value(beanName).build());
    }

    return newAnnotations;
}
 
Example #2
Source File: ProjectionMethodExpression.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@Override
protected ProjectionMethodExpression initProjection(@NonNull MethodMatchContext matchContext, String remaining) {
    if (StringUtils.isEmpty(remaining)) {
        matchContext.fail(getClass().getSimpleName() + " projection requires a property name");
        return null;
    } else {

        this.property = NameUtils.decapitalize(remaining);
        this.persistentProperty = (SourcePersistentProperty) matchContext.getRootEntity().getPropertyByPath(property).orElse(null);
        if (persistentProperty == null || persistentProperty.getType() == null) {
            matchContext.fail("Cannot project on non-existent property " + property);
            return null;
        }
        this.expectedType = resolveExpectedType(matchContext, persistentProperty.getType());
        return this;
    }
}
 
Example #3
Source File: MicronautBeanFactory.java    From micronaut-spring with Apache License 2.0 6 votes vote down vote up
@Override
public @Nonnull
String[] getBeanNamesForType(Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
    // ignore certain common cases
    if (type == null || Object.class == type || List.class == type || beanExcludes.contains(type)) {
        return StringUtils.EMPTY_STRING_ARRAY;
    }
    String[] names = beanNamesForTypeCache.get(type);
    if (names == null) {
        final String[] superResult = MicronautBeanFactory.super.getBeanNamesForType(type, includeNonSingletons, allowEagerInit);
        if (ArrayUtils.isNotEmpty(superResult)) {
            names = superResult;
        } else {
            final Collection<? extends BeanDefinition<?>> beanDefinitions = beanContext.getBeanDefinitions(type);
            names = beansToNames(beanDefinitions);
        }
        beanNamesForTypeCache.put(type, names);
    }
    return names;
}
 
Example #4
Source File: ProjectionMethodExpression.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@Override
protected ProjectionMethodExpression initProjection(@NonNull MethodMatchContext matchContext, String remaining) {
    if (StringUtils.isEmpty(remaining)) {
        this.expectedType = matchContext.getRootEntity().getType();
        return this;
    } else {
        this.property = NameUtils.decapitalize(remaining);
        SourcePersistentProperty pp = matchContext.getRootEntity().getPropertyByName(property);
        if (pp == null || pp.getType() == null) {
            matchContext.fail("Cannot project on non-existent property " + property);
            return null;
        }
        this.expectedType = pp.getType();
        return this;
    }
}
 
Example #5
Source File: NamingStrategy.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
/**
 * Return the mapped name for the given property.
 * @param property The property
 * @return The mapped name
 */
default @NonNull String mappedName(@NonNull PersistentProperty property) {
    ArgumentUtils.requireNonNull("property", property);
    Supplier<String> defaultNameSupplier = () -> mappedName(property.getName());
    if (property instanceof Association) {
        Association association = (Association) property;
        if (association.isForeignKey()) {
            return mappedName(association.getOwner().getDecapitalizedName() +
                                association.getAssociatedEntity().getSimpleName());
        } else {
            switch (association.getKind()) {
                case ONE_TO_ONE:
                case MANY_TO_ONE:
                    return property.getAnnotationMetadata().stringValue(MappedProperty.class)
                            .orElseGet(() -> mappedName(property.getName() + getForeignKeySuffix()));
                default:
                    return property.getAnnotationMetadata().stringValue(MappedProperty.class)
                            .orElseGet(defaultNameSupplier);
            }
        }
    } else {
        return property.getAnnotationMetadata().stringValue(MappedProperty.class)
                .map(s -> StringUtils.isEmpty(s) ? defaultNameSupplier.get() : s)
                .orElseGet(defaultNameSupplier);
    }
}
 
Example #6
Source File: GraphQLWsMessageHandler.java    From micronaut-graphql with Apache License 2.0 6 votes vote down vote up
private Publisher<GraphQLWsResponse> startOperation(GraphQLWsRequest request, WebSocketSession session) {
    if (request.getId() == null) {
        LOG.warn("GraphQL operation id is required with type start");
        return Flowable.just(new GraphQLWsResponse(GQL_ERROR));
    }

    if (state.operationExists(request, session)) {
        LOG.info("Already subscribed to operation {} in session {}", request.getId(), session.getId());
        return Flowable.empty();
    }

    GraphQLRequestBody payload = request.getPayload();
    if (payload == null || StringUtils.isEmpty(payload.getQuery())) {
        LOG.info("Payload was null or query empty for operation {} in session {}", request.getId(),
                 session.getId());
        return Flowable.just(new GraphQLWsResponse(GQL_ERROR, request.getId()));
    }

    return executeRequest(request.getId(), payload, session);
}
 
Example #7
Source File: SourcePersistentEntity.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public SourcePersistentProperty getPropertyByName(String name) {
    if (StringUtils.isNotEmpty(name)) {
        final PropertyElement prop = beanProperties.get(name);
        if (prop != null) {
            if (prop.hasStereotype(Relation.class)) {
                if (isEmbedded(prop)) {
                    return new SourceEmbedded(this, prop, entityResolver);
                } else {
                    return new SourceAssociation(this, prop, entityResolver);
                }
            } else {
                return new SourcePersistentProperty(this, prop);
            }
        }
    }
    return null;
}
 
Example #8
Source File: EC2ServiceInstance.java    From micronaut-aws with Apache License 2.0 6 votes vote down vote up
/**
 * Container to hold AWS EC2 Instance info.
 * @param id if of the instance
 * @param uri uri to access this instance
 */
public EC2ServiceInstance(String id, URI uri) {
    this.id = id;

    String userInfo = uri.getUserInfo();
    if (StringUtils.isNotEmpty(userInfo)) {
        try {
            this.uri = new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());
            this.metadata = ConvertibleValues.of(Collections.singletonMap(
                HttpHeaders.AUTHORIZATION_INFO, userInfo
            ));
        } catch (URISyntaxException e) {
            throw new IllegalStateException("ServiceInstance URI is invalid: " + e.getMessage(), e);
        }
    } else {
        this.uri = uri;
    }
}
 
Example #9
Source File: ProjectionMethodExpression.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
protected ProjectionMethodExpression initProjection(@NonNull MethodMatchContext matchContext, @Nullable String remaining) {
    String str = topMatcher.group(2);
    try {
        max = StringUtils.isNotEmpty(str) ? Integer.parseInt(str) : 1;
    } catch (NumberFormatException e) {
        matchContext.fail("Invalid number specified to top: " + str);
        return null;
    }
    return this;
}
 
Example #10
Source File: SqlQueryBuilder.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
public String getTableName(PersistentEntity entity) {
    boolean escape = shouldEscape(entity);
    String tableName = entity.getPersistedName();
    String schema = entity.getAnnotationMetadata().stringValue(MappedEntity.class, SqlMembers.SCHEMA).orElse(null);
    if (StringUtils.isNotEmpty(schema)) {
        if (escape) {
            return quote(schema) + '.' + quote(tableName);
        } else {
            return schema + '.' + tableName;
        }
    } else {
        return escape ? quote(tableName) : tableName;
    }
}
 
Example #11
Source File: DeleteByMethod.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean hasQueryAnnotation(@NonNull MethodElement methodElement) {
    final String str = methodElement.stringValue(Query.class).orElse(null);
    if (StringUtils.isNotEmpty(str)) {
        return str.trim().toLowerCase(Locale.ENGLISH).startsWith("delete");
    }
    return false;
}
 
Example #12
Source File: GoogleMethodRouteBuilder.java    From micronaut-gcp with Apache License 2.0 5 votes vote down vote up
@Override
protected UriRoute buildBeanRoute(String httpMethodName, HttpMethod httpMethod, String uri, BeanDefinition<?> beanDefinition, ExecutableMethod<?, ?> method) {
    String cp = contextPathProvider.getContextPath();
    if (cp != null) {
        uri = StringUtils.prependUri(cp, uri);
    }
    return super.buildBeanRoute(httpMethodName, httpMethod, uri, beanDefinition, method);
}
 
Example #13
Source File: KafkaConsumerProcessor.java    From micronaut-kafka with Apache License 2.0 5 votes vote down vote up
@Override
public void resume(@Nonnull String id) {
    if (StringUtils.isNotEmpty(id) && consumers.containsKey(id)) {
        paused.remove(id);
    } else {
        throw new IllegalArgumentException("No consumer found for ID: " + id);
    }
}
 
Example #14
Source File: KafkaConsumerProcessor.java    From micronaut-kafka with Apache License 2.0 5 votes vote down vote up
@Override
public void pause(@Nonnull String id) {
    if (StringUtils.isNotEmpty(id) && consumers.containsKey(id)) {
        paused.add(id);
    } else {
        throw new IllegalArgumentException("No consumer found for ID: " + id);
    }
}
 
Example #15
Source File: KafkaConsumerProcessor.java    From micronaut-kafka with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isPaused(@Nonnull String id) {
    if (StringUtils.isNotEmpty(id) && consumers.containsKey(id)) {
        return paused.contains(id) && pausedConsumers.containsKey(id);
    }
    return false;
}
 
Example #16
Source File: AbstractMicronautLambdaRuntime.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
/**
 * Get the X-Ray tracing header from the Lambda-Runtime-Trace-Id header in the API response.
 * Set the _X_AMZN_TRACE_ID environment variable with the same value for the X-Ray SDK to use.
 * @param headers next API Response HTTP Headers
 */
@SuppressWarnings("EmptyBlock")
protected void propagateTraceId(HttpHeaders headers) {
    String traceId = headers.get(LambdaRuntimeInvocationResponseHeaders.LAMBDA_RUNTIME_TRACE_ID);
    logn(LogLevel.DEBUG, "Trace id: " + traceId + "\n");
    if (StringUtils.isNotEmpty(traceId)) {
        //TODO Set Env.variable _X_AMZN_TRACE_ID with value traceId
    }
}
 
Example #17
Source File: AbstractMicronautLambdaRuntime.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
private URL lookupRuntimeApiEndpoint() throws MalformedURLException {
    final String runtimeApiEndpoint = getEnv(ReservedRuntimeEnvironmentVariables.AWS_LAMBDA_RUNTIME_API);
    if (StringUtils.isEmpty(runtimeApiEndpoint)) {
        throw new IllegalStateException("Missing " + ReservedRuntimeEnvironmentVariables.AWS_LAMBDA_RUNTIME_API + " environment variable. Custom runtime can only be run within AWS Lambda environment.");
    }
    return new URL("http://" + runtimeApiEndpoint);
}
 
Example #18
Source File: GrpcNameResolverFactory.java    From micronaut-grpc with Apache License 2.0 5 votes vote down vote up
/**
 * A GRPC name resolver factory that integrates with Micronaut's discovery client.
 * @param discoveryClient The discovery client
 * @param serviceInstanceLists The service instance list
 * @return The name resolver
 */
@Singleton
@Requires(beans = DiscoveryClient.class)
@Requires(property = ENABLED, value = StringUtils.TRUE, defaultValue = StringUtils.FALSE)
protected NameResolver.Factory nameResolverFactory(
        DiscoveryClient discoveryClient,
        List<ServiceInstanceList> serviceInstanceLists) {
    return new GrpcNameResolverProvider(discoveryClient, serviceInstanceLists);
}
 
Example #19
Source File: AbstractSqlLikeQueryBuilder.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
private String buildAdditionalWhereString(PersistentEntity entity, AnnotationMetadata annotationMetadata) {
    final String whereStr = resolveWhereForAnnotationMetadata(annotationMetadata);
    if (StringUtils.isNotEmpty(whereStr)) {
        return whereStr;
    } else {
        return resolveWhereForAnnotationMetadata(entity.getAnnotationMetadata());
    }
}
 
Example #20
Source File: AbstractSqlLikeQueryBuilder.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
private String resolveWhereForAnnotationMetadata(AnnotationMetadata annotationMetadata) {
    return annotationMetadata.getAnnotationValuesByType(Where.class)
            .stream()
            .map(av -> av.stringValue().orElse(null))
            .filter(StringUtils::isNotEmpty)
            .collect(Collectors.joining(LOGICAL_AND));
}
 
Example #21
Source File: UpdateByMethod.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean hasQueryAnnotation(@NonNull MethodElement methodElement) {
    final String str = methodElement.stringValue(Query.class).orElse(null);
    if (StringUtils.isNotEmpty(str)) {
        return str.trim().toLowerCase(Locale.ENGLISH).startsWith("update");
    }
    return false;
}
 
Example #22
Source File: NamingStrategy.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
/**
 * Return the mapped name for the given entity.
 * @param entity The entity
 * @return The mapped name
 */
default @NonNull String mappedName(@NonNull PersistentEntity entity) {
    ArgumentUtils.requireNonNull("entity", entity);
    return entity.getAnnotationMetadata().stringValue(MappedEntity.class)
            .filter(StringUtils::isNotEmpty)
            .orElseGet(() -> mappedName(entity.getSimpleName()));
}
 
Example #23
Source File: AbstractQueryInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
public String[] getParameterNames() {
    if (parameterNames == null) {
        return StringUtils.EMPTY_STRING_ARRAY;
    }
    return this.parameterNames;
}
 
Example #24
Source File: AbstractQueryInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
public String[] getIndexedParameterPaths() {
    if (parameterPaths != null) {
        return parameterPaths;
    }
    return StringUtils.EMPTY_STRING_ARRAY;
}
 
Example #25
Source File: GrpcNameResolverFactory.java    From micronaut-grpc with Apache License 2.0 5 votes vote down vote up
/**
 * A GRPC name resolver factory that integrates with Micronaut's discovery client.
 * @param discoveryClient The discovery client
 * @param serviceInstanceLists The service instance list
 * @return The name resolver
 */
@Singleton
@Requires(beans = DiscoveryClient.class)
@Requires(property = ENABLED, value = StringUtils.TRUE, defaultValue = StringUtils.FALSE)
protected NameResolver.Factory nameResolverFactory(
        DiscoveryClient discoveryClient,
        List<ServiceInstanceList> serviceInstanceLists) {
    return new GrpcNameResolverProvider(discoveryClient, serviceInstanceLists);
}
 
Example #26
Source File: GrpcChannelScope.java    From micronaut-grpc with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T get(
        BeanResolutionContext resolutionContext,
        BeanDefinition<T> beanDefinition,
        BeanIdentifier identifier,
        Provider<T> provider) {
    BeanResolutionContext.Segment segment = resolutionContext.getPath().currentSegment().orElseThrow(() ->
            new IllegalStateException("@GrpcChannel used in invalid location")
    );
    Argument argument = segment.getArgument();
    String value = argument.getAnnotationMetadata().getValue(GrpcChannel.class, String.class).orElse(null);
    if (StringUtils.isEmpty(value)) {
        throw new DependencyInjectionException(resolutionContext, argument, "No value specified to @GrpcChannel annotation");
    }
    if (!Channel.class.isAssignableFrom(argument.getType())) {
        throw new DependencyInjectionException(resolutionContext, argument, "@GrpcChannel used on type that is not a Channel");
    }

    if ("grpc-server".equalsIgnoreCase(value)) {
        return (T) applicationContext.getBean(ManagedChannel.class, Qualifiers.byName("grpc-server"));
    }

    if (!(provider instanceof ParametrizedProvider)) {
        throw new DependencyInjectionException(resolutionContext, argument, "GrpcChannelScope called with invalid bean provider");
    }
    value = applicationContext.resolveRequiredPlaceholders(value);
    String finalValue = value;
    return (T) channels.computeIfAbsent(new ChannelKey(identifier, value), channelKey ->
            (ManagedChannel) ((ParametrizedProvider<T>) provider).get(finalValue)
    );
}
 
Example #27
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 #28
Source File: MicronautBeanFactory.java    From micronaut-spring with Apache License 2.0 5 votes vote down vote up
@Override
public @Nonnull
String[] getBeanNamesForType(@Nonnull ResolvableType type) {
    final Class<?> resolved = type.resolve();
    if (resolved != null) {
        return getBeanNamesForType(resolved);
    }
    return StringUtils.EMPTY_STRING_ARRAY;
}
 
Example #29
Source File: WebBindAnnotationMapper.java    From micronaut-spring with Apache License 2.0 5 votes vote down vote up
@Override
protected List<AnnotationValue<?>> mapInternal(AnnotationValue<Annotation> annotation, VisitorContext visitorContext) {
    List<AnnotationValue<?>> mappedAnnotations = new ArrayList<>();

    final String name = annotation.getValue(String.class).orElseGet(() -> annotation.get("name", String.class).orElse(null));
    final String defaultValue = annotation.get("defaultValue", String.class).orElse(null);
    final boolean required = annotation.get("required", boolean.class).orElse(true);

    final AnnotationValueBuilder<?> builder = AnnotationValue.builder(annotationType());
    final AnnotationValueBuilder<Bindable> bindableBuilder = AnnotationValue.builder(Bindable.class);
    if (StringUtils.isNotEmpty(name)) {
        builder.value(name);
        bindableBuilder.value(name);
    }
    if (StringUtils.isNotEmpty(defaultValue)) {
        builder.member("defaultValue", name);
        bindableBuilder.member("defaultValue", defaultValue);
    }

    mappedAnnotations.add(builder.build());
    mappedAnnotations.add(bindableBuilder.build());
    if (!required) {
        mappedAnnotations.add(AnnotationValue.builder(Nullable.class).build());
    }

    return mappedAnnotations;
}
 
Example #30
Source File: MicronautLockConfigurationExtractor.java    From ShedLock with Apache License 2.0 5 votes vote down vote up
private Duration getValue(AnnotationValue<SchedulerLock> annotation, Duration defaultValue, String paramName) {
    String stringValueFromAnnotation = annotation.get(paramName, String.class).orElse("");
    if (StringUtils.hasText(stringValueFromAnnotation)) {
        return conversionService.convert(stringValueFromAnnotation, Duration.class)
            .orElseThrow(() -> new IllegalArgumentException("Invalid " + paramName + " value \"" + stringValueFromAnnotation + "\" - cannot parse into duration"));
    } else {
        return defaultValue;
    }
}