Example usage for java.lang.reflect InvocationHandler invoke

List of usage examples for java.lang.reflect InvocationHandler invoke

Introduction

In this page you can find the example usage for java.lang.reflect InvocationHandler invoke.

Prototype

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable;

Source Link

Document

Processes a method invocation on a proxy instance and returns the result.

Usage

From source file:io.dyn.core.handler.GuardedHandlerMethodInvoker.java

@Override
public Object invoke(HandlerMethod method, Object handler, EvaluationContext evalCtx, Object... args)
        throws Exception {
    if (null == evalCtx) {
        StandardEvaluationContext ec = new StandardEvaluationContext();
        if (null != applicationContext) {
            ec.setBeanResolver(new BeanFactoryResolver(applicationContext));
        }// w  ww.j  a va 2  s.co m
        evalCtx = ec;
    }

    HandlerMethodArgument[] handlerMethodArguments = method.arguments();
    int argc = handlerMethodArguments.length;
    Object[] argv = new Object[argc];
    for (int i = 0; i < argc; i++) {
        HandlerMethodArgument handlerArg = handlerMethodArguments[i];
        if (ClassUtils.isAssignable(EvaluationContext.class, handlerArg.targetType())) {
            argv[i] = evalCtx;
        } else if (null != handlerArg.valueExpression()) {
            try {
                argv[i] = handlerArg.valueExpression().getValue(evalCtx, handlerArg.targetType());
            } catch (SpelEvaluationException e) {
                argv[i] = null;
            }
        } else {
            try {
                Object o = args[handlerArg.index()];
                if (ClassUtils.isAssignable(handlerArg.targetType(), o.getClass())) {
                    argv[i] = o;
                } else if (null != customConversionService
                        && customConversionService.canConvert(o.getClass(), handlerArg.targetType())) {
                    argv[i] = customConversionService.convert(o, handlerArg.targetType());
                } else {
                    argv[i] = Sys.DEFAULT_CONVERSION_SERVICE.convert(o, handlerArg.targetType());
                }
            } catch (IndexOutOfBoundsException e) {
            }
        }
        evalCtx.setVariable(handlerArg.name(), argv[i]);
    }

    InvocationHandler invoker = method.invocationHandler();
    Method m = method.methodToInvoke();
    if (null != method.guard()) {
        if (method.guard().checkGuard(null, evalCtx)) {
            if (null != invoker) {
                try {
                    invoker.invoke(handler, m, argv);
                } catch (Throwable throwable) {
                    throw new IllegalStateException(throwable);
                }
            } else {
                return m.invoke(handler, argv);
            }
        } else {
            //LOG.debug("Guard expression %s failed", method.guard().expression().getExpressionString());
        }
    } else {
        if (null != invoker) {
            try {
                return invoker.invoke(handler, m, argv);
            } catch (Throwable throwable) {
                throw new IllegalStateException(throwable);
            }
        } else {
            return m.invoke(handler, argv);
        }
    }

    return null;
}

From source file:com.p5solutions.core.utils.ReflectionUtility.java

/**
 * Invoke.//  w ww .j ava 2  s  . c om
 * 
 * @param <O>
 *          the generic type
 * @param <I>
 *          the generic type
 * @param object
 *          the object
 * @param method
 *          the method
 * @param ignoreAccess
 *          the ignore access
 * @param args
 *          the args
 * @return the object
 */
@SuppressWarnings("unchecked")
public static <O, I> O invokeWithAccessWithArguments(I object, Method method, boolean ignoreAccess,
        Object... args) {
    if (object == null) {
        throw new RuntimeException("Object cannot be null when invoking its methods");
    }

    Object returnObject = null;
    Class<?> clazz = object.getClass();

    try {

        /* call the method */
        if (method != null) {
            if (AopUtils.isAopProxy(object)) {
                InvocationHandler handler = Proxy.getInvocationHandler(object);
                returnObject = handler.invoke(object, method, args);
            } else {
                boolean isAccessible = method.isAccessible();
                try {
                    if (!isAccessible && ignoreAccess) {
                        method.setAccessible(true);
                    }
                    returnObject = method.invoke(object, args);
                } finally {
                    if (ignoreAccess) {
                        method.setAccessible(isAccessible);
                    }
                }
            }
        } else {
            throw new RuntimeException("Method cannot be null");
        }
    } catch (Throwable e) {
        // get the target class if its a proxy
        clazz = AopUtils.getTargetClass(object);

        /* Logger that is available to subclasses */
        Log logger = LogFactory.getLog(clazz);
        // logger.error("Unable to invoke method " + method.getName() + " within "
        // + clazz.getCanonicalName() + "\n"
        // + getStackTrace(e));

        throw new RuntimeException(e);
    }

    return (O) returnObject;
}

From source file:org.apache.hadoop.hbase.client.coprocessor.Batch.java

/**
 * Creates a new {@link Batch.Call} instance that invokes a method
 * with the given parameters and returns the result.
 *
 * @param method the method reference to invoke
 * @param args zero or more arguments to be passed to the method
 * @param <T> the class type of the protocol implementation being invoked
 * @param <R> the return type for the method call
 * @return a {@code Callable} instance that will invoke the given method and
 * return the results/*from w ww  .  j  a va 2s  .c  om*/
 * @see org.apache.hadoop.hbase.client.HTable#coprocessorExec(Class, byte[], byte[], org.apache.hadoop.hbase.client.coprocessor.Batch.Call, org.apache.hadoop.hbase.client.coprocessor.Batch.Callback)
 */
public static <T extends CoprocessorProtocol, R> Call<T, R> forMethod(final Method method,
        final Object... args) {
    return new Call<T, R>() {
        public R call(T instance) throws IOException {
            try {
                if (Proxy.isProxyClass(instance.getClass())) {
                    InvocationHandler invoker = Proxy.getInvocationHandler(instance);
                    return (R) invoker.invoke(instance, method, args);
                } else {
                    LOG.warn("Non proxied invocation of method '" + method.getName() + "'!");
                    return (R) method.invoke(instance, args);
                }
            } catch (IllegalAccessException iae) {
                throw new IOException("Unable to invoke method '" + method.getName() + "'", iae);
            } catch (InvocationTargetException ite) {
                throw new IOException(ite.toString(), ite);
            } catch (Throwable t) {
                throw new IOException(t.toString(), t);
            }
        }
    };
}

From source file:org.hyperic.hq.agent.client.AbstractCommandsClient.java

/**
 * Retrieve a synchronous proxy to a remote service.
 * //from  w  w  w  .  j  a v  a 2  s . c  om
 * @param serviceInterface The service interface. It is expected that all 
 *                         service interface operations throw an 
 *                         {@link AgentRemoteException}.
 * @return The synchronous proxy.
 * @throws AgentConnectionException if there is an error creating the proxy.
 * @throws IllegalArgumentException if any of the service interface operations 
 *                                  do not throw an {@link AgentRemoteException}.
 */
protected final Object getSynchronousProxy(Class serviceInterface) throws AgentConnectionException {

    TransportUtils.assertOperationsThrowException(serviceInterface, AgentRemoteException.class);

    Object proxy;

    try {
        proxy = _factory.createSyncService(_agent, serviceInterface);
    } catch (Exception e) {
        _log.error("Error creating proxy to remote service.", e);
        throw new AgentConnectionException("Error creating proxy to remote service.", e);
    }

    if (_agent.isUnidirectional()) {
        // For unidirectional agents, if a synchronous request blocks for 
        // more than the specified timeout (see ResponseHandler#RESPONSE_WAIT_TIME) 
        // waiting for the response, then a TimeoutException is thrown. This 
        // exception will be wrapped in an HQ-specific checked exception 
        // (AgentRemoteException).

        final InvocationHandler handler = Proxy.getInvocationHandler(proxy);

        InvocationHandler timeoutExceptionHandler = new InvocationHandler() {

            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                try {
                    return handler.invoke(proxy, method, args);
                } catch (TimeoutException e) {
                    throw new AgentRemoteException("Timeout occurred waiting on agent response.", e);
                }
            }

        };

        proxy = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[] { serviceInterface }, timeoutExceptionHandler);
    }

    return proxy;
}

From source file:org.wso2.carbon.apimgt.everywhere.webapp.publisher.APIPublisherLifecycleListener.java

private static void showAPIinfo(ServletContext context, Class<?> clazz, Class<Path> pathClazz) {

    Annotation rootContectAnno = clazz.getAnnotation(pathClazz);

    log.info("======================== API INFO ======================= ");
    if (context != null) {
        log.info("Application Context root = " + context.getContextPath());
    }//from  w w w. j a  v a2  s . c  o  m

    if (rootContectAnno != null) {
        InvocationHandler handler = Proxy.getInvocationHandler(rootContectAnno);
        Method[] methods = pathClazz.getMethods();
        String root;

        try {
            root = (String) handler.invoke(rootContectAnno, methods[0], null);

            log.info("API Root  Context = " + root);
            log.info("API Sub Context List ");
            for (Method method : clazz.getDeclaredMethods()) {
                Annotation methodContextAnno = method.getAnnotation(pathClazz);
                if (methodContextAnno != null) {
                    InvocationHandler methodHandler = Proxy.getInvocationHandler(methodContextAnno);
                    String subCtx = (String) methodHandler.invoke(methodContextAnno, methods[0], null);
                    ;
                    log.info("  " + root + "/" + subCtx);
                }
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

        log.info("===================================================== ");
        //todo log.info summery of the api context info resulting from the scan
    }
}

From source file:org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util.AnnotationProcessor.java

private Map<String, ApiScope> processAPIScopes(Annotation annotation) throws Throwable {
    Map<String, ApiScope> scopes = new HashMap<>();

    InvocationHandler methodHandler = Proxy.getInvocationHandler(annotation);
    Annotation[] annotatedScopes = (Annotation[]) methodHandler.invoke(annotation,
            scopesClass.getMethod(ANNOTATIONS_SCOPES, null), null);

    ApiScope scope;/*  w ww. j a v a 2s.com*/
    String permissions[];
    StringBuilder aggregatedPermissions;
    for (int i = 0; i < annotatedScopes.length; i++) {
        aggregatedPermissions = new StringBuilder();
        methodHandler = Proxy.getInvocationHandler(annotatedScopes[i]);
        scope = new ApiScope();
        scope.setName(invokeMethod(scopeClass.getMethod(SWAGGER_ANNOTATIONS_PROPERTIES_NAME),
                annotatedScopes[i], STRING));
        scope.setDescription(invokeMethod(scopeClass.getMethod(SWAGGER_ANNOTATIONS_PROPERTIES_DESCRIPTION),
                annotatedScopes[i], STRING));
        scope.setKey(invokeMethod(scopeClass.getMethod(SWAGGER_ANNOTATIONS_PROPERTIES_KEY), annotatedScopes[i],
                STRING));
        permissions = (String[]) methodHandler.invoke(annotatedScopes[i],
                scopeClass.getMethod(SWAGGER_ANNOTATIONS_PROPERTIES_PERMISSIONS, null), null);
        for (String permission : permissions) {
            aggregatedPermissions.append(PERMISSION_PREFIX);
            aggregatedPermissions.append(permission);
            aggregatedPermissions.append(" ");
        }
        scope.setRoles(aggregatedPermissions.toString().trim());
        scopes.put(scope.getKey(), scope);
    }
    return scopes;
}

From source file:org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util.AnnotationProcessor.java

/**
 * Iterate API annotation and build API Configuration
 *
 * @param annotation reading @SwaggerDefinition annotation
 * @return APIResourceConfiguration which compose with an API information which has its name, context,version,and tags
 * @throws Throwable/* w  w  w.j  av a 2s .c o m*/
 */
private APIResourceConfiguration processAPIAnnotation(Annotation annotation) throws Throwable {
    InvocationHandler methodHandler = Proxy.getInvocationHandler(annotation);
    Annotation info = (Annotation) methodHandler.invoke(annotation,
            apiClazz.getMethod(SWAGGER_ANNOTATIONS_INFO, null), null);
    Annotation[] tags = (Annotation[]) methodHandler.invoke(annotation,
            apiClazz.getMethod(SWAGGER_ANNOTATIONS_TAGS, null), null);
    String[] tagNames = new String[tags.length];
    for (int i = 0; i < tags.length; i++) {
        methodHandler = Proxy.getInvocationHandler(tags[i]);
        tagNames[i] = (String) methodHandler.invoke(tags[i],
                tagClass.getMethod(SWAGGER_ANNOTATIONS_PROPERTIES_NAME, null), null);
    }
    methodHandler = Proxy.getInvocationHandler(info);
    String version = (String) methodHandler.invoke(info,
            infoClass.getMethod(SWAGGER_ANNOTATIONS_PROPERTIES_VERSION, null), null);
    if ("".equals(version))
        return null;
    Annotation[] apiInfo = (Annotation[]) methodHandler.invoke(info,
            infoClass.getMethod(SWAGGER_ANNOTATIONS_EXTENSIONS, null), null);
    methodHandler = Proxy.getInvocationHandler(apiInfo[0]);
    Annotation[] properties = (Annotation[]) methodHandler.invoke(apiInfo[0],
            extensionClass.getMethod(SWAGGER_ANNOTATIONS_PROPERTIES, null), null);
    APIResourceConfiguration apiResourceConfig = new APIResourceConfiguration();
    for (Annotation property : properties) {
        methodHandler = Proxy.getInvocationHandler(property);
        String key = (String) methodHandler.invoke(property,
                extensionPropertyClass.getMethod(SWAGGER_ANNOTATIONS_PROPERTIES_NAME, null), null);
        String value = (String) methodHandler.invoke(property,
                extensionPropertyClass.getMethod(SWAGGER_ANNOTATIONS_PROPERTIES_VALUE, null), null);
        if ("".equals(key))
            return null;
        switch (key) {
        case SWAGGER_ANNOTATIONS_PROPERTIES_NAME:
            if ("".equals(value))
                return null;
            apiResourceConfig.setName(value);
            break;
        case SWAGGER_ANNOTATIONS_PROPERTIES_CONTEXT:
            if ("".equals(value))
                return null;
            apiResourceConfig.setContext(value);
            break;
        default:
            break;
        }
    }
    apiResourceConfig.setVersion(version);
    apiResourceConfig.setTags(tagNames);
    return apiResourceConfig;
}

From source file:org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util.AnnotationProcessor.java

/**
 * When an annotation and method is passed, this method invokes that executes said method against the annotation
 *
 * @param method//from  w ww. j  a v  a  2  s.  co m
 * @param annotation
 * @param returnType
 * @return
 * @throws Throwable
 */
private String invokeMethod(Method method, Annotation annotation, String returnType) throws Throwable {
    InvocationHandler methodHandler = Proxy.getInvocationHandler(annotation);
    switch (returnType) {
    case STRING:
        return (String) methodHandler.invoke(annotation, method, null);
    case STRING_ARR:
        return ((String[]) methodHandler.invoke(annotation, method, null))[0];
    default:
        return null;
    }
}

From source file:org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util.AnnotationProcessor.java

private ApiScope getScope(Annotation currentMethod) throws Throwable {
    InvocationHandler methodHandler = Proxy.getInvocationHandler(currentMethod);
    Annotation[] extensions = (Annotation[]) methodHandler.invoke(currentMethod,
            apiOperation.getMethod(SWAGGER_ANNOTATIONS_EXTENSIONS, null), null);
    if (extensions != null) {
        methodHandler = Proxy.getInvocationHandler(extensions[0]);
        Annotation[] properties = (Annotation[]) methodHandler.invoke(extensions[0],
                extensionClass.getMethod(SWAGGER_ANNOTATIONS_PROPERTIES, null), null);
        String scopeKey;//  www  .j a v  a2 s. com
        String propertyName;
        for (Annotation property : properties) {
            methodHandler = Proxy.getInvocationHandler(property);
            propertyName = (String) methodHandler.invoke(property,
                    extensionPropertyClass.getMethod(SWAGGER_ANNOTATIONS_PROPERTIES_NAME, null), null);
            if (ANNOTATIONS_SCOPE.equals(propertyName)) {
                scopeKey = (String) methodHandler.invoke(property,
                        extensionPropertyClass.getMethod(SWAGGER_ANNOTATIONS_PROPERTIES_VALUE, null), null);
                if (scopeKey.isEmpty()) {
                    return null;
                }
                return apiScopes.get(scopeKey);
            }
        }
    }
    return null;
}

From source file:org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util.AnnotationUtil.java

/**
 * When an annotation and method is passed, this method invokes that executes said method against the annotation
 *//*from w w w .j a  va  2  s.  c  om*/
private String[] invokeMethod(Method method, Annotation annotation) throws Throwable {
    InvocationHandler methodHandler = Proxy.getInvocationHandler(annotation);
    return ((String[]) methodHandler.invoke(annotation, method, null));
}