Java Code Examples for org.springframework.aop.framework.Advised

The following are top voted examples for showing how to use org.springframework.aop.framework.Advised. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: spring-oauth2-samples   File: AbstractIntegrationTests.java   Source Code and License 8 votes vote down vote up
private void clear(TokenStore tokenStore) throws Exception {
	if (tokenStore instanceof Advised) {
		Advised advised = (Advised) tokenStore;
		TokenStore target = (TokenStore) advised.getTargetSource().getTarget();
		clear(target);
		return;
	}
	if (tokenStore instanceof InMemoryTokenStore) {
		((InMemoryTokenStore) tokenStore).clear();
	}
	if (tokenStore instanceof JdbcTokenStore) {
		JdbcTemplate template = new JdbcTemplate(dataSource);
		template.execute("delete from oauth_access_token");
		template.execute("delete from oauth_refresh_token");
		template.execute("delete from oauth_client_token");
		template.execute("delete from oauth_code");
	}
}
 
Example 2
Project: oma-riista-web   File: TestUtils.java   Source Code and License 6 votes vote down vote up
public static <T> T unwrapProxy(final Class<T> clazz, final Object proxy) {
    Object target = proxy;

    if (AopUtils.isAopProxy(proxy) && proxy instanceof Advised) {
        try {
            target = Advised.class.cast(proxy).getTargetSource().getTarget();
        } catch (final Exception e) {
            throw new RuntimeException(e);
        }
    }

    if (target != null && clazz.isAssignableFrom(target.getClass())) {
        return clazz.cast(target);
    }

    throw new IllegalArgumentException("proxy object does not represent given class: " + clazz.getSimpleName());
}
 
Example 3
Project: spring4-understanding   File: ConcurrencyThrottleInterceptorTests.java   Source Code and License 6 votes vote down vote up
@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);
	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();
}
 
Example 4
Project: spring4-understanding   File: EnableAsyncTests.java   Source Code and License 6 votes vote down vote up
@Test
public void customAsyncAnnotationIsPropagated() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(CustomAsyncAnnotationConfig.class);
	ctx.refresh();

	Object bean = ctx.getBean(CustomAsyncBean.class);
	assertTrue(AopUtils.isAopProxy(bean));
	boolean isAsyncAdvised = false;
	for (Advisor advisor : ((Advised)bean).getAdvisors()) {
		if (advisor instanceof AsyncAnnotationAdvisor) {
			isAsyncAdvised = true;
			break;
		}
	}
	assertTrue("bean was not async advised as expected", isAsyncAdvised);
}
 
Example 5
Project: spring4-understanding   File: AdvisedJRubyScriptFactoryTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testAdviseWithProxyFactoryBean() {
	ClassPathXmlApplicationContext ctx =
		new ClassPathXmlApplicationContext(FACTORYBEAN_CONTEXT, CLASS);
	try {
		Messenger bean = (Messenger) ctx.getBean("messenger");
		assertTrue("Bean is not a proxy", AopUtils.isAopProxy(bean));
		assertTrue("Bean is not an Advised object", bean instanceof Advised);

		CountingBeforeAdvice advice = (CountingBeforeAdvice) ctx.getBean("advice");
		assertEquals(0, advice.getCalls());
		bean.getMessage();
		assertEquals(1, advice.getCalls());
	} finally {
		ctx.close();
	}
}
 
Example 6
Project: spring4-understanding   File: AdvisedJRubyScriptFactoryTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testAdviseWithBeanNameAutoProxyCreator() {
	ClassPathXmlApplicationContext ctx =
		new ClassPathXmlApplicationContext(APC_CONTEXT, CLASS);
	try {
		Messenger bean = (Messenger) ctx.getBean("messenger");
		assertTrue("Bean is not a proxy", AopUtils.isAopProxy(bean));
		assertTrue("Bean is not an Advised object", bean instanceof Advised);

		CountingBeforeAdvice advice = (CountingBeforeAdvice) ctx.getBean("advice");
		assertEquals(0, advice.getCalls());
		bean.getMessage();
		assertEquals(1, advice.getCalls());
	} finally {
		ctx.close();
	}
}
 
Example 7
Project: spring4-understanding   File: AnnotationDrivenEventListenerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void eventListenerWorksWithSimpleInterfaceProxy() throws Exception {
	load(ScopedProxyTestBean.class);

	SimpleService proxy = this.context.getBean(SimpleService.class);
	assertTrue("bean should be a proxy", proxy instanceof Advised);
	this.eventCollector.assertNoEventReceived(proxy.getId());

	this.context.publishEvent(new ContextRefreshedEvent(this.context));
	this.eventCollector.assertNoEventReceived(proxy.getId());

	TestEvent event = new TestEvent();
	this.context.publishEvent(event);
	this.eventCollector.assertEvent(proxy.getId(), event);
	this.eventCollector.assertTotalEventsCount(1);
}
 
Example 8
Project: spring4-understanding   File: AnnotationDrivenEventListenerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void eventListenerWorksWithAnnotatedInterfaceProxy() throws Exception {
	load(AnnotatedProxyTestBean.class);

	AnnotatedSimpleService proxy = this.context.getBean(AnnotatedSimpleService.class);
	assertTrue("bean should be a proxy", proxy instanceof Advised);
	this.eventCollector.assertNoEventReceived(proxy.getId());

	this.context.publishEvent(new ContextRefreshedEvent(this.context));
	this.eventCollector.assertNoEventReceived(proxy.getId());

	TestEvent event = new TestEvent();
	this.context.publishEvent(event);
	this.eventCollector.assertEvent(proxy.getId(), event);
	this.eventCollector.assertTotalEventsCount(1);
}
 
Example 9
Project: spring4-understanding   File: BeanNamePointcutAtAspectTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testProgrammaticProxyCreation() {
	ITestBean testBean = new TestBean();

	AspectJProxyFactory factory = new AspectJProxyFactory();
	factory.setTarget(testBean);

	CounterAspect myCounterAspect = new CounterAspect();
	factory.addAspect(myCounterAspect);

	ITestBean proxyTestBean = factory.getProxy();

	assertTrue("Expected a proxy", proxyTestBean instanceof Advised);
	proxyTestBean.setAge(20);
	assertEquals("Programmatically created proxy shouldn't match bean()", 0, myCounterAspect.count);
}
 
Example 10
Project: spring4-understanding   File: AfterReturningAdviceBindingTests.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
	ClassPathXmlApplicationContext ctx =
		new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass());

	afterAdviceAspect = (AfterReturningAdviceBindingTestAspect) ctx.getBean("testAspect");

	mockCollaborator = mock(AfterReturningAdviceBindingCollaborator.class);
	afterAdviceAspect.setCollaborator(mockCollaborator);

	testBeanProxy = (ITestBean) ctx.getBean("testBean");
	assertTrue(AopUtils.isAopProxy(testBeanProxy));

	// we need the real target too, not just the proxy...
	this.testBeanTarget = (TestBean) ((Advised)testBeanProxy).getTargetSource().getTarget();
}
 
Example 11
Project: spring4-understanding   File: AroundAdviceBindingTests.java   Source Code and License 6 votes vote down vote up
@Before
public void onSetUp() throws Exception {
	ctx = new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass());

	AroundAdviceBindingTestAspect  aroundAdviceAspect = ((AroundAdviceBindingTestAspect) ctx.getBean("testAspect"));

	ITestBean injectedTestBean = (ITestBean) ctx.getBean("testBean");
	assertTrue(AopUtils.isAopProxy(injectedTestBean));

	this.testBeanProxy = injectedTestBean;
	// we need the real target too, not just the proxy...

	this.testBeanTarget = (TestBean) ((Advised) testBeanProxy).getTargetSource().getTarget();

	mockCollaborator = mock(AroundAdviceBindingCollaborator.class);
	aroundAdviceAspect.setCollaborator(mockCollaborator);
}
 
Example 12
Project: spring4-understanding   File: BenchmarkTests.java   Source Code and License 6 votes vote down vote up
private long testBeforeAdviceWithoutJoinPoint(String file, int howmany, String technology) {
	ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(file, CLASS);

	StopWatch sw = new StopWatch();
	sw.start(howmany + " repeated before advice invocations with " + technology);
	ITestBean adrian = (ITestBean) bf.getBean("adrian");

	assertTrue(AopUtils.isAopProxy(adrian));
	Advised a = (Advised) adrian;
	assertTrue(a.getAdvisors().length >= 3);
	assertEquals("adrian", adrian.getName());

	for (int i = 0; i < howmany; i++) {
		adrian.getName();
	}

	sw.stop();
	System.out.println(sw.prettyPrint());
	return sw.getLastTaskTimeMillis();
}
 
Example 13
Project: spring4-understanding   File: BenchmarkTests.java   Source Code and License 6 votes vote down vote up
private long testAfterReturningAdviceWithoutJoinPoint(String file, int howmany, String technology) {
	ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(file, CLASS);

	StopWatch sw = new StopWatch();
	sw.start(howmany + " repeated after returning advice invocations with " + technology);
	ITestBean adrian = (ITestBean) bf.getBean("adrian");

	assertTrue(AopUtils.isAopProxy(adrian));
	Advised a = (Advised) adrian;
	assertTrue(a.getAdvisors().length >= 3);
	// Hits joinpoint
	adrian.setAge(25);

	for (int i = 0; i < howmany; i++) {
		adrian.setAge(i);
	}

	sw.stop();
	System.out.println(sw.prettyPrint());
	return sw.getLastTaskTimeMillis();
}
 
Example 14
Project: spring4-understanding   File: BeforeAdviceBindingTests.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
	ClassPathXmlApplicationContext ctx =
		new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass());

	testBeanProxy = (ITestBean) ctx.getBean("testBean");
	assertTrue(AopUtils.isAopProxy(testBeanProxy));

	// we need the real target too, not just the proxy...
	testBeanTarget = (TestBean) ((Advised) testBeanProxy).getTargetSource().getTarget();

	AdviceBindingTestAspect beforeAdviceAspect = (AdviceBindingTestAspect) ctx.getBean("testAspect");

	mockCollaborator = mock(AdviceBindingCollaborator.class);
	beforeAdviceAspect.setCollaborator(mockCollaborator);
}
 
Example 15
Project: spring4-understanding   File: AnnotationTransactionAttributeSourceTests.java   Source Code and License 6 votes vote down vote up
@Test
public void serializable() throws Exception {
	TestBean1 tb = new TestBean1();
	CallCountingTransactionManager ptm = new CallCountingTransactionManager();
	AnnotationTransactionAttributeSource tas = new AnnotationTransactionAttributeSource();
	TransactionInterceptor ti = new TransactionInterceptor(ptm, tas);

	ProxyFactory proxyFactory = new ProxyFactory();
	proxyFactory.setInterfaces(new Class[] {ITestBean.class});
	proxyFactory.addAdvice(ti);
	proxyFactory.setTarget(tb);
	ITestBean proxy = (ITestBean) proxyFactory.getProxy();
	proxy.getAge();
	assertEquals(1, ptm.commits);

	ITestBean serializedProxy = (ITestBean) SerializationTestUtils.serializeAndDeserialize(proxy);
	serializedProxy.getAge();
	Advised advised = (Advised) serializedProxy;
	TransactionInterceptor serializedTi = (TransactionInterceptor) advised.getAdvisors()[0].getAdvice();
	CallCountingTransactionManager serializedPtm =
			(CallCountingTransactionManager) serializedTi.getTransactionManager();
	assertEquals(2, serializedPtm.commits);
}
 
Example 16
Project: spring4-understanding   File: EnableTransactionManagementIntegrationTests.java   Source Code and License 6 votes vote down vote up
private void assertTxProxying(AnnotationConfigApplicationContext ctx) {
	FooRepository repo = ctx.getBean(FooRepository.class);

	boolean isTxProxy = false;
	if (AopUtils.isAopProxy(repo)) {
		for (Advisor advisor : ((Advised)repo).getAdvisors()) {
			if (advisor instanceof BeanFactoryTransactionAttributeSourceAdvisor) {
				isTxProxy = true;
				break;
			}
		}
	}
	assertTrue("FooRepository is not a TX proxy", isTxProxy);

	// trigger a transaction
	repo.findAll();
}
 
Example 17
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: MockitoAopProxyTargetInterceptor.java   Source Code and License 6 votes vote down vote up
@Autowired
public static void applyTo(Object source) {
	Assert.state(AopUtils.isAopProxy(source), "Source must be an AOP proxy");
	try {
		Advised advised = (Advised) source;
		for (Advisor advisor : advised.getAdvisors()) {
			if (advisor instanceof MockitoAopProxyTargetInterceptor) {
				return;
			}
		}
		Object target = AopTestUtils.getUltimateTargetObject(source);
		Advice advice = new MockitoAopProxyTargetInterceptor(source, target);
		advised.addAdvice(0, advice);
	}
	catch (Exception ex) {
		throw new IllegalStateException("Unable to apply Mockito AOP support", ex);
	}
}
 
Example 18
Project: strategy-spring-security-acl   File: AclJpaQuery.java   Source Code and License 6 votes vote down vote up
private AclPredicateTargetSource installAclPredicateTargetSource() {
  synchronized (cachedCriteriaQuery) {
    Predicate restriction = cachedCriteriaQuery.getRestriction();

    if (restriction instanceof Advised) {
      Advised advised = (Advised) restriction;
      if (advised.getTargetSource() instanceof AclPredicateTargetSource) {
        return (AclPredicateTargetSource) advised.getTargetSource();
      }
    }

    AclPredicateTargetSource targetSource = new AclPredicateTargetSource(em.getCriteriaBuilder(), restriction);
    ProxyFactoryBean factoryBean = new ProxyFactoryBean();
    factoryBean.setTargetSource(targetSource);
    factoryBean.setAutodetectInterfaces(true);
    Predicate enhancedPredicate = (Predicate) factoryBean.getObject();
    logger.debug("ACL Jpa Specification target source initialized for criteria {}", cachedCriteriaQuery);

    // install proxy inside criteria
    cachedCriteriaQuery.where(enhancedPredicate);
    return targetSource;
  }
}
 
Example 19
Project: spring-boot-concourse   File: MockitoAopProxyTargetInterceptor.java   Source Code and License 6 votes vote down vote up
@Autowired
public static void applyTo(Object source) {
	Assert.state(AopUtils.isAopProxy(source), "Source must be an AOP proxy");
	try {
		Advised advised = (Advised) source;
		for (Advisor advisor : advised.getAdvisors()) {
			if (advisor instanceof MockitoAopProxyTargetInterceptor) {
				return;
			}
		}
		Object target = AopTestUtils.getUltimateTargetObject(source);
		Advice advice = new MockitoAopProxyTargetInterceptor(source, target);
		advised.addAdvice(0, advice);
	}
	catch (Exception ex) {
		throw new IllegalStateException("Unable to apply Mockito AOP support", ex);
	}
}
 
Example 20
Project: bd-codes   File: FXmain.java   Source Code and License 6 votes vote down vote up
public static void aopSchema() {
	// 参见com.bdsoft.bdceo.spring.aop.schema包和配置文件
	ApplicationContext app = iocInit("");

	// demo测试
	AOPDemo demo = null;
	try {
		Object target = ((Advised) app.getBean("aopDemo"))
				.getTargetSource().getTarget();
		demo = (AOPDemo) target;
		demo.login("bdceo", "");

		int c = ((ICounter) target).getCounter();
		System.out.println("计数:" + c);
	} catch (Exception e) {
		System.out.println("业务层捕获异常:" + e.getMessage());
	}

}
 
Example 21
Project: kc-rice   File: ProviderRegistryImpl.java   Source Code and License 6 votes vote down vote up
/**
   * Returns the object being proxied, otherwise the given object is returned.
   *
   * @param bean The proxy to get the underlying object.
   * @return object being proxied, otherwise the given object is returned.
   * @throws Exception if errors while getting the underlying object.
   */
  private Object unwrapProxy(Object bean) throws Exception {

/*
 * If the given object is a proxy, set the return value as the object
 * being proxied, otherwise return the given object.
 */
      if (AopUtils.isAopProxy(bean) && bean instanceof Advised) {

          Advised advised = (Advised) bean;

          bean = advised.getTargetSource().getTarget();
      }

      return bean;
  }
 
Example 22
Project: parfait   File: AdviceNotifier.java   Source Code and License 6 votes vote down vote up
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
		throws BeansException {
	if (bean instanceof Advised) {
		Advised advised = (Advised) bean;

		for (Advisor advisor : advised.getAdvisors()) {
			if (advisor instanceof AspectJPointcutAdvisor) {
				String foundName = ((AbstractAspectJAdvice) ((AspectJPointcutAdvisor) advisor)
						.getAdvice()).getAspectName();
				if (aspect.getName().equals(foundName)) {
					LOG.info(String.format("Found bean '%s' advised by %s; injecting", beanName, aspect));
					try {
						aspect.addAdvised(advised.getTargetSource().getTarget(), beanName);
					} catch (Exception e) {
						throw new RuntimeException(e);
					}
				}
			}
		}
	}
	return bean;
}
 
Example 23
Project: SecureBPMN   File: ProcessStartAnnotationBeanPostProcessor.java   Source Code and License 6 votes vote down vote up
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
 	if (bean instanceof AopInfrastructureBean) {
		// Ignore AOP infrastructure such as scoped proxies.
		return bean;
	}
	Class<?> targetClass = AopUtils.getTargetClass(bean);
	if (AopUtils.canApply(this.advisor, targetClass)) {
		if (bean instanceof Advised) {
			((Advised) bean).addAdvisor(0, this.advisor);
			return bean;
		}
		else {
			ProxyFactory proxyFactory = new ProxyFactory(bean);
			// Copy our properties (proxyTargetClass etc) inherited from ProxyConfig.
			proxyFactory.copyFrom(this);
			proxyFactory.addAdvisor(this.advisor);
			return proxyFactory.getProxy(this.beanClassLoader);
		}
	}
	else {
		// No async proxy needed.
		return bean;
	}
}
 
Example 24
Project: spring-cloud-task   File: TaskBatchExecutionListenerFactoryBean.java   Source Code and License 6 votes vote down vote up
private MapTaskBatchDao getMapTaskBatchDao() throws Exception {
	Field taskExecutionDaoField = ReflectionUtils.findField(SimpleTaskExplorer.class, "taskExecutionDao");
	taskExecutionDaoField.setAccessible(true);

	MapTaskExecutionDao taskExecutionDao;

	if(AopUtils.isJdkDynamicProxy(this.taskExplorer)) {
		SimpleTaskExplorer dereferencedTaskRepository = (SimpleTaskExplorer) ((Advised) this.taskExplorer).getTargetSource().getTarget();

		taskExecutionDao =
				(MapTaskExecutionDao) ReflectionUtils.getField(taskExecutionDaoField, dereferencedTaskRepository);
	}
	else {
		taskExecutionDao =
				(MapTaskExecutionDao) ReflectionUtils.getField(taskExecutionDaoField, this.taskExplorer);
	}

	return new MapTaskBatchDao(taskExecutionDao.getBatchJobAssociations());
}
 
Example 25
Project: cosmo   File: ExternalComponentDecorator.java   Source Code and License 6 votes vote down vote up
private static Object unwrapIfNecessary(Object obj, Provided annotation){
 	if(!annotation.unwrapIfProxied()){
 		return obj;
 	}
 	
 	if(AopUtils.isAopProxy(obj) && obj instanceof Advised) {
try {
	return ((Advised)obj).getTargetSource().getTarget();
} catch (Exception e) {
	LOGGER.error("Exception occured", e);
	throw new RuntimeException(e);
}
 	}
 	
 	return obj;
 }
 
Example 26
Project: stability-utils   File: JmxExportingAspectCircuitBreakerBeanPostprocessorTest.java   Source Code and License 6 votes vote down vote up
private Object extractPojo(MyService svc)
{
	Advised advisedBean = (Advised) svc;
	Advisor[] advisors = advisedBean.getAdvisors();
	for(Advisor advisor : advisors)
	{
		Advice advice = advisor.getAdvice();
		if(advice instanceof AbstractAspectJAdvice)
		{
			AbstractAspectJAdvice aaja = (AbstractAspectJAdvice) advice;
			Object target = aaja.getAspectInstanceFactory().getAspectInstance();
			return target;
		}
	}
	return null;
}
 
Example 27
Project: spring-cloud-commons   File: GenericScope.java   Source Code and License 6 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
	Method method = invocation.getMethod();
	if (AopUtils.isEqualsMethod(method)
			|| AopUtils.isToStringMethod(method)
			|| AopUtils.isHashCodeMethod(method)
			|| isScopedObjectGetTargetObject(method)) {
		return invocation.proceed();
	}
	Object proxy = getObject();
	Lock lock = locks.get(this.targetBeanName).readLock();
	lock.lock();
	try {
		if (proxy instanceof Advised) {
			Advised advised = (Advised) proxy;
			ReflectionUtils.makeAccessible(method);
			return ReflectionUtils.invokeMethod(method,
					advised.getTargetSource().getTarget(),
					invocation.getArguments());
		}
		return invocation.proceed();
	}
	finally {
		lock.unlock();
	}
}
 
Example 28
Project: class-guard   File: ConcurrencyThrottleInterceptorTests.java   Source Code and License 6 votes vote down vote up
@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);
	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();
}
 
Example 29
Project: class-guard   File: EnableAsyncTests.java   Source Code and License 6 votes vote down vote up
@Test
public void customAsyncAnnotationIsPropagated() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(CustomAsyncAnnotationConfig.class);
	ctx.refresh();

	Object bean = ctx.getBean(CustomAsyncBean.class);
	assertTrue(AopUtils.isAopProxy(bean));
	boolean isAsyncAdvised = false;
	for (Advisor advisor : ((Advised)bean).getAdvisors()) {
		if (advisor instanceof AsyncAnnotationAdvisor) {
			isAsyncAdvised = true;
			break;
		}
	}
	assertTrue("bean was not async advised as expected", isAsyncAdvised);
}
 
Example 30
Project: class-guard   File: AdvisedJRubyScriptFactoryTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testAdviseWithProxyFactoryBean() {
	ClassPathXmlApplicationContext ctx =
		new ClassPathXmlApplicationContext(FACTORYBEAN_CONTEXT, CLASS);
	try {
		Messenger bean = (Messenger) ctx.getBean("messenger");
		assertTrue("Bean is not a proxy", AopUtils.isAopProxy(bean));
		assertTrue("Bean is not an Advised object", bean instanceof Advised);

		CountingBeforeAdvice advice = (CountingBeforeAdvice) ctx.getBean("advice");
		assertEquals(0, advice.getCalls());
		bean.getMessage();
		assertEquals(1, advice.getCalls());
	} finally {
		ctx.close();
	}
}
 
Example 31
Project: class-guard   File: AdvisedJRubyScriptFactoryTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testAdviseWithBeanNameAutoProxyCreator() {
	ClassPathXmlApplicationContext ctx =
		new ClassPathXmlApplicationContext(APC_CONTEXT, CLASS);
	try {
		Messenger bean = (Messenger) ctx.getBean("messenger");
		assertTrue("Bean is not a proxy", AopUtils.isAopProxy(bean));
		assertTrue("Bean is not an Advised object", bean instanceof Advised);

		CountingBeforeAdvice advice = (CountingBeforeAdvice) ctx.getBean("advice");
		assertEquals(0, advice.getCalls());
		bean.getMessage();
		assertEquals(1, advice.getCalls());
	} finally {
		ctx.close();
	}
}
 
Example 32
Project: class-guard   File: BeanNamePointcutAtAspectTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testProgrammaticProxyCreation() {
	ITestBean testBean = new TestBean();

	AspectJProxyFactory factory = new AspectJProxyFactory();
	factory.setTarget(testBean);

	CounterAspect myCounterAspect = new CounterAspect();
	factory.addAspect(myCounterAspect);

	ITestBean proxyTestBean = factory.getProxy();

	assertTrue("Expected a proxy", proxyTestBean instanceof Advised);
	proxyTestBean.setAge(20);
	assertEquals("Programmatically created proxy shouldn't match bean()", 0, myCounterAspect.count);
}
 
Example 33
Project: class-guard   File: AfterReturningAdviceBindingTests.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
	ClassPathXmlApplicationContext ctx =
		new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass());

	afterAdviceAspect = (AfterReturningAdviceBindingTestAspect) ctx.getBean("testAspect");

	mockCollaborator = mock(AfterReturningAdviceBindingCollaborator.class);
	afterAdviceAspect.setCollaborator(mockCollaborator);

	testBeanProxy = (ITestBean) ctx.getBean("testBean");
	assertTrue(AopUtils.isAopProxy(testBeanProxy));

	// we need the real target too, not just the proxy...
	this.testBeanTarget = (TestBean) ((Advised)testBeanProxy).getTargetSource().getTarget();
}
 
Example 34
Project: class-guard   File: AroundAdviceBindingTests.java   Source Code and License 6 votes vote down vote up
@Before
public void onSetUp() throws Exception {
	ctx = new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass());

	AroundAdviceBindingTestAspect  aroundAdviceAspect = ((AroundAdviceBindingTestAspect) ctx.getBean("testAspect"));

	ITestBean injectedTestBean = (ITestBean) ctx.getBean("testBean");
	assertTrue(AopUtils.isAopProxy(injectedTestBean));

	this.testBeanProxy = injectedTestBean;
	// we need the real target too, not just the proxy...

	this.testBeanTarget = (TestBean) ((Advised) testBeanProxy).getTargetSource().getTarget();

	mockCollaborator = mock(AroundAdviceBindingCollaborator.class);
	aroundAdviceAspect.setCollaborator(mockCollaborator);
}
 
Example 35
Project: class-guard   File: BenchmarkTests.java   Source Code and License 6 votes vote down vote up
private long testBeforeAdviceWithoutJoinPoint(String file, int howmany, String technology) {
	ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(file, CLASS);

	StopWatch sw = new StopWatch();
	sw.start(howmany + " repeated before advice invocations with " + technology);
	ITestBean adrian = (ITestBean) bf.getBean("adrian");

	assertTrue(AopUtils.isAopProxy(adrian));
	Advised a = (Advised) adrian;
	assertTrue(a.getAdvisors().length >= 3);
	assertEquals("adrian", adrian.getName());

	for (int i = 0; i < howmany; i++) {
		adrian.getName();
	}

	sw.stop();
	System.out.println(sw.prettyPrint());
	return sw.getLastTaskTimeMillis();
}
 
Example 36
Project: class-guard   File: BenchmarkTests.java   Source Code and License 6 votes vote down vote up
private long testAfterReturningAdviceWithoutJoinPoint(String file, int howmany, String technology) {
	ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(file, CLASS);

	StopWatch sw = new StopWatch();
	sw.start(howmany + " repeated after returning advice invocations with " + technology);
	ITestBean adrian = (ITestBean) bf.getBean("adrian");

	assertTrue(AopUtils.isAopProxy(adrian));
	Advised a = (Advised) adrian;
	assertTrue(a.getAdvisors().length >= 3);
	// Hits joinpoint
	adrian.setAge(25);

	for (int i = 0; i < howmany; i++) {
		adrian.setAge(i);
	}

	sw.stop();
	System.out.println(sw.prettyPrint());
	return sw.getLastTaskTimeMillis();
}
 
Example 37
Project: class-guard   File: BeforeAdviceBindingTests.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
	ClassPathXmlApplicationContext ctx =
		new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass());

	testBeanProxy = (ITestBean) ctx.getBean("testBean");
	assertTrue(AopUtils.isAopProxy(testBeanProxy));

	// we need the real target too, not just the proxy...
	testBeanTarget = (TestBean) ((Advised) testBeanProxy).getTargetSource().getTarget();

	AdviceBindingTestAspect beforeAdviceAspect = (AdviceBindingTestAspect) ctx.getBean("testAspect");

	mockCollaborator = mock(AdviceBindingCollaborator.class);
	beforeAdviceAspect.setCollaborator(mockCollaborator);
}
 
Example 38
Project: class-guard   File: AnnotationTransactionAttributeSourceTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testSerializable() throws Exception {
	TestBean1 tb = new TestBean1();
	CallCountingTransactionManager ptm = new CallCountingTransactionManager();
	AnnotationTransactionAttributeSource tas = new AnnotationTransactionAttributeSource();
	TransactionInterceptor ti = new TransactionInterceptor(ptm, tas);

	ProxyFactory proxyFactory = new ProxyFactory();
	proxyFactory.setInterfaces(new Class[] {ITestBean.class});
	proxyFactory.addAdvice(ti);
	proxyFactory.setTarget(tb);
	ITestBean proxy = (ITestBean) proxyFactory.getProxy();
	proxy.getAge();
	assertEquals(1, ptm.commits);

	ITestBean serializedProxy = (ITestBean) SerializationTestUtils.serializeAndDeserialize(proxy);
	serializedProxy.getAge();
	Advised advised = (Advised) serializedProxy;
	TransactionInterceptor serializedTi = (TransactionInterceptor) advised.getAdvisors()[0].getAdvice();
	CallCountingTransactionManager serializedPtm =
			(CallCountingTransactionManager) serializedTi.getTransactionManager();
	assertEquals(2, serializedPtm.commits);
}
 
Example 39
Project: class-guard   File: EnableTransactionManagementIntegrationTests.java   Source Code and License 6 votes vote down vote up
private void assertTxProxying(AnnotationConfigApplicationContext ctx) {
	FooRepository repo = ctx.getBean(FooRepository.class);

	boolean isTxProxy = false;
	if (AopUtils.isAopProxy(repo)) {
		for (Advisor advisor : ((Advised)repo).getAdvisors()) {
			if (advisor instanceof BeanFactoryTransactionAttributeSourceAdvisor) {
				isTxProxy = true;
				break;
			}
		}
	}
	assertTrue("FooRepository is not a TX proxy", isTxProxy);

	// trigger a transaction
	repo.findAll();
}
 
Example 40
Project: vaadin4spring   File: ScopedEventBus.java   Source Code and License 6 votes vote down vote up
/**
 * @param scope          the scope of the events that this event bus handles.
 * @param parentEventBus the parent event bus to use, may be {@code null};
 */
public ScopedEventBus(EventScope scope, EventBus parentEventBus) {
    eventScope = scope;
    this.parentEventBus = parentEventBus;
    if (parentEventBus != null) {
        if (AopUtils.isJdkDynamicProxy(parentEventBus)) {
            logger.debug("Parent event bus [{}] is proxied, trying to get the real EventBus instance",
                    parentEventBus);
            try {
                this.parentEventBus = (EventBus) ((Advised) parentEventBus).getTargetSource().getTarget();
            } catch (Exception e) {
                logger.error("Could not get target EventBus from proxy", e);
                throw new RuntimeException("Could not get parent event bus", e);
            }
        }
        logger.debug("Using parent event bus [{}]", this.parentEventBus);
        this.parentEventBus.subscribe(parentListener);
    }
}