moving unit tests from .testsuite -> .aop

This commit is contained in:
Chris Beams
2008-12-11 21:55:53 +00:00
parent 3ca36b39e0
commit 3412f9b6f9
21 changed files with 1260 additions and 10 deletions

View File

@@ -0,0 +1,924 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.annotation;
import static org.junit.Assert.*;
import java.io.FileNotFoundException;
import java.lang.reflect.UndeclaredThrowableException;
import java.rmi.RemoteException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.DeclarePrecedence;
import org.aspectj.lang.annotation.Pointcut;
import org.junit.Test;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.annotation.ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor;
import org.springframework.aop.framework.Advised;
import org.springframework.aop.framework.AopConfigException;
import org.springframework.aop.framework.Lockable;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.interceptor.ExposeInvocationInterceptor;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.core.OrderComparator;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
/**
* Abstract tests for AspectJAdvisorFactory.
* See subclasses for tests of concrete factories.
*
* @author Rod Johnson
*/
public abstract class AbstractAspectJAdvisorFactoryTests {
/**
* To be overridden by concrete test subclasses.
* @return the fixture
*/
protected abstract AspectJAdvisorFactory getFixture();
@Test
public void testRejectsPerCflowAspect() {
try {
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new PerCflowAspect(),"someBean"));
fail("Cannot accept cflow");
}
catch (AopConfigException ex) {
assertTrue(ex.getMessage().indexOf("PERCFLOW") != -1);
}
}
@Test
public void testRejectsPerCflowBelowAspect() {
try {
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new PerCflowBelowAspect(),"someBean"));
fail("Cannot accept cflowbelow");
}
catch (AopConfigException ex) {
assertTrue(ex.getMessage().indexOf("PERCFLOWBELOW") != -1);
}
}
@Test
public void testPerTargetAspect() throws SecurityException, NoSuchMethodException {
TestBean target = new TestBean();
int realAge = 65;
target.setAge(realAge);
TestBean itb = (TestBean) createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new PerTargetAspect(), "someBean")),
TestBean.class);
assertEquals("Around advice must NOT apply", realAge, itb.getAge());
Advised advised = (Advised) itb;
SyntheticInstantiationAdvisor sia = (SyntheticInstantiationAdvisor) advised.getAdvisors()[1];
assertTrue(sia.getPointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null));
InstantiationModelAwarePointcutAdvisorImpl imapa = (InstantiationModelAwarePointcutAdvisorImpl) advised.getAdvisors()[3];
LazySingletonAspectInstanceFactoryDecorator maaif =
(LazySingletonAspectInstanceFactoryDecorator) imapa.getAspectInstanceFactory();
assertFalse(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());
assertEquals("Around advice must apply", 0, itb.getAge());
assertEquals("Around advice must apply", 1, itb.getAge());
}
@Test
public void testMultiplePerTargetAspects() throws SecurityException, NoSuchMethodException {
TestBean target = new TestBean();
int realAge = 65;
target.setAge(realAge);
List<Advisor> advisors = new LinkedList<Advisor>();
PerTargetAspect aspect1 = new PerTargetAspect();
aspect1.count = 100;
aspect1.setOrder(10);
advisors.addAll(
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(aspect1, "someBean1")));
PerTargetAspect aspect2 = new PerTargetAspect();
aspect2.setOrder(5);
advisors.addAll(
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(aspect2, "someBean2")));
Collections.sort(advisors, new OrderComparator());
TestBean itb = (TestBean) createProxy(target, advisors, TestBean.class);
assertEquals("Around advice must NOT apply", realAge, itb.getAge());
// Hit the method in the per clause to instantiate the aspect
itb.getSpouse();
assertEquals("Around advice must apply", 0, itb.getAge());
assertEquals("Around advice must apply", 1, itb.getAge());
}
@Test
public void testMultiplePerTargetAspectsWithOrderAnnotation() throws SecurityException, NoSuchMethodException {
TestBean target = new TestBean();
int realAge = 65;
target.setAge(realAge);
List<Advisor> advisors = new LinkedList<Advisor>();
PerTargetAspectWithOrderAnnotation10 aspect1 = new PerTargetAspectWithOrderAnnotation10();
aspect1.count = 100;
advisors.addAll(
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(aspect1, "someBean1")));
PerTargetAspectWithOrderAnnotation5 aspect2 = new PerTargetAspectWithOrderAnnotation5();
advisors.addAll(
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(aspect2, "someBean2")));
Collections.sort(advisors, new OrderComparator());
TestBean itb = (TestBean) createProxy(target, advisors, TestBean.class);
assertEquals("Around advice must NOT apply", realAge, itb.getAge());
// Hit the method in the per clause to instantiate the aspect
itb.getSpouse();
assertEquals("Around advice must apply", 0, itb.getAge());
assertEquals("Around advice must apply", 1, itb.getAge());
}
@Test
public void testPerThisAspect() throws SecurityException, NoSuchMethodException {
TestBean target = new TestBean();
int realAge = 65;
target.setAge(realAge);
TestBean itb = (TestBean) createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new PerThisAspect(), "someBean")),
TestBean.class);
assertEquals("Around advice must NOT apply", realAge, itb.getAge());
Advised advised = (Advised) itb;
// Will be ExposeInvocationInterceptor, synthetic instantiation advisor, 2 method advisors
assertEquals(4, advised.getAdvisors().length);
SyntheticInstantiationAdvisor sia = (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();
assertFalse(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 apply", 0, itb.getAge());
assertEquals("Around advice must apply", 1, itb.getAge());
}
@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);
SyntheticInstantiationAdvisor sia = (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());
}
@Test
public void testNamedPointcutAspectWithFQN() {
testNamedPointcuts(new NamedPointcutAspectWithFQN());
}
@Test
public void testNamedPointcutAspectWithoutFQN() {
testNamedPointcuts(new NamedPointcutAspectWithoutFQN());
}
@Test
public void testNamedPointcutFromAspectLibrary() {
testNamedPointcuts(new NamedPointcutAspectFromLibrary());
}
@Test
public void testNamedPointcutFromAspectLibraryWithBinding() {
TestBean target = new TestBean();
ITestBean itb = (ITestBean) createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new NamedPointcutAspectFromLibraryWithBinding(),"someBean")),
ITestBean.class);
itb.setAge(10);
assertEquals("Around advice must apply", 20, itb.getAge());
assertEquals(20,target.getAge());
}
private void testNamedPointcuts(Object aspectInstance) {
TestBean target = new TestBean();
int realAge = 65;
target.setAge(realAge);
ITestBean itb = (ITestBean) createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(aspectInstance,"someBean")),
ITestBean.class);
assertEquals("Around advice must apply", -1, itb.getAge());
assertEquals(realAge, target.getAge());
}
@Test
public void testBindingWithSingleArg() {
TestBean target = new TestBean();
ITestBean itb = (ITestBean) createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new BindingAspectWithSingleArg(),"someBean")),
ITestBean.class);
itb.setAge(10);
assertEquals("Around advice must apply", 20, itb.getAge());
assertEquals(20,target.getAge());
}
@Test
public void testBindingWithMultipleArgsDifferentlyOrdered() {
ManyValuedArgs target = new ManyValuedArgs();
ManyValuedArgs mva = (ManyValuedArgs) createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new ManyValuedArgs(),"someBean")),
ManyValuedArgs.class);
String a = "a";
int b = 12;
int c = 25;
String d = "d";
StringBuffer e = new StringBuffer("stringbuf");
String expectedResult = a + b+ c + d + e;
assertEquals(expectedResult, mva.mungeArgs(a, b, c, d, e));
}
/**
* In this case the introduction will be made.
*/
@Test
public void testIntroductionOnTargetNotImplementingInterface() {
NotLockable notLockableTarget = new NotLockable();
assertFalse(notLockableTarget instanceof Lockable);
NotLockable notLockable1 = (NotLockable) createProxy(notLockableTarget,
getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(),"someBean")),
NotLockable.class);
assertTrue(notLockable1 instanceof Lockable);
Lockable lockable = (Lockable) notLockable1;
assertFalse(lockable.locked());
lockable.lock();
assertTrue(lockable.locked());
NotLockable notLockable2Target = new NotLockable();
NotLockable notLockable2 = (NotLockable) createProxy(notLockable2Target,
getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(),"someBean")),
NotLockable.class);
assertTrue(notLockable2 instanceof Lockable);
Lockable lockable2 = (Lockable) notLockable2;
assertFalse(lockable2.locked());
notLockable2.setIntValue(1);
lockable2.lock();
try {
notLockable2.setIntValue(32);
fail();
}
catch (IllegalStateException ex) {
}
assertTrue(lockable2.locked());
}
@Test
public void testIntroductionAdvisorExcludedFromTargetImplementingInterface() {
assertTrue(AopUtils.findAdvisorsThatCanApply(
getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(
new MakeLockable(),"someBean")),
CannotBeUnlocked.class).isEmpty());
assertEquals(2, AopUtils.findAdvisorsThatCanApply(getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(),"someBean")), NotLockable.class).size());
}
@Test
public void testIntroductionOnTargetImplementingInterface() {
CannotBeUnlocked target = new CannotBeUnlocked();
Lockable proxy = (Lockable) createProxy(target,
// Ensure that we exclude
AopUtils.findAdvisorsThatCanApply(
getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(), "someBean")),
CannotBeUnlocked.class
),
CannotBeUnlocked.class);
assertTrue(proxy instanceof Lockable);
Lockable lockable = (Lockable) proxy;
assertTrue("Already locked", lockable.locked());
lockable.lock();
assertTrue("Real target ignores locking", lockable.locked());
try {
lockable.unlock();
fail();
}
catch (UnsupportedOperationException ex) {
// Ok
}
}
@SuppressWarnings("unchecked")
@Test
public void testIntroductionOnTargetExcludedByTypePattern() {
LinkedList target = new LinkedList();
List proxy = (List) createProxy(target,
AopUtils.findAdvisorsThatCanApply(
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(), "someBean")),
List.class
),
CannotBeUnlocked.class);
assertFalse("Type pattern must have excluded mixin", proxy instanceof Lockable);
}
// TODO: Why does this test fail? It hasn't been run before, so it maybe never actually passed...
public void XtestIntroductionWithArgumentBinding() {
TestBean target = new TestBean();
List<Advisor> advisors = getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new MakeITestBeanModifiable(),"someBean"));
advisors.addAll(getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(),"someBean")));
Modifiable modifiable = (Modifiable) createProxy(target,
advisors,
ITestBean.class);
assertTrue(modifiable instanceof Modifiable);
Lockable lockable = (Lockable) modifiable;
assertFalse(lockable.locked());
ITestBean itb = (ITestBean) modifiable;
assertFalse(modifiable.isModified());
int oldAge = itb.getAge();
itb.setAge(oldAge + 1);
assertTrue(modifiable.isModified());
modifiable.acceptChanges();
assertFalse(modifiable.isModified());
itb.setAge(itb.getAge());
assertFalse("Setting same value does not modify", modifiable.isModified());
itb.setName("And now for something completely different");
assertTrue(modifiable.isModified());
lockable.lock();
assertTrue(lockable.locked());
try {
itb.setName("Else");
fail("Should be locked");
}
catch (IllegalStateException ex) {
// Ok
}
lockable.unlock();
itb.setName("Tony");
}
@Test
public void testAspectMethodThrowsExceptionLegalOnSignature() {
TestBean target = new TestBean();
UnsupportedOperationException expectedException = new UnsupportedOperationException();
List<Advisor> advisors = getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new ExceptionAspect(expectedException),"someBean"));
assertEquals("One advice method was found", 1, advisors.size());
ITestBean itb = (ITestBean) createProxy(target,
advisors,
ITestBean.class);
try {
itb.getAge();
fail();
}
catch (UnsupportedOperationException ex) {
assertSame(expectedException, ex);
}
}
// TODO document this behaviour.
// Is it different AspectJ behaviour, at least for checked exceptions?
@Test
public void testAspectMethodThrowsExceptionIllegalOnSignature() {
TestBean target = new TestBean();
RemoteException expectedException = new RemoteException();
List<Advisor> advisors = getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new ExceptionAspect(expectedException),"someBean"));
assertEquals("One advice method was found", 1, advisors.size());
ITestBean itb = (ITestBean) createProxy(target,
advisors,
ITestBean.class);
try {
itb.getAge();
fail();
}
catch (UndeclaredThrowableException ex) {
assertSame(expectedException, ex.getCause());
}
}
protected Object createProxy(Object target, List<Advisor> advisors, Class<?>... interfaces) {
ProxyFactory pf = new ProxyFactory(target);
if (interfaces.length > 1 || interfaces[0].isInterface()) {
pf.setInterfaces(interfaces);
}
else {
pf.setProxyTargetClass(true);
}
// Required everywhere we use AspectJ proxies
pf.addAdvice(ExposeInvocationInterceptor.INSTANCE);
for (Object a : advisors) {
pf.addAdvisor((Advisor) a);
}
pf.setExposeProxy(true);
return pf.getProxy();
}
@Test
public void testTwoAdvicesOnOneAspect() {
TestBean target = new TestBean();
TwoAdviceAspect twoAdviceAspect = new TwoAdviceAspect();
List<Advisor> advisors = getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(twoAdviceAspect,"someBean"));
assertEquals("Two advice methods found", 2, advisors.size());
ITestBean itb = (ITestBean) createProxy(target,
advisors,
ITestBean.class);
itb.setName("");
assertEquals(0, itb.getAge());
int newAge = 32;
itb.setAge(newAge);
assertEquals(1, itb.getAge());
}
@Test
public void testAfterAdviceTypes() throws Exception {
Echo target = new Echo();
ExceptionHandling afterReturningAspect = new ExceptionHandling();
List<Advisor> advisors = getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(afterReturningAspect,"someBean"));
Echo echo = (Echo) createProxy(target,
advisors,
Echo.class);
assertEquals(0, afterReturningAspect.successCount);
assertEquals("", echo.echo(""));
assertEquals(1, afterReturningAspect.successCount);
assertEquals(0, afterReturningAspect.failureCount);
try {
echo.echo(new FileNotFoundException());
fail();
}
catch (FileNotFoundException ex) {
// Ok
}
catch (Exception ex) {
fail();
}
assertEquals(1, afterReturningAspect.successCount);
assertEquals(1, afterReturningAspect.failureCount);
assertEquals(afterReturningAspect.failureCount + afterReturningAspect.successCount, afterReturningAspect.afterCount);
}
@Test
public void testFailureWithoutExplicitDeclarePrecedence() {
TestBean target = new TestBean();
ITestBean itb = (ITestBean) createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new NoDeclarePrecedenceShouldFail(), "someBean")),
ITestBean.class);
try {
itb.getAge();
fail();
}
catch (IllegalStateException ex) {
// expected
}
}
@Test
public void testDeclarePrecedenceNotSupported() {
TestBean target = new TestBean();
try {
createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(
new DeclarePrecedenceShouldSucceed(),"someBean")),
ITestBean.class);
fail();
}
catch (IllegalArgumentException ex) {
// Not supported in 2.0
}
}
/** Not supported in 2.0!
public void testExplicitDeclarePrecedencePreventsFailure() {
TestBean target = new TestBean();
ITestBean itb = (ITestBean) createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new DeclarePrecedenceShouldSucceed(), "someBean")),
ITestBean.class);
assertEquals(666, itb.getAge());
}
*/
@Aspect("percflow(execution(* *(..)))")
public static class PerCflowAspect {
}
@Aspect("percflowbelow(execution(* *(..)))")
public static class PerCflowBelowAspect {
}
@Aspect("pertarget(execution(* *.getSpouse()))")
public static class PerTargetAspect implements Ordered {
public int count;
private int order = Ordered.LOWEST_PRECEDENCE;
@Around("execution(int *.getAge())")
public int returnCountAsAge() {
return count++;
}
@Before("execution(void *.set*(int))")
public void countSetter() {
++count;
}
public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
}
}
@Aspect("pertarget(execution(* *.getSpouse()))")
@Order(10)
public static class PerTargetAspectWithOrderAnnotation10 {
public int count;
@Around("execution(int *.getAge())")
public int returnCountAsAge() {
return count++;
}
@Before("execution(void *.set*(int))")
public void countSetter() {
++count;
}
}
@Aspect("pertarget(execution(* *.getSpouse()))")
@Order(5)
public static class PerTargetAspectWithOrderAnnotation5 {
public int count;
@Around("execution(int *.getAge())")
public int returnCountAsAge() {
return count++;
}
@Before("execution(void *.set*(int))")
public void countSetter() {
++count;
}
}
@Aspect("perthis(execution(* *.getSpouse()))")
public static class PerThisAspect {
public int count;
/**
* Just to check that this doesn't cause problems with introduction processing
*/
private ITestBean fieldThatShouldBeIgnoredBySpringAtAspectJProcessing = new TestBean();
@Around("execution(int *.getAge())")
public int returnCountAsAge() {
return count++;
}
@Before("execution(void *.set*(int))")
public void countSetter() {
++count;
}
}
@Aspect("pertypewithin(org.springframework.beans.IOther+)")
public static class PerTypeWithinAspect {
public int count;
@Around("execution(int *.getAge())")
public int returnCountAsAge() {
return count++;
}
@Before("execution(void *.*(..))")
public void countAnythingVoid() {
++count;
}
}
private class PerTypeWithinAspectInstanceFactory implements MetadataAwareAspectInstanceFactory {
private int count;
public int getInstantiationCount() {
return this.count;
}
public Object getAspectInstance() {
++this.count;
return new PerTypeWithinAspect();
}
public ClassLoader getAspectClassLoader() {
return PerTypeWithinAspect.class.getClassLoader();
}
public AspectMetadata getAspectMetadata() {
return new AspectMetadata(PerTypeWithinAspect.class, "perTypeWithin");
}
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
}
@Aspect
public static class NamedPointcutAspectWithFQN {
private ITestBean fieldThatShouldBeIgnoredBySpringAtAspectJProcessing = new TestBean();
@Pointcut("execution(* getAge())")
public void getAge() {
}
@Around("org.springframework.aop.aspectj.annotation.AbstractAspectJAdvisorFactoryTests.NamedPointcutAspectWithFQN.getAge()")
public int changeReturnValue(ProceedingJoinPoint pjp) {
return -1;
}
}
@Aspect
public static class NamedPointcutAspectWithoutFQN {
@Pointcut("execution(* getAge())")
public void getAge() {
}
@Around("getAge()")
public int changeReturnValue(ProceedingJoinPoint pjp) {
return -1;
}
}
@Aspect
public static class NamedPointcutAspectFromLibrary {
@Around("org.springframework.aop.aspectj.annotation.AbstractAspectJAdvisorFactoryTests.Library.propertyAccess()")
public int changeReturnType(ProceedingJoinPoint pjp) {
return -1;
}
@Around(value="org.springframework.aop.aspectj.annotation.AbstractAspectJAdvisorFactoryTests.Library.integerArgOperation(x)", argNames="x")
public void doubleArg(ProceedingJoinPoint pjp, int x) throws Throwable {
pjp.proceed(new Object[] {x*2});
}
}
@Aspect
public static class Library {
@Pointcut("execution(!void get*())")
public void propertyAccess() {}
@Pointcut("execution(* *(..)) && args(i)")
public void integerArgOperation(int i) {}
}
@Aspect
public static class NamedPointcutAspectFromLibraryWithBinding {
@Around(value="org.springframework.aop.aspectj.annotation.AbstractAspectJAdvisorFactoryTests.Library.integerArgOperation(x)", argNames="x")
public void doubleArg(ProceedingJoinPoint pjp, int x) throws Throwable {
pjp.proceed(new Object[] {x*2});
}
}
@Aspect
public static class BindingAspectWithSingleArg {
@Pointcut(value="args(a)", argNames="a")
public void setAge(int a) {}
@Around(value="setAge(age)",argNames="age")
// @ArgNames({"age"}) // AMC needs more work here? ignoring pjp arg... ok??
// // argNames should be suported in Around as it is in Pointcut
public void changeReturnType(ProceedingJoinPoint pjp, int age) throws Throwable {
pjp.proceed(new Object[] {age*2});
}
}
@Aspect
public static class ManyValuedArgs {
public String mungeArgs(String a, int b, int c, String d, StringBuffer e) {
return a + b + c + d + e;
}
@Around(value="execution(String mungeArgs(..)) && args(a, b, c, d, e)",
argNames="b,c,d,e,a")
public String reverseAdvice(ProceedingJoinPoint pjp, int b, int c, String d, StringBuffer e, String a) throws Throwable {
assertEquals(a + b+ c+ d+ e, pjp.proceed());
return a + b + c + d + e;
}
}
@Aspect
public static class ExceptionAspect {
private final Exception ex;
public ExceptionAspect(Exception ex) {
this.ex = ex;
}
@Before("execution(* getAge())")
public void throwException() throws Exception {
throw ex;
}
}
@Aspect
public static class TwoAdviceAspect {
private int totalCalls;
@Around("execution(* getAge())")
public int returnCallCount(ProceedingJoinPoint pjp) throws Exception {
return totalCalls;
}
@Before("execution(* setAge(int)) && args(newAge)")
public void countSet(int newAge) throws Exception {
++totalCalls;
}
}
public static class Echo {
public Object echo(Object o) throws Exception {
if (o instanceof Exception) {
throw (Exception) o;
}
return o;
}
}
@Aspect
public static class ExceptionHandling {
public int successCount;
public int failureCount;
public int afterCount;
@AfterReturning("execution(* echo(*))")
public void succeeded() {
++successCount;
}
@AfterThrowing("execution(* echo(*))")
public void failed() {
++failureCount;
}
@After("execution(* echo(*))")
public void invoked() {
++afterCount;
}
}
@Aspect
public static class NoDeclarePrecedenceShouldFail {
@Pointcut("execution(int *.getAge())")
public void getAge() {
}
@Before("getAge()")
public void blowUpButDoesntMatterBecauseAroundAdviceWontLetThisBeInvoked() {
throw new IllegalStateException();
}
@Around("getAge()")
public int preventExecution(ProceedingJoinPoint pjp) {
return 666;
}
}
@Aspect
@DeclarePrecedence("org.springframework..*")
public static class DeclarePrecedenceShouldSucceed {
@Pointcut("execution(int *.getAge())")
public void getAge() {
}
@Before("getAge()")
public void blowUpButDoesntMatterBecauseAroundAdviceWontLetThisBeInvoked() {
throw new IllegalStateException();
}
@Around("getAge()")
public int preventExecution(ProceedingJoinPoint pjp) {
return 666;
}
}
}

View File

@@ -0,0 +1,109 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.annotation;
import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.util.ObjectUtils;
/**
* Add a DeclareParents field in concrete subclasses, to identify
* the type pattern to apply the introduction to.
*
* @author Rod Johnson
* @since 2.0
*/
@Aspect
public abstract class AbstractMakeModifiable {
public interface MutableModifable extends Modifiable {
void markDirty();
}
public static class ModifiableImpl implements MutableModifable {
private boolean modified;
public void acceptChanges() {
modified = false;
}
public boolean isModified() {
return modified;
}
public void markDirty() {
this.modified = true;
}
}
@Before(value="execution(void set*(*)) && this(modifiable) && args(newValue)",
argNames="modifiable,newValue")
public void recordModificationIfSetterArgumentDiffersFromOldValue(JoinPoint jp,
MutableModifable mixin, Object newValue) {
/*
* We use the mixin to check and, if necessary, change,
* modification status. We need the JoinPoint to get the
* setter method. We use newValue for comparison.
* We try to invoke the getter if possible.
*/
if (mixin.isModified()) {
// Already changed, don't need to change again
//System.out.println("changed");
return;
}
// Find the current raw value, by invoking the corresponding setter
Method correspondingGetter = getGetterFromSetter(((MethodSignature) jp.getSignature()).getMethod());
boolean modified = true;
if (correspondingGetter != null) {
try {
Object oldValue = correspondingGetter.invoke(jp.getTarget());
//System.out.println("Old value=" + oldValue + "; new=" + newValue);
modified = !ObjectUtils.nullSafeEquals(oldValue, newValue);
}
catch (Exception ex) {
ex.printStackTrace();
// Don't sweat on exceptions; assume value was modified
}
}
else {
//System.out.println("cannot get getter for " + jp);
}
if (modified) {
mixin.markDirty();
}
}
private Method getGetterFromSetter(Method setter) {
String getterName = setter.getName().replaceFirst("set", "get");
try {
return setter.getDeclaringClass().getMethod(getterName, (Class[]) null);
}
catch (NoSuchMethodException ex) {
// must be write only
return null;
}
}
}

View File

@@ -0,0 +1,41 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.annotation;
import org.springframework.aop.framework.Lockable;
/**
* @author Rod Johnson
*/
public class CannotBeUnlocked implements Lockable, Comparable<Object> {
public void lock() {
}
public void unlock() {
throw new UnsupportedOperationException();
}
public boolean locked() {
return true;
}
public int compareTo(Object arg0) {
throw new UnsupportedOperationException();
}
}

View File

@@ -0,0 +1,28 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.annotation;
import org.aspectj.lang.annotation.Aspect;
/**
* @author Rob Harrop
* @since 2.o
*/
@Aspect
public class FooAspect {
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.annotation;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.DeclareParents;
/**
* Adds a declare parents pointcut.
* @author Rod Johnson
* @since 2.0
*/
@Aspect
public class MakeITestBeanModifiable extends AbstractMakeModifiable {
@DeclareParents(value = "org.springframework.beans.ITestBean+",
defaultImpl=ModifiableImpl.class)
public static MutableModifable mixin;
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.annotation;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.DeclareParents;
import org.springframework.aop.framework.DefaultLockable;
import org.springframework.aop.framework.Lockable;
/**
* Demonstrates introductions, AspectJ annotation style.
* <p>
* @author Rod Johnson
* @since 2.0
*/
@Aspect
public class MakeLockable {
@DeclareParents(value = "org.springframework..*",
defaultImpl=DefaultLockable.class)
public static Lockable mixin;
@Before(value="execution(void set*(*)) && this(mixin)", argNames="mixin")
public void checkNotLocked(
Lockable mixin) // Bind to arg
{
// Can also obtain the mixin (this) this way
//Lockable mixin = (Lockable) jp.getThis();
if (mixin.locked()) {
throw new IllegalStateException();
}
}
}
/*
*
* public aspect MakeLockable {
*
* declare parents org....* implements Lockable;
*
* private boolean Lockable.locked;
* public void Lockable.lock() {
this.locked = true;
}
* public void Lockable.unlock() {
this.locked = false;
}
* public boolean Lockable.locked() {
return this.locked;
}
*
*
* }
*/

View File

@@ -0,0 +1,30 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.annotation;
/**
* Used as a mixin.
*
* @author Rod Johnson
*/
public interface Modifiable {
boolean isModified();
void acceptChanges();
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.annotation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
/**
* @author Adrian Colyer
*/
@Aspect
public class NamedPointcutWithArgs {
@Pointcut("execution(* *(..)) && args(s,..)")
public void pointcutWithArgs(String s) {}
@Around("pointcutWithArgs(aString)")
public Object doAround(ProceedingJoinPoint pjp, String aString) throws Throwable {
System.out.println("got '" + aString + "' at '" + pjp + "'");
throw new IllegalArgumentException(aString);
}
}

View File

@@ -0,0 +1,15 @@
package org.springframework.aop.aspectj.annotation;
public class NotLockable {
private int intValue;
public int getIntValue() {
return intValue;
}
public void setIntValue(int intValue) {
this.intValue = intValue;
}
}

View File

@@ -0,0 +1,33 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.annotation;
/**
* Tests for ReflectiveAtAspectJAdvisorFactory.
* Tests are inherited: we only set the test fixture here.
*
* @author Rod Johnson
* @since 2.0
*/
public class ReflectiveAspectJAdvisorFactoryTests extends AbstractAspectJAdvisorFactoryTests {
@Override
protected AspectJAdvisorFactory getFixture() {
return new ReflectiveAspectJAdvisorFactory();
}
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.framework;
/**
* Simple implementation of Lockable interface for use in mixins.
*
* @author Rod Johnson
*/
public class DefaultLockable implements Lockable {
private boolean locked;
public void lock() {
this.locked = true;
}
public void unlock() {
this.locked = false;
}
public boolean locked() {
return this.locked;
}
}

View File

@@ -0,0 +1,33 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.framework;
/**
* Simple interface to use for mixins
*
* @author Rod Johnson
*
*/
public interface Lockable {
void lock();
void unlock();
boolean locked();
}

View File

@@ -0,0 +1,36 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
import org.springframework.core.enums.ShortCodedLabeledEnum;
/**
* @author Rob Harrop
*/
@SuppressWarnings("serial")
public class Colour extends ShortCodedLabeledEnum {
public static final Colour RED = new Colour(0, "RED");
public static final Colour BLUE = new Colour(1, "BLUE");
public static final Colour GREEN = new Colour(2, "GREEN");
public static final Colour PURPLE = new Colour(3, "PURPLE");
private Colour(int code, String label) {
super(code, label);
}
}

View File

@@ -0,0 +1,23 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
public interface INestedTestBean {
public String getCompany();
}

View File

@@ -0,0 +1,24 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
public interface IOther {
void absquatulate();
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
import java.io.IOException;
/**
* Interface used for {@link org.springframework.beans.TestBean}.
*
* <p>Two methods are the same as on Person, but if this
* extends person it breaks quite a few tests..
*
* @author Rod Johnson
* @author Juergen Hoeller
*/
public interface ITestBean {
int getAge();
void setAge(int age);
String getName();
void setName(String name);
ITestBean getSpouse();
void setSpouse(ITestBean spouse);
ITestBean[] getSpouses();
String[] getStringArray();
void setStringArray(String[] stringArray);
/**
* Throws a given (non-null) exception.
*/
void exceptional(Throwable t) throws Throwable;
Object returnsThis();
INestedTestBean getDoctor();
INestedTestBean getLawyer();
IndexedTestBean getNestedIndexedBean();
/**
* Increment the age by one.
* @return the previous age
*/
int haveBirthday();
void unreliableFileOperation() throws IOException;
}

View File

@@ -0,0 +1,145 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* @author Juergen Hoeller
* @since 11.11.2003
*/
public class IndexedTestBean {
private TestBean[] array;
private Collection<TestBean> collection;
private List<TestBean> list;
private Set<TestBean> set;
private SortedSet<TestBean> sortedSet;
private Map<String, ? super Object> map;
private SortedMap<?, ?> sortedMap;
public IndexedTestBean() {
this(true);
}
public IndexedTestBean(boolean populate) {
if (populate) {
populate();
}
}
public void populate() {
TestBean tb0 = new TestBean("name0", 0);
TestBean tb1 = new TestBean("name1", 0);
TestBean tb2 = new TestBean("name2", 0);
TestBean tb3 = new TestBean("name3", 0);
TestBean tb4 = new TestBean("name4", 0);
TestBean tb5 = new TestBean("name5", 0);
TestBean tb6 = new TestBean("name6", 0);
TestBean tb7 = new TestBean("name7", 0);
TestBean tbX = new TestBean("nameX", 0);
TestBean tbY = new TestBean("nameY", 0);
this.array = new TestBean[] {tb0, tb1};
this.list = new ArrayList<TestBean>();
this.list.add(tb2);
this.list.add(tb3);
this.set = new TreeSet<TestBean>();
this.set.add(tb6);
this.set.add(tb7);
this.map = new HashMap<String, Object>();
this.map.put("key1", tb4);
this.map.put("key2", tb5);
this.map.put("key.3", tb5);
List<TestBean> list = new ArrayList<TestBean>();
list.add(tbX);
list.add(tbY);
this.map.put("key4", list);
}
public TestBean[] getArray() {
return array;
}
public void setArray(TestBean[] array) {
this.array = array;
}
public Collection<TestBean> getCollection() {
return collection;
}
public void setCollection(Collection<TestBean> collection) {
this.collection = collection;
}
public List<TestBean> getList() {
return list;
}
public void setList(List<TestBean> list) {
this.list = list;
}
public Set<TestBean> getSet() {
return set;
}
public void setSet(Set<TestBean> set) {
this.set = set;
}
public SortedSet<TestBean> getSortedSet() {
return sortedSet;
}
public void setSortedSet(SortedSet<TestBean> sortedSet) {
this.sortedSet = sortedSet;
}
public Map<String, ? super Object> getMap() {
return map;
}
public void setMap(Map<String, ? super Object> map) {
this.map = map;
}
public SortedMap<?, ?> getSortedMap() {
return sortedMap;
}
public void setSortedMap(SortedMap<?, ?> sortedMap) {
this.sortedMap = sortedMap;
}
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
/**
* Simple nested test bean used for testing bean factories, AOP framework etc.
*
* @author Trevor D. Cook
* @since 30.09.2003
*/
public class NestedTestBean implements INestedTestBean {
private String company = "";
public NestedTestBean() {
}
public NestedTestBean(String company) {
setCompany(company);
}
public void setCompany(String company) {
this.company = (company != null ? company : "");
}
public String getCompany() {
return company;
}
public boolean equals(Object obj) {
if (!(obj instanceof NestedTestBean)) {
return false;
}
NestedTestBean ntb = (NestedTestBean) obj;
return this.company.equals(ntb.company);
}
public int hashCode() {
return this.company.hashCode();
}
public String toString() {
return "NestedTestBean: " + this.company;
}
}

View File

@@ -0,0 +1,424 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.springframework.util.ObjectUtils;
/**
* Simple test bean used for testing bean factories, the AOP framework etc.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since 15 April 2001
*/
public class TestBean implements ITestBean, IOther, Comparable<Object> {
private String beanName;
private String country;
private boolean postProcessed;
private String name;
private String sex;
private int age;
private boolean jedi;
private ITestBean[] spouses;
private String touchy;
private String[] stringArray;
private Integer[] someIntegerArray;
private Date date = new Date();
private Float myFloat = new Float(0.0);
private Collection<?> friends = new LinkedList<Object>();
private Set<?> someSet = new HashSet<Object>();
private Map<?, ?> someMap = new HashMap<Object, Object>();
private List<?> someList = new ArrayList<Object>();
private Properties someProperties = new Properties();
private INestedTestBean doctor = new NestedTestBean();
private INestedTestBean lawyer = new NestedTestBean();
private IndexedTestBean nestedIndexedBean;
private boolean destroyed;
private Number someNumber;
private Colour favouriteColour;
private Boolean someBoolean;
private List<?> otherColours;
private List<?> pets;
public TestBean() {
}
public TestBean(String name) {
this.name = name;
}
public TestBean(ITestBean spouse) {
this.spouses = new ITestBean[] {spouse};
}
public TestBean(String name, int age) {
this.name = name;
this.age = age;
}
public TestBean(ITestBean spouse, Properties someProperties) {
this.spouses = new ITestBean[] {spouse};
this.someProperties = someProperties;
}
public TestBean(List<?> someList) {
this.someList = someList;
}
public TestBean(Set<?> someSet) {
this.someSet = someSet;
}
public TestBean(Map<?, ?> someMap) {
this.someMap = someMap;
}
public TestBean(Properties someProperties) {
this.someProperties = someProperties;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
public String getBeanName() {
return beanName;
}
public void setPostProcessed(boolean postProcessed) {
this.postProcessed = postProcessed;
}
public boolean isPostProcessed() {
return postProcessed;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
if (this.name == null) {
this.name = sex;
}
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isJedi() {
return jedi;
}
public void setJedi(boolean jedi) {
this.jedi = jedi;
}
public ITestBean getSpouse() {
return (spouses != null ? spouses[0] : null);
}
public void setSpouse(ITestBean spouse) {
this.spouses = new ITestBean[] {spouse};
}
public ITestBean[] getSpouses() {
return spouses;
}
public String getTouchy() {
return touchy;
}
public void setTouchy(String touchy) throws Exception {
if (touchy.indexOf('.') != -1) {
throw new Exception("Can't contain a .");
}
if (touchy.indexOf(',') != -1) {
throw new NumberFormatException("Number format exception: contains a ,");
}
this.touchy = touchy;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String[] getStringArray() {
return stringArray;
}
public void setStringArray(String[] stringArray) {
this.stringArray = stringArray;
}
public Integer[] getSomeIntegerArray() {
return someIntegerArray;
}
public void setSomeIntegerArray(Integer[] someIntegerArray) {
this.someIntegerArray = someIntegerArray;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Float getMyFloat() {
return myFloat;
}
public void setMyFloat(Float myFloat) {
this.myFloat = myFloat;
}
public Collection<?> getFriends() {
return friends;
}
public void setFriends(Collection<?> friends) {
this.friends = friends;
}
public Set<?> getSomeSet() {
return someSet;
}
public void setSomeSet(Set<?> someSet) {
this.someSet = someSet;
}
public Map<?, ?> getSomeMap() {
return someMap;
}
public void setSomeMap(Map<?, ?> someMap) {
this.someMap = someMap;
}
public List<?> getSomeList() {
return someList;
}
public void setSomeList(List<?> someList) {
this.someList = someList;
}
public Properties getSomeProperties() {
return someProperties;
}
public void setSomeProperties(Properties someProperties) {
this.someProperties = someProperties;
}
public INestedTestBean getDoctor() {
return doctor;
}
public void setDoctor(INestedTestBean doctor) {
this.doctor = doctor;
}
public INestedTestBean getLawyer() {
return lawyer;
}
public void setLawyer(INestedTestBean lawyer) {
this.lawyer = lawyer;
}
public Number getSomeNumber() {
return someNumber;
}
public void setSomeNumber(Number someNumber) {
this.someNumber = someNumber;
}
public Colour getFavouriteColour() {
return favouriteColour;
}
public void setFavouriteColour(Colour favouriteColour) {
this.favouriteColour = favouriteColour;
}
public Boolean getSomeBoolean() {
return someBoolean;
}
public void setSomeBoolean(Boolean someBoolean) {
this.someBoolean = someBoolean;
}
public IndexedTestBean getNestedIndexedBean() {
return nestedIndexedBean;
}
public void setNestedIndexedBean(IndexedTestBean nestedIndexedBean) {
this.nestedIndexedBean = nestedIndexedBean;
}
public List<?> getOtherColours() {
return otherColours;
}
public void setOtherColours(List<?> otherColours) {
this.otherColours = otherColours;
}
public List<?> getPets() {
return pets;
}
public void setPets(List<?> pets) {
this.pets = pets;
}
/**
* @see ITestBean#exceptional(Throwable)
*/
public void exceptional(Throwable t) throws Throwable {
if (t != null) {
throw t;
}
}
public void unreliableFileOperation() throws IOException {
throw new IOException();
}
/**
* @see ITestBean#returnsThis()
*/
public Object returnsThis() {
return this;
}
/**
* @see IOther#absquatulate()
*/
public void absquatulate() {
}
public int haveBirthday() {
return age++;
}
public void destroy() {
this.destroyed = true;
}
public boolean wasDestroyed() {
return destroyed;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || !(other instanceof TestBean)) {
return false;
}
TestBean tb2 = (TestBean) other;
return (ObjectUtils.nullSafeEquals(this.name, tb2.name) && this.age == tb2.age);
}
public int hashCode() {
return this.age;
}
public int compareTo(Object other) {
if (this.name != null && other instanceof TestBean) {
return this.name.compareTo(((TestBean) other).getName());
}
else {
return 1;
}
}
public String toString() {
return this.name;
}
}