Example usage for java.lang.reflect Proxy isProxyClass

List of usage examples for java.lang.reflect Proxy isProxyClass

Introduction

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

Prototype

public static boolean isProxyClass(Class<?> cl) 

Source Link

Document

Returns true if the given class is a proxy class.

Usage

From source file:com.taobao.ad.easyschedule.security.ActionSecurityBean.java

/**
 * ??BO?Annotation??Annotation?/*from www  .j  a  v  a 2 s  . c om*/
 */
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    String[] beanNames = applicationContext.getBeanDefinitionNames();
    if (beanNames == null || beanNames.length == 0) {
        System.err.println(
                "Warning: seems there are no Spring Beans defined, please double check..................");
        return;
    }
    for (String name : beanNames) {
        if (!name.endsWith("Action")) {
            continue;
        }
        Class<?> c = AopUtils.getTargetClass(applicationContext.getBean(name));
        Object bean = applicationContext.getBean(name);

        while (Proxy.isProxyClass(c) && (bean instanceof Advised)) {
            try {
                bean = ((Advised) bean).getTargetSource();
                bean = ((TargetSource) bean).getTarget();
                c = bean.getClass();
            } catch (Exception e) {
                throw new IllegalStateException("Can't initialize SecurityBean, due to:" + e.getMessage());
            }
        }
        long moduleIdDefinedInInterface = -1;
        ActionSecurity moduleAnno = AnnotationUtils.findAnnotation(c, ActionSecurity.class);
        if (moduleAnno != null) {
            moduleIdDefinedInInterface = moduleAnno.module();
        }
        Method[] methods = c.getDeclaredMethods();
        for (Method method : methods) {
            ActionSecurity methodAnno = AnnotationUtils.findAnnotation(method, ActionSecurity.class);
            if (methodAnno != null || moduleIdDefinedInInterface != -1) {
                if (methodAnno == null) {
                    methodAnno = moduleAnno; // use interface annotation
                }
                long module = methodAnno.module() == 0 ? moduleIdDefinedInInterface : methodAnno.module();
                Module myModule = moduleIndex.get(module);
                if (myModule == null) {
                    throw new IllegalArgumentException(
                            "Found invalid module id:" + module + " in method annotation:" + method
                                    + " valid module ids are: " + moduleIndex.keySet());
                }
                if (methodAnno.enable()) {
                    myModule.addOperation(method, methodAnno, methodIndex);
                }
            }
        }
    }
    System.out.println("[ActionSecurityBean] Total " + methodIndex.size() + " methods are secured!");
}

From source file:org.springframework.aop.framework.JdkDynamicAopProxy.java

/**
 * Equality means interfaces, advisors and TargetSource are equal.
 * <p>The compared object may be a JdkDynamicAopProxy instance itself
 * or a dynamic proxy wrapping a JdkDynamicAopProxy instance.
 *///  ww  w.  ja  va  2s.  c  o m
@Override
public boolean equals(@Nullable Object other) {
    if (other == this) {
        return true;
    }
    if (other == null) {
        return false;
    }

    JdkDynamicAopProxy otherProxy;
    if (other instanceof JdkDynamicAopProxy) {
        otherProxy = (JdkDynamicAopProxy) other;
    } else if (Proxy.isProxyClass(other.getClass())) {
        InvocationHandler ih = Proxy.getInvocationHandler(other);
        if (!(ih instanceof JdkDynamicAopProxy)) {
            return false;
        }
        otherProxy = (JdkDynamicAopProxy) ih;
    } else {
        // Not a valid comparison...
        return false;
    }

    // If we get here, otherProxy is the other AopProxy.
    return AopProxyUtils.equalsInProxy(this.advised, otherProxy.advised);
}

From source file:com.mystudy.source.spring.aop.JdkDynamicAopProxy.java

/**
 * Equality means interfaces, advisors and TargetSource are equal.
 * <p>The compared object may be a JdkDynamicAopProxy instance itself
 * or a dynamic proxy wrapping a JdkDynamicAopProxy instance.
 */// ww  w  . j ava 2 s .  com
@Override
public boolean equals(Object other) {
    if (other == this) {
        return true;
    }
    if (other == null) {
        return false;
    }

    JdkDynamicAopProxy otherProxy;
    if (other instanceof JdkDynamicAopProxy) {
        otherProxy = (JdkDynamicAopProxy) other;
    } else if (Proxy.isProxyClass(other.getClass())) {
        InvocationHandler ih = Proxy.getInvocationHandler(other);
        if (!(ih instanceof JdkDynamicAopProxy)) {
            return false;
        }
        otherProxy = (JdkDynamicAopProxy) ih;
    } else {
        // Not a valid comparison...
        return false;
    }

    // If we get here, otherProxy is the other AopProxy.
    return AopProxyUtils.equalsInProxy(this.advised, otherProxy.advised);
}

From source file:com.googlecode.jsonrpc4j.JsonRpcServer.java

/**
 * Returns the handler's class or interfaces.  The variable serviceName
 * is ignored in this class./*w w w  .j  av a 2  s .c om*/
 *
 * @param serviceName the optional name of a service
 * @return the class
 */
protected Class<?>[] getHandlerInterfaces(String serviceName) {
    if (remoteInterface != null) {
        return new Class<?>[] { remoteInterface };
    } else if (Proxy.isProxyClass(handler.getClass())) {
        return handler.getClass().getInterfaces();
    } else {
        return new Class<?>[] { handler.getClass() };
    }
}

From source file:org.apache.openejb.resource.AutoConnectionTracker.java

private Object newProxy(final Object handle, final InvocationHandler invocationHandler) {
    ClassLoader loader = handle.getClass().getClassLoader();
    if (loader == null) {
        loader = ClassLoader.getSystemClassLoader();
    }//from  ww  w.  ja  va  2  s. c  om
    if (!Proxy.isProxyClass(handle.getClass())) {
        final Object proxy = LocalBeanProxyFactory.Unsafe.allocateInstance(getProxy(handle.getClass(), loader));
        DynamicSubclass.setHandler(proxy, invocationHandler);
        return proxy;
    }

    return Proxy.newProxyInstance(loader, getAPi(handle.getClass()), invocationHandler);
}

From source file:org.kuali.coeus.sys.impl.service.SpringBeanConfigurationTest.java

/**
 * This method looks for the same bean name in different context but of different class types.
 * This is either a "partial" bean override or a bean name conflict
 *//*from   www  .  jav a2  s . com*/
@Test
public void test_beans_across_other_contexts_name_conflict() {
    final HashMap<String, Set<Class<?>>> beans = new HashMap<>();
    toEachSpringBean(new VoidFunction() {
        @Override
        public void r(ApplicationContext context, String name) {
            Object o = context.getBean(name);
            if (o != null) {
                Set<Class<?>> beanClasses = beans.get(name);
                if (beanClasses == null) {
                    beanClasses = new HashSet<>();
                }

                final Class<?> clazz;
                if (Proxy.isProxyClass(o.getClass())) {
                    try {
                        clazz = (Class<?>) Proxy.getInvocationHandler(o).invoke(o,
                                Object.class.getMethod("getClass", new Class[] {}), new Object[] {});
                    } catch (Throwable e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    clazz = o.getClass();
                }

                beanClasses.add(clazz);
                beans.put(name, beanClasses);
            } else {
                LOG.warn("bean " + name + " is null");
            }

        }
    }, true);

    final Set<Map.Entry<String, Set<Class<?>>>> entrySet = new HashSet<>(beans.entrySet());
    CollectionUtils.filter(entrySet, new Predicate<Map.Entry<String, Set<Class<?>>>>() {
        @Override
        public boolean evaluate(Map.Entry<String, Set<Class<?>>> object) {
            return object.getValue().size() > 1;
        }
    });

    Assert.assertTrue(
            "The following bean names are duplicated in different contexts with different class names "
                    + entrySet,
            entrySet.isEmpty());
}

From source file:org.zanata.ZanataInit.java

private static void list(Context ctx, String indent, StringBuffer buffer, boolean verbose) {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    try {/*from w ww  . j  a v a2s .c  o m*/
        NamingEnumeration<NameClassPair> ne = ctx.list("");
        while (ne.hasMore()) {
            NameClassPair pair = ne.next();
            String name = pair.getName();
            String className = pair.getClassName();
            boolean recursive = false;
            boolean isLinkRef = false;
            boolean isProxy = false;
            Class<?> c = null;
            try {
                c = loader.loadClass(className);
                if (Context.class.isAssignableFrom(c)) {
                    recursive = true;
                }
                if (LinkRef.class.isAssignableFrom(c)) {
                    isLinkRef = true;
                }
                isProxy = Proxy.isProxyClass(c);
            } catch (ClassNotFoundException cnfe) {
                // If this is a $Proxy* class its a proxy
                if (className.startsWith("$Proxy")) {
                    isProxy = true;
                    // We have to get the class from the binding
                    try {
                        Object p = ctx.lookup(name);
                        c = p.getClass();
                    } catch (NamingException e) {
                        Throwable t = e.getRootCause();
                        if (t instanceof ClassNotFoundException) {
                            // Get the class name from the exception msg
                            String msg = t.getMessage();
                            if (msg != null) {
                                // Reset the class name to the CNFE class
                                className = msg;
                            }
                        }
                    }
                }
            }
            buffer.append(indent).append(" +- ").append(name);
            // Display reference targets
            if (isLinkRef) {
                // Get the
                try {
                    Object obj = ctx.lookupLink(name);
                    LinkRef link = (LinkRef) obj;
                    buffer.append("[link -> ");
                    buffer.append(link.getLinkName());
                    buffer.append(']');
                } catch (Throwable t) {
                    buffer.append("invalid]");
                }
            }
            // Display proxy interfaces
            if (isProxy) {
                buffer.append(" (proxy: ").append(pair.getClassName());
                if (c != null) {
                    Class<?>[] ifaces = c.getInterfaces();
                    buffer.append(" implements ");
                    for (Class<?> iface : ifaces) {
                        buffer.append(iface);
                        buffer.append(',');
                    }
                    buffer.setCharAt(buffer.length() - 1, ')');
                } else {
                    buffer.append(" implements ").append(className).append(")");
                }
            } else if (verbose) {
                buffer.append(" (class: ").append(pair.getClassName()).append(")");
            }
            buffer.append('\n');
            if (recursive) {
                try {
                    Object value = ctx.lookup(name);
                    if (value instanceof Context) {
                        Context subctx = (Context) value;
                        list(subctx, indent + " |  ", buffer, verbose);
                    } else {
                        buffer.append(indent).append(" |   NonContext: ").append(value);
                        buffer.append('\n');
                    }
                } catch (Throwable t) {
                    buffer.append("Failed to lookup: ").append(name).append(", errmsg=").append(t.getMessage());
                    buffer.append('\n');
                }
            }
        }
        ne.close();
    } catch (NamingException ne) {
        buffer.append("error while listing context ").append(ctx.toString()).append(": ")
                .append(ne.toString(true));
    }
}

From source file:org.springmodules.xt.model.generator.factory.FactoryGeneratorInterceptor.java

private boolean doEquals(Object proxy, Object other) {
    if (other != null && Proxy.isProxyClass(other.getClass())) {
        return Proxy.getInvocationHandler(proxy) == Proxy.getInvocationHandler(other);
    } else {/*  w w  w.jav  a2 s.  c  o m*/
        return false;
    }
}

From source file:org.wso2.carbon.identity.common.testng.CarbonBasedTestListener.java

private void createKeyStore(Class realClass, WithKeyStore withKeyStore) {

    try {/*from w  w  w . j av a 2  s .c om*/
        RegistryService registryService = createRegistryService(realClass, withKeyStore.tenantId(),
                withKeyStore.tenantDomain());
        ServerConfiguration serverConfigurationService = ServerConfiguration.getInstance();
        serverConfigurationService.init(realClass.getResourceAsStream("/repository/conf/carbon.xml"));
        KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(withKeyStore.tenantId(),
                serverConfigurationService, registryService);
        if (!Proxy.isProxyClass(keyStoreManager.getClass())
                && !keyStoreManager.getClass().getName().contains("EnhancerByMockitoWithCGLIB")) {
            KeyStore keyStore = ReadCertStoreSampleUtil.createKeyStore(getClass());
            org.wso2.carbon.identity.testutil.Whitebox.setInternalState(keyStoreManager, "primaryKeyStore",
                    keyStore);
            org.wso2.carbon.identity.testutil.Whitebox.setInternalState(keyStoreManager, "registryKeyStore",
                    keyStore);
        }
        CarbonCoreDataHolder.getInstance().setRegistryService(registryService);
        CarbonCoreDataHolder.getInstance().setServerConfigurationService(serverConfigurationService);
    } catch (Exception e) {
        throw new TestCreationException(
                "Unhandled error while reading cert for test class:  " + realClass.getName(), e);
    }
}

From source file:io.coala.enterprise.Actor.java

/**
 * @param actorType the type of {@link Actor} to mimic
 * @param callObserver an {@link Observer} of method call, or {@code null}
 * @return the {@link Proxy} instance/*from   w  w w . ja va2 s  . c o  m*/
 */
@SuppressWarnings("unchecked")
static <A extends Actor<T>, F extends Fact, T extends F> A proxyAs(final Actor<F> impl,
        final Class<A> actorType, final Observer<Method> callObserver) {
    final A proxy = (A) Proxy.newProxyInstance(actorType.getClassLoader(), new Class<?>[] { actorType },
            (self, method, args) -> {
                try {
                    final Object result = method.isDefault() && Proxy.isProxyClass(self.getClass())
                            ? ReflectUtil.invokeDefaultMethod(self, method, args)
                            : method.invoke(impl, args);
                    if (callObserver != null)
                        callObserver.onNext(method);
                    return result;
                } catch (Throwable e) {
                    if (e instanceof IllegalArgumentException)
                        try {
                            return ReflectUtil.invokeAsBean(impl.properties(), actorType, method, args);
                        } catch (final Exception ignore) {
                            LogUtil.getLogger(Fact.class).warn("{}method call failed: {}",
                                    method.isDefault() ? "default " : "", method, ignore);
                        }
                    if (e instanceof InvocationTargetException)
                        e = e.getCause();
                    if (callObserver != null)
                        callObserver.onError(e);
                    throw e;
                }
            });
    return proxy;
}