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.epam.reportportal.junit.JUnitProvider.java

@Override
public IListenerHandler get() {
    if (reportPortalService.getParameters().getEnable()) {
        return new ParallelRunningHandler(parallelRunningContext, reportPortalService);
    }/*ww  w . j  ava 2  s  . com*/

    return (IListenerHandler) Proxy.newProxyInstance(this.getClass().getClassLoader(),
            new Class[] { IListenerHandler.class }, new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    Class<?> returnType = method.getReturnType();

                    if (ClassUtils.isAssignable(returnType, Boolean.class, true)) {
                        return false;
                    }

                    return null;
                }
            });
}

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

public <T> T javascriptProxyForModule(Class<T> baseInterface, Class<?>... otherClasses) {
    Class<?>[] allClasses;//from  w  ww .j  a  v a 2 s .  co m

    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 {
            mKirinHelper.jsMethod(method.getName(), (Object[]) args);
            return null;
        }
    };

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

From source file:org.jcurl.core.jnlp.FileDialogWebstart.java

/**
 * Dynamic Interface Wrapper (or dynamic Delegate) using
 * {@link Proxy#newProxyInstance(ClassLoader, Class[], InvocationHandler)}
 * mapping only identical methods./*  w w  w .ja  v  a 2  s .  c o  m*/
 * <p>
 * The two interfaces must have identical methods!
 * </p>
 * 
 * @param src
 *            the source instance (the one to wrap)
 * @param dstT
 *            destination interface type
 * @return target interface instance.
 */
static Object wrap(final Object src, final Class<?> dstT) {
    if (log.isDebugEnabled())
        log.debug("wrap(" + src + ", " + dstT + ")");
    if (src == null)
        return null;
    return Proxy.newProxyInstance(FileDialogWebstart.class.getClassLoader(), new Class[] { dstT },
            new InvocationHandler() {
                public Object invoke(final Object proxy, final Method method, final Object[] args)
                        throws Throwable {
                    final Class<?> srcT = src.getClass();
                    // Wrap ALL Methods (also getClass, equals, toString,
                    // ...)
                    final Method dstM = srcT.getMethod(method.getName(), method.getParameterTypes());
                    if (log.isDebugEnabled()) {
                        log.debug("proxy: " + proxy.getClass());
                        log.debug("method: " + method);
                        log.debug("args: " + args);
                        log.debug("srcT: " + srcT);
                        log.debug("dstM: " + dstM);
                    }
                    final Object ret = dstM.invoke(src, args);
                    if (log.isDebugEnabled())
                        log.debug("ret: " + ret);
                    return ret;
                }
            });
}

From source file:com.quatico.base.aem.test.api.setup.SetupFactory.java

public T getSetup(final Object... implementors) {
    final Map<Class<?>, Object> interfaces = new HashMap<>();
    for (Object implementor : implementors) {
        List<Class<?>> implementorInterfaces = ClassUtils.getAllInterfaces(implementor.getClass());

        assert !implementorInterfaces.isEmpty();

        for (Class<?> implementorInterface : implementorInterfaces) {
            interfaces.put(implementorInterface, implementor);
        }//from   w w w.ja  v  a2 s  .c o  m
    }

    @SuppressWarnings("unchecked")
    T result = (T) Proxy.newProxyInstance(this.interfaze.getClassLoader(), new Class<?>[] { this.interfaze },
            new InvocationHandler() {
                private final Object fProxyObject = new Object() {
                    @Override
                    public String toString() {
                        return "Proxy for: " + SetupFactory.this.interfaze.getDeclaringClass().getName(); //$NON-NLS-1$
                    }
                };

                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if (method.getDeclaringClass().equals(Object.class)) {
                        method.invoke(this.fProxyObject, args);
                    }

                    if (interfaces.containsKey(method.getDeclaringClass())) {
                        return method.invoke(interfaces.get(method.getDeclaringClass()), args);
                    }

                    throw new UnsupportedOperationException(
                            "Created proxy has not received an implementation that supports this method: " //$NON-NLS-1$
                                    + method.getName());
                }
            });

    return result;
}

From source file:com.netflix.paas.config.base.DynamicProxyArchaeusConfigurationFactory.java

@SuppressWarnings({ "unchecked", "static-access" })
public <T> T get(Class<T> configClass, DynamicPropertyFactory propertyFactory,
        AbstractConfiguration configuration) throws Exception {
    final Map<String, Supplier<?>> methods = ConfigurationProxyUtils.getMethodSuppliers(configClass,
            propertyFactory, configuration);

    if (configClass.isInterface()) {
        Class<?> proxyClass = Proxy.getProxyClass(configClass.getClassLoader(), new Class[] { configClass });

        return (T) proxyClass.getConstructor(new Class[] { InvocationHandler.class })
                .newInstance(new Object[] { new InvocationHandler() {
                    @Override/*from   www .j av  a 2 s . c o m*/
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Supplier<?> supplier = (Supplier<?>) methods.get(method.getName());
                        return supplier.get();
                    }
                } });
    } else {
        final Enhancer enhancer = new Enhancer();
        final Object obj = (T) enhancer.create(configClass, new net.sf.cglib.proxy.InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Supplier<?> supplier = (Supplier<?>) methods.get(method.getName());
                if (supplier == null) {
                    return method.invoke(proxy, args);
                }
                return supplier.get();
            }
        });

        ConfigurationProxyUtils.assignFieldValues(obj, configClass, propertyFactory, configuration);
        return (T) obj;
    }
}

From source file:com.netflix.paas.config.base.JavaAssistArchaeusConfigurationFactory.java

@SuppressWarnings({ "unchecked", "static-access" })
public <T> T get(Class<T> configClass, DynamicPropertyFactory propertyFactory,
        AbstractConfiguration configuration) throws Exception {
    final Map<String, Supplier<?>> methods = ConfigurationProxyUtils.getMethodSuppliers(configClass,
            propertyFactory, configuration);

    if (configClass.isInterface()) {
        Class<?> proxyClass = Proxy.getProxyClass(configClass.getClassLoader(), new Class[] { configClass });

        return (T) proxyClass.getConstructor(new Class[] { InvocationHandler.class })
                .newInstance(new Object[] { new InvocationHandler() {
                    @Override//w  w  w. ja  v a 2 s .  c  o m
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Supplier<?> supplier = (Supplier<?>) methods.get(method.getName());
                        if (supplier == null) {
                            return method.invoke(proxy, args);
                        }
                        return supplier.get();
                    }
                } });
    } else {
        final Enhancer enhancer = new Enhancer();
        final Object obj = (T) enhancer.create(configClass, new net.sf.cglib.proxy.InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Supplier<?> supplier = (Supplier<?>) methods.get(method.getName());
                if (supplier == null) {
                    return method.invoke(proxy, args);
                }
                return supplier.get();
            }
        });

        ConfigurationProxyUtils.assignFieldValues(obj, configClass, propertyFactory, configuration);
        return (T) obj;
    }
}

From source file:jp.primecloud.auto.ui.mock.MockBeanContext.java

protected ApplicationContext createMockContext() {
    InvocationHandler handler = new InvocationHandler() {
        @Override/*ww w.j  a  v a2  s  .com*/
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if ("getBean".equals(method.getName())) {
                return getBean((String) args[0]);
            } else if ("getBeansOfType".equals(method.getName())) {
                return getBeansOfType((Class<?>) args[0]);
            }
            throw new UnsupportedOperationException(method.getName());
        }
    };

    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    Class<?>[] interfaces = new Class<?>[] { ApplicationContext.class };
    return (ApplicationContext) Proxy.newProxyInstance(loader, interfaces, handler);
}

From source file:org.ebayopensource.twin.ElementImpl.java

/** 
 * For internal use only. Creates an Element wrapping the given RemoteObject 
 * This should be used instead of new Element(), as it will instantiate the correct subclass.
 *//* w  ww . ja  va  2s.c o m*/
public static Element create(RemoteObject o) {
    if (o == null)
        return null;

    List<Class<?>> interfaces = new ArrayList<Class<?>>();
    interfaces.add(Element.class);
    interfaces.add(RemoteResourceInterface.class);

    final Class<? extends ControlType> controlTypeInterface = NameMappings
            .getTypeInterface((String) o.properties.get("controlType"));
    if (controlTypeInterface.equals(Desktop.class))
        return new DesktopImpl(o.session);
    if (controlTypeInterface != null)
        interfaces.add(controlTypeInterface);

    List<Class<? extends ControlPattern>> controlPatternInterfaces = getControlPatternInterfaces(o);
    interfaces.addAll(controlPatternInterfaces);

    final ElementImpl impl = new ElementImpl(o, controlTypeInterface, controlPatternInterfaces);
    if (interfaces.isEmpty())
        return impl;

    final HashSet<Class<?>> implementedPatterns = new HashSet<Class<?>>();
    for (Class<?> iface : interfaces)
        if (isInterfaceExtending(iface, ControlPattern.class))
            implementedPatterns.add(iface);

    return (Element) Proxy.newProxyInstance(ElementImpl.class.getClassLoader(),
            interfaces.toArray(new Class[interfaces.size()]), new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    Method implMethod = null;
                    try {
                        implMethod = impl.getClass().getMethod(method.getName(), method.getParameterTypes());
                    } catch (NoSuchMethodException e) {
                        implMethod = impl.getClass().getDeclaredMethod(method.getName(),
                                method.getParameterTypes());
                    }
                    Require requirement = implMethod.getAnnotation(Require.class);
                    if (requirement != null) {
                        for (Class<?> pattern : requirement.pattern())
                            if (!implementedPatterns.contains(pattern))
                                throw new TwinException("This "
                                        + (impl.getControlType() == null ? "Unknown" : impl.getControlType())
                                        + " does not implement the control pattern " + pattern.getSimpleName());
                        if (requirement.type() != Void.class)
                            if (controlTypeInterface != requirement.type())
                                throw new TwinException("This "
                                        + (impl.getControlType() == null ? "Unknown" : impl.getControlType())
                                        + " is not of ControlType " + requirement.type().getSimpleName());
                    }
                    try {
                        return implMethod.invoke(impl, args);
                    } catch (InvocationTargetException e) {
                        throw e.getCause();
                    }
                }
            });
}

From source file:com.mirth.connect.server.api.providers.MirthResourceInvocationHandlerProvider.java

@Override
public InvocationHandler create(Invocable method) {
    return new InvocationHandler() {
        @Override/* ww w . ja  v a 2 s . c o  m*/
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            String originalThreadName = Thread.currentThread().getName();

            try {
                if (proxy instanceof MirthServlet) {
                    try {
                        MirthServlet mirthServlet = (MirthServlet) proxy;

                        Map<Method, MethodInfo> methodMap = infoMap.get(proxy.getClass());
                        if (methodMap == null) {
                            methodMap = new ConcurrentHashMap<Method, MethodInfo>();
                            infoMap.put(mirthServlet.getClass(), methodMap);
                        }

                        MethodInfo methodInfo = methodMap.get(method);
                        if (methodInfo == null) {
                            methodInfo = new MethodInfo();
                            methodMap.put(method, methodInfo);
                        }

                        Operation operation = methodInfo.getOperation();
                        if (operation == null) {
                            /*
                             * Get the operation from the MirthOperation annotation present on
                             * the interface method.
                             */
                            Class<?> clazz = proxy.getClass();

                            while (clazz != null && operation == null) {
                                for (Class<?> interfaceClass : clazz.getInterfaces()) {
                                    if (BaseServletInterface.class.isAssignableFrom(interfaceClass)) {
                                        operation = OperationUtil.getOperation(interfaceClass, method);
                                        if (operation != null) {
                                            methodInfo.setOperation(operation);
                                            break;
                                        }
                                    }
                                }

                                clazz = clazz.getSuperclass();
                            }
                        }
                        mirthServlet.setOperation(operation);

                        // Set thread name based on the servlet class and operation name
                        Thread.currentThread().setName(mirthServlet.getClass().getSimpleName() + " Thread ("
                                + operation.getDisplayName() + ") < " + originalThreadName);

                        /*
                         * If a DontCheckAuthorized annotation is present on the server
                         * implementation method, then no auditing is done now and the servlet
                         * is expected to call checkUserAuthorized. Two other optional
                         * annotations determine whether the channel/user ID should be used in
                         * the authorization check.
                         */
                        Boolean checkAuthorized = methodInfo.getCheckAuthorized();
                        if (checkAuthorized == null) {
                            checkAuthorized = true;

                            Method matchingMethod = mirthServlet.getClass().getMethod(method.getName(),
                                    method.getParameterTypes());
                            if (matchingMethod != null) {
                                checkAuthorized = matchingMethod
                                        .getAnnotation(DontCheckAuthorized.class) == null;
                                methodInfo.setCheckAuthorizedChannelId(
                                        matchingMethod.getAnnotation(CheckAuthorizedChannelId.class));
                                methodInfo.setCheckAuthorizedUserId(
                                        matchingMethod.getAnnotation(CheckAuthorizedUserId.class));
                            }

                            methodInfo.setCheckAuthorized(checkAuthorized);
                        }

                        if (checkAuthorized) {
                            /*
                             * We need to know what parameter index the channel/user ID resides
                             * at so we can correctly include it with the authorization request.
                             */
                            Integer channelIdIndex = methodInfo.getChannelIdIndex();
                            Integer userIdIndex = methodInfo.getUserIdIndex();

                            if (args.length > 0) {
                                List<String> paramNames = methodInfo.getParamNames();
                                if (paramNames == null) {
                                    paramNames = new ArrayList<String>();
                                    List<Integer> notFoundIndicies = new ArrayList<Integer>();

                                    /*
                                     * The Param annotation lets us know at runtime the name to
                                     * use when adding entries into the parameter map, which
                                     * will eventually be stored in the event logs.
                                     */
                                    int count = 0;
                                    for (Annotation[] paramAnnotations : method.getParameterAnnotations()) {
                                        boolean found = false;
                                        for (Annotation annotation : paramAnnotations) {
                                            if (annotation instanceof Param) {
                                                Param param = (Param) annotation;
                                                // Set the name to null if we're not including it in the parameter map
                                                paramNames.add(param.excludeFromAudit() ? null : param.value());
                                                found = true;
                                                break;
                                            }
                                        }
                                        if (!found) {
                                            notFoundIndicies.add(count);
                                            paramNames.add(null);
                                        }
                                        count++;
                                    }

                                    // For each parameter name that wasn't found, replace it with a default name to use in the parameter map
                                    if (CollectionUtils.isNotEmpty(notFoundIndicies)) {
                                        for (Integer index : notFoundIndicies) {
                                            paramNames.set(index, getDefaultParamName(paramNames));
                                        }
                                    }

                                    methodInfo.setParamNames(paramNames);
                                }

                                // Add all arguments to the parameter map, except those that had excludeFromAudit enabled.
                                for (int i = 0; i < args.length; i++) {
                                    String paramName = paramNames.get(i);
                                    if (paramName != null) {
                                        mirthServlet.addToParameterMap(paramNames.get(i), args[i]);
                                    }
                                }

                                if (channelIdIndex == null) {
                                    channelIdIndex = -1;
                                    if (methodInfo.getCheckAuthorizedChannelId() != null) {
                                        channelIdIndex = paramNames
                                                .indexOf(methodInfo.getCheckAuthorizedChannelId().paramName());
                                    }
                                    methodInfo.setChannelIdIndex(channelIdIndex);
                                }

                                if (userIdIndex == null) {
                                    userIdIndex = -1;
                                    if (methodInfo.getCheckAuthorizedUserId() != null) {
                                        userIdIndex = paramNames
                                                .indexOf(methodInfo.getCheckAuthorizedUserId().paramName());
                                    }
                                    methodInfo.setUserIdIndex(userIdIndex);
                                }
                            }

                            // Authorize the request
                            if (channelIdIndex != null && channelIdIndex >= 0) {
                                mirthServlet.checkUserAuthorized((String) args[channelIdIndex]);
                            } else if (userIdIndex != null && userIdIndex >= 0) {
                                mirthServlet.checkUserAuthorized((Integer) args[userIdIndex],
                                        methodInfo.getCheckAuthorizedUserId().auditCurrentUser());
                            } else {
                                mirthServlet.checkUserAuthorized();
                            }
                        }
                    } catch (Throwable t) {
                        Throwable converted = convertThrowable(t, new HashSet<Throwable>());
                        if (converted != null) {
                            t = converted;
                        }

                        if (!(t instanceof WebApplicationException)) {
                            t = new MirthApiException(t);
                        }
                        throw new InvocationTargetException(t);
                    }
                }

                try {
                    return method.invoke(proxy, args);
                } catch (InvocationTargetException e) {
                    Throwable converted = convertThrowable(e, new HashSet<Throwable>());
                    if (converted != null && converted instanceof InvocationTargetException) {
                        e = (InvocationTargetException) converted;
                    }
                    throw e;
                }
            } finally {
                Thread.currentThread().setName(originalThreadName);
            }
        }
    };
}

From source file:org.eclipse.wb.internal.rcp.model.rcp.PageInfo.java

@Override
protected void applyActionBars() throws Exception {
    ClassLoader editorLoader = JavaInfoUtils.getClassLoader(this);
    Class<?> pageSiteClass = editorLoader.loadClass("org.eclipse.ui.part.IPageSite");
    // create IPageSite
    final Object pageSite = Proxy.newProxyInstance(editorLoader, new Class<?>[] { pageSiteClass },
            new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    String signature = ReflectionUtils.getMethodSignature(method);
                    if (signature.equals("getActionBars()")) {
                        return m_actionBars;
                    }/*from   w w  w.j  a va  2 s  .  c  o  m*/
                    if (signature
                            .equals("setSelectionProvider(org.eclipse.jface.viewers.ISelectionProvider)")) {
                        return null;
                    }
                    throw new NotImplementedException();
                }
            });
    // call init(IPageSite)
    ReflectionUtils.invokeMethod(getObject(), "init(org.eclipse.ui.part.IPageSite)", pageSite);
}