Example usage for java.lang.reflect InvocationHandler InvocationHandler

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

Introduction

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

Prototype

InvocationHandler

Source Link

Usage

From source file:com.sourcesense.alfresco.opensso.MockAlfrescoApplicationContext.java

@Override
public Object getBean(String name) throws BeansException {
    try {/* w ww .j a v a2  s . c  o  m*/
        Class clazz = beans.get(name);
        Object newProxyInstance = Proxy.newProxyInstance(getClassLoader(), new Class[] { clazz },
                new InvocationHandler() {
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        return null;
                    }
                });
        return newProxyInstance;
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.futureplatforms.kirin.internal.attic.ProxyGenerator.java

public <T> T javascriptProxyForRequest(final JSONObject obj, Class<T> baseInterface, Class<?>... otherClasses) {
    Class<?>[] allClasses;/*from   www . j  a  v a2  s  . com*/

    if (otherClasses.length == 0) {
        allClasses = new Class[] { baseInterface };
    } else {
        allClasses = new Class[otherClasses.length + 1];
        allClasses[0] = baseInterface;
        System.arraycopy(otherClasses, 0, allClasses, 1, otherClasses.length);
    }
    InvocationHandler h = new InvocationHandler() {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            String methodName = method.getName();
            Class<?> returnType = method.getReturnType();

            if (obj.has(methodName)) {
                String id = obj.optString("__id");

                if (id != null) {
                    // so assume it's a callback
                    if (void.class.equals(returnType)) {
                        mKirinHelper.jsCallbackObjectMethod(id, methodName, (Object[]) args);
                    } else {
                        return mKirinHelper.jsSyncCallbackObjectMethod(id, returnType, methodName,
                                (Object[]) args);
                    }
                }
                return null;
            }

            String propertyName = findGetter(methodName);
            if (propertyName != null) {
                return handleGetter(obj, returnType, propertyName);
            }

            if ("toString".equals(methodName) && String.class.equals(returnType)) {
                return obj.toString();
            }

            return null;
        }
    };

    Object proxy = Proxy.newProxyInstance(baseInterface.getClassLoader(), allClasses, h);
    return baseInterface.cast(proxy);
}

From source file:org.dimitrovchi.conf.service.ServiceParameterUtils.java

@SuppressWarnings({ "element-type-mismatch" })
public static <P> P mergeAnnotationParameters() {
    final AnnotationParameters aParameters = annotationParameters();
    return (P) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
            aParameters.annotations.toArray(new Class[aParameters.annotations.size()]),
            new InvocationHandler() {
                @Override//from  w  w  w.  j a  v a2  s  . c  o  m
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if ("toString".equals(method.getName())) {
                        return reflectToString(aParameters.topCaller.getSimpleName(), proxy);
                    }
                    final Class<?> annotationClass = method.getDeclaringClass();
                    final List<Annotation> annotations = aParameters.annotationMap.containsKey(annotationClass)
                            ? aParameters.annotationMap.get(annotationClass)
                            : Collections.<Annotation>emptyList();
                    for (final Annotation annotation : annotations) {
                        final Object value = method.invoke(annotation, args);
                        if (!Objects.deepEquals(method.getDefaultValue(), value)) {
                            return value;
                        }
                    }
                    return method.getDefaultValue();
                }
            });
}

From source file:com.nineteendrops.tracdrops.client.core.TracInvocationObjectFactoryImpl.java

public Object newInstance(ClassLoader classLoader, final Class aClass, final String remoteName) {

    return Proxy.newProxyInstance(classLoader, new Class[] { aClass }, new InvocationHandler() {

        public Object invoke(Object pProxy, Method pMethod, Object[] pArgs) throws Throwable {

            String tracClassName = Utils.findTracClassName(aClass);
            if (tracClassName == null) {
                throw new TracException(
                        MessageUtils.registerErrorLog(log, "core.no.trac.classname.found", aClass.getName()));
            }/*www .  ja v  a  2s .  com*/

            TracClassMethod tracClassMethodMetadata = Utils.getTracClassMethodAnnotation(pMethod);

            String methodName = Utils.buildTracMethodNameInvocation(tracClassName, tracClassMethodMetadata);

            Object result = null;
            try {

                result = getClient().execute(methodName, pArgs);

            } catch (XmlRpcInvocationException e) {
                throw new TracException(MessageUtils.registerErrorLog(log,
                        "core.invocation.factory.invocation.exception", e.getMessage()), e);

            } catch (XmlRpcException e) {
                throw new TracException(MessageUtils.registerErrorLog(log,
                        "core.invocation.factory.xmlrpc.exception", e.getMessage()), e);
            } catch (Throwable e) {
                throw new TracException(MessageUtils.registerErrorLog(log,
                        "core.invocation.factory.unknown.exception", e.getMessage()), e);
            }

            Class returnType = tracClassMethodMetadata.tracReturnType();
            if (returnType == Object.class) {
                returnType = pMethod.getReturnType();
            }

            TypeConverter typeConverter = typeConverterFactory.getTypeConverter(returnType);
            return typeConverter.convert(result);

        }
    });

}

From source file:org.opendaylight.ovsdb.lib.jsonrpc.JsonRpcEndpoint.java

public <T> T getClient(final Object context, Class<T> klazz) {

    return Reflection.newProxy(klazz, new InvocationHandler() {
        @Override//from w  w w  .  jav a  2s .  c om
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (method.getName().equals(OvsdbRPC.REGISTER_CALLBACK_METHOD)) {
                if ((args == null) || args.length != 1 || !(args[0] instanceof OvsdbRPC.Callback)) {
                    return false;
                }
                requestCallbacks.put(context, (OvsdbRPC.Callback) args[0]);
                return true;
            }

            JsonRpc10Request request = new JsonRpc10Request(UUID.randomUUID().toString());
            request.setMethod(method.getName());

            if (args != null && args.length != 0) {
                List<Object> params = null;

                if (args.length == 1) {
                    if (args[0] instanceof Params) {
                        params = ((Params) args[0]).params();
                    } else if (args[0] instanceof List) {
                        params = (List<Object>) args[0];
                    }

                    if (params == null) {
                        throw new UnsupportedArgumentException("do not understand this argument yet");
                    }
                    request.setParams(params);
                }
            }

            String requestString = objectMapper.writeValueAsString(request);
            logger.trace("getClient Request : {}", requestString);

            SettableFuture<Object> sf = SettableFuture.create();
            methodContext.put(request.getId(), new CallContext(request, method, sf));

            nettyChannel.writeAndFlush(requestString);

            return sf;
        }
    });
}

From source file:org.libreplan.web.common.ExceptionCatcherProxy.java

public T applyTo(final T instance) {
    return interfaceKlass.cast(Proxy.newProxyInstance(instance.getClass().getClassLoader(),
            new Class[] { interfaceKlass }, new InvocationHandler() {

                @Override/*from  w ww  .  ja va2 s .co m*/
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    Object result;
                    try {
                        result = method.invoke(instance, args);
                        return result;
                    } catch (InvocationTargetException e) {
                        Throwable cause = e.getCause();
                        if (!handled(cause)) {
                            throw cause;
                        }
                        // we don't know what would be the result, so we
                        // return null
                        return null;
                    }
                }

            }));
}

From source file:com.nineteendrops.tracdrops.client.core.TracClientObjectFactoryImpl.java

protected Object newInstance(ClassLoader classLoader, final Class aClass, final String remoteName) {

    return Proxy.newProxyInstance(classLoader, new Class[] { aClass }, new InvocationHandler() {

        public Object invoke(Object pProxy, Method pMethod, Object[] pArgs) throws Throwable {

            String tracClassName = Utils.findTracClassName(aClass);
            if (tracClassName == null) {
                throw new TracException(
                        MessageUtils.registerErrorLog(log, "core.no.trac.classname.found", aClass.getName()));
            }//from   w  w w .ja  va  2  s  . co m

            TracClassMethod tracClassMethodMetadata = Utils.getTracClassMethodAnnotation(pMethod);

            String tracClassMethodName = Utils.buildTracMethodNameInvocation(tracClassName,
                    tracClassMethodMetadata);

            Class returnDecoder = tracClassMethodMetadata.returnDecoder();

            ArrayList encodedPARGS = new ArrayList();
            Annotation[][] parameterAnnotations = pMethod.getParameterAnnotations();

            int parameterOrder = 0;
            ArrayList keptParametersForDecoder = new ArrayList();
            for (Annotation[] annotations : parameterAnnotations) {

                Object currentParameter = pArgs[parameterOrder];
                boolean skipInvocationRegistration = false;
                for (Annotation annotation : annotations) {
                    if (annotation instanceof TracParameterEncoder) {
                        Class encoder = ((TracParameterEncoder) annotation).encoder();
                        ParameterEncoder parameterEncoder = (ParameterEncoder) encoder.newInstance();
                        currentParameter = parameterEncoder.encode(tracProperties, currentParameter);
                    }
                    if (annotation instanceof TracParameterPolicy) {
                        TracParameterPolicy tracParameterPolicy = (TracParameterPolicy) annotation;
                        if (tracParameterPolicy.keptForDecoder()) {
                            keptParametersForDecoder.add(currentParameter);
                        }
                        if (tracParameterPolicy.removeFromInvocation()) {
                            skipInvocationRegistration = true;
                        }
                    }
                }
                if (!skipInvocationRegistration) {
                    if (currentParameter instanceof MultiParameter) {
                        MultiParameter multiParameter = (MultiParameter) currentParameter;
                        for (Object objectFromMultiparameter : multiParameter.getParameters()) {
                            encodedPARGS.add(objectFromMultiparameter);
                        }

                    } else {
                        encodedPARGS.add(currentParameter);
                    }
                }
                parameterOrder++;
            }

            if (MulticallManager.multicallActive()) {

                MulticallManager.multicallRegisterCall(aClass, tracClassMethodName, encodedPARGS.toArray(),
                        returnDecoder, keptParametersForDecoder);

                if (log.isDebugEnabled()) {
                    log.debug(MessageUtils.getMessage("core.invocation.multicall"));
                }

                return null;

            } else {

                MulticallManager.multicallStart(tracInvocationObjectFactory);
                MulticallManager.multicallRegisterCall(aClass, tracClassMethodName, encodedPARGS.toArray(),
                        returnDecoder, keptParametersForDecoder);

                ArrayList result = MulticallManager.launchMulticall(tracProperties);

                if (log.isDebugEnabled()) {
                    log.debug(MessageUtils.getMessage("core.invocation.singlecall"));
                }

                return result.get(0);

            }
        }
    });

}

From source file:org.midonet.config.ConfigProvider.java

public static <Config> Config getConfig(Class<Config> interfaces, final ConfigProvider provider) {

    ClassLoader classLoader = provider.getClass().getClassLoader();

    InvocationHandler handler = new InvocationHandler() {
        @Override/*from w w w.  j  a  va  2 s. c  om*/
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return handleInvocation(method, args, provider);
        }
    };

    Class[] intsArray = { interfaces };

    @SuppressWarnings("unchecked")
    Config proxyConfig = (Config) Proxy.newProxyInstance(classLoader, intsArray, handler);
    return proxyConfig;
}

From source file:org.apache.ftpserver.FtpLogFactory.java

/**
 * Create a proxy log object to redirect log message.
 *///from ww w.j a va 2 s . c o m
private Log createProxyLog(final Log original) {
    InvocationHandler handler = new InvocationHandler() {
        public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
            Object retVal = m.invoke(original, args);
            for (int i = m_logs.size(); --i >= 0;) {
                Log log = (Log) m_logs.get(i);
                m.invoke(log, args);
            }
            return retVal;
        }
    };

    return (Log) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { Log.class }, handler);
}

From source file:com.infinities.skyport.timeout.ServiceProviderTimeLimiter.java

public <T> T newProxy(final T target, Class<T> interfaceType, final Object configuration)
        throws InitializationException {
    if (target == null) {
        return target;
    }/*from  w  w w.ja v  a  2  s.c om*/
    checkNotNull(interfaceType);
    checkNotNull(configuration);
    checkArgument(interfaceType.isInterface(), "interfaceType must be an interface type");

    checkMethodOwnFunctionConfiguration(interfaceType, configuration);

    final Set<Method> interruptibleMethods = findInterruptibleMethods(interfaceType);

    InvocationHandler handler = new InvocationHandler() {

        @Override
        public Object invoke(Object obj, final Method method, final Object[] args) throws Throwable {
            String methodName = method.getName();
            long timeoutDuration = 0;
            TimeUnit timeUnit = TimeUnit.SECONDS;
            try {
                FunctionConfiguration functionConfiguration = (FunctionConfiguration) PropertyUtils
                        .getProperty(configuration, methodName);
                Time timeout = functionConfiguration.getTimeout();
                if (timeout != null) {
                    timeoutDuration = timeout.getNumber();
                    timeUnit = timeout.getUnit();
                }
            } catch (NoSuchMethodException | IllegalArgumentException e) {
                if (IGNORED_SET.contains(method.getName()) || method.getAnnotation(Deprecated.class) != null) {
                    return method.invoke(target, args);
                }
                throwCause(e, false);
                throw new AssertionError("can't get here");
            } catch (InvocationTargetException e) {
                throwCause(e, false);
                throw new AssertionError("can't get here");
            }
            Callable<Object> callable = new Callable<Object>() {

                @Override
                public Object call() throws Exception {
                    try {
                        return method.invoke(target, args);
                    } catch (InvocationTargetException e) {
                        throwCause(e, false);
                        throw new AssertionError("can't get here");
                    }
                }
            };
            if (timeoutDuration > 0) {
                return limiter.callWithTimeout(callable, timeoutDuration, timeUnit,
                        interruptibleMethods.contains(method));
            } else {
                // no timeout
                return method.invoke(target, args);
            }
        }
    };
    return newProxy(interfaceType, handler);
}