org.springframework.aop.framework.Advised Java Examples

The following examples show how to use org.springframework.aop.framework.Advised. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AnnotationTransactionAttributeSourceTests.java    From spring-analysis-note with MIT 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(ITestBean1.class);
	proxyFactory.addAdvice(ti);
	proxyFactory.setTarget(tb);
	ITestBean1 proxy = (ITestBean1) proxyFactory.getProxy();
	proxy.getAge();
	assertEquals(1, ptm.commits);

	ITestBean1 serializedProxy = (ITestBean1) 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 #2
Source File: SpringContextUtil.java    From tcc-transaction with Apache License 2.0 6 votes vote down vote up
/**
 * 根据模块中的实例获取模块标识
 * @param target
 * @return
 */
public static String getModuleIdByTarget(Object target){
    if(target instanceof ModuleContextAdapter){
        return ((ModuleContextAdapter)target).getModuleContext().getModuleId();
    }
    //如果是Aop代理则需要获取targetClass的ClassLoader
    ClassLoader classLoader= target.getClass().getClassLoader();
    if(target instanceof Advised){
        classLoader= ((Advised)target).getTargetClass().getClassLoader();
    }
    for(ModuleContext each: moduleContexts.values()){
        if(each.getClassLoader()==classLoader){
            return each.getModuleId();
        }
    }
    return "webapplication";
}
 
Example #3
Source File: JdbcFixture.java    From spring-data-dev-tools with Apache License 2.0 6 votes vote down vote up
private static void disableEntityCallbacks(ApplicationContext context) {
	
	JdbcBookRepository repository = context.getBean(JdbcBookRepository.class);

	Field field = ReflectionUtils.findField(SimpleJdbcRepository.class, "entityOperations");
	ReflectionUtils.makeAccessible(field);
	
	try {
		JdbcAggregateTemplate aggregateTemplate = (JdbcAggregateTemplate) ReflectionUtils.getField(field,
				((Advised) repository).getTargetSource().getTarget());

		field = ReflectionUtils.findField(JdbcAggregateTemplate.class, "publisher");
		ReflectionUtils.makeAccessible(field);
		ReflectionUtils.setField(field, aggregateTemplate, NoOpApplicationEventPublisher.INSTANCE);
		
		aggregateTemplate.setEntityCallbacks(NoOpEntityCallbacks.INSTANCE);
		
	} catch (Exception o_O) {
		throw new RuntimeException(o_O);
	}
}
 
Example #4
Source File: TaskBatchExecutionListenerFactoryBean.java    From spring-cloud-task with Apache License 2.0 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 #5
Source File: AroundAdviceBindingTests.java    From spring4-understanding with Apache License 2.0 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 #6
Source File: ConcurrencyThrottleInterceptorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testSerializable() throws Exception {
	DerivedTestBean tb = new DerivedTestBean();
	ProxyFactory proxyFactory = new ProxyFactory();
	proxyFactory.setInterfaces(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 #7
Source File: ProcessStartAnnotationBeanPostProcessor.java    From camunda-bpm-platform with Apache License 2.0 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 #8
Source File: AmazonS3ClientFactory.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
private static AmazonS3Client getAmazonS3ClientFromProxy(AmazonS3 amazonS3) {
	if (AopUtils.isAopProxy(amazonS3)) {
		Advised advised = (Advised) amazonS3;
		Object target = null;
		try {
			target = advised.getTargetSource().getTarget();
		}
		catch (Exception e) {
			return null;
		}
		return target instanceof AmazonS3Client ? (AmazonS3Client) target : null;
	}
	else {
		return amazonS3 instanceof AmazonS3Client ? (AmazonS3Client) amazonS3 : null;
	}
}
 
Example #9
Source File: EnableAsyncTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void customAsyncAnnotationIsPropagated() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(CustomAsyncAnnotationConfig.class, CustomAsyncBean.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);

	ctx.close();
}
 
Example #10
Source File: StatsUpdateManagerTest.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testConfigIsEventContextSupported() throws Exception {
	// #3: EventContextSupported
	assertEquals(true, statsManager.isEventContextSupported());

	// make sure it processes both events
	Event e1 = statsUpdateManager.buildEvent(new Date(), FakeData.EVENT_CONTENTNEW, "/content/group/non_existent_site/resource_id", FakeData.SITE_A_ID, FakeData.USER_A_ID, "session-id-a");
	Event e2 = statsUpdateManager.buildEvent(new Date(), FakeData.EVENT_CONTENTNEW, "/content/group/"+FakeData.SITE_A_ID+"/resource_id", null, FakeData.USER_B_ID, "session-id-a");
	statsUpdateManager.collectEvents(Arrays.asList(e1, e2));
	List<EventStat> results1 = (List<EventStat>) db.getResultsForClass(EventStatImpl.class);
	assertEquals(2, results1.size());

	// none of these events will be picked up
	((StatsManagerImpl) ((Advised) statsManager).getTargetSource().getTarget()).setEventContextSupported(false);
	assertEquals(false, statsManager.isEventContextSupported());
	Event e3 = statsUpdateManager.buildEvent(new Date(), FakeData.EVENT_CONTENTREAD, "/content/group/non_existent_site/resource_id", FakeData.SITE_A_ID, FakeData.USER_A_ID, "session-id-a");
	Event e4 = statsUpdateManager.buildEvent(new Date(), FakeData.EVENT_CONTENTNEW, "/content/group/"+FakeData.SITE_B_ID+"/resource_id", null, FakeData.USER_B_ID, "session-id-a");
	statsUpdateManager.collectEvents(Arrays.asList(e3, e4));
	List<EventStat> results2 = (List<EventStat>) db.getResultsForClass(EventStatImpl.class);
	assertEquals(2, results2.size());
}
 
Example #11
Source File: AroundAdviceBindingTests.java    From spring-analysis-note with MIT 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
Source File: BeforeAdviceBindingTests.java    From java-technology-stack with MIT 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 #13
Source File: SpringContextUtil.java    From galaxy with Apache License 2.0 6 votes vote down vote up
/**
 * 根据模块中的实例获取模块标识
 * @param target
 * @return
 */
public static String getModuleIdByTarget(Object target){
    if(target instanceof ModuleContextAdapter){
        return ((ModuleContextAdapter)target).getModuleContext().getModuleId();
    }
    //如果是Aop代理则需要获取targetClass的ClassLoader
    ClassLoader classLoader= target.getClass().getClassLoader();
    if(target instanceof Advised){
        classLoader= ((Advised)target).getTargetClass().getClassLoader();
    }
    for(ModuleContext each: moduleContexts.values()){
        if(each.getClassLoader()==classLoader){
            return each.getModuleId();
        }
    }
    return "webapplication";
}
 
Example #14
Source File: ConcurrencyThrottleInterceptorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testSerializable() throws Exception {
	DerivedTestBean tb = new DerivedTestBean();
	ProxyFactory proxyFactory = new ProxyFactory();
	proxyFactory.setInterfaces(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 #15
Source File: AopTestUtils.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Get the ultimate <em>target</em> object of the supplied {@code candidate}
 * object, unwrapping not only a top-level proxy but also any number of
 * nested proxies.
 * <p>If the supplied {@code candidate} is a Spring
 * {@linkplain AopUtils#isAopProxy proxy}, the ultimate target of all
 * nested proxies will be returned; otherwise, the {@code candidate}
 * will be returned <em>as is</em>.
 * @param candidate the instance to check (potentially a Spring AOP proxy;
 * never {@code null})
 * @return the target object or the {@code candidate} (never {@code null})
 * @throws IllegalStateException if an error occurs while unwrapping a proxy
 * @see Advised#getTargetSource()
 * @see org.springframework.aop.framework.AopProxyUtils#ultimateTargetClass
 */
@SuppressWarnings("unchecked")
public static <T> T getUltimateTargetObject(Object candidate) {
	Assert.notNull(candidate, "Candidate must not be null");
	try {
		if (AopUtils.isAopProxy(candidate) && candidate instanceof Advised) {
			Object target = ((Advised) candidate).getTargetSource().getTarget();
			if (target != null) {
				return (T) getUltimateTargetObject(target);
			}
		}
	}
	catch (Throwable ex) {
		throw new IllegalStateException("Failed to unwrap proxied object", ex);
	}
	return (T) candidate;
}
 
Example #16
Source File: BeanNamePointcutAtAspectTests.java    From spring-analysis-note with MIT 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 #17
Source File: BenchmarkTests.java    From spring-analysis-note with MIT 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 #18
Source File: StatsUpdateManagerTest.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testConfigIsEventContextSupported() throws Exception {
	// #3: EventContextSupported
	assertEquals(true, statsManager.isEventContextSupported());

	// make sure it processes both events
	Event e1 = statsUpdateManager.buildEvent(new Date(), FakeData.EVENT_CONTENTNEW, "/content/group/non_existent_site/resource_id", FakeData.SITE_A_ID, FakeData.USER_A_ID, "session-id-a");
	Event e2 = statsUpdateManager.buildEvent(new Date(), FakeData.EVENT_CONTENTNEW, "/content/group/"+FakeData.SITE_A_ID+"/resource_id", null, FakeData.USER_B_ID, "session-id-a");
	statsUpdateManager.collectEvents(Arrays.asList(e1, e2));
	List<EventStat> results1 = (List<EventStat>) db.getResultsForClass(EventStatImpl.class);
	assertEquals(2, results1.size());

	// none of these events will be picked up
	((StatsManagerImpl) ((Advised) statsManager).getTargetSource().getTarget()).setEventContextSupported(false);
	assertEquals(false, statsManager.isEventContextSupported());
	Event e3 = statsUpdateManager.buildEvent(new Date(), FakeData.EVENT_CONTENTREAD, "/content/group/non_existent_site/resource_id", FakeData.SITE_A_ID, FakeData.USER_A_ID, "session-id-a");
	Event e4 = statsUpdateManager.buildEvent(new Date(), FakeData.EVENT_CONTENTNEW, "/content/group/"+FakeData.SITE_B_ID+"/resource_id", null, FakeData.USER_B_ID, "session-id-a");
	statsUpdateManager.collectEvents(Arrays.asList(e3, e4));
	List<EventStat> results2 = (List<EventStat>) db.getResultsForClass(EventStatImpl.class);
	assertEquals(2, results2.size());
}
 
Example #19
Source File: ProxyUtils.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T getTargetObject(Object candidate) {
	try {
		if (AopUtils.isAopProxy(candidate) && (candidate instanceof Advised)) {
			return (T) ((Advised) candidate).getTargetSource().getTarget();
		}
	}
	catch (Exception ex) {
		throw new IllegalStateException("Failed to unwrap proxied object", ex);
	}
	return (T) candidate;
}
 
Example #20
Source File: RefreshScopeIntegrationTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Test
@DirtiesContext
public void testSimpleProperties() throws Exception {
	then(this.service.getMessage()).isEqualTo("Hello scope!");
	then(this.service instanceof Advised).isTrue();
	// Change the dynamic property source...
	this.properties.setMessage("Foo");
	// ...but don't refresh, so the bean stays the same:
	then(this.service.getMessage()).isEqualTo("Hello scope!");
	then(ExampleService.getInitCount()).isEqualTo(0);
	then(ExampleService.getDestroyCount()).isEqualTo(0);
}
 
Example #21
Source File: BenchmarkTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private long testMix(String file, int howmany, String technology) {
	ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(file, CLASS);

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

	assertTrue(AopUtils.isAopProxy(adrian));
	Advised a = (Advised) adrian;
	assertTrue(a.getAdvisors().length >= 3);

	for (int i = 0; i < howmany; i++) {
		// Hit all 3 joinpoints
		adrian.getAge();
		adrian.getName();
		adrian.setAge(i);

		// Invoke three non-advised methods
		adrian.getDoctor();
		adrian.getLawyer();
		adrian.getSpouse();
	}

	sw.stop();
	System.out.println(sw.prettyPrint());
	return sw.getLastTaskTimeMillis();
}
 
Example #22
Source File: StatsUpdateManagerTest.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Before
public void onSetUp() throws Exception {
	db.deleteAll();
	memoryService.resetCachers();

	FakeSite userSiteA = spy(FakeSite.class).set("~"+FakeData.USER_A_ID);
	FakeSite userSiteB = spy(FakeSite.class).set("~"+FakeData.USER_B_ID);
	when(siteService.getSiteUserId(FakeData.USER_A_ID)).thenReturn("~"+FakeData.USER_A_ID);
	when(siteService.getSiteUserId(FakeData.USER_B_ID)).thenReturn("~"+FakeData.USER_B_ID);
	when(siteService.getSiteUserId("no_user")).thenReturn(null);
	when(siteService.getSite("~"+FakeData.USER_A_ID)).thenReturn(userSiteA);
	when(siteService.getSite("~"+FakeData.USER_B_ID)).thenReturn(userSiteB);

	// Site A has tools {SiteStats, Chat}, has {user-a,user-b}
	FakeSite siteA = spy(FakeSite.class).set(FakeData.SITE_A_ID, Arrays.asList(StatsManager.SITESTATS_TOOLID, FakeData.TOOL_CHAT, StatsManager.RESOURCES_TOOLID));
	siteA.setUsers(new HashSet<>(Arrays.asList(FakeData.USER_A_ID, FakeData.USER_B_ID)));
	siteA.setMembers(new HashSet<>(Arrays.asList(FakeData.USER_A_ID, FakeData.USER_B_ID)));
	when(siteService.getSite(FakeData.SITE_A_ID)).thenReturn(siteA);
	when(siteService.isUserSite(FakeData.SITE_A_ID)).thenReturn(false);
	when(siteService.isSpecialSite(FakeData.SITE_A_ID)).thenReturn(false);

	// Site B has tools {TOOL_CHAT}, has {user-a}, notice this site doesn't have the site stats tool
	FakeSite siteB = spy(FakeSite.class).set(FakeData.SITE_B_ID, Arrays.asList(FakeData.TOOL_CHAT));
	siteB.setUsers(new HashSet<>(Collections.singletonList(FakeData.USER_A_ID)));
	siteB.setMembers(new HashSet<>(Collections.singletonList(FakeData.USER_A_ID)));
	when(siteService.getSite(FakeData.SITE_B_ID)).thenReturn(siteB);
	when(siteService.isUserSite(FakeData.SITE_B_ID)).thenReturn(false);
	when(siteService.isSpecialSite(FakeData.SITE_B_ID)).thenReturn(false);

	// This is needed to make the tests deterministic, otherwise on occasion the collect thread will run
	// and break the tests.
	statsUpdateManager.setCollectThreadEnabled(false);

	((StatsManagerImpl) ((Advised) statsManager).getTargetSource().getTarget()).setShowAnonymousAccessEvents(true);
	((StatsManagerImpl) ((Advised) statsManager).getTargetSource().getTarget()).setEnableSitePresences(true);
	((ReportManagerImpl) ((Advised) reportManager).getTargetSource().getTarget()).setResourceLoader(resourceLoader);
}
 
Example #23
Source File: AopNamespaceHandlerScopeIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testSessionScoping() throws Exception {
	MockHttpSession oldSession = new MockHttpSession();
	MockHttpSession newSession = new MockHttpSession();

	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setSession(oldSession);
	RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));

	ITestBean scoped = (ITestBean) this.context.getBean("sessionScoped");
	assertTrue("Should be AOP proxy", AopUtils.isAopProxy(scoped));
	assertFalse("Should not be target class proxy", scoped instanceof TestBean);

	ITestBean scopedAlias = (ITestBean) this.context.getBean("sessionScopedAlias");
	assertSame(scoped, scopedAlias);

	ITestBean testBean = (ITestBean) this.context.getBean("testBean");
	assertTrue("Should be AOP proxy", AopUtils.isAopProxy(testBean));
	assertFalse("Regular bean should be JDK proxy", testBean instanceof TestBean);

	String rob = "Rob Harrop";
	String bram = "Bram Smeets";

	assertEquals(rob, scoped.getName());
	scoped.setName(bram);
	request.setSession(newSession);
	assertEquals(rob, scoped.getName());
	request.setSession(oldSession);
	assertEquals(bram, scoped.getName());

	assertTrue("Should have advisors", ((Advised) scoped).getAdvisors().length > 0);
}
 
Example #24
Source File: AfterAdviceBindingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public void setup() throws Exception {
	ClassPathXmlApplicationContext ctx =
			new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass());
	AdviceBindingTestAspect afterAdviceAspect = (AdviceBindingTestAspect) ctx.getBean("testAspect");

	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();

	mockCollaborator = mock(AdviceBindingCollaborator.class);
	afterAdviceAspect.setCollaborator(mockCollaborator);
}
 
Example #25
Source File: CallUtil.java    From telekom-workflow-engine with MIT License 5 votes vote down vote up
private static String getTargetName(final Object target) {
    if (Proxy.isProxyClass(target.getClass())) {
        if (target instanceof Advised) {
            try {
                return ((Advised)target).getTargetSource().getTarget().getClass().getName();
            } catch (Exception e) {
                // Nothing to do here.
            }
        }
        return target.getClass().getName() + " (unresolved proxy)";
    }
    return target.getClass().getName();
}
 
Example #26
Source File: EnableCachingIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void assertCacheProxying(AnnotationConfigApplicationContext ctx) {
	FooRepository repo = ctx.getBean(FooRepository.class);

	boolean isCacheProxy = false;
	if (AopUtils.isAopProxy(repo)) {
		for (Advisor advisor : ((Advised)repo).getAdvisors()) {
			if (advisor instanceof BeanFactoryCacheOperationSourceAdvisor) {
				isCacheProxy = true;
				break;
			}
		}
	}
	assertTrue("FooRepository is not a cache proxy", isCacheProxy);
}
 
Example #27
Source File: AopNamespaceHandlerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsProxy() throws Exception {
	ITestBean bean = getTestBean();

	assertTrue("Bean is not a proxy", AopUtils.isAopProxy(bean));

	// check the advice details
	Advised advised = (Advised) bean;
	Advisor[] advisors = advised.getAdvisors();

	assertTrue("Advisors should not be empty", advisors.length > 0);
}
 
Example #28
Source File: PersistenceExceptionTranslationPostProcessorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
protected void checkWillTranslateExceptions(Object o) {
	assertTrue(o instanceof Advised);
	Advised a = (Advised) o;
	for (Advisor advisor : a.getAdvisors()) {
		if (advisor instanceof PersistenceExceptionTranslationAdvisor) {
			return;
		}
	}
	fail("No translation");
}
 
Example #29
Source File: NameMatchMethodPointcutTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testSerializable() throws Throwable {
	testSets();
	// Count is now 2
	Person p2 = (Person) SerializationTestUtils.serializeAndDeserialize(proxied);
	NopInterceptor nop2 = (NopInterceptor) ((Advised) p2).getAdvisors()[0].getAdvice();
	p2.getName();
	assertEquals(2, nop2.getCount());
	p2.echo(null);
	assertEquals(3, nop2.getCount());
}
 
Example #30
Source File: AbstractAspectJAdvisorFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testPerTypeWithinAspect() throws SecurityException, NoSuchMethodException {
	TestBean target = new TestBean();
	int realAge = 65;
	target.setAge(realAge);
	PerTypeWithinAspectInstanceFactory aif = new PerTypeWithinAspectInstanceFactory();
	TestBean itb = (TestBean) createProxy(target, getFixture().getAdvisors(aif), TestBean.class);
	assertEquals("No method calls", 0, aif.getInstantiationCount());
	assertEquals("Around advice must now apply", 0, itb.getAge());

	Advised advised = (Advised) itb;
	// Will be ExposeInvocationInterceptor, synthetic instantiation advisor, 2 method advisors
	assertEquals(4, advised.getAdvisors().length);
	ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor sia =
			(ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor) advised.getAdvisors()[1];
	assertTrue(sia.getPointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null));
	InstantiationModelAwarePointcutAdvisorImpl imapa = (InstantiationModelAwarePointcutAdvisorImpl) advised.getAdvisors()[2];
	LazySingletonAspectInstanceFactoryDecorator maaif =
			(LazySingletonAspectInstanceFactoryDecorator) imapa.getAspectInstanceFactory();
	assertTrue(maaif.isMaterialized());

	// Check that the perclause pointcut is valid
	assertTrue(maaif.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null));
	assertNotSame(imapa.getDeclaredPointcut(), imapa.getPointcut());

	// Hit the method in the per clause to instantiate the aspect
	itb.getSpouse();

	assertTrue(maaif.isMaterialized());

	assertTrue(imapa.getDeclaredPointcut().getMethodMatcher().matches(TestBean.class.getMethod("getAge"), null));

	assertEquals("Around advice must still apply", 1, itb.getAge());
	assertEquals("Around advice must still apply", 2, itb.getAge());

	TestBean itb2 = (TestBean) createProxy(target, getFixture().getAdvisors(aif), TestBean.class);
	assertEquals(1, aif.getInstantiationCount());
	assertEquals("Around advice be independent for second instance", 0, itb2.getAge());
	assertEquals(2, aif.getInstantiationCount());
}