Search in sources :

Example 1 with ConversionContext

use of io.micronaut.core.convert.ConversionContext in project micronaut-core by micronaut-projects.

the class PropertySourcePropertyResolver method resolveSubProperties.

/**
 * @param name              The property name
 * @param entries           The entries
 * @param conversionContext The conversion context
 * @return The subproperties
 */
protected Properties resolveSubProperties(String name, Map<String, Object> entries, ArgumentConversionContext<?> conversionContext) {
    // special handling for maps for resolving sub keys
    Properties properties = new Properties();
    AnnotationMetadata annotationMetadata = conversionContext.getAnnotationMetadata();
    StringConvention keyConvention = annotationMetadata.enumValue(MapFormat.class, "keyFormat", StringConvention.class).orElse(null);
    if (keyConvention == StringConvention.RAW) {
        entries = resolveEntriesForKey(name, false, PropertyCatalog.RAW);
    }
    String prefix = name + '.';
    entries.entrySet().stream().filter(map -> map.getKey().startsWith(prefix)).forEach(entry -> {
        Object value = entry.getValue();
        if (value != null) {
            String key = entry.getKey().substring(prefix.length());
            key = keyConvention != null ? keyConvention.format(key) : key;
            properties.put(key, resolvePlaceHoldersIfNecessary(value.toString()));
        }
    });
    return properties;
}
Also used : Arrays(java.util.Arrays) ListIterator(java.util.ListIterator) StringConvention(io.micronaut.core.naming.conventions.StringConvention) ArgumentConversionContext(io.micronaut.core.convert.ArgumentConversionContext) HashMap(java.util.HashMap) Random(java.util.Random) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) PropertyResolver(io.micronaut.core.value.PropertyResolver) Matcher(java.util.regex.Matcher) EnvironmentProperties(io.micronaut.core.util.EnvironmentProperties) Nullable(io.micronaut.core.annotation.Nullable) MapPropertyResolver(io.micronaut.core.value.MapPropertyResolver) Map(java.util.Map) Argument(io.micronaut.core.type.Argument) NameUtils(io.micronaut.core.naming.NameUtils) ConversionService(io.micronaut.core.convert.ConversionService) StaticOptimizations(io.micronaut.core.optim.StaticOptimizations) ConfigurationException(io.micronaut.context.exceptions.ConfigurationException) ClassUtils(io.micronaut.core.reflect.ClassUtils) Logger(org.slf4j.Logger) Properties(java.util.Properties) ValueException(io.micronaut.core.value.ValueException) SocketUtils(io.micronaut.core.io.socket.SocketUtils) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) MapFormat(io.micronaut.core.convert.format.MapFormat) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) Consumer(java.util.function.Consumer) NonNull(io.micronaut.core.annotation.NonNull) StringUtils(io.micronaut.core.util.StringUtils) List(java.util.List) ConversionContext(io.micronaut.core.convert.ConversionContext) CollectionUtils(io.micronaut.core.util.CollectionUtils) Optional(java.util.Optional) AnnotationMetadata(io.micronaut.core.annotation.AnnotationMetadata) Pattern(java.util.regex.Pattern) Collections(java.util.Collections) MapFormat(io.micronaut.core.convert.format.MapFormat) StringConvention(io.micronaut.core.naming.conventions.StringConvention) EnvironmentProperties(io.micronaut.core.util.EnvironmentProperties) Properties(java.util.Properties) AnnotationMetadata(io.micronaut.core.annotation.AnnotationMetadata)

Example 2 with ConversionContext

use of io.micronaut.core.convert.ConversionContext in project micronaut-core by micronaut-projects.

the class EnvironmentConvertibleValuesMap method get.

@Override
public <T> Optional<T> get(CharSequence name, ArgumentConversionContext<T> conversionContext) {
    V value = map.get(name);
    if (value instanceof AnnotationClassValue) {
        AnnotationClassValue acv = (AnnotationClassValue) value;
        return environment.convert(acv, conversionContext);
    } else if (value instanceof CharSequence) {
        PropertyPlaceholderResolver placeholderResolver = environment.getPlaceholderResolver();
        String str = doResolveIfNecessary((CharSequence) value, placeholderResolver);
        return environment.convert(str, conversionContext);
    } else if (value instanceof String[]) {
        PropertyPlaceholderResolver placeholderResolver = environment.getPlaceholderResolver();
        String[] resolved = Arrays.stream((String[]) value).flatMap(val -> {
            try {
                String[] values = placeholderResolver.resolveRequiredPlaceholder(val, String[].class);
                return Arrays.stream(values);
            } catch (ConfigurationException e) {
                return Stream.of(doResolveIfNecessary(val, placeholderResolver));
            }
        }).toArray(String[]::new);
        return environment.convert(resolved, conversionContext);
    } else if (value instanceof io.micronaut.core.annotation.AnnotationValue[]) {
        io.micronaut.core.annotation.AnnotationValue[] annotationValues = (io.micronaut.core.annotation.AnnotationValue[]) value;
        io.micronaut.core.annotation.AnnotationValue[] b = new AnnotationValue[annotationValues.length];
        for (int i = 0; i < annotationValues.length; i++) {
            io.micronaut.core.annotation.AnnotationValue annotationValue = annotationValues[i];
            b[i] = new EnvironmentAnnotationValue(environment, annotationValue);
        }
        return environment.convert(b, conversionContext);
    } else if (value instanceof io.micronaut.core.annotation.AnnotationValue) {
        io.micronaut.core.annotation.AnnotationValue av = (io.micronaut.core.annotation.AnnotationValue) value;
        av = new EnvironmentAnnotationValue(environment, av);
        return environment.convert(av, conversionContext);
    } else {
        return super.get(name, conversionContext);
    }
}
Also used : Environment(io.micronaut.context.env.Environment) ConfigurationException(io.micronaut.context.exceptions.ConfigurationException) ConvertibleValues(io.micronaut.core.convert.value.ConvertibleValues) Arrays(java.util.Arrays) ConvertibleValuesMap(io.micronaut.core.convert.value.ConvertibleValuesMap) ArgumentConversionContext(io.micronaut.core.convert.ArgumentConversionContext) Collection(java.util.Collection) Internal(io.micronaut.core.annotation.Internal) Collectors(java.util.stream.Collectors) ConversionContext(io.micronaut.core.convert.ConversionContext) Stream(java.util.stream.Stream) AnnotationValue(io.micronaut.core.annotation.AnnotationValue) Map(java.util.Map) Optional(java.util.Optional) PropertyPlaceholderResolver(io.micronaut.context.env.PropertyPlaceholderResolver) Argument(io.micronaut.core.type.Argument) AnnotationClassValue(io.micronaut.core.annotation.AnnotationClassValue) PropertyPlaceholderResolver(io.micronaut.context.env.PropertyPlaceholderResolver) AnnotationClassValue(io.micronaut.core.annotation.AnnotationClassValue) ConfigurationException(io.micronaut.context.exceptions.ConfigurationException) AnnotationValue(io.micronaut.core.annotation.AnnotationValue) AnnotationValue(io.micronaut.core.annotation.AnnotationValue)

Example 3 with ConversionContext

use of io.micronaut.core.convert.ConversionContext in project micronaut-core by micronaut-projects.

the class AbstractRouteMatch method convertValueAndAddToList.

private void convertValueAndAddToList(ConversionService conversionService, List argumentList, Argument argument, Object value, Class argumentType) {
    if (argumentType.isInstance(value)) {
        if (argument.isContainerType()) {
            if (argument.hasTypeVariables()) {
                ConversionContext conversionContext = ConversionContext.of(argument);
                Optional<?> result = conversionService.convert(value, argumentType, conversionContext);
                argumentList.add(resolveValueOrError(argument, conversionContext, result));
            } else {
                argumentList.add(value);
            }
        } else {
            argumentList.add(value);
        }
    } else {
        ConversionContext conversionContext = ConversionContext.of(argument);
        Optional<?> result = conversionService.convert(value, argumentType, conversionContext);
        argumentList.add(resolveValueOrError(argument, conversionContext, result));
    }
}
Also used : ArgumentConversionContext(io.micronaut.core.convert.ArgumentConversionContext) ConversionContext(io.micronaut.core.convert.ConversionContext)

Example 4 with ConversionContext

use of io.micronaut.core.convert.ConversionContext in project micronaut-core by micronaut-projects.

the class TimeConverterRegistrar method register.

@Override
public void register(ConversionService<?> conversionService) {
    final BiFunction<CharSequence, ConversionContext, Optional<Duration>> durationConverter = (object, context) -> {
        String value = object.toString().trim();
        if (value.startsWith("P")) {
            try {
                return Optional.of(Duration.parse(value));
            } catch (DateTimeParseException e) {
                context.reject(value, e);
                return Optional.empty();
            }
        } else {
            Matcher matcher = DURATION_MATCHER.matcher(value);
            if (matcher.find()) {
                String amount = matcher.group(1);
                final String g2 = matcher.group(2);
                char type = g2.charAt(0);
                try {
                    switch(type) {
                        case 's':
                            return Optional.of(Duration.ofSeconds(Integer.parseInt(amount)));
                        case 'm':
                            String ms = matcher.group(MILLIS);
                            if (StringUtils.hasText(ms)) {
                                return Optional.of(Duration.ofMillis(Integer.parseInt(amount)));
                            } else {
                                return Optional.of(Duration.ofMinutes(Integer.parseInt(amount)));
                            }
                        case 'h':
                            return Optional.of(Duration.ofHours(Integer.parseInt(amount)));
                        case 'd':
                            return Optional.of(Duration.ofDays(Integer.parseInt(amount)));
                        default:
                            final String seq = g2 + matcher.group(3);
                            switch(seq) {
                                case "ns":
                                    return Optional.of(Duration.ofNanos(Integer.parseInt(amount)));
                                default:
                                    context.reject(value, new DateTimeParseException("Unparseable date format (" + value + "). Should either be a ISO-8601 duration or a round number followed by the unit type", value, 0));
                                    return Optional.empty();
                            }
                    }
                } catch (NumberFormatException e) {
                    context.reject(value, e);
                }
            }
        }
        return Optional.empty();
    };
    // CharSequence -> Duration
    conversionService.addConverter(CharSequence.class, Duration.class, (object, targetType, context) -> durationConverter.apply(object, context));
    // CharSequence -> TemporalAmount
    conversionService.addConverter(CharSequence.class, TemporalAmount.class, (object, targetType, context) -> durationConverter.apply(object, context).map(TemporalAmount.class::cast));
    // CharSequence -> LocalDateTime
    conversionService.addConverter(CharSequence.class, LocalDateTime.class, (object, targetType, context) -> {
        try {
            DateTimeFormatter formatter = resolveFormatter(context);
            LocalDateTime result = LocalDateTime.parse(object, formatter);
            return Optional.of(result);
        } catch (DateTimeParseException e) {
            context.reject(object, e);
            return Optional.empty();
        }
    });
    // TemporalAccessor - CharSequence
    final TypeConverter<TemporalAccessor, CharSequence> temporalConverter = (object, targetType, context) -> {
        try {
            DateTimeFormatter formatter = resolveFormatter(context);
            return Optional.of(formatter.format(object));
        } catch (DateTimeParseException e) {
            context.reject(object, e);
            return Optional.empty();
        }
    };
    conversionService.addConverter(TemporalAccessor.class, CharSequence.class, temporalConverter);
    // CharSequence -> LocalDate
    conversionService.addConverter(CharSequence.class, LocalDate.class, (object, targetType, context) -> {
        try {
            DateTimeFormatter formatter = resolveFormatter(context);
            LocalDate result = LocalDate.parse(object, formatter);
            return Optional.of(result);
        } catch (DateTimeParseException e) {
            context.reject(object, e);
            return Optional.empty();
        }
    });
    // CharSequence -> ZonedDateTime
    conversionService.addConverter(CharSequence.class, ZonedDateTime.class, (object, targetType, context) -> {
        try {
            DateTimeFormatter formatter = resolveFormatter(context);
            ZonedDateTime result = ZonedDateTime.parse(object, formatter);
            return Optional.of(result);
        } catch (DateTimeParseException e) {
            context.reject(object, e);
            return Optional.empty();
        }
    });
    // CharSequence -> OffsetDateTime
    conversionService.addConverter(CharSequence.class, OffsetDateTime.class, (object, targetType, context) -> {
        try {
            DateTimeFormatter formatter = resolveFormatter(context);
            OffsetDateTime result = OffsetDateTime.parse(object, formatter);
            return Optional.of(result);
        } catch (DateTimeParseException e) {
            context.reject(object, e);
            return Optional.empty();
        }
    });
}
Also used : Environment(io.micronaut.context.env.Environment) TypeConverter(io.micronaut.core.convert.TypeConverter) BiFunction(java.util.function.BiFunction) Singleton(jakarta.inject.Singleton) TemporalAccessor(java.time.temporal.TemporalAccessor) StringUtils(io.micronaut.core.util.StringUtils) Format(io.micronaut.core.convert.format.Format) java.time(java.time) DateTimeParseException(java.time.format.DateTimeParseException) ConversionContext(io.micronaut.core.convert.ConversionContext) Matcher(java.util.regex.Matcher) BootstrapContextCompatible(io.micronaut.context.annotation.BootstrapContextCompatible) DateTimeFormatter(java.time.format.DateTimeFormatter) Requires(io.micronaut.context.annotation.Requires) TemporalAmount(java.time.temporal.TemporalAmount) Optional(java.util.Optional) TypeConverterRegistrar(io.micronaut.core.convert.TypeConverterRegistrar) Pattern(java.util.regex.Pattern) TypeHint(io.micronaut.core.annotation.TypeHint) ConversionService(io.micronaut.core.convert.ConversionService) TemporalAccessor(java.time.temporal.TemporalAccessor) ConversionContext(io.micronaut.core.convert.ConversionContext) Optional(java.util.Optional) Matcher(java.util.regex.Matcher) DateTimeParseException(java.time.format.DateTimeParseException) DateTimeFormatter(java.time.format.DateTimeFormatter)

Example 5 with ConversionContext

use of io.micronaut.core.convert.ConversionContext in project micronaut-core by micronaut-projects.

the class InstantiationUtils method tryInstantiate.

/**
 * Try to instantiate the given class using {@link io.micronaut.core.beans.BeanIntrospector}.
 *
 * @param type The type
 * @param propertiesMap The properties values {@link Map} of the instance
 * @param context The Conversion context
 * @param <T> The generic type
 * @return The instantiated instance or {@link Optional#empty()}
 * @throws InstantiationException When an error occurs
 */
@NonNull
public static <T> Optional<T> tryInstantiate(@NonNull Class<T> type, Map propertiesMap, ConversionContext context) {
    ArgumentUtils.requireNonNull("type", type);
    if (propertiesMap.isEmpty()) {
        return tryInstantiate(type);
    }
    final Supplier<T> reflectionFallback = () -> {
        Logger log = LoggerFactory.getLogger(InstantiationUtils.class);
        if (log.isDebugEnabled()) {
            log.debug("Tried, but could not instantiate type: " + type);
        }
        return null;
    };
    T result = BeanIntrospector.SHARED.findIntrospection(type).map(introspection -> {
        T instance;
        Argument[] constructorArguments = introspection.getConstructorArguments();
        List<Object> arguments = new ArrayList<>(constructorArguments.length);
        try {
            if (constructorArguments.length > 0) {
                Map bindMap = new LinkedHashMap(propertiesMap.size());
                Set<Map.Entry<?, ?>> entries = propertiesMap.entrySet();
                for (Map.Entry<?, ?> entry : entries) {
                    Object key = entry.getKey();
                    bindMap.put(NameUtils.decapitalize(NameUtils.dehyphenate(key.toString())), entry.getValue());
                }
                for (Argument<?> argument : constructorArguments) {
                    if (bindMap.containsKey(argument.getName())) {
                        Object converted = ConversionService.SHARED.convert(bindMap.get(argument.getName()), argument.getType(), ConversionContext.of(argument)).orElseThrow(() -> new ConversionErrorException(argument, context.getLastError().orElse(() -> new IllegalArgumentException("Value [" + bindMap.get(argument.getName()) + "] cannot be converted to type : " + argument.getType()))));
                        arguments.add(converted);
                    } else if (argument.isDeclaredNullable()) {
                        arguments.add(null);
                    } else {
                        context.reject(new ConversionErrorException(argument, () -> new IllegalArgumentException("No Value found for argument " + argument.getName())));
                    }
                }
                instance = introspection.instantiate(arguments.toArray());
            } else {
                instance = introspection.instantiate();
            }
            return instance;
        } catch (InstantiationException e) {
            return reflectionFallback.get();
        }
    }).orElseGet(reflectionFallback);
    return Optional.ofNullable(result);
}
Also used : java.util(java.util) Logger(org.slf4j.Logger) LoggerFactory(org.slf4j.LoggerFactory) ConversionErrorException(io.micronaut.core.convert.exceptions.ConversionErrorException) Constructor(java.lang.reflect.Constructor) Function(java.util.function.Function) Supplier(java.util.function.Supplier) NonNull(io.micronaut.core.annotation.NonNull) ConversionContext(io.micronaut.core.convert.ConversionContext) BeanIntrospection(io.micronaut.core.beans.BeanIntrospection) ArgumentUtils(io.micronaut.core.util.ArgumentUtils) Argument(io.micronaut.core.type.Argument) NameUtils(io.micronaut.core.naming.NameUtils) BeanIntrospector(io.micronaut.core.beans.BeanIntrospector) ConversionService(io.micronaut.core.convert.ConversionService) InstantiationException(io.micronaut.core.reflect.exception.InstantiationException) Argument(io.micronaut.core.type.Argument) Logger(org.slf4j.Logger) ConversionErrorException(io.micronaut.core.convert.exceptions.ConversionErrorException) InstantiationException(io.micronaut.core.reflect.exception.InstantiationException) NonNull(io.micronaut.core.annotation.NonNull)

Aggregations

ConversionContext (io.micronaut.core.convert.ConversionContext)6 ArgumentConversionContext (io.micronaut.core.convert.ArgumentConversionContext)4 ConversionService (io.micronaut.core.convert.ConversionService)4 Argument (io.micronaut.core.type.Argument)4 ConfigurationException (io.micronaut.context.exceptions.ConfigurationException)3 StringUtils (io.micronaut.core.util.StringUtils)3 Optional (java.util.Optional)3 BootstrapContextCompatible (io.micronaut.context.annotation.BootstrapContextCompatible)2 Environment (io.micronaut.context.env.Environment)2 AnnotationMetadata (io.micronaut.core.annotation.AnnotationMetadata)2 AnnotationValue (io.micronaut.core.annotation.AnnotationValue)2 Internal (io.micronaut.core.annotation.Internal)2 NonNull (io.micronaut.core.annotation.NonNull)2 Nullable (io.micronaut.core.annotation.Nullable)2 ConversionErrorException (io.micronaut.core.convert.exceptions.ConversionErrorException)2 Format (io.micronaut.core.convert.format.Format)2 NameUtils (io.micronaut.core.naming.NameUtils)2 Arrays (java.util.Arrays)2 Collection (java.util.Collection)2 Map (java.util.Map)2