Search in sources :

Example 1 with TypeConverter

use of io.micronaut.core.convert.TypeConverter 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 2 with TypeConverter

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

the class DefaultApplicationContext method initializeTypeConverters.

/**
 * @param beanContext The bean context
 */
protected void initializeTypeConverters(BeanContext beanContext) {
    Collection<BeanRegistration<TypeConverter>> typeConverters = beanContext.getBeanRegistrations(TypeConverter.class);
    for (BeanRegistration<TypeConverter> typeConverterRegistration : typeConverters) {
        TypeConverter typeConverter = typeConverterRegistration.getBean();
        List<Argument<?>> typeArguments = typeConverterRegistration.getBeanDefinition().getTypeArguments(TypeConverter.class);
        if (typeArguments.size() == 2) {
            Class source = typeArguments.get(0).getType();
            Class target = typeArguments.get(1).getType();
            if (source != null && target != null && !(source == Object.class && target == Object.class)) {
                getConversionService().addConverter(source, target, typeConverter);
            }
        }
    }
    Collection<TypeConverterRegistrar> registrars = beanContext.getBeansOfType(TypeConverterRegistrar.class);
    for (TypeConverterRegistrar registrar : registrars) {
        registrar.register(conversionService);
    }
}
Also used : TypeConverter(io.micronaut.core.convert.TypeConverter) Argument(io.micronaut.core.type.Argument) TypeConverterRegistrar(io.micronaut.core.convert.TypeConverterRegistrar)

Aggregations

TypeConverter (io.micronaut.core.convert.TypeConverter)2 TypeConverterRegistrar (io.micronaut.core.convert.TypeConverterRegistrar)2 BootstrapContextCompatible (io.micronaut.context.annotation.BootstrapContextCompatible)1 Requires (io.micronaut.context.annotation.Requires)1 Environment (io.micronaut.context.env.Environment)1 TypeHint (io.micronaut.core.annotation.TypeHint)1 ConversionContext (io.micronaut.core.convert.ConversionContext)1 ConversionService (io.micronaut.core.convert.ConversionService)1 Format (io.micronaut.core.convert.format.Format)1 Argument (io.micronaut.core.type.Argument)1 StringUtils (io.micronaut.core.util.StringUtils)1 Singleton (jakarta.inject.Singleton)1 java.time (java.time)1 DateTimeFormatter (java.time.format.DateTimeFormatter)1 DateTimeParseException (java.time.format.DateTimeParseException)1 TemporalAccessor (java.time.temporal.TemporalAccessor)1 TemporalAmount (java.time.temporal.TemporalAmount)1 Optional (java.util.Optional)1 BiFunction (java.util.function.BiFunction)1 Matcher (java.util.regex.Matcher)1