io.micronaut.core.naming.NameUtils Java Examples

The following examples show how to use io.micronaut.core.naming.NameUtils. 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: ConfigurationPropertiesAnnotationMapper.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) {
    String prefix = annotation.get("prefix", String.class).orElseGet(() -> annotation.getValue(String.class).orElse(null));
    if (prefix != null) {
        prefix = NameUtils.hyphenate(prefix, true);
        return Arrays.asList(
                AnnotationValue.builder(ConfigurationReader.class)
                        .member("prefix", prefix)
                        .build(),
                AnnotationValue.builder(ConfigurationProperties.class)
                        .value(prefix)
                        .build()
        );
    } else {
        return Collections.emptyList();
    }
}
 
Example #2
Source File: KafkaProducerConfiguration.java    From micronaut-kafka with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs the default producer configuration.
 *
 * @param producerName The name of the producer
 * @param defaultConfiguration The default Kafka configuration
 * @param environment The environment
 */
public KafkaProducerConfiguration(
        @Parameter String producerName,
        KafkaDefaultConfiguration defaultConfiguration,
        Environment environment) {
    super(new Properties());
    Properties config = getConfig();
    config.putAll(defaultConfiguration.getConfig());
    String propertyKey = PREFIX + '.' + NameUtils.hyphenate(producerName, true);
    if (environment.containsProperties(propertyKey)) {
        config.putAll(
                environment.getProperties(propertyKey, StringConvention.RAW)
        );
    }

}
 
Example #3
Source File: GraphiQLController.java    From micronaut-graphql with Apache License 2.0 6 votes vote down vote up
private String resolvedTemplate() {
    Map<String, String> parameters = new HashMap<>();
    parameters.put("graphiqlVersion", graphiQLConfiguration.getVersion());
    parameters.put("graphqlPath", graphQLConfiguration.getPath());
    String graphQLWsPath = graphQLWsConfiguration.isEnabled() ? graphQLWsConfiguration.getPath() : "";
    parameters.put("graphqlWsPath", graphQLWsPath);
    parameters.put("pageTitle", graphiQLConfiguration.getPageTitle());
    if (graphiQLConfiguration.getTemplateParameters() != null) {
        graphiQLConfiguration.getTemplateParameters().forEach((name, value) ->
                // De-capitalize and de-hyphenate the parameter names.
                // Otherwise `graphiql.template-parameters.magicWord` would be put as `magic-word` in the
                // parameters map as Micronaut normalises properties and stores them lowercase hyphen separated.
                parameters.put(NameUtils.decapitalize(NameUtils.dehyphenate(name)), value));
    }
    return replaceParameters(this.rawTemplate, parameters);
}
 
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: 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 #6
Source File: KafkaConsumerConfiguration.java    From micronaut-kafka with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a new {@link KafkaConsumerConfiguration} for the given defaults.
 *
 * @param consumerName The name of the consumer
 * @param defaultConfiguration The default configuration
 * @param environment The environment
 */
public KafkaConsumerConfiguration(
        @Parameter String consumerName,
        KafkaDefaultConfiguration defaultConfiguration,
        Environment environment) {
    super(new Properties());
    Properties config = getConfig();
    config.putAll(defaultConfiguration.getConfig());
    String propertyKey = PREFIX + '.' + NameUtils.hyphenate(consumerName, true);
    if (environment.containsProperties(propertyKey)) {
        config.putAll(
                environment.getProperties(propertyKey, StringConvention.RAW)
        );
    }
}
 
Example #7
Source File: PropertyResolverAdapter.java    From micronaut-spring with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T getRequiredProperty(String key, Class<T> targetType) throws IllegalStateException {
    T v = getProperty(NameUtils.hyphenate(key), targetType, null);
    if (v == null) {
        throw new IllegalStateException("Property [" + key + "] not found");
    }
    return v;
}
 
Example #8
Source File: AbstractQueryInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
/**
 * Return whether the metadata indicates the instance is nullable.
 * @param metadata The metadata
 * @return True if it is nullable
 */
protected boolean isNullable(@NonNull AnnotationMetadata metadata) {
    return metadata
            .getDeclaredAnnotationNames()
            .stream()
            .anyMatch(n -> NameUtils.getSimpleName(n).equalsIgnoreCase("nullable"));
}
 
Example #9
Source File: PersistentProperty.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
/**
 * Return whether the metadata indicates the instance is nullable.
 * @param metadata The metadata
 * @return True if it is nullable
 */
static boolean isNullableMetadata(@NonNull AnnotationMetadata metadata) {
    return metadata
            .getDeclaredAnnotationNames()
            .stream()
            .anyMatch(n -> NameUtils.getSimpleName(n).equalsIgnoreCase("nullable"));
}
 
Example #10
Source File: ProjectionMethodExpression.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the projection or returns null if an error occurred reporting the error to the visitor context.
 * @param matchContext The visitor context
 * @param projectionDefinition The projection definition
 * @return The projection
 */
protected final @Nullable ProjectionMethodExpression init(
        @NonNull MethodMatchContext matchContext,
        @NonNull String projectionDefinition
) {
    int len = getClass().getSimpleName().length();
    if (projectionDefinition.length() >= len && !getClass().equals(Property.class)) {
        String remaining = projectionDefinition.substring(len);
        return initProjection(matchContext, NameUtils.decapitalize(remaining));
    } else {
        return initProjection(matchContext, projectionDefinition);
    }
}
 
Example #11
Source File: KafkaStreamsConfiguration.java    From micronaut-kafka with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a new {@link KafkaStreamsConfiguration} for the given defaults.
 *
 * @param streamName The stream name
 * @param defaultConfiguration The default configuration
 * @param applicationConfiguration The application configuration
 * @param environment The environment
 */
public KafkaStreamsConfiguration(
        @Parameter String streamName,
        KafkaDefaultConfiguration defaultConfiguration,
        ApplicationConfiguration applicationConfiguration,
        Environment environment) {
    super(defaultConfiguration);
    Properties config = getConfig();
    String propertyKey = PREFIX + '.' + NameUtils.hyphenate(streamName, true);
    config.putAll(environment.getProperty(propertyKey, Properties.class).orElseGet(Properties::new));
    init(applicationConfiguration, environment, config);
}
 
Example #12
Source File: NamingStrategies.java    From micronaut-data with Apache License 2.0 4 votes vote down vote up
@NonNull
@Override
public String mappedName(@NonNull String name) {
    return NameUtils.underscoreSeparate(name).toLowerCase(Locale.ENGLISH);
}
 
Example #13
Source File: NamingStrategies.java    From micronaut-data with Apache License 2.0 4 votes vote down vote up
@NonNull
@Override
public String mappedName(@NonNull String name) {
    return NameUtils.hyphenate(name);
}
 
Example #14
Source File: PersistentEntity.java    From micronaut-data with Apache License 2.0 4 votes vote down vote up
/**
 * @return Returns the name of the class decapitalized form
 */
default @NonNull String getDecapitalizedName() {
    return NameUtils.decapitalize(getSimpleName());
}
 
Example #15
Source File: PersistentEntity.java    From micronaut-data with Apache License 2.0 4 votes vote down vote up
/**
 * @return The simple name without the package of entity
 */
@NonNull
default String getSimpleName() {
    return NameUtils.getSimpleName(getName());
}
 
Example #16
Source File: TestActiveCondition.java    From micronaut-test with Apache License 2.0 4 votes vote down vote up
@Override
public boolean matches(ConditionContext context) {
    if (context.getComponent() instanceof BeanDefinition) {
        BeanDefinition<?> definition = (BeanDefinition<?>) context.getComponent();
        final BeanContext beanContext = context.getBeanContext();
        final Optional<Class<?>> declaringType = definition.getDeclaringType();

        if (beanContext instanceof ApplicationContext) {
            ApplicationContext applicationContext = (ApplicationContext) beanContext;
            final Class activeSpecClazz = applicationContext.get(ACTIVE_SPEC_CLAZZ, Class.class).orElse(null);
            final String activeSpecName = Optional.ofNullable(activeSpecClazz).map(clazz -> clazz.getPackage().getName() + "." + clazz.getSimpleName()).orElse(null);
            if (definition.isAnnotationPresent(MockBean.class) && declaringType.isPresent()) {
                final Class<?> declaringTypeClass = declaringType.get();
                String declaringTypeName = declaringTypeClass.getName();
                if (activeSpecClazz != null) {
                    if (definition.isProxy()) {
                        final String packageName = NameUtils.getPackageName(activeSpecName);
                        final String simpleName = NameUtils.getSimpleName(activeSpecName);
                        final String rootName = packageName + ".$" + simpleName;
                        return declaringTypeClass.isAssignableFrom(activeSpecClazz) || declaringTypeName.equals(rootName) || declaringTypeName.startsWith(rootName + "$");
                    } else {
                        return declaringTypeClass.isAssignableFrom(activeSpecClazz) || activeSpecName.equals(declaringTypeName) || declaringTypeName.startsWith(activeSpecName + "$");
                    }
                } else {
                    context.fail(
                            "@MockBean of type " + definition.getBeanType() + " not within scope of parent test."
                    );
                    return false;
                }
            } else {
                if (activeSpecName != null) {
                    boolean beanTypeMatches = activeSpecName.equals(definition.getBeanType().getName());
                    return beanTypeMatches || (declaringType.isPresent() && activeSpecClazz == declaringType.get());
                } else {
                    return false;
                }
            }
        } else {
            return false;
        }
    } else {
        return true;
    }
}
 
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: PropertyResolverAdapter.java    From micronaut-spring with Apache License 2.0 4 votes vote down vote up
@Override
public boolean containsProperty(String key) {
    return propertyResolver.getProperty(NameUtils.hyphenate(key), String.class).isPresent();
}
 
Example #19
Source File: PropertyResolverAdapter.java    From micronaut-spring with Apache License 2.0 4 votes vote down vote up
@Override
public String getProperty(String key) {
    return propertyResolver.getProperty(NameUtils.hyphenate(key), String.class).orElse(null);
}
 
Example #20
Source File: PropertyResolverAdapter.java    From micronaut-spring with Apache License 2.0 4 votes vote down vote up
@Override
public String getProperty(String key, String defaultValue) {
    return getProperty(NameUtils.hyphenate(key), String.class, null);
}
 
Example #21
Source File: PropertyResolverAdapter.java    From micronaut-spring with Apache License 2.0 4 votes vote down vote up
@Override
public <T> T getProperty(String key, Class<T> targetType) {
    return getProperty(NameUtils.hyphenate(key), targetType, null);
}
 
Example #22
Source File: PropertyResolverAdapter.java    From micronaut-spring with Apache License 2.0 4 votes vote down vote up
@Override
public <T> T getProperty(String key, Class<T> targetType, T defaultValue) {
    return propertyResolver.getProperty(NameUtils.hyphenate(key), targetType, defaultValue);
}
 
Example #23
Source File: PropertyResolverAdapter.java    From micronaut-spring with Apache License 2.0 4 votes vote down vote up
@Override
public String getRequiredProperty(String key) throws IllegalStateException {
    return getRequiredProperty(NameUtils.hyphenate(key), String.class);
}
 
Example #24
Source File: ProjectionMethodExpression.java    From micronaut-data with Apache License 2.0 4 votes vote down vote up
/**
 * Match a projection.
 * @param matchContext The context
 * @param projection The projection to match
 * @return An expression or null if no match is possible or an error occurred.
 */
public static @Nullable ProjectionMethodExpression matchProjection(@NonNull MethodMatchContext matchContext, @NonNull String projection) {

    Class<?>[] innerClasses = ProjectionMethodExpression.class.getClasses();
    SourcePersistentEntity entity = matchContext.getRootEntity();
    String decapitilized = NameUtils.decapitalize(projection);
    Optional<String> path = entity.getPath(decapitilized);
    if (path.isPresent()) {
        return new Property().init(matchContext, projection);
    } else {

        for (Class<?> innerClass : innerClasses) {
            String simpleName = innerClass.getSimpleName();
            if (projection.startsWith(simpleName)) {
                Object o;
                try {
                    o = innerClass.newInstance();
                } catch (Throwable e) {
                    continue;
                }


                if (o instanceof ProjectionMethodExpression) {
                    ProjectionMethodExpression pme = (ProjectionMethodExpression) o;
                    ProjectionMethodExpression initialized = pme.init(matchContext, projection);
                    if (initialized != null) {
                        return initialized;
                    }
                }
            }
        }

        // allow findAllBy as an alternative to findBy
        if (!Arrays.asList("all", "one").contains(decapitilized)) {
            Matcher topMatcher = Pattern.compile("^(top|first)(\\d*)$").matcher(decapitilized);
            if (topMatcher.find()) {
                return new RestrictMaxResultProjection(topMatcher, matchContext).initProjection(matchContext, decapitilized);
            }
            // if the return type simple name is the same then we assume this is ok
            // this allows for Optional findOptionalByName
            if (!projection.equals(matchContext.getReturnType().getSimpleName())) {
                matchContext.fail("Cannot project on non-existent property: " + decapitilized);
            }
        }
        return null;
    }
}
 
Example #25
Source File: NamingStrategies.java    From micronaut-data with Apache License 2.0 4 votes vote down vote up
@NonNull
@Override
public String mappedName(@NonNull String name) {
    return NameUtils.environmentName(name);
}
 
Example #26
Source File: PersistentProperty.java    From micronaut-data with Apache License 2.0 2 votes vote down vote up
/**
 * The name with the first letter in upper case as per Java bean conventions.
 * @return The capitilized name
 */
default @NonNull String getCapitilizedName() {
    return NameUtils.capitalize(getName());
}