Search in sources :

Example 1 with ConversionErrorException

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

the class JsonBeanPropertyBinder method bind.

@Override
public <T2> T2 bind(T2 object, Set<? extends Map.Entry<? extends CharSequence, Object>> source) throws ConversionErrorException {
    try {
        JsonNode objectNode = buildSourceObjectNode(source);
        jsonMapper.updateValueFromTree(object, objectNode);
    } catch (Exception e) {
        throw newConversionError(object, e);
    }
    return object;
}
Also used : JsonNode(io.micronaut.json.tree.JsonNode) ConversionErrorException(io.micronaut.core.convert.exceptions.ConversionErrorException) IOException(java.io.IOException)

Example 2 with ConversionErrorException

use of io.micronaut.core.convert.exceptions.ConversionErrorException 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)

Example 3 with ConversionErrorException

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

the class DefaultExecutableBinder method bind.

@Override
public <T, R> BoundExecutable<T, R> bind(Executable<T, R> target, ArgumentBinderRegistry<S> registry, S source) throws UnsatisfiedArgumentException {
    Argument[] arguments = target.getArguments();
    Object[] boundArguments = new Object[arguments.length];
    for (int i = 0; i < arguments.length; i++) {
        Argument<?> argument = arguments[i];
        if (preBound.containsKey(argument)) {
            boundArguments[i] = preBound.get(argument);
        } else {
            Optional<? extends ArgumentBinder<?, S>> argumentBinder = registry.findArgumentBinder(argument, source);
            if (argumentBinder.isPresent()) {
                ArgumentBinder<?, S> binder = argumentBinder.get();
                ArgumentConversionContext conversionContext = ConversionContext.of(argument);
                ArgumentBinder.BindingResult<?> bindingResult = binder.bind(conversionContext, source);
                if (!bindingResult.isPresentAndSatisfied()) {
                    if (argument.isNullable()) {
                        boundArguments[i] = null;
                    } else {
                        final Optional<ConversionError> lastError = conversionContext.getLastError();
                        if (lastError.isPresent()) {
                            throw new ConversionErrorException(argument, lastError.get());
                        } else {
                            throw new UnsatisfiedArgumentException(argument);
                        }
                    }
                } else {
                    boundArguments[i] = bindingResult.get();
                }
            } else {
                throw new UnsatisfiedArgumentException(argument);
            }
        }
    }
    return new BoundExecutable<T, R>() {

        @Override
        public Executable<T, R> getTarget() {
            return target;
        }

        @Override
        public R invoke(T instance) {
            return target.invoke(instance, getBoundArguments());
        }

        @Override
        public Object[] getBoundArguments() {
            return boundArguments;
        }
    };
}
Also used : UnsatisfiedArgumentException(io.micronaut.core.bind.exceptions.UnsatisfiedArgumentException) Argument(io.micronaut.core.type.Argument) ConversionError(io.micronaut.core.convert.ConversionError) ConversionErrorException(io.micronaut.core.convert.exceptions.ConversionErrorException) ArgumentConversionContext(io.micronaut.core.convert.ArgumentConversionContext)

Example 4 with ConversionErrorException

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

the class StreamFunctionExecutor method doConvertInput.

private Object doConvertInput(ConversionService<?> conversionService, Argument<?> arg, Object object) {
    ArgumentConversionContext conversionContext = ConversionContext.of(arg);
    Optional<?> convert = conversionService.convert(object, conversionContext);
    if (convert.isPresent()) {
        return convert.get();
    } else {
        Optional<ConversionError> lastError = conversionContext.getLastError();
        if (lastError.isPresent()) {
            throw new ConversionErrorException(arg, lastError.get());
        }
    }
    return null;
}
Also used : ArgumentConversionContext(io.micronaut.core.convert.ArgumentConversionContext) ConversionError(io.micronaut.core.convert.ConversionError) ConversionErrorException(io.micronaut.core.convert.exceptions.ConversionErrorException)

Example 5 with ConversionErrorException

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

the class DatabindPropertyBinderExceptionHandler method toConversionError.

@Override
public Optional<ConversionErrorException> toConversionError(@Nullable Object object, @NonNull Exception e) {
    if (e instanceof InvalidFormatException) {
        InvalidFormatException ife = (InvalidFormatException) e;
        Object originalValue = ife.getValue();
        ConversionError conversionError = new ConversionError() {

            @Override
            public Exception getCause() {
                return e;
            }

            @Override
            public Optional<Object> getOriginalValue() {
                return Optional.ofNullable(originalValue);
            }
        };
        Class<?> type = object != null ? object.getClass() : Object.class;
        List<JsonMappingException.Reference> path = ife.getPath();
        String name;
        if (!path.isEmpty()) {
            name = path.get(path.size() - 1).getFieldName();
        } else {
            name = NameUtils.decapitalize(type.getSimpleName());
        }
        return Optional.of(new ConversionErrorException(Argument.of(ife.getTargetType(), name), conversionError));
    }
    return Optional.empty();
}
Also used : ConversionError(io.micronaut.core.convert.ConversionError) ConversionErrorException(io.micronaut.core.convert.exceptions.ConversionErrorException) InvalidFormatException(com.fasterxml.jackson.databind.exc.InvalidFormatException)

Aggregations

ConversionErrorException (io.micronaut.core.convert.exceptions.ConversionErrorException)12 ConversionError (io.micronaut.core.convert.ConversionError)7 Argument (io.micronaut.core.type.Argument)6 ArgumentConversionContext (io.micronaut.core.convert.ArgumentConversionContext)4 ConversionContext (io.micronaut.core.convert.ConversionContext)3 Function (java.util.function.Function)3 AnnotationMetadata (io.micronaut.core.annotation.AnnotationMetadata)2 NonNull (io.micronaut.core.annotation.NonNull)2 Nullable (io.micronaut.core.annotation.Nullable)2 ConversionService (io.micronaut.core.convert.ConversionService)2 Format (io.micronaut.core.convert.format.Format)2 ArrayUtils (io.micronaut.core.util.ArrayUtils)2 CollectionUtils (io.micronaut.core.util.CollectionUtils)2 StringUtils (io.micronaut.core.util.StringUtils)2 URI (java.net.URI)2 Collection (java.util.Collection)2 Optional (java.util.Optional)2 Subscription (org.reactivestreams.Subscription)2 InvalidFormatException (com.fasterxml.jackson.databind.exc.InvalidFormatException)1 InterceptedMethod (io.micronaut.aop.InterceptedMethod)1