⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 proxyfactorybeantests.java

📁 Java/J2EE application framework based on [Expert One-on-One J2EE Design and Development] by Rod John
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
		int oldCount = config.getAdvisors().length;
		config.addAdvisor(0, new DefaultIntroductionAdvisor(ti, TimeStamped.class));
		assertTrue(config.getAdvisors().length == oldCount + 1);
		
		TimeStamped ts = (TimeStamped) factory.getBean("test2");
		assertEquals(time, ts.getTimeStamp());
		
		// Can remove
		config.removeAdvice(ti);
		assertTrue(config.getAdvisors().length == oldCount);
		
		// Check no change on existing object reference
		assertTrue(ts.getTimeStamp() == time);
		
		try {
			ts = (TimeStamped) factory.getBean("test2");
			fail("Should no longer implement TimeStamped");
		}
		catch (ClassCastException ex) {
		}
		
		// Now check non-effect of removing interceptor that isn't there
		config.removeAdvice(new DebugInterceptor());
		assertTrue(config.getAdvisors().length == oldCount);
		
		ITestBean it = (ITestBean) ts;
		DebugInterceptor debugInterceptor = new DebugInterceptor();
		config.addAdvice(0, debugInterceptor);
		it.getSpouse();
		// Won't affect existing reference
		assertTrue(debugInterceptor.getCount() == 0);
		it = (ITestBean) factory.getBean("test2");
		it.getSpouse();
		assertEquals(1, debugInterceptor.getCount());
		config.removeAdvice(debugInterceptor);
		it.getSpouse();
		
		// Still invoked wiht old reference
		assertEquals(2, debugInterceptor.getCount());
		
		// not invoked with new object
		it = (ITestBean) factory.getBean("test2");
		it.getSpouse();
		assertEquals(2, debugInterceptor.getCount());
		
		// Our own timestamped reference should still work
		assertEquals(time, ts.getTimeStamp());
	}
	
	
	
	/**
	 * Note that we can't add or remove interfaces without reconfiguring the
	 * singleton. 
	 * TODO address this?
	 *
	 */
	public void testCanAddAndRemoveAspectInterfacesOnSingletonByCasting() {
		ITestBean it = (ITestBean) factory.getBean("test1");
		Advised pc = (Advised) it;
		it.getAge();
		NopInterceptor di = new NopInterceptor();
		pc.addAdvice(0, di);
		assertEquals(0, di.getCount());
		it.setAge(25);
		assertEquals(25, it.getAge());
		assertEquals(2, di.getCount());
	}
	
	
	public void testMethodPointcuts() {
		ITestBean tb = (ITestBean) factory.getBean("pointcuts");
		PointcutForVoid.reset();
		assertTrue("No methods intercepted", PointcutForVoid.methodNames.isEmpty());
		tb.getAge();
		assertTrue("Not void: shouldn't have intercepted", PointcutForVoid.methodNames.isEmpty());
		tb.setAge(1);
		tb.getAge();
		tb.setName("Tristan");
		tb.toString();
		assertEquals("Recorded wrong number of invocations", 2, PointcutForVoid.methodNames.size());
		assertTrue(PointcutForVoid.methodNames.get(0).equals("setAge"));
		assertTrue(PointcutForVoid.methodNames.get(1).equals("setName"));
	}
	
	public void testCanAddThrowsAdviceWithoutAdvisor() throws Throwable {
		BeanFactory f = new XmlBeanFactory(new ClassPathResource("throwsAdvice.xml", getClass()));
		ThrowsAdviceInterceptorTests.MyThrowsHandler th = (ThrowsAdviceInterceptorTests.MyThrowsHandler) f.getBean("throwsAdvice");
		CountingBeforeAdvice cba = (CountingBeforeAdvice) f.getBean("countingBeforeAdvice");
		assertEquals(0, cba.getCalls());
		assertEquals(0, th.getCalls());
		ThrowsAdviceInterceptorTests.IEcho echo = (ThrowsAdviceInterceptorTests.IEcho) f.getBean("throwsAdvised");
		int i = 12;
		echo.setA(i);
		assertEquals(i, echo.getA());
		assertEquals(2, cba.getCalls());
		assertEquals(0, th.getCalls());
		Exception expected = new Exception();
		try {
			echo.echoException(1, expected);
			fail();
		}
		catch (Exception ex) {
			assertEquals(expected, ex);
		}
		// No throws handler method: count should still be 0
		assertEquals(0, th.getCalls());
		
		// Handler knows how to handle this exception
		expected = new ServletException();
		try {
			echo.echoException(1, expected);
			fail();
		}
		catch (ServletException ex) {
			assertEquals(expected, ex);
		}
		// One match
		assertEquals(1, th.getCalls("servletException"));
	}
	
	
	// These two fail the whole bean factory
	// TODO put in sep file to check quality of error message
	/*
	public void testNoInterceptorNamesWithoutTarget() {
		try {
			ITestBean tb = (ITestBean) factory.getBean("noInterceptorNamesWithoutTarget");
			fail("Should require interceptor names");
		}
		catch (AopConfigException ex) {
			// Ok
		}
	}
	
	public void testNoInterceptorNamesWithTarget() {
		ITestBean tb = (ITestBean) factory.getBean("noInterceptorNamesWithoutTarget");
	}
	*/
	
	public void testEmptyInterceptorNames() {
		try {
			ITestBean tb = (ITestBean) factory.getBean("emptyInterceptorNames");
			fail("Interceptor names cannot be empty");
		}
		catch (BeanCreationException ex) {
			// Ok
		}
	}
	
	/**
	 * Globals must be followed by a target.
	 */
	public void testGlobalsWithoutTarget() {
		try {
			ITestBean tb = (ITestBean) factory.getBean("globalsWithoutTarget");
			fail("Should require target name");
		}
		catch (BeanCreationException ex) {
			assertTrue(ex.getCause() instanceof AopConfigException);
		}
	}
	
	/**
	 * Checks that globals get invoked,
	 * and that they can add aspect interfaces unavailable
	 * to other beans. These interfaces don't need
	 * to be included in proxiedInterface [].
	 */
	public void testGlobalsCanAddAspectInterfaces() {
		AddedGlobalInterface agi = (AddedGlobalInterface) factory.getBean("autoInvoker");
		assertTrue(agi.globalsAdded() == -1);
		
		ProxyFactoryBean pfb = (ProxyFactoryBean) factory.getBean("&validGlobals");
		// 2 globals + 2 explicit
		assertEquals("Have 2 globals and 2 explicit advisors", 3, pfb.getAdvisors().length);
		
		ApplicationListener l = (ApplicationListener) factory.getBean("validGlobals");
		agi = (AddedGlobalInterface) l;
		assertTrue(agi.globalsAdded() == -1);
		
		try {
			agi = (AddedGlobalInterface) factory.getBean("test1");
			fail("Aspect interface should't be implemeneted without globals");
		}
		catch (ClassCastException ex) {
		}
	}
	
	public void testSerializableSingletonProxy() throws Exception {
		BeanFactory bf = new XmlBeanFactory(new ClassPathResource("serializationTests.xml", getClass()));
		Person p = (Person) bf.getBean("serializableSingleton");
		assertSame("Should be a Singleton", p, bf.getBean("serializableSingleton"));
		Person p2 = (Person) SerializationTestUtils.serializeAndDeserialize(p);
		assertEquals(p, p2);
		assertNotSame(p, p2);
		assertEquals("serializableSingleton", p2.getName());
		
		// Add unserializable advice
		Advice nop = new NopInterceptor();
		((Advised) p).addAdvice(nop);
		// Check it still works
		assertEquals(p2.getName(), p2.getName());
		assertFalse("Not serializable because an interceptor isn't serializable", SerializationTestUtils.isSerializable(p));
		
		// Remove offending interceptor...
		assertTrue(((Advised) p).removeAdvice(nop));
		assertTrue("Serializable again because offending interceptor was removed", SerializationTestUtils.isSerializable(p));	
	}
	
	public void testSerializablePrototypeProxy() throws Exception {
		BeanFactory bf = new XmlBeanFactory(new ClassPathResource("serializationTests.xml", getClass()));
		Person p = (Person) bf.getBean("serializablePrototype");
		assertNotSame("Should not be a Singleton", p, bf.getBean("serializablePrototype"));
		Person p2 = (Person) SerializationTestUtils.serializeAndDeserialize(p);
		assertEquals(p, p2);
		assertNotSame(p, p2);
		assertEquals("serializablePrototype", p2.getName());
	}
	
	public void testProxyNotSerializableBecauseOfAdvice() throws Exception {
		BeanFactory bf = new XmlBeanFactory(new ClassPathResource("serializationTests.xml", getClass()));
		Person p = (Person) bf.getBean("interceptorNotSerializableSingleton");
		assertFalse("Not serializable because an interceptor isn't serializable", SerializationTestUtils.isSerializable(p));
	}

	public void testPrototypeAdvisor() {
		BeanFactory bf = new XmlBeanFactory(new ClassPathResource("proxyFactoryTests.xml", getClass()));

		ITestBean bean1 = (ITestBean) bf.getBean("prototypeTestBeanProxy");
		ITestBean bean2 = (ITestBean) bf.getBean("prototypeTestBeanProxy");

		bean1.setAge(3);
		bean2.setAge(4);

		assertEquals(3, bean1.getAge());
		assertEquals(4, bean2.getAge());

		((Lockable) bean1).lock();

		try {
			bean1.setAge(5);
			fail("expected LockedException");
		}
		catch (LockedException ex) {
			// expected
		}

		try {
			bean2.setAge(6);
		}
		catch (LockedException ex) {
			fail("did not expect LockedException");
		}
	}

	public void testPrototypeInterceptorSingletonTarget() {
		BeanFactory bf = new XmlBeanFactory(new ClassPathResource("proxyFactoryTests.xml", getClass()));

		ITestBean bean1 = (ITestBean) bf.getBean("prototypeTestBeanProxySingletonTarget");
		ITestBean bean2 = (ITestBean) bf.getBean("prototypeTestBeanProxySingletonTarget");

		bean1.setAge(1);
		bean2.setAge(2);

		assertEquals(2, bean1.getAge());

		((Lockable) bean1).lock();

		try {
			bean1.setAge(5);
			fail("expected LockedException");
		}
		catch (LockedException ex) {
			// expected
		}

		try {
			bean2.setAge(6);
		}
		catch (LockedException ex) {
			fail("did not expect LockedException");
		}
	}
	

	/**
	 * Fires only on void methods. Saves list of methods intercepted.
	 */
	public static class PointcutForVoid extends DynamicMethodMatcherPointcutAdvisor {
		
		public static List methodNames = new LinkedList();
		
		public static void reset() {
			methodNames.clear();
		}
		
		public PointcutForVoid() {
			super( new MethodInterceptor() {
				public Object invoke(MethodInvocation invocation) throws Throwable {
					methodNames.add(invocation.getMethod().getName());
					return invocation.proceed();
				}
			});
		}
		
		/** Should fire only if it returns null */
		public boolean matches(Method m, Class targetClass, Object[] args) {//, AttributeRegistry attributeRegistry) {
			//System.out.println(mi.getMethod().getReturnType());
			return m.getReturnType() == Void.TYPE;
		}
	}


	/**
	 * Aspect interface
	 */
	public interface AddedGlobalInterface {
		int globalsAdded();
	}


	/**
	 * Use as a global interceptor. Checks that 
	 * global interceptors can add aspect interfaces.
	 * NB: Add only via global interceptors in XML file.
	 */
	public static class GlobalAspectInterfaceInterceptor implements IntroductionInterceptor {

		public boolean implementsInterface(Class intf) {
			return intf.equals(AddedGlobalInterface.class);
		}

		public Object invoke(MethodInvocation mi) throws Throwable {
			if (mi.getMethod().getDeclaringClass().equals(AddedGlobalInterface.class)) {
				return new Integer(-1);
			}
			return mi.proceed();
		}
	}


	public static class GlobalIntroductionAdvice implements IntroductionAdvisor {
		
		private IntroductionInterceptor gi = new GlobalAspectInterfaceInterceptor();

		public ClassFilter getClassFilter() {
			return ClassFilter.TRUE;
		}

		public Advice getAdvice() {
			return this.gi;
		}

		public Class[] getInterfaces() {
			return new Class[] { AddedGlobalInterface.class };
		}

		public boolean isPerInstance() {
			return false;
		}
		
		public void validateInterfaces() {
		}
	}
	
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -