Example usage for org.springframework.cglib.proxy Enhancer setInterfaces

List of usage examples for org.springframework.cglib.proxy Enhancer setInterfaces

Introduction

In this page you can find the example usage for org.springframework.cglib.proxy Enhancer setInterfaces.

Prototype

public void setInterfaces(Class[] interfaces) 

Source Link

Document

Set the interfaces to implement.

Usage

From source file:net.kaczmarzyk.spring.data.jpa.web.EnhancerUtil.java

@SuppressWarnings("unchecked")
static <T> T wrapWithIfaceImplementation(final Class<T> iface, final Specification<Object> targetSpec) {
    Enhancer enhancer = new Enhancer();
    enhancer.setInterfaces(new Class[] { iface });
    enhancer.setCallback(new MethodInterceptor() {
        @Override//from   w  w w . j  ava2  s .  c  o  m
        public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
            if ("toString".equals(method.getName())) {
                return iface.getSimpleName() + "[" + proxy.invoke(targetSpec, args) + "]";
            }
            return proxy.invoke(targetSpec, args);
        }
    });

    return (T) enhancer.create();
}

From source file:io.syndesis.runtime.Recordings.java

static public <T> T recorder(Object object, Class<T> as) {
    if (as.isInterface()) {
        // If it's just an interface, use standard java reflect proxying
        return as.cast(Proxy.newProxyInstance(as.getClassLoader(), new Class[] { as },
                new RecordingInvocationHandler(object)));
    }// w ww  . j a  va 2  s  .c  o  m

    // If it's a class then use gclib to implement a subclass to implement proxying
    RecordingInvocationHandler ih = new RecordingInvocationHandler(object);
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(as);
    enhancer.setInterfaces(new Class[] { RecordingProxy.class });
    enhancer.setCallback(new org.springframework.cglib.proxy.InvocationHandler() {
        @Override
        public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
            return ih.invoke(o, method, objects);
        }
    });
    return as.cast(enhancer.create());
}

From source file:com.newtranx.util.cassandra.spring.AccessorScannerConfigurer.java

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory context) throws BeansException {
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
            false) {/*from  ww w  . j  a v  a2s  .  c  o m*/

        @Override
        protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
            return beanDefinition.getMetadata().isInterface();
        }

    };
    scanner.addIncludeFilter(new AnnotationTypeFilter(Accessor.class));
    for (BeanDefinition bd : scanner.findCandidateComponents(basePackage)) {
        Class<?> accessorCls;
        try {
            accessorCls = Class.forName(bd.getBeanClassName());
        } catch (ClassNotFoundException e) {
            throw new AssertionError(e);
        }
        log.info("Creating proxy accessor: " + accessorCls.getName());
        MethodInterceptor interceptor = new MethodInterceptor() {

            private final Lazy<?> target = new Lazy<>(() -> {
                log.info("Creating actual accessor: " + accessorCls.getName());
                Session session;
                if (AccessorScannerConfigurer.this.session == null)
                    session = mainContext.getBean(Session.class);
                else
                    session = AccessorScannerConfigurer.this.session;
                MappingManager mappingManager = new MappingManager(session);
                return mappingManager.createAccessor(accessorCls);
            });

            @Override
            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy)
                    throws Throwable {
                if ("toString".equals(method.getName())) {
                    return accessorCls.getName();
                }
                return method.invoke(target.get(), args);
            }

        };
        Enhancer enhancer = new Enhancer();
        enhancer.setInterfaces(new Class<?>[] { accessorCls });
        enhancer.setCallback(interceptor);
        Object bean = enhancer.create();
        String beanName = StringUtils.uncapitalize(accessorCls.getSimpleName());
        context.registerSingleton(beanName, bean);
        log.info("Bean registed, name=" + beanName + ", bean=" + bean.toString());
    }
}

From source file:io.neba.core.resourcemodels.mapping.ResourceToModelMapperTest.java

private void withSpringAopProxyFor(Class<TestModel> superclass) throws Exception {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(superclass);// ww w  . ja  v  a2  s  .  c o  m
    enhancer.setCallback(NoOp.INSTANCE);
    enhancer.setInterfaces(new Class[] { Advised.class });
    Object enhanced = spy(enhancer.create());
    assertThat(enhanced).isNotNull();

    this.targetSource = mock(TargetSource.class);
    TestModel unwrappedBeanInstance = new TestModel();
    doReturn(this.targetSource).when((Advised) enhanced).getTargetSource();
    doReturn(unwrappedBeanInstance).when(this.targetSource).getTarget();

    this.model = (TestModel) enhanced;
}

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

@Override
public Object getProxy(@Nullable ClassLoader classLoader) {
    if (logger.isDebugEnabled()) {
        logger.debug("Creating CGLIB proxy: target source is " + this.advised.getTargetSource());
    }//from  ww w  .  j ava  2s  . co  m

    try {
        Class<?> rootClass = this.advised.getTargetClass();
        Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy");

        Class<?> proxySuperClass = rootClass;
        if (ClassUtils.isCglibProxyClass(rootClass)) {
            proxySuperClass = rootClass.getSuperclass();
            Class<?>[] additionalInterfaces = rootClass.getInterfaces();
            for (Class<?> additionalInterface : additionalInterfaces) {
                this.advised.addInterface(additionalInterface);
            }
        }

        // Validate the class, writing log messages as necessary.
        validateClassIfNecessary(proxySuperClass, classLoader);

        // Configure CGLIB Enhancer...
        Enhancer enhancer = createEnhancer();
        if (classLoader != null) {
            enhancer.setClassLoader(classLoader);
            if (classLoader instanceof SmartClassLoader
                    && ((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) {
                enhancer.setUseCache(false);
            }
        }
        enhancer.setSuperclass(proxySuperClass);
        enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
        enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
        enhancer.setStrategy(new ClassLoaderAwareUndeclaredThrowableStrategy(classLoader));

        Callback[] callbacks = getCallbacks(rootClass);
        Class<?>[] types = new Class<?>[callbacks.length];
        for (int x = 0; x < types.length; x++) {
            types[x] = callbacks[x].getClass();
        }
        // fixedInterceptorMap only populated at this point, after getCallbacks call above
        enhancer.setCallbackFilter(new ProxyCallbackFilter(this.advised.getConfigurationOnlyCopy(),
                this.fixedInterceptorMap, this.fixedInterceptorOffset));
        enhancer.setCallbackTypes(types);

        // Generate the proxy class and create a proxy instance.
        return createProxyClassAndInstance(enhancer, callbacks);
    } catch (CodeGenerationException | IllegalArgumentException ex) {
        throw new AopConfigException(
                "Could not generate CGLIB subclass of class [" + this.advised.getTargetClass() + "]: "
                        + "Common causes of this problem include using a final class or a non-visible class",
                ex);
    } catch (Throwable ex) {
        // TargetSource.getTarget() failed
        throw new AopConfigException("Unexpected AOP exception", ex);
    }
}

From source file:org.springframework.cloud.iot.coap.method.ResolvableMethod.java

@SuppressWarnings("unchecked")
private static <T> T initProxy(Class<?> type, MethodInvocationInterceptor interceptor) {
    Assert.notNull(type, "'type' must not be null");
    if (type.isInterface()) {
        ProxyFactory factory = new ProxyFactory(EmptyTargetSource.INSTANCE);
        factory.addInterface(type);//from w  w  w. ja v a  2  s .  co  m
        factory.addInterface(Supplier.class);
        factory.addAdvice(interceptor);
        return (T) factory.getProxy();
    }

    else {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(type);
        enhancer.setInterfaces(new Class<?>[] { Supplier.class });
        enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
        enhancer.setCallbackType(org.springframework.cglib.proxy.MethodInterceptor.class);

        Class<?> proxyClass = enhancer.createClass();
        Object proxy = null;

        if (objenesis.isWorthTrying()) {
            try {
                proxy = objenesis.newInstance(proxyClass, enhancer.getUseCache());
            } catch (ObjenesisException ex) {
                logger.debug("Objenesis failed, falling back to default constructor", ex);
            }
        }

        if (proxy == null) {
            try {
                proxy = ReflectionUtils.accessibleConstructor(proxyClass).newInstance();
            } catch (Throwable ex) {
                throw new IllegalStateException("Unable to instantiate proxy "
                        + "via both Objenesis and default constructor fails as well", ex);
            }
        }

        ((Factory) proxy).setCallbacks(new Callback[] { interceptor });
        return (T) proxy;
    }
}

From source file:org.springframework.context.annotation.ConfigurationClassEnhancer.java

/**
 * Creates a new CGLIB {@link Enhancer} instance.
 *///from  ww w  .  j  a v a2  s  .  c o  m
private Enhancer newEnhancer(Class<?> superclass, @Nullable ClassLoader classLoader) {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(superclass);
    enhancer.setInterfaces(new Class<?>[] { EnhancedConfiguration.class });
    enhancer.setUseFactory(false);
    enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
    enhancer.setStrategy(new BeanFactoryAwareGeneratorStrategy(classLoader));
    enhancer.setCallbackFilter(CALLBACK_FILTER);
    enhancer.setCallbackTypes(CALLBACK_FILTER.getCallbackTypes());
    return enhancer;
}

From source file:org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.java

@SuppressWarnings("unchecked")
private static <T> T initProxy(Class<?> type, ControllerMethodInvocationInterceptor interceptor) {
    if (type.isInterface()) {
        ProxyFactory factory = new ProxyFactory(EmptyTargetSource.INSTANCE);
        factory.addInterface(type);/*w ww.  j  a  v a2 s  .c o m*/
        factory.addInterface(MethodInvocationInfo.class);
        factory.addAdvice(interceptor);
        return (T) factory.getProxy();
    }

    else {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(type);
        enhancer.setInterfaces(new Class<?>[] { MethodInvocationInfo.class });
        enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
        enhancer.setCallbackType(org.springframework.cglib.proxy.MethodInterceptor.class);

        Class<?> proxyClass = enhancer.createClass();
        Object proxy = null;

        if (objenesis.isWorthTrying()) {
            try {
                proxy = objenesis.newInstance(proxyClass, enhancer.getUseCache());
            } catch (ObjenesisException ex) {
                logger.debug("Unable to instantiate controller proxy using Objenesis, "
                        + "falling back to regular construction", ex);
            }
        }

        if (proxy == null) {
            try {
                proxy = ReflectionUtils.accessibleConstructor(proxyClass).newInstance();
            } catch (Throwable ex) {
                throw new IllegalStateException(
                        "Unable to instantiate controller proxy using Objenesis, "
                                + "and regular controller instantiation via default constructor fails as well",
                        ex);
            }
        }

        ((Factory) proxy).setCallbacks(new Callback[] { interceptor });
        return (T) proxy;
    }
}

From source file:org.springframework.web.servlet.mvc.support.MvcUrlUtils.java

@SuppressWarnings("unchecked")
private static <T> T initProxy(Class<?> type, ControllerMethodInvocationInterceptor interceptor) {

    if (type.isInterface()) {
        ProxyFactory factory = new ProxyFactory(EmptyTargetSource.INSTANCE);
        factory.addInterface(type);//from  w w w  .  j a  v a  2 s  . c o  m
        factory.addInterface(ControllerMethodValues.class);
        factory.addAdvice(interceptor);
        return (T) factory.getProxy();
    } else {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(type);
        enhancer.setInterfaces(new Class<?>[] { ControllerMethodValues.class });
        enhancer.setCallbackType(org.springframework.cglib.proxy.MethodInterceptor.class);

        Factory factory = (Factory) OBJENESIS.newInstance(enhancer.createClass());
        factory.setCallbacks(new Callback[] { interceptor });
        return (T) factory;
    }
}