Example usage for org.springframework.aop.framework ProxyFactory ProxyFactory

List of usage examples for org.springframework.aop.framework ProxyFactory ProxyFactory

Introduction

In this page you can find the example usage for org.springframework.aop.framework ProxyFactory ProxyFactory.

Prototype

public ProxyFactory() 

Source Link

Document

Create a new ProxyFactory.

Usage

From source file:org.springframework.aop.interceptor.ConcurrencyThrottleInterceptorTests.java

@Test
public void testSerializable() throws Exception {
    DerivedTestBean tb = new DerivedTestBean();
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setInterfaces(new Class[] { ITestBean.class });
    ConcurrencyThrottleInterceptor cti = new ConcurrencyThrottleInterceptor();
    proxyFactory.addAdvice(cti);//  w ww.  j  a  va 2  s.c  o  m
    proxyFactory.setTarget(tb);
    ITestBean proxy = (ITestBean) proxyFactory.getProxy();
    proxy.getAge();

    ITestBean serializedProxy = (ITestBean) SerializationTestUtils.serializeAndDeserialize(proxy);
    Advised advised = (Advised) serializedProxy;
    ConcurrencyThrottleInterceptor serializedCti = (ConcurrencyThrottleInterceptor) advised.getAdvisors()[0]
            .getAdvice();
    assertEquals(cti.getConcurrencyLimit(), serializedCti.getConcurrencyLimit());
    serializedProxy.getAge();
}

From source file:org.springframework.aop.interceptor.ConcurrencyThrottleInterceptorTests.java

private void testMultipleThreads(int concurrencyLimit) {
    TestBean tb = new TestBean();
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setInterfaces(new Class[] { ITestBean.class });
    ConcurrencyThrottleInterceptor cti = new ConcurrencyThrottleInterceptor();
    cti.setConcurrencyLimit(concurrencyLimit);
    proxyFactory.addAdvice(cti);/*from  w  w  w.j a  va2 s.c  om*/
    proxyFactory.setTarget(tb);
    ITestBean proxy = (ITestBean) proxyFactory.getProxy();

    Thread[] threads = new Thread[NR_OF_THREADS];
    for (int i = 0; i < NR_OF_THREADS; i++) {
        threads[i] = new ConcurrencyThread(proxy, null);
        threads[i].start();
    }
    for (int i = 0; i < NR_OF_THREADS / 10; i++) {
        try {
            Thread.sleep(5);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        threads[i] = new ConcurrencyThread(proxy,
                i % 2 == 0 ? (Throwable) new OutOfMemoryError() : (Throwable) new IllegalStateException());
        threads[i].start();
    }
    for (int i = 0; i < NR_OF_THREADS; i++) {
        try {
            threads[i].join();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:org.springframework.batch.core.listener.AbstractListenerFactoryBean.java

@Override
public Object getObject() {
    if (metaDataMap == null) {
        metaDataMap = new HashMap<String, String>();
    }//from   w w  w. j av  a 2 s .  com
    // Because all annotations and interfaces should be checked for, make
    // sure that each meta data
    // entry is represented.
    for (ListenerMetaData metaData : this.getMetaDataValues()) {
        if (!metaDataMap.containsKey(metaData.getPropertyName())) {
            // put null so that the annotation and interface is checked
            metaDataMap.put(metaData.getPropertyName(), null);
        }
    }

    Set<Class<?>> listenerInterfaces = new HashSet<Class<?>>();

    // For every entry in the map, try and find a method by interface, name,
    // or annotation. If the same
    Map<String, Set<MethodInvoker>> invokerMap = new HashMap<String, Set<MethodInvoker>>();
    boolean synthetic = false;
    for (Entry<String, String> entry : metaDataMap.entrySet()) {
        final ListenerMetaData metaData = this.getMetaDataFromPropertyName(entry.getKey());
        Set<MethodInvoker> invokers = new HashSet<MethodInvoker>();

        MethodInvoker invoker;
        invoker = getMethodInvokerForInterface(metaData.getListenerInterface(), metaData.getMethodName(),
                delegate, metaData.getParamTypes());
        if (invoker != null) {
            invokers.add(invoker);
        }

        invoker = getMethodInvokerByName(entry.getValue(), delegate, metaData.getParamTypes());
        if (invoker != null) {
            invokers.add(invoker);
            synthetic = true;
        }

        if (metaData.getAnnotation() != null) {
            invoker = getMethodInvokerByAnnotation(metaData.getAnnotation(), delegate,
                    metaData.getParamTypes());
            if (invoker != null) {
                invokers.add(invoker);
                synthetic = true;
            }
        }

        if (!invokers.isEmpty()) {
            invokerMap.put(metaData.getMethodName(), invokers);
            listenerInterfaces.add(metaData.getListenerInterface());
        }

    }

    if (listenerInterfaces.isEmpty()) {
        listenerInterfaces.add(this.getDefaultListenerClass());
    }

    if (!synthetic) {
        int count = 0;
        for (Class<?> listenerInterface : listenerInterfaces) {
            if (listenerInterface.isInstance(delegate)) {
                count++;
            }
        }
        // All listeners can be supplied by the delegate itself
        if (count == listenerInterfaces.size()) {
            return delegate;
        }
    }

    boolean ordered = false;
    if (delegate instanceof Ordered) {
        ordered = true;
        listenerInterfaces.add(Ordered.class);
    }

    // create a proxy listener for only the interfaces that have methods to
    // be called
    ProxyFactory proxyFactory = new ProxyFactory();
    if (delegate instanceof Advised) {
        proxyFactory.setTargetSource(((Advised) delegate).getTargetSource());
    } else {
        proxyFactory.setTarget(delegate);
    }
    proxyFactory.setInterfaces(listenerInterfaces.toArray(new Class[0]));
    proxyFactory
            .addAdvisor(new DefaultPointcutAdvisor(new MethodInvokerMethodInterceptor(invokerMap, ordered)));
    return proxyFactory.getProxy();

}

From source file:org.springframework.batch.core.step.item.FaultTolerantStepFactoryBeanTests.java

/**
 * Check ItemStream is opened//from  w w  w  . j a  v  a  2 s .c  o  m
 */
@SuppressWarnings("unchecked")
@Test
public void testProxiedItemStreamOpened() throws Exception {
    writer.setFailures("4");

    ItemStreamReader<String> reader = new ItemStreamReader<String>() {
        @Override
        public void close() throws ItemStreamException {
            closed = true;
        }

        @Override
        public void open(ExecutionContext executionContext) throws ItemStreamException {
            opened = true;
        }

        @Override
        public void update(ExecutionContext executionContext) throws ItemStreamException {
        }

        @Override
        public String read() throws Exception, UnexpectedInputException, ParseException {
            return null;
        }
    };

    ProxyFactory proxy = new ProxyFactory();
    proxy.setTarget(reader);
    proxy.setInterfaces(new Class<?>[] { ItemReader.class, ItemStream.class });
    proxy.addAdvice(new MethodInterceptor() {
        @Override
        public Object invoke(MethodInvocation invocation) throws Throwable {
            return invocation.proceed();
        }
    });
    Object advised = proxy.getProxy();

    factory.setItemReader((ItemReader<? extends String>) advised);
    factory.setStreams(new ItemStream[] { (ItemStream) advised });

    Step step = factory.getObject();

    step.execute(stepExecution);

    assertTrue(opened);
    assertTrue(closed);
    assertEquals(BatchStatus.COMPLETED, stepExecution.getStatus());
}

From source file:org.springframework.jmx.export.MBeanExporter.java

/**
 * Registers beans that are configured for lazy initialization with the
 * <code>MBeanServer<code> indirectly through a proxy.
 * @param beanName the name of the bean in the <code>BeanFactory</code>
 * @param beanKey the key associated with this bean in the beans map
 * @return the <code>ObjectName</code> under which the bean was registered
 * with the <code>MBeanServer</code>
 * @throws JMException an error in the underlying JMX infrastructure
 * @throws InvalidTargetObjectTypeException an error in the definition of the MBean resource
 *//*w w w  . jav  a  2 s .c  om*/
private ObjectName registerLazyInit(String beanName, String beanKey)
        throws JMException, InvalidTargetObjectTypeException {

    LazyInitTargetSource targetSource = new LazyInitTargetSource();
    targetSource.setTargetBeanName(beanName);
    targetSource.setBeanFactory(this.beanFactory);

    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setTargetSource(targetSource);
    proxyFactory.setProxyTargetClass(true);
    proxyFactory.setFrozen(true);

    Object proxy = proxyFactory.getProxy();
    ObjectName objectName = getObjectName(proxy, beanKey);
    if (logger.isDebugEnabled()) {
        logger.debug("Registering lazy-init MBean [" + objectName + "]");
    }

    ModelMBean mbean = createModelMBean();
    mbean.setModelMBeanInfo(getMBeanInfo(proxy, beanKey));
    mbean.setManagedResource(proxy, MR_TYPE_OBJECT_REFERENCE);

    return doRegister(mbean, objectName);
}

From source file:org.springframework.osgi.service.OsgiServiceProxyFactoryBean.java

/**
 * We proxy the actual service so that we can listen to service events
 * and rebind transparently if the service goes down and comes back up
 * for example/*from   ww w  . ja  va2 s  .com*/
 */
private Object getServiceProxyFor(Object target, String lookupFilter) {
    ProxyFactory pf = new ProxyFactory();
    if (getServiceType().isInterface()) {
        pf.setInterfaces(new Class[] { getServiceType() });
    }
    HotSwappableTargetSource targetSource = new HotSwappableTargetSource(target);
    pf.setTargetSource(targetSource);
    OsgiServiceInterceptor interceptor = new OsgiServiceInterceptor(this.bundleContext, this.serviceReference,
            targetSource, getServiceType(), lookupFilter);
    interceptor.setMaxRetries(this.retryOnUnregisteredService ? this.maxRetries : 0);
    interceptor.setRetryIntervalMillis(this.millisBetweenRetries);
    pf.addAdvice(interceptor);
    ClassLoader classLoader = ((DefaultResourceLoader) this.applicationContext).getClassLoader();
    return pf.getProxy(classLoader);
}

From source file:org.springframework.remoting.support.RemoteExporter.java

/**
 * Get a proxy for the given service object, implementing the specified
 * service interface.//  ww w. j av a  2  s  . c  o m
 * <p>Used to export a proxy that does not expose any internals but just
 * a specific interface intended for remote access. Furthermore, a
 * RemoteInvocationTraceInterceptor gets registered (by default).
 * @return the proxy
 * @see #setServiceInterface
 * @see #setRegisterTraceInterceptor
 * @see RemoteInvocationTraceInterceptor
 */
protected Object getProxyForService() {
    checkService();
    checkServiceInterface();
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.addInterface(getServiceInterface());
    if (isRegisterTraceInterceptor()) {
        proxyFactory.addAdvice(new RemoteInvocationTraceInterceptor(getExporterName()));
    }
    proxyFactory.setTarget(getService());
    return proxyFactory.getProxy();
}

From source file:org.springframework.scripting.support.ScriptFactoryPostProcessor.java

/**
 * Create a refreshable proxy for the given AOP TargetSource.
 * @param ts the refreshable TargetSource
 * @param interfaces the proxy interfaces (may be {@code null} to
 * indicate proxying of all interfaces implemented by the target class)
 * @return the generated proxy/*from ww  w  .j  a v  a 2  s . c om*/
 * @see RefreshableScriptTargetSource
 */
protected Object createRefreshableProxy(TargetSource ts, @Nullable Class<?>[] interfaces,
        boolean proxyTargetClass) {
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setTargetSource(ts);
    ClassLoader classLoader = this.beanClassLoader;

    if (interfaces != null) {
        proxyFactory.setInterfaces(interfaces);
    } else {
        Class<?> targetClass = ts.getTargetClass();
        if (targetClass != null) {
            proxyFactory.setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, this.beanClassLoader));
        }
    }

    if (proxyTargetClass) {
        classLoader = null; // force use of Class.getClassLoader()
        proxyFactory.setProxyTargetClass(true);
    }

    DelegatingIntroductionInterceptor introduction = new DelegatingIntroductionInterceptor(ts);
    introduction.suppressInterface(TargetSource.class);
    proxyFactory.addAdvice(introduction);

    return proxyFactory.getProxy(classLoader);
}