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;
}
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);
}
}
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));
}
}
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();
}
});
}
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);
}
Aggregations