Search in sources :

Example 1 with InvocationException

use of io.micronaut.core.reflect.exception.InvocationException in project micronaut-core by micronaut-projects.

the class StreamFunctionExecutor method execute.

/**
 * Execute the function with given context object.
 *
 * @param input   The {@link InputStream}
 * @param output  THe {@link OutputStream}
 * @param context The context object
 * @throws IOException If an error occurs
 */
protected void execute(InputStream input, OutputStream output, C context) throws IOException {
    final ApplicationContext applicationContext = buildApplicationContext(context);
    if (context == null) {
        context = (C) applicationContext;
    }
    final Environment env = startEnvironment(applicationContext);
    final String functionName = resolveFunctionName(env);
    if (functionName == null) {
        throw new InvocationException("No Function name configured. Set 'micronaut.function.name' in your Function configuration");
    }
    LocalFunctionRegistry localFunctionRegistry = applicationContext.getBean(LocalFunctionRegistry.class);
    ExecutableMethod<Object, Object> method = resolveFunction(localFunctionRegistry, functionName);
    Class<?> returnJavaType = method.getReturnType().getType();
    Argument[] requiredArguments = method.getArguments();
    int argCount = requiredArguments.length;
    Object result;
    Qualifier<Object> qualifier = Qualifiers.byName(functionName);
    Class<Object> functionType = method.getDeclaringType();
    BeanDefinition<Object> beanDefinition = applicationContext.getBeanDefinition(functionType, qualifier);
    Object bean = applicationContext.getBean(functionType, qualifier);
    List<Argument<?>> typeArguments = beanDefinition.getTypeArguments();
    try {
        switch(argCount) {
            case 0:
                result = method.invoke(bean);
                break;
            case 1:
                Argument arg = requiredArguments[0];
                if (!typeArguments.isEmpty()) {
                    arg = Argument.of(typeArguments.get(0).getType(), arg.getName());
                }
                Object value = decodeInputArgument(env, localFunctionRegistry, arg, input);
                result = method.invoke(bean, value);
                break;
            case 2:
                Argument firstArgument = requiredArguments[0];
                Argument secondArgument = requiredArguments[1];
                if (!typeArguments.isEmpty()) {
                    firstArgument = Argument.of(typeArguments.get(0).getType(), firstArgument.getName());
                }
                Object first = decodeInputArgument(env, localFunctionRegistry, firstArgument, input);
                Object second = decodeContext(env, secondArgument, context);
                result = method.invoke(bean, first, second);
                break;
            default:
                throw new InvocationException("Function [" + functionName + "] cannot be made executable.");
        }
        if (result != null) {
            encode(env, localFunctionRegistry, returnJavaType, result, output);
        }
    } finally {
        close();
    }
}
Also used : Argument(io.micronaut.core.type.Argument) LocalFunctionRegistry(io.micronaut.function.LocalFunctionRegistry) ApplicationContext(io.micronaut.context.ApplicationContext) InvocationException(io.micronaut.core.reflect.exception.InvocationException) Environment(io.micronaut.context.env.Environment)

Example 2 with InvocationException

use of io.micronaut.core.reflect.exception.InvocationException in project micronaut-core by micronaut-projects.

the class ReflectionUtils method setField.

/**
 * Sets the value of the given field reflectively.
 * @param field The field
 * @param instance The instance
 * @param value The value
 */
public static void setField(@NonNull Field field, @NonNull Object instance, @Nullable Object value) {
    try {
        ClassUtils.REFLECTION_LOGGER.debug("Reflectively setting field {} to value {} on object {}", field, value, value);
        field.setAccessible(true);
        field.set(instance, value);
    } catch (Throwable e) {
        throw new InvocationException("Exception occurred setting field [" + field + "]: " + e.getMessage(), e);
    }
}
Also used : InvocationException(io.micronaut.core.reflect.exception.InvocationException)

Example 3 with InvocationException

use of io.micronaut.core.reflect.exception.InvocationException in project micronaut-core by micronaut-projects.

the class StreamFunctionExecutor method encode.

/**
 * Encode and write to output stream.
 *
 * @param environment environment
 * @param registry local function registry
 * @param returnType return type as Class
 * @param result result object
 * @param output outputstream
 * @throws IOException input/output exception
 */
static void encode(Environment environment, LocalFunctionRegistry registry, Class returnType, Object result, OutputStream output) throws IOException {
    if (ClassUtils.isJavaLangType(returnType)) {
        if (result instanceof Byte) {
            output.write((Byte) result);
        } else if (result instanceof Boolean) {
            output.write(((Boolean) result) ? 1 : 0);
        } else if (result instanceof byte[]) {
            output.write((byte[]) result);
        } else {
            byte[] bytes = environment.convert(result.toString(), byte[].class).orElseThrow(() -> new InvocationException("Unable to convert result [" + result + "] for output stream"));
            output.write(bytes);
        }
    } else {
        if (result instanceof Writable) {
            Writable writable = (Writable) result;
            writable.writeTo(output, environment.getProperty(LocalFunctionRegistry.FUNCTION_CHARSET, Charset.class, StandardCharsets.UTF_8));
        } else {
            Optional<MediaTypeCodec> codec = registry instanceof MediaTypeCodecRegistry ? ((MediaTypeCodecRegistry) registry).findCodec(MediaType.APPLICATION_JSON_TYPE) : Optional.empty();
            if (codec.isPresent()) {
                codec.get().encode(result, output);
            } else {
                byte[] bytes = environment.convert(result, byte[].class).orElseThrow(() -> new InvocationException("Unable to convert result [" + result + "] for output stream"));
                output.write(bytes);
            }
        }
    }
}
Also used : InvocationException(io.micronaut.core.reflect.exception.InvocationException) Writable(io.micronaut.core.io.Writable) Charset(java.nio.charset.Charset) MediaTypeCodecRegistry(io.micronaut.http.codec.MediaTypeCodecRegistry) MediaTypeCodec(io.micronaut.http.codec.MediaTypeCodec)

Example 4 with InvocationException

use of io.micronaut.core.reflect.exception.InvocationException in project odi by eclipse-ee4j.

the class BuildTimeExtensionRegistry method runEnhancement.

private void runEnhancement(ClassElement originatingElement, ClassElement typeToEnhance, VisitorContext visitorContext, BuildCompatibleExtension extension, Method enhanceMethod) {
    try {
        final Class<?>[] parameterTypes = enhanceMethod.getParameterTypes();
        Object[] parameters = new Object[parameterTypes.length];
        final TypesImpl types = new TypesImpl(visitorContext);
        ExtensionParameter extensionParameter = null;
        for (int i = 0; i < parameterTypes.length; i++) {
            Class<?> parameterType = parameterTypes[i];
            if (DeclarationInfo.class.isAssignableFrom(parameterType)) {
                extensionParameter = newExtensionParameter(parameterType, i, extensionParameter);
            } else if (DeclarationConfig.class.isAssignableFrom(parameterType)) {
                extensionParameter = newExtensionParameter(parameterType, i, extensionParameter);
            } else if (parameterType == Messages.class) {
                parameters[i] = new MessagesImpl(visitorContext);
            } else if (parameterType == Types.class) {
                parameters[i] = types;
            } else {
                unsupportedParameter(originatingElement, visitorContext, extension, enhanceMethod, parameterType);
                return;
            }
        }
        if (extensionParameter != null) {
            final Class<?> type = extensionParameter.type;
            final ClassConfigImpl classConfig = new ClassConfigImpl(typeToEnhance, types, visitorContext);
            if (ClassConfig.class == type || ClassInfo.class == type) {
                parameters[extensionParameter.index] = ClassInfo.class == type ? classConfig.info() : classConfig;
                invokeExtensionMethod(extension, enhanceMethod, parameters);
            } else if (FieldConfig.class == type || FieldInfo.class == type) {
                final Collection<FieldConfig> fields = classConfig.fields();
                for (FieldConfig field : fields) {
                    parameters[extensionParameter.index] = FieldInfo.class == type ? field.info() : field;
                    invokeExtensionMethod(extension, enhanceMethod, parameters);
                }
            } else if (MethodConfig.class == type || MethodInfo.class == type) {
                final Collection<MethodConfig> methods = classConfig.methods();
                for (MethodConfig method : methods) {
                    parameters[extensionParameter.index] = MethodInfo.class == type ? method.info() : method;
                    invokeExtensionMethod(extension, enhanceMethod, parameters);
                }
            }
        }
    } catch (Throwable e) {
        if (e instanceof InvocationException) {
            e = e.getCause();
        }
        if (e instanceof InvocationTargetException) {
            e = e.getCause();
        }
        visitorContext.fail("Error running build time enhancement in method '" + enhanceMethod.getName() + "' of extension " + "[" + extension.getClass().getName() + "]: " + e.getMessage(), originatingElement);
    }
}
Also used : Types(jakarta.enterprise.inject.build.compatible.spi.Types) ClassConfig(jakarta.enterprise.inject.build.compatible.spi.ClassConfig) FieldConfig(jakarta.enterprise.inject.build.compatible.spi.FieldConfig) InvocationTargetException(java.lang.reflect.InvocationTargetException) DeclarationConfig(jakarta.enterprise.inject.build.compatible.spi.DeclarationConfig) MethodConfig(jakarta.enterprise.inject.build.compatible.spi.MethodConfig) InvocationException(io.micronaut.core.reflect.exception.InvocationException) Collection(java.util.Collection) MethodInfo(jakarta.enterprise.lang.model.declarations.MethodInfo) FieldInfo(jakarta.enterprise.lang.model.declarations.FieldInfo) ClassInfo(jakarta.enterprise.lang.model.declarations.ClassInfo)

Aggregations

InvocationException (io.micronaut.core.reflect.exception.InvocationException)4 ApplicationContext (io.micronaut.context.ApplicationContext)1 Environment (io.micronaut.context.env.Environment)1 Writable (io.micronaut.core.io.Writable)1 Argument (io.micronaut.core.type.Argument)1 LocalFunctionRegistry (io.micronaut.function.LocalFunctionRegistry)1 MediaTypeCodec (io.micronaut.http.codec.MediaTypeCodec)1 MediaTypeCodecRegistry (io.micronaut.http.codec.MediaTypeCodecRegistry)1 ClassConfig (jakarta.enterprise.inject.build.compatible.spi.ClassConfig)1 DeclarationConfig (jakarta.enterprise.inject.build.compatible.spi.DeclarationConfig)1 FieldConfig (jakarta.enterprise.inject.build.compatible.spi.FieldConfig)1 MethodConfig (jakarta.enterprise.inject.build.compatible.spi.MethodConfig)1 Types (jakarta.enterprise.inject.build.compatible.spi.Types)1 ClassInfo (jakarta.enterprise.lang.model.declarations.ClassInfo)1 FieldInfo (jakarta.enterprise.lang.model.declarations.FieldInfo)1 MethodInfo (jakarta.enterprise.lang.model.declarations.MethodInfo)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Charset (java.nio.charset.Charset)1 Collection (java.util.Collection)1