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:com.alibaba.cobar.client.datasources.ha.FailoverHotSwapDataSourceCreator.java

public DataSource createHADataSource(CobarDataSourceDescriptor descriptor) throws Exception {
    DataSource activeDataSource = descriptor.getTargetDataSource();
    DataSource standbyDataSource = descriptor.getStandbyDataSource();
    if (activeDataSource == null && standbyDataSource == null) {
        throw new IllegalArgumentException("must have at least one data source active.");
    }//from  w  w  w. j a v  a 2 s. co  m
    if (activeDataSource == null || standbyDataSource == null) {
        logger.warn("only one data source is available for use, so no HA support.");
        if (activeDataSource == null) {
            return standbyDataSource;
        }
        return activeDataSource;
    }

    HotSwappableTargetSource targetSource = new HotSwappableTargetSource(activeDataSource);
    ProxyFactory pf = new ProxyFactory();
    pf.setInterfaces(new Class[] { DataSource.class });
    pf.setTargetSource(targetSource);

    if (isPositiveFailoverEnable()) {
        DataSource targetDetectorDataSource = descriptor.getTargetDetectorDataSource();
        DataSource standbyDetectorDataSource = descriptor.getStandbyDetectorDataSource();
        if (targetDetectorDataSource == null || standbyDetectorDataSource == null) {
            throw new IllegalArgumentException(
                    "targetDetectorDataSource or standbyDetectorDataSource can't be null if positive failover is enabled.");
        }
        // 1. create active monitoring job for failover event
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        ExecutorService jobExecutor = Executors.newFixedThreadPool(1);
        jobExecutorRegistry.add(jobExecutor);
        FailoverMonitorJob job = new FailoverMonitorJob(jobExecutor);
        //    1.1  inject dependencies
        job.setHotSwapTargetSource(targetSource);
        job.setMasterDataSource(activeDataSource);
        job.setStandbyDataSource(standbyDataSource);
        job.setMasterDetectorDataSource(targetDetectorDataSource);
        job.setStandbyDetectorDataSource(standbyDetectorDataSource);
        job.setCurrentDetectorDataSource(targetDetectorDataSource);
        job.setDetectingRequestTimeout(getDetectingTimeoutThreshold());
        job.setDetectingSQL(getDetectingSql());
        job.setRecheckInterval(recheckInterval);
        job.setRecheckTimes(recheckTimes);
        //    1.2  start scheduling and keep reference for canceling and shutdown
        ScheduledFuture<?> future = scheduler.scheduleWithFixedDelay(job, initialDelay, monitorPeriod,
                TimeUnit.MILLISECONDS);
        schedulerFutures.put(future, scheduler);
    }

    if (isPassiveFailoverEnable()) {
        // 2. create data source proxy with passive event advice
        PassiveEventHotSwappableAdvice advice = new PassiveEventHotSwappableAdvice();
        advice.setRetryInterval(recheckInterval);
        advice.setRetryTimes(recheckTimes);
        advice.setDetectingSql(detectingSql);
        advice.setTargetSource(targetSource);
        advice.setMainDataSource(activeDataSource);
        advice.setStandbyDataSource(standbyDataSource);
        pf.addAdvice(advice);
    }

    return (DataSource) pf.getProxy();
}

From source file:cn.vko.cache.dao.ha.FailoverHotSwapDataSourceCreator.java

@Override
public DataSource createHADataSource(DataSourceDescriptor descriptor) throws Exception {
    DataSource activeDataSource = descriptor.getTarget();
    DataSource standbyDataSource = descriptor.getStandby();
    if (activeDataSource == null && standbyDataSource == null) {
        throw new IllegalArgumentException("must have at least one data source active.");
    }//from  ww w  . j  ava2s .com
    if (activeDataSource == null || standbyDataSource == null) {
        logger.warn("only one data source is available for use, so no HA support.");
        if (activeDataSource == null) {
            return standbyDataSource;
        }
        return activeDataSource;
    }

    HotSwappableTargetSource targetSource = new HotSwappableTargetSource(activeDataSource);
    ProxyFactory pf = new ProxyFactory();
    pf.setInterfaces(new Class[] { DataSource.class });
    pf.setTargetSource(targetSource);

    if (isPositiveFailoverEnable()) {
        DataSource targetDetectorDataSource = descriptor.getTarget();
        DataSource standbyDetectorDataSource = descriptor.getStandby();
        if (targetDetectorDataSource == null || standbyDetectorDataSource == null) {
            throw new IllegalArgumentException(
                    "targetDetectorDataSource or standbyDetectorDataSource can't be null if positive failover is enabled.");
        }
        // 1. create active monitoring job for failover event
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        ExecutorService jobExecutor = Executors.newFixedThreadPool(1);
        jobExecutorRegistry.add(jobExecutor);
        FailoverMonitorJob job = new FailoverMonitorJob(jobExecutor);
        //    1.1  inject dependencies
        job.setHotSwapTargetSource(targetSource);
        job.setMasterDataSource(activeDataSource);
        job.setStandbyDataSource(standbyDataSource);
        job.setMasterDetectorDataSource(targetDetectorDataSource);
        job.setStandbyDetectorDataSource(standbyDetectorDataSource);
        job.setCurrentDetectorDataSource(targetDetectorDataSource);
        job.setDetectingRequestTimeout(getDetectingTimeoutThreshold());
        job.setDetectingSQL(getDetectingSql());
        job.setRecheckInterval(recheckInterval);
        job.setRecheckTimes(recheckTimes);
        //    1.2  start scheduling and keep reference for canceling and shutdown
        ScheduledFuture<?> future = scheduler.scheduleWithFixedDelay(job, initialDelay, monitorPeriod,
                TimeUnit.MILLISECONDS);
        schedulerFutures.put(future, scheduler);
    }

    if (isPassiveFailoverEnable()) {
        // 2. create data source proxy with passive event advice
        PassiveEventHotSwappableAdvice advice = new PassiveEventHotSwappableAdvice();
        advice.setRetryInterval(recheckInterval);
        advice.setRetryTimes(recheckTimes);
        advice.setDetectingSql(detectingSql);
        advice.setTargetSource(targetSource);
        advice.setMainDataSource(activeDataSource);
        advice.setStandbyDataSource(standbyDataSource);
        pf.addAdvice(advice);
    }

    return (DataSource) pf.getProxy();
}

From source file:org.codehaus.grepo.core.repository.GenericRepositoryFactoryBean.java

/**
 * {@inheritDoc}/*w  w w .  ja  va  2 s . co  m*/
 */
public Object getObject() throws Exception {
    // validate factory configuration
    validate();

    // create target
    T target = createTarget();
    configureTarget(target);

    // create proxy
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setTarget(target);
    proxyFactory.setInterfaces(new Class[] { proxyInterface });
    proxyFactory.addAdvice(configuration.getMethodInterceptor());
    return proxyFactory.getProxy();
}

From source file:com.sinosoft.one.data.jpa.repository.support.OneRepositoryFactorySupport.java

/**
 * Returns a repository instance for the given interface backed by an instance providing implementation logic for
 * custom logic./*from w  w  w. ja  v  a2 s . c o  m*/
 *
 * @param <T>
 * @param repositoryInterface
 * @param customImplementation
 * @return
 */
@SuppressWarnings({ "unchecked" })
public <T> T getRepository(Class<T> repositoryInterface, Object customImplementation) {

    RepositoryMetadata metadata = getRepositoryMetadata(repositoryInterface);
    Class<?> customImplementationClass = null == customImplementation ? null : customImplementation.getClass();
    RepositoryInformation information = getRepositoryInformation(metadata, customImplementationClass);

    validate(information, customImplementation);

    Object target = getTargetRepository(information);

    // Create proxy
    ProxyFactory result = new ProxyFactory();
    result.setTarget(target);
    result.setInterfaces(new Class[] { repositoryInterface, Repository.class });

    for (RepositoryProxyPostProcessor processor : postProcessors) {
        processor.postProcess(result);
    }

    result.addAdvice(new OneQueryExecutorMethodInterceptor(information, customImplementation, target));

    return (T) result.getProxy();
}

From source file:savetheenvironment.refresh.RefreshableFactoryBean.java

@Override
@SuppressWarnings("unchecked")
public T getObject() throws Exception {

    if (null == this.atomicReference.get()) {
        updateBeanReference();/*from  w  w w  .jav a 2  s. c  o  m*/
    }

    T beanReference = atomicReference.get();

    ProxyFactory pf = new ProxyFactory(beanReference);
    pf.setProxyTargetClass(true);
    List<Class<?>> listOfClasses = new ArrayList<Class<?>>();
    listOfClasses.add(Refreshable.class);
    listOfClasses.add(ApplicationListener.class);
    listOfClasses.add(DisposableBean.class);
    listOfClasses.addAll(Arrays.asList(beanReference.getClass().getInterfaces()));
    pf.setInterfaces(listOfClasses.toArray(new Class[listOfClasses.size()]));
    pf.addAdvice(new MethodInterceptor() {

        @Override
        public Object invoke(MethodInvocation invocation) throws Throwable {
            Method method = invocation.getMethod();
            // if someone externally calls refresh, then rebuild the reference
            if (method.equals(refreshMethod)) {
                updateBeanReference();
                return atomicReference.get();
            } else if (method.equals(disposeMethod)) {
                T atomicT = atomicReference.get();
                if (atomicT instanceof DisposableBean) {
                    ((DisposableBean) atomicT).destroy();
                }
            } else if (method.equals(onApplicationEventMethod)) {
                Object[] arguments = invocation.getArguments();
                if (arguments[0] instanceof RefreshEvent) {
                    updateBeanReference();
                }
                return null;
            }
            // otherwise send the request on through to the underlying object unchanged
            Object ref = atomicReference.get();
            return method.invoke(ref, invocation.getArguments());

        }
    });
    Object o = pf.getProxy();
    return (T) o;
}

From source file:org.synyx.hades.dao.orm.GenericDaoFactory.java

/**
 * Returns a DAO instance for the given interface backed by an instance
 * providing implementation logic for custom logic.
 * //from w  w  w .j  av a 2  s .  com
 * @param <T>
 * @param daoInterface
 * @param customDaoImplementation
 * @return
 */
@SuppressWarnings("unchecked")
public <T extends GenericDao<?, ?>> T getDao(Class<T> daoInterface, Object customDaoImplementation) {

    validate(daoInterface, customDaoImplementation);

    try {
        // Instantiate generic dao
        @SuppressWarnings("rawtypes")
        GenericDaoSupport genericJpaDao = getDaoClass().newInstance();
        genericJpaDao.setEntityManager(entityManager);
        genericJpaDao.setDomainClass(ClassUtils.getDomainClass(daoInterface));
        genericJpaDao.validate();

        // Create proxy
        ProxyFactory result = new ProxyFactory();
        result.setTarget(genericJpaDao);
        result.setInterfaces(new Class[] { daoInterface });

        for (DaoProxyPostProcessor processor : postProcessors) {
            processor.postProcess(result);
        }

        result.addAdvice(
                new QueryExecuterMethodInterceptor(daoInterface, customDaoImplementation, genericJpaDao));

        return (T) result.getProxy();
    } catch (InstantiationException e) {
        throw new IllegalStateException(e);
    } catch (IllegalAccessException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.springmodules.cache.interceptor.proxy.CacheProxyFactoryBean.java

/**
 * Creates the proxy for target object. This method is invoked by a
 * BeanFactory after it has set all bean properties supplied.
 * /*w w w .j av a2 s  .c o m*/
 * @throws IllegalStateException
 *           if target is <code>null</code>.
 * @throws AopConfigException
 *           if the proxy interfaces or proxyTargetClass are not set and the
 *           target type is <code>org.springframework.aop.TargetSource</code>.
 */
public void afterPropertiesSet() throws IllegalStateException, AopConfigException {
    cachingInterceptor.afterPropertiesSet();
    flushingInterceptor.afterPropertiesSet();

    if (target == null) {
        throw new IllegalStateException("Property 'target' is required");
    }

    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.addAdvisor(new CachingModelSourceAdvisor(cachingInterceptor));

    if (hasFlushingModels) {
        proxyFactory.addAdvisor(new FlushingModelSourceAdvisor(flushingInterceptor));
    }

    proxyFactory.copyFrom(this);

    TargetSource targetSource = createTargetSource(target);
    proxyFactory.setTargetSource(targetSource);

    if (proxyInterfaces != null) {
        proxyFactory.setInterfaces(proxyInterfaces);
    } else if (!isProxyTargetClass()) {
        if (target instanceof TargetSource) {
            throw new AopConfigException("Either 'proxyInterfaces' or 'proxyTargetClass' is required "
                    + "when using a TargetSource as 'target'");
        }

        // rely on AOP infrastructure to tell us what interfaces to proxy
        proxyFactory.setInterfaces(ClassUtils.getAllInterfaces(target));
    }

    proxy = proxyFactory.getProxy();
}

From source file:org.iff.infra.util.spring.script.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   www.j  a v a 2  s .co m*/
 * @see RefreshableScriptTargetSource
 */
protected Object createRefreshableProxy(TargetSource ts, Class<?>[] interfaces, boolean proxyTargetClass) {
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setTargetSource(ts);
    ClassLoader classLoader = this.beanClassLoader;

    if (interfaces == null) {
        interfaces = ClassUtils.getAllInterfacesForClass(ts.getTargetClass(), this.beanClassLoader);
    }
    proxyFactory.setInterfaces(interfaces);
    if (proxyTargetClass) {
        classLoader = null; // force use of Class.getClassLoader()
        proxyFactory.setProxyTargetClass(proxyTargetClass);
    }

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

    return proxyFactory.getProxy(classLoader);
}

From source file:com.helpinput.spring.proxy.OptimizeTransactionProxyFactoryBean.java

public void afterPropertiesSet() {
    if (this.target == null) {
        throw new IllegalArgumentException("Property 'target' is required");
    }/*  w ww  . ja  va 2s .c om*/
    if (this.target instanceof String) {
        throw new IllegalArgumentException("'target' needs to be a bean reference, not a bean name as value");
    }

    ClassLoader proxyClassLoader = target.getClass().getClassLoader();

    ProxyFactory proxyFactory = new ProxyFactory();

    if (this.preInterceptors != null) {
        for (Object interceptor : this.preInterceptors) {
            proxyFactory.addAdvisor(this.advisorAdapterRegistry.wrap(interceptor));
        }
    }

    // Add the main interceptor (typically an Advisor).
    proxyFactory.addAdvisor(this.advisorAdapterRegistry.wrap(createMainInterceptor()));

    if (this.postInterceptors != null) {
        for (Object interceptor : this.postInterceptors) {
            proxyFactory.addAdvisor(this.advisorAdapterRegistry.wrap(interceptor));
        }
    }

    proxyFactory.copyFrom(this);

    TargetSource targetSource = createTargetSource(this.target);
    proxyFactory.setTargetSource(targetSource);

    if (this.proxyInterfaces != null) {
        proxyFactory.setInterfaces(this.proxyInterfaces);
    } else if (!isProxyTargetClass()) {
        // Rely on AOP infrastructure to tell us what interfaces to proxy.
        proxyFactory.setInterfaces(
                ClassUtils.getAllInterfacesForClass(targetSource.getTargetClass(), proxyClassLoader));
    }

    /**
     * use this option to let proxyFactory user cglib to create proxy,otherwise in dynamic script ,this is no dynamic interface
     * ? cglib ??java??
     */
    proxyFactory.setOptimize(true);
    this.proxy = proxyFactory.getProxy(proxyClassLoader);
}