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

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

Introduction

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

Prototype

public void setInterfaces(Class<?>... interfaces) 

Source Link

Document

Set the interfaces to be proxied.

Usage

From source file:org.nabucco.alfresco.enhScriptEnv.common.script.converter.rhino.ScriptableFacadeMapConverter.java

/**
 * {@inheritDoc}/*from www.  j a va2  s.co  m*/
 */
@Override
public Object convertValueForScript(final Object value, final ValueConverter globalDelegate,
        final Class<?> expectedClass) {
    if (!(value instanceof Map<?, ?>)) {
        throw new IllegalArgumentException("value must be a Map");
    }

    final Object result;

    final ProxyFactory proxyFactory = new ProxyFactory();

    proxyFactory.addAdvice(new AdapterObjectInterceptor());
    proxyFactory.addAdvice(new ScriptableBaseAdapterInterceptor());
    proxyFactory.addAdvice(new ScriptableListLikeMapAdapterInterceptor());
    proxyFactory.addAdvice(new ScriptableMapListAdapterInterceptor());
    proxyFactory.addAdvice(new MapLengthFacadeInterceptor(Undefined.instance, false));
    // proxyFactory.addAdvice(new ListLikeMapAdapterInterceptor());
    // some existing scripts in Alfresco expect Map-contained strings not to be converted
    proxyFactory.addAdvice(new ValueConvertingMapInterceptor(globalDelegate, true));

    // this somehow worked in Java 8 Nashorn PoC, but return types of remove(Object) differ between Map and List
    // proxyFactory.setInterfaces(ClassUtils.collectInterfaces(value, Arrays.<Class<?>> asList(Scriptable.class, List.class, AdapterObject.class)));
    proxyFactory.setInterfaces(ClassUtils.collectInterfaces(value,
            Arrays.<Class<?>>asList(Scriptable.class, AdapterObject.class)));

    proxyFactory.setTarget(value);

    result = proxyFactory.getProxy();
    return result;
}

From source file:ome.services.blitz.impl.AbstractAmdServant.java

/**
 * Applies the hard-wired intercepting to this instance. It is not possible
 * to configure hard-wired interceptors in Spring, instead they must be
 * passed in at runtime from a properly compiled class.
 *///from www  .j a  v a2s  .c o  m
public final void applyHardWiredInterceptors(List<HardWiredInterceptor> cptors,
        AopContextInitializer initializer) {

    if (service != null) {
        ProxyFactory wiredService = new ProxyFactory();
        wiredService.setInterfaces(service.getClass().getInterfaces());
        wiredService.setTarget(service);

        List<HardWiredInterceptor> reversed = new ArrayList<HardWiredInterceptor>(cptors);
        Collections.reverse(reversed);
        for (HardWiredInterceptor hwi : reversed) {
            wiredService.addAdvice(0, hwi);
        }
        wiredService.addAdvice(0, initializer);
        service = (ServiceInterface) wiredService.getProxy();
    }
}

From source file:org.impalaframework.service.proxy.ProxyHelper.java

/**
 * Possibly wraps bean with proxy. Based on following rules:
 * <ul>//from   ww w . j  av  a  2 s.com
 * <li>if proxyEntries is false, then does not wrap
 * <li>if the bean does not implement any interface, then does not wrap
 * <li>if proxyInterfaces is not empty, but bean does not implement any of the specified interface, then does not wrap
 * <li>if proxyInterfaces is not empty, then wraps with proxy, exposing with interfaces which are both are in proxyInterfaces and implemented by bean
 * <li>if proxyInterfaces is null or empty, then wraps with proxy, exposing with all interfaces implemented by bean
 * </ul>
 */
public Object maybeGetProxy(ServiceRegistryEntry entry) {

    Object bean = entry.getServiceBeanReference().getService();

    if (!proxyEntries) {
        return bean;
    }

    final List<Class<?>> interfaces = ReflectionUtils.findInterfaceList(bean);

    if (interfaces.size() == 0) {
        logger.warn("Bean of instance " + bean.getClass().getName()
                + " could not be backed by a proxy as it does not implement an interface");
        return bean;
    }

    final Class<?>[] proxyInterfaces = this.proxyInterfaces;

    final List<Class<?>> filteredInterfaces = filterInterfaces(interfaces, proxyInterfaces);

    if (filteredInterfaces.size() == 0) {
        logger.warn("Bean of instance " + bean.getClass().getName()
                + " does not implement any of the specified interfaces: " + proxyInterfaces);
        return bean;
    }

    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setInterfaces(filteredInterfaces.toArray(new Class[0]));
    proxyFactory.setTarget(bean);
    final Object proxyObject = proxyFactory.getProxy();
    return proxyObject;
}

From source file:org.openengsb.core.services.internal.ConnectorRegistrationManager.java

private Connector proxyForSecurity(String id, ConnectorDescription description, Connector serviceInstance,
        Class<?>[] clazzes) {
    if (INTERCEPTOR_BLACKLIST.contains(description.getDomainType())) {
        LOGGER.info("not proxying service because domain is blacklisted: {} ", serviceInstance);
        return serviceInstance;
    }/*ww  w.  j  a va  2s. c om*/
    if (securityInterceptor == null) {
        LOGGER.warn("security interceptor is not available yet");
        return serviceInstance;
    }
    // @extract-start register-secure-service-code
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setInterfaces(clazzes);
    proxyFactory.addAdvice(securityInterceptor);
    proxyFactory.setTarget(serviceInstance);
    Connector result = (Connector) proxyFactory.getProxy(this.getClass().getClassLoader());
    // @extract-end
    attributeStore.replaceAttributes(serviceInstance, new SecurityAttributeEntry("name", id));
    return result;
}

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);//www  . j  ava  2  s  . com
    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);/* ww w  .j  av a  2  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 a v  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  a2s .c om*/
 */
@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.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/* w w  w  . j  av  a  2s .  c o m*/
 */
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.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   w  ww .  j  av a  2s . 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);
}